ceulen 0.20.0 → 0.25.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 (53) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/extensions/lib/env.test.ts +45 -0
  3. package/extensions/lib/env.ts +56 -3
  4. package/extensions/lib/registry.ts +8 -0
  5. package/extensions/lib/skill-path.test.ts +1 -1
  6. package/extensions/modules/a2a/lib/gateway.ts +3 -0
  7. package/extensions/modules/a2a/lib/persistence.ts +3 -2
  8. package/extensions/modules/a2a/test/persistence.test.ts +12 -0
  9. package/extensions/modules/classifier/index.ts +12 -1
  10. package/extensions/modules/classifier/lib/settings.ts +21 -0
  11. package/extensions/modules/classifier/lib/think-gate.ts +211 -0
  12. package/extensions/modules/classifier/test/classifier.test.ts +285 -1
  13. package/extensions/modules/composer/lib/shapes.ts +2 -1
  14. package/extensions/modules/cron/index.ts +1 -0
  15. package/extensions/modules/cron/lib/jobs.ts +2 -1
  16. package/extensions/modules/cron/test/cwd-repro.test.ts +10 -1
  17. package/extensions/modules/goal/configPanel.ts +63 -0
  18. package/extensions/modules/goal/index.ts +545 -0
  19. package/extensions/modules/goal/lib/settings.ts +73 -0
  20. package/extensions/modules/goal/lib/state.ts +223 -0
  21. package/extensions/modules/goal/test/goal.test.ts +522 -0
  22. package/extensions/modules/jfind/index.ts +13 -4
  23. package/extensions/modules/jfind/lib/cascade.ts +5 -2
  24. package/extensions/modules/jfind/lib/tree.ts +8 -3
  25. package/extensions/modules/jfind/test/cascade.test.ts +28 -1
  26. package/extensions/modules/munin/configPanel.ts +13 -3
  27. package/extensions/modules/munin/index.ts +7 -4
  28. package/extensions/modules/munin/test/configPanel.test.ts +9 -3
  29. package/extensions/modules/munin/test/extension.test.ts +31 -0
  30. package/extensions/modules/permission/index.ts +20 -9
  31. package/extensions/modules/permission/test/permission.test.ts +33 -1
  32. package/extensions/modules/plan/index.ts +36 -7
  33. package/extensions/modules/plan/lib/shell-gate.ts +93 -26
  34. package/extensions/modules/plan/test/module.test.ts +114 -1
  35. package/extensions/modules/plan/test/shell-gate.test.ts +64 -0
  36. package/extensions/modules/repair/lib/guards.ts +4 -1
  37. package/extensions/modules/repair/test/guards.test.ts +9 -0
  38. package/extensions/modules/router/lib/client.ts +24 -0
  39. package/extensions/modules/router/test/unit.test.ts +33 -3
  40. package/extensions/modules/sg/index.ts +3 -3
  41. package/extensions/modules/sg/lib/ops.ts +15 -1
  42. package/extensions/modules/sg/test/sg.test.ts +16 -2
  43. package/extensions/modules/subagent/index.ts +12 -1
  44. package/extensions/modules/subagent/lib/herdr.ts +37 -3
  45. package/extensions/modules/subagent/lib/history.ts +6 -2
  46. package/extensions/modules/subagent/lib/settings.ts +2 -1
  47. package/extensions/modules/subagent/test/extension.test.ts +31 -0
  48. package/extensions/modules/subagent/test/file-modes.test.ts +40 -0
  49. package/extensions/modules/subagent/test/herdr-stalled.test.ts +39 -0
  50. package/extensions/modules/web/lib/chatgpt.ts +2 -1
  51. package/extensions/scripts/probe-thinking.mjs +108 -0
  52. package/package.json +4 -4
  53. package/skills/review/SKILL.md +45 -0
@@ -0,0 +1,522 @@
1
+ /**
2
+ * goal module tests — the pure state machine, command parsing, the
3
+ * continuation loop, budget flow, the goal tool, and rehydration.
4
+ * Untyped harness stub: only the pi surface the module touches
5
+ * (usage/ponytail/todo test tradition).
6
+ */
7
+
8
+ import assert from "node:assert/strict";
9
+ import { describe, it } from "node:test";
10
+
11
+ import goalModule, { defaultBudget, defaultMaxTurns } from "../index.ts";
12
+ import {
13
+ activePrompt,
14
+ applyUsage,
15
+ budgetError,
16
+ budgetLimitPrompt,
17
+ completionBudgetReport,
18
+ continuationPrompt,
19
+ goalTokenDelta,
20
+ shouldContinue,
21
+ statusLine,
22
+ type GoalState,
23
+ } from "../lib/state.ts";
24
+
25
+ const fresh = (over: Partial<GoalState> = {}): GoalState => ({
26
+ objective: "make the tests pass",
27
+ status: "active",
28
+ tokenBudget: undefined,
29
+ tokensUsed: 0,
30
+ timeUsedSeconds: 0,
31
+ turns: 0,
32
+ maxTurns: 3,
33
+ startedAt: Date.now(),
34
+ ...over,
35
+ });
36
+
37
+ // ---------- pure state machine ----------
38
+
39
+ describe("goalTokenDelta", () => {
40
+ it("sums positive input+cacheWrite+output deltas; cacheRead excluded; negatives clamp to 0", () => {
41
+ assert.equal(
42
+ goalTokenDelta(
43
+ { input: 120, output: 40, cacheRead: 5000, cacheWrite: 30 },
44
+ { input: 100, output: 10, cacheRead: 4000, cacheWrite: 10 },
45
+ ),
46
+ 20 + 20 + 30,
47
+ );
48
+ // A compaction/shrink (input lower than baseline) never produces negative billing.
49
+ assert.equal(goalTokenDelta({ input: 50, output: 0, cacheRead: 0, cacheWrite: 0 }, { input: 100, output: 10, cacheRead: 0, cacheWrite: 0 }), 0);
50
+ });
51
+ });
52
+
53
+ describe("applyUsage", () => {
54
+ it("accumulates and flips active → budget-limited exactly at the budget", () => {
55
+ const s = fresh({ tokenBudget: 100 });
56
+ assert.equal(applyUsage(s, 60), false);
57
+ assert.equal(applyUsage(s, 39), false);
58
+ assert.equal(applyUsage(s, 1), true, "flip at >= budget");
59
+ assert.equal(s.status, "budget-limited");
60
+ assert.equal(s.tokensUsed, 100);
61
+ });
62
+
63
+ it("never flips when unbounded, and does not flip a paused goal", () => {
64
+ const s = fresh();
65
+ assert.equal(applyUsage(s, 10_000), false);
66
+ const p = fresh({ status: "paused", tokenBudget: 10 });
67
+ applyUsage(p, 500);
68
+ assert.equal(p.status, "paused");
69
+ });
70
+ });
71
+
72
+ describe("shouldContinue", () => {
73
+ it("continues only for an active, non-aborted, non-plan, under-cap goal", () => {
74
+ assert.equal(shouldContinue(fresh(), { aborted: false, planActive: false }), "continue");
75
+ assert.equal(shouldContinue(fresh({ turns: 3, maxTurns: 3 }), { aborted: false, planActive: false }), "stop");
76
+ assert.equal(shouldContinue(fresh(), { aborted: true, planActive: false }), "pause");
77
+ assert.equal(shouldContinue(fresh(), { aborted: false, planActive: true }), "pause");
78
+ assert.equal(shouldContinue(fresh({ status: "budget-limited" }), { aborted: false, planActive: false }), "none");
79
+ assert.equal(shouldContinue(fresh({ status: "paused" }), { aborted: false, planActive: false }), "none");
80
+ assert.equal(shouldContinue(fresh({ status: "complete" }), { aborted: false, planActive: false }), "none");
81
+ assert.equal(shouldContinue(undefined, { aborted: false, planActive: false }), "none");
82
+ });
83
+ });
84
+
85
+ describe("budget validation + completion report", () => {
86
+ it("budgetError rejects non-positive-integers only", () => {
87
+ assert.equal(budgetError(undefined), undefined);
88
+ assert.equal(budgetError(1000), undefined);
89
+ assert.match(budgetError(0)!, /positive integer/);
90
+ assert.match(budgetError(-5)!, /positive integer/);
91
+ assert.match(budgetError(1.5)!, /positive integer/);
92
+ });
93
+
94
+ it("completionBudgetReport mentions budget and time only when present", () => {
95
+ assert.equal(completionBudgetReport(fresh()), null);
96
+ const r = completionBudgetReport(fresh({ tokenBudget: 500, tokensUsed: 420, timeUsedSeconds: 90 }));
97
+ assert.match(r!, /tokens used: 420 of 500/);
98
+ assert.match(r!, /time used: 90 seconds/);
99
+ });
100
+ });
101
+
102
+ // ---------- prompts ----------
103
+
104
+ describe("prompts", () => {
105
+ it("escape XML-sensitive objective text at render time (raw state stays intact)", () => {
106
+ const s = fresh({ objective: 'fix "a<b> & c' });
107
+ const p = continuationPrompt(s);
108
+ assert.ok(p.includes("&lt;b&gt;"), "objective must be escaped in the prompt");
109
+ assert.ok(!p.includes("<b>"), "raw <b> must not appear");
110
+ assert.equal(s.objective, 'fix "a<b> & c');
111
+ assert.ok(activePrompt(s).includes("&quot;"));
112
+ });
113
+
114
+ it("continuation prompt carries the audit ladder and the no-narration rule", () => {
115
+ const p = continuationPrompt(fresh({ tokenBudget: 9000, tokensUsed: 3000 }));
116
+ for (const frag of [
117
+ "Continue active goal.",
118
+ "make the tests pass",
119
+ "NEVER redefine success as a smaller",
120
+ "Verification scope = claim scope",
121
+ "Budget exhaustion ≠ completion",
122
+ "NEVER narrate continuation — execute",
123
+ "Tokens remaining: 6000",
124
+ ]) {
125
+ assert.ok(p.includes(frag), `missing: ${frag}`);
126
+ }
127
+ });
128
+
129
+ it("budget-limit prompt forbids new work and completion", () => {
130
+ const p = budgetLimitPrompt(fresh({ tokenBudget: 1000, tokensUsed: 1100 }));
131
+ assert.ok(p.includes("NEVER start new substantive work"));
132
+ assert.ok(p.includes("Tokens used: 1100"));
133
+ });
134
+
135
+ it("statusLine composes the readout", () => {
136
+ const line = statusLine(fresh({ tokensUsed: 250, tokenBudget: 1000, turns: 2, maxTurns: 50 }));
137
+ assert.match(line, /make the tests pass/);
138
+ assert.match(line, /\[active\]/);
139
+ assert.match(line, /turn 2\/50/);
140
+ assert.match(line, /25% of 1000/);
141
+ });
142
+ });
143
+
144
+ // ---------- module (harness) ----------
145
+
146
+ /** Module harness: captures the pi surface goal uses. Plan-bridge is module
147
+ * state — reset it through the real setter to keep the loop honest. */
148
+ async function createHarness() {
149
+ const { setPlanActive } = await import("../../../lib/plan-bridge.ts");
150
+ setPlanActive(false);
151
+ const savedAgentDir = process.env.PI_CODING_AGENT_DIR;
152
+ process.env.PI_CODING_AGENT_DIR = "/tmp/ceulen-goal-test-settings";
153
+
154
+ const events = new Map<string, (event: unknown, ctx: unknown) => unknown>();
155
+ const commands = new Map<string, { handler: (args: string, ctx: unknown) => Promise<void> | void }>();
156
+ const tools = new Map<string, any>();
157
+ const entries: Array<{ customType: string; data: unknown }> = [];
158
+ let branchEntries: unknown[] = [];
159
+ const statusCalls: Array<[string, string | undefined]> = [];
160
+ const notifications: Array<{ message: string; level?: string }> = [];
161
+ const sends: Array<{ msg: { customType: string; content: string; display?: boolean }; opts?: { triggerTurn?: boolean; deliverAs?: string } }> = [];
162
+ const userSends: Array<{ content: string; opts?: { deliverAs?: string } }> = [];
163
+
164
+ const ui = {
165
+ notify: (m: string, level?: string) => {
166
+ notifications.push({ message: m, level });
167
+ },
168
+ setStatus: (k: string, t: string | undefined) => {
169
+ statusCalls.push([k, t]);
170
+ },
171
+ };
172
+ const ctx: any = { ui, sessionManager: { getBranch: () => branchEntries } };
173
+
174
+ const pi: any = {
175
+ on: (n: string, h: any) => {
176
+ events.set(n, h);
177
+ },
178
+ registerTool: (t: any) => {
179
+ tools.set(t.name, t);
180
+ },
181
+ registerCommand: (n: string, o: any) => {
182
+ commands.set(n, o);
183
+ },
184
+ registerMessageRenderer: undefined, // optional-chained in the module
185
+ appendEntry: (customType: string, data: unknown) => {
186
+ entries.push({ customType, data });
187
+ },
188
+ sendMessage: (msg: any, opts?: any) => {
189
+ sends.push({ msg, opts });
190
+ },
191
+ sendUserMessage: (content: string, opts?: any) => {
192
+ userSends.push({ content, opts });
193
+ },
194
+ };
195
+ goalModule(pi);
196
+
197
+ const h = {
198
+ events,
199
+ commands,
200
+ tools,
201
+ entries,
202
+ statusCalls,
203
+ notifications,
204
+ sends,
205
+ userSends,
206
+ ctx,
207
+ setPlanActive,
208
+ setBranch: (e: unknown[]) => {
209
+ branchEntries = e;
210
+ },
211
+ command: (args: string) => commands.get("goal")!.handler(args, ctx),
212
+ /** Fire the goal tool through the real execute() path. */
213
+ tool: (params: Record<string, unknown>) => tools.get("goal").execute("t1", params, undefined, undefined, ctx),
214
+ settle: (aborted = false) => events.get("agent_settled")!({ type: "agent_settled", aborted }, ctx),
215
+ assistantEnd: (usage: Record<string, number>) =>
216
+ events.get("message_end")!({ message: { role: "assistant", usage } }, ctx),
217
+ turnEnd: () => events.get("turn_end")!({ type: "turn_end" }, ctx),
218
+ restore() {
219
+ if (savedAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
220
+ else process.env.PI_CODING_AGENT_DIR = savedAgentDir;
221
+ },
222
+ };
223
+ return h;
224
+ }
225
+
226
+ describe("goal command", () => {
227
+ it("sets a goal, starts the first turn, and refuses a second / plan-mode set", async () => {
228
+ const h = await createHarness();
229
+ try {
230
+ await h.command("make the tests pass --budget 12345");
231
+ const [entry] = h.entries.filter((e) => e.customType === "ceulen-goal");
232
+ assert.equal((entry.data as GoalState).status, "active");
233
+ assert.equal((entry.data as GoalState).tokenBudget, 12345);
234
+ assert.equal(h.userSends.length, 1, "the objective itself starts the first work turn");
235
+ assert.equal(h.userSends[0].opts?.deliverAs, "followUp");
236
+
237
+ await h.command("another objective");
238
+ assert.match(h.notifications.at(-1)!.message, /already active/);
239
+
240
+ h.setPlanActive(true);
241
+ await h.command("third objective after clearing");
242
+ assert.match(h.notifications.at(-1)!.message, /Exit plan mode/);
243
+ assert.equal(h.entries.filter((e) => e.customType === "ceulen-goal").length, 1, "no state written");
244
+ } finally {
245
+ h.restore();
246
+ }
247
+ });
248
+
249
+ it("pause/resume/clear round-trip; resume fires a continuation turn", async () => {
250
+ const h = await createHarness();
251
+ try {
252
+ await h.command("ship it");
253
+ await h.command("pause");
254
+ assert.equal(lastState(h.entries)!.status, "paused");
255
+ assert.equal(h.sends.length, 0, "pause sends nothing");
256
+
257
+ await h.command("resume");
258
+ assert.equal(lastState(h.entries)!.status, "active");
259
+ assert.equal(h.sends.length, 1);
260
+ assert.equal(h.sends[0].opts?.triggerTurn, true, "resume starts the next turn");
261
+ assert.match(h.sends[0].msg.content, /Continue active goal/);
262
+
263
+ await h.command("clear");
264
+ // Terminal tombstone: the LAST entry must never be "active" or a
265
+ // restart would resurrect the cleared goal.
266
+ assert.equal(lastState(h.entries)!.status, "stopped");
267
+ await h.command("status");
268
+ assert.match(h.notifications.at(-1)!.message, /No goal set/);
269
+ } finally {
270
+ h.restore();
271
+ }
272
+ });
273
+
274
+ it("budget mutations: invalid refused, off unbounds and un-limits, raise revives", async () => {
275
+ const h = await createHarness();
276
+ try {
277
+ // Pre-goal usage establishes the baseline.
278
+ h.assistantEnd({ input: 10, output: 10, cacheRead: 0, cacheWrite: 0 });
279
+ await h.command("ship it --budget 100");
280
+ // In-goal response bills the full delta: 40+50 = 90... plus nothing — 90 < 100, so push higher.
281
+ h.assistantEnd({ input: 70, output: 70, cacheRead: 0, cacheWrite: 0 }); // delta 120 ≥ 100
282
+ h.turnEnd();
283
+ assert.equal(lastState(h.entries)!.status, "budget-limited");
284
+ await h.command("budget off");
285
+ assert.equal(lastState(h.entries)!.status, "active");
286
+ assert.equal(lastState(h.entries)!.tokenBudget, undefined);
287
+
288
+ await h.command("budget 40"); // set below usage → budget-limited NOW (OMP semantics)
289
+ const state = lastState(h.entries)!;
290
+ assert.equal(state.status, "budget-limited");
291
+ assert.equal(state.tokenBudget, 40);
292
+ // Two episodes (flip at 100, then re-limit at 40 after budget off) →
293
+ // one wrap-up PER EPISODE is the invariant.
294
+ assert.equal(h.sends.filter((s) => s.msg.customType === "ceulen-goal-budget").length, 2);
295
+
296
+ await h.command("budget 500"); // raise above usage → active again
297
+ assert.equal(lastState(h.entries)!.status, "active");
298
+ assert.equal(lastState(h.entries)!.tokenBudget, 500);
299
+
300
+ await h.command("budget abc");
301
+ assert.match(h.notifications.at(-1)!.message, /positive integer/);
302
+ } finally {
303
+ h.restore();
304
+ }
305
+ });
306
+ });
307
+
308
+ function lastState(entries: Array<{ customType: string; data: unknown }>): GoalState | undefined {
309
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
310
+ if (entries[i].customType === "ceulen-goal") return entries[i].data as GoalState;
311
+ }
312
+ return undefined;
313
+ }
314
+
315
+ describe("continuation loop", () => {
316
+ it("a clean settle fires ONE continuation with triggerTurn; abort pauses; cap stops", async () => {
317
+ const h = await createHarness();
318
+ try {
319
+ await h.command("do the thing");
320
+ h.sends.length = 0;
321
+ h.settle(false);
322
+ assert.equal(h.sends.length, 1, "exactly one continuation per settle");
323
+ assert.equal(h.sends[0].opts?.triggerTurn, true);
324
+ assert.equal(h.sends[0].opts?.deliverAs, "followUp");
325
+ assert.match(h.sends[0].msg.customType, /continue/);
326
+ assert.match(h.sends[0].msg.content, /do the thing/);
327
+ assert.equal(lastState(h.entries)!.turns, 1);
328
+
329
+ // Abort (Escape) → pause, no continuation.
330
+ h.settle(true);
331
+ assert.equal(lastState(h.entries)!.status, "paused");
332
+ assert.equal(h.sends.length, 1, "no second send");
333
+
334
+ // Cap → stopped + warning.
335
+ await h.command("resume");
336
+ const capped = lastState(h.entries)!;
337
+ capped.turns = capped.maxTurns;
338
+ h.settle(false);
339
+ assert.equal(lastState(h.entries)!.status, "stopped");
340
+ assert.match(h.notifications.at(-1)!.message, /turn cap/);
341
+ } finally {
342
+ h.restore();
343
+ }
344
+ });
345
+
346
+ it("plan mode becoming active between turns pauses instead of continuing", async () => {
347
+ const h = await createHarness();
348
+ try {
349
+ await h.command("do the thing");
350
+ h.setPlanActive(true);
351
+ h.settle(false);
352
+ assert.equal(lastState(h.entries)!.status, "paused");
353
+ assert.equal(h.sends.length, 0);
354
+ } finally {
355
+ h.restore();
356
+ }
357
+ });
358
+ });
359
+
360
+ describe("budget flow end-to-end", () => {
361
+ it("flip sends ONE wrap-up turn (triggerTurn+followUp — never a steer); later settles send nothing", async () => {
362
+ const h = await createHarness();
363
+ try {
364
+ // Pre-goal baseline, then turn-1 usage crosses the budget (delta 105 ≥ 100).
365
+ h.assistantEnd({ input: 10, output: 10, cacheRead: 0, cacheWrite: 0 });
366
+ await h.command("finish it --budget 100");
367
+ h.sends.length = 0;
368
+ h.assistantEnd({ input: 70, output: 55, cacheRead: 10_000, cacheWrite: 0 });
369
+ h.turnEnd();
370
+ assert.equal(lastState(h.entries)!.status, "budget-limited");
371
+ assert.equal(h.sends.length, 1, "the wrap-up message went out");
372
+ assert.equal(h.sends[0].opts?.triggerTurn, true, "wrap-up MUST start a turn (advisor-found stranding bug)");
373
+ assert.equal(h.sends[0].opts?.deliverAs, "followUp", "wrap-up is a followUp, not a stranded steer");
374
+ assert.match(h.sends[0].msg.content, /NEVER start new substantive work/);
375
+
376
+ // The wrap-up turn's own settle: budget-limited → none. No loop tail.
377
+ h.turnEnd(); // wrap-up turn usage — no second wrap-up (budgetReported)
378
+ h.settle(false);
379
+ assert.equal(h.sends.length, 1, "no continuation and no second wrap-up after the flip");
380
+ } finally {
381
+ h.restore();
382
+ }
383
+ });
384
+
385
+ it("rolling baseline: only the delta after the last snapshot is billed", async () => {
386
+ const h = await createHarness();
387
+ try {
388
+ // Usage BEFORE the goal exists establishes the pre-goal baseline.
389
+ h.assistantEnd({ input: 9999, output: 9999, cacheRead: 0, cacheWrite: 0 });
390
+ await h.command("new goal --budget 100");
391
+ h.sends.length = 0;
392
+ // First in-goal response: billed from the 9999 baseline, not from zero.
393
+ h.assistantEnd({ input: 10_009, output: 10_004, cacheRead: 0, cacheWrite: 0 });
394
+ h.turnEnd();
395
+ assert.equal(lastState(h.entries)!.tokensUsed, 10 + 5, "only the post-goal delta");
396
+ assert.equal(lastState(h.entries)!.status, "active");
397
+ assert.equal(h.sends.length, 0);
398
+ } finally {
399
+ h.restore();
400
+ }
401
+ });
402
+
403
+ it("lazy init: a goal born mid-turn is not billed for the in-flight response", async () => {
404
+ const h = await createHarness();
405
+ try {
406
+ h.assistantEnd({ input: 9999, output: 9999, cacheRead: 0, cacheWrite: 0 });
407
+ await h.command("new goal --budget 100");
408
+ h.sends.length = 0;
409
+ h.assistantEnd({ input: 10, output: 5, cacheRead: 0, cacheWrite: 0 });
410
+ h.turnEnd();
411
+ assert.equal(lastState(h.entries)!.tokensUsed, 0);
412
+ assert.equal(lastState(h.entries)!.status, "active");
413
+ } finally {
414
+ h.restore();
415
+ }
416
+ });
417
+
418
+ it("fresh-session first turn bills in full — zero baseline (live-test regression)", async () => {
419
+ const h = await createHarness();
420
+ try {
421
+ await h.command("find it --budget 1000");
422
+ h.sends.length = 0;
423
+ // No prior snapshot anywhere: the goal fired this session's first run,
424
+ // so the whole snapshot bills (live 2026-11-01: lazy-init dropped 46K).
425
+ h.assistantEnd({ input: 800, output: 100, cacheRead: 50, cacheWrite: 30 });
426
+ h.turnEnd();
427
+ assert.equal(lastState(h.entries)!.tokensUsed, 930, "input+output+cacheWrite from zero; cacheRead excluded");
428
+ h.assistantEnd({ input: 850, output: 110, cacheRead: 50, cacheWrite: 30 });
429
+ h.turnEnd();
430
+ assert.equal(lastState(h.entries)!.tokensUsed, 930 + 60, "second response bills its delta");
431
+ assert.equal(lastState(h.entries)!.status, "active");
432
+ } finally {
433
+ h.restore();
434
+ }
435
+ });
436
+ });
437
+
438
+ describe("goal tool", () => {
439
+ it("get renders state; complete ends the loop, reports, and clears; errors on wrong states", async () => {
440
+ const h = await createHarness();
441
+ try {
442
+ await h.command("prove it done");
443
+
444
+ const got = await h.tool({ op: "get" });
445
+ assert.match(got.content[0].text, /prove it done/);
446
+
447
+ const done = await h.tool({ op: "complete" });
448
+ assert.match(done.content[0].text, /Goal achieved/);
449
+ assert.match(h.notifications.at(-1)!.message, /Goal achieved/);
450
+ const report = h.sends.find((s) => s.msg.customType === "ceulen-goal-report");
451
+ assert.ok(report, "display entry sent");
452
+ // Terminal tombstone in the transcript + live state cleared.
453
+ assert.equal(lastState(h.entries)!.status, "complete");
454
+ const activeAfter = lastState(h.entries)!.status;
455
+ assert.ok(activeAfter === "complete", "no active snapshot left behind");
456
+
457
+ const again = await h.tool({ op: "complete" });
458
+ assert.equal(again.isError, true);
459
+
460
+ await h.command("paused goal");
461
+ await h.command("pause");
462
+ const paused = await h.tool({ op: "complete" });
463
+ assert.equal(paused.isError, true, "complete on paused is refused");
464
+ assert.match(paused.content[0].text, /paused/);
465
+ } finally {
466
+ h.restore();
467
+ }
468
+ });
469
+ });
470
+
471
+ describe("rehydration + composer", () => {
472
+ it("restores an active goal PAUSED after restart; complete stays terminal", async () => {
473
+ const h = await createHarness();
474
+ try {
475
+ h.setBranch([
476
+ { type: "message", role: "user" },
477
+ { type: "custom", customType: "ceulen-goal", data: fresh({ status: "active", turns: 4 }) },
478
+ ]);
479
+ await h.events.get("session_start")!({ type: "session_start", reason: "startup" }, h.ctx);
480
+ assert.equal(lastState([] as typeof h.entries)?.status, undefined); // entries list untouched
481
+ assert.match(h.notifications.at(-1)!.message, /restored paused/);
482
+
483
+ // A restored-paused goal never continues.
484
+ h.settle(false);
485
+ assert.equal(h.sends.length, 0);
486
+
487
+ // A complete snapshot restores as complete (terminal, no resume).
488
+ h.setBranch([{ type: "custom", customType: "ceulen-goal", data: fresh({ status: "complete" }) }]);
489
+ await h.events.get("session_start")!({ type: "session_start", reason: "startup" }, h.ctx);
490
+ const done = await h.tool({ op: "complete" });
491
+ assert.equal(done.isError, true, "still terminal after restore");
492
+ } finally {
493
+ h.restore();
494
+ }
495
+ });
496
+
497
+ it("before_agent_start appends goal context only while active/budget-limited", async () => {
498
+ const h = await createHarness();
499
+ try {
500
+ const composer = h.events.get("before_agent_start")!;
501
+ assert.equal(composer({ type: "before_agent_start", systemPrompt: "BASE" }, h.ctx), undefined);
502
+
503
+ await h.command("ctx test");
504
+ const active = composer({ type: "before_agent_start", systemPrompt: "BASE" }, h.ctx) as { systemPrompt: string };
505
+ assert.ok(active.systemPrompt.startsWith("BASE"), "append-only — base preserved verbatim");
506
+ assert.ok(active.systemPrompt.includes("<goal_context>"));
507
+ assert.match(active.systemPrompt, /ctx test/);
508
+
509
+ await h.command("pause");
510
+ assert.equal(composer({ type: "before_agent_start", systemPrompt: "BASE" }, h.ctx), undefined);
511
+ } finally {
512
+ h.restore();
513
+ }
514
+ });
515
+ });
516
+
517
+ describe("settings defaults", () => {
518
+ it("defaults resolve from the (redirected) agent dir without a settings file", () => {
519
+ assert.equal(defaultMaxTurns(), 50);
520
+ assert.equal(defaultBudget() ?? 0, 0, "0 = unbounded default");
521
+ });
522
+ });
@@ -3,8 +3,8 @@
3
3
  // modelRegistry.classify (System One via the router provider).
4
4
 
5
5
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
- import { existsSync, statSync } from "node:fs";
7
- import { resolve as resolvePath } from "node:path";
6
+ import { existsSync, lstatSync } from "node:fs";
7
+ import { relative as relPath, resolve as resolvePath } from "node:path";
8
8
  import { Type } from "typebox";
9
9
  import { formatBytes } from "./lib/format.js";
10
10
  import { runCascade, FIND_TIMEOUT_MS, type CascadeResult } from "./lib/cascade.js";
@@ -46,8 +46,17 @@ export default function jfindModule(pi: ExtensionAPI): void {
46
46
  let root = resolvePath(cwd);
47
47
  if (scopeInput.length > 0) {
48
48
  root = resolvePath(cwd, scopeInput);
49
+ // F8: the scope is a content boundary — file contents ship to the
50
+ // third-party classifier, so the root must stay inside the workspace
51
+ // (the fff contract). resolvePath against cwd first, so absolute
52
+ // paths inside cwd still work; escapes and out-of-tree absolutes throw.
53
+ const rel = relPath(cwd, root);
54
+ if (rel.startsWith("..") || rel === "" || (root.length > cwd.length && !root.startsWith(cwd + "/") && !root.startsWith(cwd + "\\"))) {
55
+ throw new Error(`Path must be inside the workspace: ${scopeInput}`);
56
+ }
49
57
  if (!existsSync(root)) throw new Error(`Path not found: ${scopeInput}`);
50
- if (!statSync(root).isFile() && !statSync(root).isDirectory()) {
58
+ const st = lstatSync(root);
59
+ if (st.isSymbolicLink() || (!st.isFile() && !st.isDirectory())) {
51
60
  throw new Error(`Path is neither a file nor a directory: ${scopeInput}`);
52
61
  }
53
62
  }
@@ -81,7 +90,7 @@ export default function jfindModule(pi: ExtensionAPI): void {
81
90
  }
82
91
  // A single-file scope that lists zero eligible files used to fall through
83
92
  // to a silent "no hits" — surface the eligibility refusal instead.
84
- if (result.stats.listed === 0 && scopeInput.length > 0 && statSync(root).isFile()) {
93
+ if (result.stats.listed === 0 && scopeInput.length > 0 && lstatSync(root).isFile()) {
85
94
  return {
86
95
  content: [{ type: "text", text: `not searchable: ${scopeInput} (deny-listed, binary, secret, or empty by jfind's eligibility rules)` }],
87
96
  details: { query },
@@ -6,7 +6,7 @@
6
6
  // budgets, and constants.
7
7
 
8
8
  import { basename } from "node:path";
9
- import { statSync } from "node:fs";
9
+ import { lstatSync } from "node:fs";
10
10
  import {
11
11
  fileScore,
12
12
  grepIndex,
@@ -375,7 +375,10 @@ class Cascade {
375
375
  * scope used to list zero files and report "no hits" silently. Wrap it as a
376
376
  * one-entry walk so the documented scope works. Exported for tests. */
377
377
  export function scopeFiles(root: string): FileEntry[] {
378
- const st = statSync(root);
378
+ // lstat + regular-file check (F8): a single-file scope must not be a
379
+ // symlink (its target could ship out-of-tree contents to the classifier).
380
+ const st = lstatSync(root);
381
+ if (st.isSymbolicLink()) return [];
379
382
  if (!st.isDirectory()) {
380
383
  const rel = basename(root);
381
384
  return eligibleFile(rel, st.size, rel.startsWith(".")) ? [{ path: root, rel, size: st.size }] : [];
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { lines, clipBytes, countOccurrences } from "./lexical.js";
7
7
  import { execFileSync } from "node:child_process";
8
- import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
8
+ import { closeSync, lstatSync, openSync, readdirSync, readSync, statSync } from "node:fs";
9
9
  import { join } from "node:path";
10
10
 
11
11
  // ── eligibility deny-lists (tree.ts, verbatim) ──────────────────────────────
@@ -155,7 +155,12 @@ export function listFiles(rootAbs: string, includeHidden = false): FileEntry[] {
155
155
  const abs = join(rootAbs, rel);
156
156
  let size = 0;
157
157
  try {
158
- size = statSync(abs).size;
158
+ // lstat: a symlink's TARGET size/status must not leak out-of-tree
159
+ // file metadata (F8) — git never tracks symlinks as regular files
160
+ // here anyway, so skipping keeps the walk in-tree.
161
+ const st = lstatSync(abs);
162
+ if (st.isSymbolicLink()) continue;
163
+ size = st.size;
159
164
  } catch {
160
165
  continue;
161
166
  }
@@ -180,7 +185,7 @@ export function listFiles(rootAbs: string, includeHidden = false): FileEntry[] {
180
185
  const rel = relPrefix ? `${relPrefix}/${name}` : name;
181
186
  let st;
182
187
  try {
183
- st = statSync(abs);
188
+ st = lstatSync(abs); // F8: never follow symlinks out of the root
184
189
  } catch {
185
190
  continue;
186
191
  }
@@ -2,7 +2,7 @@
2
2
  // network; the classifier is injected through the Judge seam.
3
3
 
4
4
  import assert from "node:assert/strict";
5
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import path from "node:path";
8
8
  import { after, before, describe, it } from "node:test";
@@ -358,3 +358,30 @@ describe("cascade", () => {
358
358
  assert.ok(Buffer.byteLength(sliced.text) <= 1024 + 8, "slice ends on a line boundary");
359
359
  });
360
360
  });
361
+
362
+ // ── F8 (security review 2026-10-17): symlinks never escape the root ──────
363
+
364
+ describe("F8 symlink + scope containment", () => {
365
+ it("listFiles skips symlinks pointing outside the root", () => {
366
+ const outDir = mkdtempSync(path.join(tmpdir(), "ceulen-jfind-out-"));
367
+ const secret = path.join(outDir, "secret.txt");
368
+ writeFileSync(secret, "top secret");
369
+ const root = mkdtempSync(path.join(tmpdir(), "ceulen-jfind-root-"));
370
+ writeFileSync(path.join(root, "real.txt"), "hello");
371
+ try {
372
+ symlinkSync(secret, path.join(root, "leak.txt"));
373
+ } catch {
374
+ return; // filesystem without symlink support
375
+ }
376
+ try {
377
+ const listed = listFiles(root);
378
+ assert.ok(listed.some((e) => e.rel === "real.txt"), "real file listed");
379
+ assert.ok(!listed.some((e) => e.rel === "leak.txt"), "symlink excluded from the walk");
380
+ // single-file symlink scope yields nothing
381
+ assert.deepEqual(scopeFiles(path.join(root, "leak.txt")), [], "symlink file scope refused");
382
+ } finally {
383
+ rmSync(root, { recursive: true, force: true });
384
+ rmSync(outDir, { recursive: true, force: true });
385
+ }
386
+ });
387
+ });