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
@@ -1,16 +1,22 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import {
4
+ buildCtxLegend,
4
5
  computeContextBreakdown,
5
6
  shortSource,
6
7
  formatCtxTokens,
7
8
  formatCtxPercent,
8
- ctxWaffle,
9
+ planCtxCells,
10
+ CTX_GRID_COLS,
11
+ CTX_GRID_ROWS,
9
12
  renderContextPanel,
10
13
  resolveReserveTokens,
11
14
  type ContextBreakdownInput,
12
15
  } from "../index.ts";
13
16
 
17
+ /** OMP messages glyph (⛃) — kept here so the assertion reads cleanly. */
18
+ const WAFFLE_MESSAGES_GLYPH = "⛃";
19
+
14
20
  /** Fixture ctx with a structured system-prompt system message + tools. */
15
21
  function fixtureCtx(overrides: Partial<ContextBreakdownInput["ctx"]> = {}): ContextBreakdownInput["ctx"] {
16
22
  const systemSections: Record<string, string | null> = {
@@ -66,30 +72,66 @@ test("formatCtxPercent slivers and normal cases", () => {
66
72
  assert.equal(formatCtxPercent(500, 0), "?");
67
73
  });
68
74
 
69
- test("ctxWaffle renders an OMP 4x10 grid that always fills the canvas", () => {
70
- const grid = ctxWaffle([{ tokens: 21450, glyph: "⛁" }, { tokens: 870000, glyph: "⛶" }, { tokens: 157286, glyph: "⛝" }], 1048576, 10, 4);
71
- assert.equal(grid.length, 4);
72
- assert.ok(grid.every((row) => [...row].length === 10), grid.join("|"));
73
- const flat = grid.join("");
74
- assert.ok(flat.includes("⛁"), "used cells render ⛁");
75
- assert.ok(flat.includes("⛶"), "free cells render ⛶");
76
- assert.ok(flat.includes("⛝"), "autocompact buffer renders ⛝ at the end");
77
- assert.equal([...flat].length, 40, "exactly rows × cols cells");
78
- // Buffer is the final slice of the window → painted at the end of the grid.
79
- assert.equal([...flat].pop(), "⛝");
75
+ test("planCtxCells paints OMP's 20x10 grid with per-category colors", () => {
76
+ const b = computeContextBreakdown(fixtureInput());
77
+ const cells = planCtxCells(b.categories, b.contextWindow);
78
+ assert.equal(cells.length, CTX_GRID_COLS * CTX_GRID_ROWS, "exactly 200 cells");
79
+ // Category color map (OMP's): prompt accent, tools warning, context
80
+ // customMessageLabel, skills success, messages userMessageText, free dim,
81
+ // buffer warning.
82
+ const byColor = new Map<string, number>();
83
+ for (const c of cells) byColor.set(c.color, (byColor.get(c.color) ?? 0) + 1);
84
+ assert.ok((byColor.get("accent") ?? 0) >= 1, "system prompt painted accent");
85
+ assert.ok((byColor.get("warning") ?? 0) >= 2, "tools + buffer painted warning");
86
+ assert.ok((byColor.get("success") ?? 0) >= 1, "skills painted success");
87
+ assert.ok((byColor.get("userMessageText") ?? 0) >= 1, "messages painted userMessageText");
88
+ assert.ok((byColor.get("customMessageLabel") ?? 0) >= 1, "system context painted customMessageLabel");
89
+ assert.ok((byColor.get("dim") ?? 0) > 100, "most of a 2.5%-used window is free (dim)");
90
+ // Glyphs follow the map: buffer hatches the tail, free fills the rest.
91
+ assert.equal(cells.at(-1)!.glyph, "⛝", "autocompact buffer is the final slice");
92
+ assert.ok(cells.some((c) => c.color === "dim" && c.glyph === "⛶"), "free cells render ⛶ dim");
80
93
  });
81
94
 
82
- test("ctxWaffle visibility-scales tiny slices to one cell and hands slack to free space", () => {
83
- // 0.05% used still gets a cell (>=0.5% threshold is one cell either way here);
84
- // an empty session shows no used cell at all.
85
- const tiny = ctxWaffle([{ tokens: 500, glyph: "⛁" }, { tokens: 196000, glyph: "⛶" }], 196608).join("");
86
- assert.equal(tiny.split("⛁").length - 1, 1, "tiny used slice keeps one visible cell");
87
- const empty = ctxWaffle([{ tokens: 0, glyph: "⛁" }, { tokens: 180224, glyph: "⛶" }, { tokens: 16384, glyph: "⛝" }], 196608).join("");
88
- assert.equal(empty.split("⛁").length - 1, 0, "zero used renders no filled cells");
89
- assert.equal(empty.split("⛝").length - 1, 3, "16K/192K buffer ≈ 3 cells");
90
- assert.equal([...empty].length, 40);
95
+ test("planCtxCells allocation: min one cell, exact fill, disabled compaction has no buffer", () => {
96
+ // A tiny nonzero category keeps one visible cell; zero categories get none.
97
+ const tiny = planCtxCells(
98
+ [
99
+ { label: "Skills", tokens: 10 },
100
+ { label: "Messages", tokens: 0 },
101
+ { label: "Free space", tokens: 99990 },
102
+ ],
103
+ 100000,
104
+ );
105
+ assert.equal(tiny.filter((c) => c.color === "success").length, 1, "tiny nonzero slice keeps one cell");
106
+ assert.equal(tiny.filter((c) => c.color === "userMessageText").length, 0, "zero slice renders no cells");
107
+ assert.equal(tiny.length, 200);
108
+
109
+ // Disabled compaction: no buffer category → no hatch cells anywhere.
110
+ const b = computeContextBreakdown(fixtureInput({ settings: { compaction: { enabled: false } } }));
111
+ const noBuffer = planCtxCells(b.categories, b.contextWindow);
112
+ assert.ok(noBuffer.every((c) => c.glyph !== "⛝"), "no buffer cells when compaction is off");
113
+
91
114
  // Unknown window → all free.
92
- assert.deepEqual(ctxWaffle([{ tokens: 5, glyph: "⛁" }], 0), Array(4).fill("⛶".repeat(10)));
115
+ const unknown = planCtxCells([{ label: "Skills", tokens: 5 }], 0);
116
+ assert.ok(unknown.every((c) => c.glyph === "⛶" && c.color === "dim"));
117
+ });
118
+
119
+ test("planCtxCells overflow trims largest-first and still fills the canvas", () => {
120
+ // Categories summing far beyond the window: trim keeps every slice ≥1 cell
121
+ // and the grid exactly full (no phantom overflow rows).
122
+ const cells = planCtxCells(
123
+ [
124
+ { label: "System prompt", tokens: 5000 },
125
+ { label: "System tools", tokens: 5000 },
126
+ { label: "Messages", tokens: 5000 },
127
+ { label: "Free space", tokens: 5000 },
128
+ ],
129
+ 4000,
130
+ );
131
+ assert.equal(cells.length, 200);
132
+ const counts = new Map<string, number>();
133
+ for (const c of cells) counts.set(c.color, (counts.get(c.color) ?? 0) + 1);
134
+ assert.ok((counts.get("accent") ?? 0) >= 1 && (counts.get("warning") ?? 0) >= 1 && (counts.get("userMessageText") ?? 0) >= 1, "each filled category keeps ≥1 cell after trim");
93
135
  });
94
136
 
95
137
  test("resolveReserveTokens mirrors pi's resolution order", () => {
@@ -187,24 +229,39 @@ test("computeContextBreakdown tolerates a throwing projection and missing usage"
187
229
  assert.equal(b.freeSpace, Math.max(0, 200000 - (10000 + b.tools.total) - 16384));
188
230
  });
189
231
 
190
- test("renderContextPanel matches the OMP layout and fires recommendations", () => {
232
+ test("renderContextPanel lays the legend beside a 20x10 grid (OMP geometry)", () => {
233
+ const b = computeContextBreakdown(fixtureInput({ model: { provider: "zai", id: "glm-5.3", name: "GLM-5.3", maxTokens: 8192, contextWindow: 200000 } }));
234
+ const lines = renderContextPanel(b);
235
+ assert.equal(lines[0], "Context Usage");
236
+ // Grid body: 10 rows of 20 space-joined cells, gutter, legend text.
237
+ const gridRows = lines.filter((l) => l.split(" ").length >= 20 && /^⛁|^⛶/.test(l));
238
+ assert.equal(gridRows.length, CTX_GRID_ROWS, "ten grid rows");
239
+ const first = lines.find((l) => l.includes("GLM-5.3")) ?? lines[3];
240
+ const gridPart = first.split(" ")[0];
241
+ assert.equal(gridPart.split(" ").filter(Boolean).length, CTX_GRID_COLS, "20 cells per row");
242
+ // Legend header rows ride beside the grid.
243
+ assert.ok(lines.some((l) => l.includes("GLM-5.3") && l.includes("200K context")), lines.join("\n"));
244
+ assert.ok(lines.some((l) => l.includes("[200K]")), "bracketed model id row");
245
+ assert.ok(lines.some((l) => l.includes("5.0K/200K tokens (2.5%)")), lines.join("\n"));
246
+ assert.ok(lines.some((l) => l.includes("Estimated usage by category")));
247
+ // Category legend lines: glyph + label + tokens + pct, one per category.
248
+ assert.ok(lines.some((l) => l.includes("⛁ System prompt:")), lines.join("\n"));
249
+ assert.ok(lines.some((l) => l.includes("⛁ System tools:")));
250
+ assert.ok(lines.some((l) => l.includes("⛁ System context:")));
251
+ assert.ok(lines.some((l) => l.includes("⛁ Skills:")));
252
+ assert.ok(lines.some((l) => l.includes("⛃ Messages:")));
253
+ assert.ok(lines.some((l) => l.includes("⛶ Free space:")));
254
+ assert.ok(lines.some((l) => l.includes("⛝ Autocompact buffer:")));
255
+ // Gutter alignment: legend lines start after the 39-char grid + 3-space gutter.
256
+ const cat = lines.find((l) => l.includes("⛁ System prompt:"))!;
257
+ assert.ok(/^[⛁⛶⛝ ]+ ⛁ System prompt:/.test(cat), cat);
258
+ });
259
+
260
+ test("renderContextPanel fires recommendations above thresholds", () => {
191
261
  // Tiny-ish window so the 516-token tool fixture crosses the 40% recommendation threshold.
192
262
  const b = computeContextBreakdown(fixtureInput({ ctx: fixtureCtx(), model: { maxTokens: 8192, contextWindow: 1200 } }));
193
263
  const lines = renderContextPanel(b);
194
- assert.equal(lines[0], "Context Usage");
195
- // Header: 4 waffle rows (10 cells each) with model info on the right.
196
- const gridRows = lines.slice(2, 6);
197
- assert.ok(gridRows.every((l) => /^[⛁⛶⛝]{10}/.test(l)), gridRows.join("|"));
198
264
  assert.ok(lines.some((l) => l.includes("5.0K/1.2K tokens (416.7%)")), lines.join("\n"));
199
- // Disjoint, glyph-prefixed category block (core prompt excludes context + skills).
200
- assert.ok(lines.some((l) => l.startsWith(" ⛁ System prompt:")), lines.join("\n"));
201
- assert.ok(lines.some((l) => l.startsWith(" ⛁ System tools:")));
202
- assert.ok(lines.some((l) => l.startsWith(" ⛁ System context:")));
203
- assert.ok(lines.some((l) => l.startsWith(" ⛁ Skills:")));
204
- assert.ok(lines.some((l) => l.startsWith(" ⛁ Messages:")));
205
- assert.ok(lines.some((l) => l.startsWith(" ⛶ Free space:")));
206
- assert.ok(lines.some((l) => l.startsWith(" ⛝ Autocompact buffer:")));
207
- // Detail lists.
208
265
  assert.ok(lines.some((l) => l.includes("pi-web:")), lines.join("\n"));
209
266
  assert.ok(!lines.some((l) => l.includes("@bacnh85/")), "package labels are shortened");
210
267
  assert.ok(lines.some((l) => l.includes("project_context: 2.0K")));
@@ -226,56 +283,32 @@ test("renderContextPanel fires memory + skills recommendations above thresholds"
226
283
  assert.ok(lines.some((l) => l.includes("disable-model-invocation")));
227
284
  });
228
285
 
229
- test("/context handler posts a transcript message; renderer tints glyphs", async () => {
230
- const { default: extension } = await import("../index.ts");
231
- const commands: Record<string, { handler: (args: string, ctx: unknown) => Promise<void> }> = {};
232
- const renderers: Record<string, (m: unknown, o: unknown, t: unknown) => { render(w: number): string[] } | undefined> = {};
233
- const sent: Array<{ customType: string; content: string; display?: boolean; details?: { lines?: string[] } }> = [];
234
- const fakePi = {
235
- on: () => {},
236
- registerCommand: (name: string, def: { handler: (args: string, ctx: unknown) => Promise<void> }) => { commands[name] = def; },
237
- registerTool: () => {},
238
- registerMessageRenderer: (type: string, renderer: never) => { renderers[type] = renderer; },
239
- sendMessage: (msg: { customType: string; content: string; display?: boolean; details?: { lines?: string[] } }) => { sent.push(msg); },
240
- getAllTools: () => (fixtureCtx() as never as { getAllTools(): unknown[] }).getAllTools(),
241
- getActiveTools: () => ["read", "web_search"],
242
- };
243
- (extension as unknown as (pi: unknown) => void)(fakePi);
244
- const handler = commands.context?.handler;
245
- assert.ok(handler, "/context registered");
246
- assert.ok(renderers["ceulen-usage-context"], "transcript renderer registered");
247
-
248
- const mkCtx = (mode: string) => ({
249
- mode,
250
- model: { maxTokens: 8192, contextWindow: 200000 },
251
- getContextUsage: () => ({ tokens: 5000, contextWindow: 200000, percent: 2.5 }),
252
- getSystemPrompt: () => "x".repeat(40000),
253
- sessionManager: { buildSessionProjection: () => ({ messages: [] }) },
254
- ui: { notify: () => {}, theme: { fg: (_c: string, s: string) => s } },
255
- });
256
-
257
- // TUI: panel posted as a displayable transcript message carrying the lines.
258
- await handler!("", mkCtx("tui"));
259
- assert.equal(sent.length, 1);
260
- assert.equal(sent[0].customType, "ceulen-usage-context");
261
- assert.equal(sent[0].display, true, "message is displayed in the transcript");
262
- const lines = sent[0].details?.lines ?? [];
263
- assert.ok(lines.some((l) => l.startsWith(" ⛁ System prompt:")), lines.join("\n"));
264
- assert.ok(lines.some((l) => l.startsWith(" ⛶ Free space:")));
265
-
266
- // Renderer: colors the glyph, keeps the body plain, and clamps to width.
267
- const comp = renderers["ceulen-usage-context"]!({ details: { lines: [" ⛁ System prompt: 1K tokens (1.0%)"] } }, {}, { fg: (c: string, s: string) => `<${c}>${s}</>` });
268
- const out = comp!.render(200);
269
- assert.ok(out[0].includes("<accent>⛁</>"), out[0]);
270
- assert.ok(out[0].includes("System prompt: 1K tokens"), out[0]);
271
- // Width clamp applies to the source line (before ANSI codes are added).
272
- const narrow = comp!.render(10);
273
- assert.ok(narrow[0].includes("⛁"), "glyph survives the clamp");
274
- assert.ok(!narrow[0].includes("System prompt"), "body beyond the width is dropped");
275
-
276
- // Plain-text content always rides along as the renderer-less fallback.
277
- assert.ok(sent[0].content.includes("Context Usage"), "content carries a plain-text fallback");
278
- assert.ok(sent[0].content.includes("⛁ System prompt:"), sent[0].content);
286
+ test("buildCtxLegend mirrors OMP's run structure and colors", () => {
287
+ const b = computeContextBreakdown(fixtureInput({ model: { provider: "zai", id: "glm-5.3-flash", name: "GLM-5.3 Flash", maxTokens: 8192, contextWindow: 1_000_000 } }));
288
+ const legend = buildCtxLegend(b);
289
+ // Line 1: model name strong + window dim. Line 2: bare id[window] muted.
290
+ assert.deepEqual(legend[0], [
291
+ { t: "GLM-5.3 Flash", s: "strong" },
292
+ { t: " (1m context)", s: "dim" },
293
+ ]);
294
+ assert.deepEqual(legend[1], [{ t: "glm-5.3-flash[1m]", s: "muted" }]);
295
+ // Line 3: used strong, window dim, pct muted.
296
+ assert.deepEqual(legend[2], [
297
+ { t: "5.0K", s: "strong" },
298
+ { t: "/1m tokens", s: "dim" },
299
+ { t: " (0.5%)", s: "muted" },
300
+ ]);
301
+ assert.deepEqual(legend[3], []);
302
+ assert.deepEqual(legend[4], [{ t: "Estimated usage by category", s: "muted" }]);
303
+ // Category lines: colored glyph, strong tokens, dim pct.
304
+ const prompt = legend.find((l) => l.some((p) => p.t === " System prompt: "))!;
305
+ assert.equal(prompt[0].s, "accent");
306
+ assert.ok(prompt.some((p) => p.s === "strong"), "token count is bold");
307
+ const msgs = legend.find((l) => l.some((p) => p.t.includes("Messages")) && l.some((p) => p.t === WAFFLE_MESSAGES_GLYPH));
308
+ assert.equal(msgs?.[0].s, "userMessageText");
309
+ // No model → no header rows, legend still renders.
310
+ const bare = buildCtxLegend({ ...b, modelName: undefined, modelLabel: undefined });
311
+ assert.ok(bare[0].some((p) => p.t.includes("tokens")), "first line is the totals without a model");
279
312
  });
280
313
 
281
314
  test("categories are disjoint, reconcile with usage, and partition the window", () => {
@@ -313,17 +346,18 @@ test("Messages is a residual so no row exceeds the headline total", () => {
313
346
  assert.equal(over.categories.reduce((a, c) => a + c.tokens, 0), 200000);
314
347
  });
315
348
 
316
- test("/context handler posts a transcript message; renderer tints glyphs", async () => {
349
+ test("/context handler posts v2 grid+legend; renderer paints live theme; legacy lines still render", async () => {
317
350
  const { default: extension } = await import("../index.ts");
318
351
  const commands: Record<string, { handler: (args: string, ctx: unknown) => Promise<void> }> = {};
319
352
  const renderers: Record<string, (m: unknown, o: unknown, t: unknown) => { render(w: number): string[] } | undefined> = {};
320
- const sent: Array<{ customType: string; content: string; display?: boolean; details?: { lines?: string[] } }> = [];
353
+ type SentMsg = { customType: string; content: string; display?: boolean; details?: { grid?: unknown[][]; legend?: unknown[][]; lines?: string[] } };
354
+ const sent: SentMsg[] = [];
321
355
  const fakePi = {
322
356
  on: () => {},
323
357
  registerCommand: (name: string, def: { handler: (args: string, ctx: unknown) => Promise<void> }) => { commands[name] = def; },
324
358
  registerTool: () => {},
325
359
  registerMessageRenderer: (type: string, renderer: never) => { renderers[type] = renderer; },
326
- sendMessage: (msg: { customType: string; content: string; display?: boolean; details?: { lines?: string[] } }) => { sent.push(msg); },
360
+ sendMessage: (msg: SentMsg) => { sent.push(msg); },
327
361
  getAllTools: () => (fixtureCtx() as never as { getAllTools(): unknown[] }).getAllTools(),
328
362
  getActiveTools: () => ["read", "web_search"],
329
363
  };
@@ -332,50 +366,56 @@ test("/context handler posts a transcript message; renderer tints glyphs", async
332
366
  assert.ok(handler, "/context registered");
333
367
  assert.ok(renderers["ceulen-usage-context"], "transcript renderer registered");
334
368
 
335
- const mkCtx = (mode: string) => ({
336
- mode,
337
- model: { maxTokens: 8192, contextWindow: 200000 },
369
+ const mkCtx = () => ({
370
+ mode: "tui",
371
+ model: { provider: "zai", id: "glm-5.3", name: "GLM-5.3", maxTokens: 8192, contextWindow: 200000 },
338
372
  getContextUsage: () => ({ tokens: 5000, contextWindow: 200000, percent: 2.5 }),
339
373
  getSystemPrompt: () => "x".repeat(40000),
340
374
  sessionManager: { buildSessionProjection: () => ({ messages: [] }) },
341
375
  ui: { notify: () => {}, theme: { fg: (_c: string, s: string) => s } },
342
376
  });
343
377
 
344
- // TUI: panel posted as a displayable transcript message carrying the lines.
345
- await handler!("", mkCtx("tui"));
378
+ // TUI: panel posted as a displayable transcript message carrying v2 details.
379
+ await handler!("", mkCtx());
346
380
  assert.equal(sent.length, 1);
347
381
  assert.equal(sent[0].customType, "ceulen-usage-context");
348
382
  assert.equal(sent[0].display, true, "message is displayed in the transcript");
349
- const lines = sent[0].details?.lines ?? [];
350
- assert.ok(lines.some((l) => l.startsWith(" ⛁ System prompt:")), lines.join("\n"));
351
- assert.ok(lines.some((l) => l.startsWith(" ⛶ Free space:")));
352
-
353
- // Renderer: colors the glyph, keeps the body plain, and clamps to width.
354
- const comp = renderers["ceulen-usage-context"]!({ details: { lines: [" ⛁ System prompt: 1K tokens (1.0%)"] } }, {}, { fg: (c: string, s: string) => `<${c}>${s}</>` });
355
- const out = comp!.render(200);
356
- assert.ok(out[0].includes("<accent>⛁</>"), out[0]);
357
- assert.ok(out[0].includes("System prompt: 1K tokens"), out[0]);
358
- // Width clamp applies to the source line (before ANSI codes are added).
359
- const narrow = comp!.render(10);
360
- assert.ok(narrow[0].includes("⛁"), "glyph survives the clamp");
361
- assert.ok(!narrow[0].includes("System prompt"), "body beyond the width is dropped");
362
-
383
+ const grid = sent[0].details?.grid as Array<Array<{ glyph: string; color: string }>> | undefined;
384
+ const legend = sent[0].details?.legend as Array<Array<{ t: string; s?: string }>> | undefined;
385
+ assert.ok(Array.isArray(grid) && grid.length === CTX_GRID_ROWS, "details.grid is 10 rows");
386
+ assert.ok(grid!.every((row) => row.length === CTX_GRID_COLS), "every row has 20 cells");
387
+ assert.ok(Array.isArray(legend) && legend.length >= 8, "details.legend carries the full legend");
388
+ assert.ok(legend![0].some((p) => p.t === "GLM-5.3" && p.s === "strong"), "legend header is styled");
363
389
  // Plain-text content always rides along as the renderer-less fallback.
364
390
  assert.ok(sent[0].content.includes("Context Usage"), "content carries a plain-text fallback");
365
391
  assert.ok(sent[0].content.includes("⛁ System prompt:"), sent[0].content);
366
- });
367
392
 
368
- test("categories are disjoint, reconcile with usage, and partition the window", () => {
369
- const b = computeContextBreakdown(fixtureInput());
370
- const core = b.categories.find((c) => c.label === "System prompt")!.tokens;
371
- const context = b.categories.find((c) => c.label === "System context")!.tokens;
372
- const skills = b.categories.find((c) => c.label === "Skills")!.tokens;
373
- // No double-counting: core + context + skills reconstruct the system prompt.
374
- assert.equal(core + context + skills, b.systemPrompt.total);
375
- // The buffer is a fixed reserve — estimation drift must never inflate it.
376
- assert.equal(b.categories.find((c) => c.label === "Autocompact buffer")?.tokens, 16384);
377
- // Whatever the drift sign, the slices always add up to the whole window.
378
- assert.equal(b.categories.reduce((a, c) => a + c.tokens, 0), b.contextWindow);
393
+ // v2 renderer: paints cell colors + legend runs from the live theme, clamps.
394
+ // Real ANSI wrappers (like pi's theme) so visible-width assertions exercise the actual measure.
395
+ const theme = { fg: (c: string, s: string) => `\u001b[38;5;${c.length}m${s}\u001b[0m`, bold: (s: string) => `\u001b[1m${s}\u001b[0m` };
396
+ const comp = renderers["ceulen-usage-context"]!({ details: { grid, legend } }, {}, theme);
397
+ const out = comp!.render(400);
398
+ assert.ok(out[0].includes("\u001b[38;5;6m⛁"), `grid cell painted: ${out[0].slice(0, 80)}`);
399
+ assert.ok(out[0].includes("\u001b[1mGLM-5.3\u001b[0m"), "legend header bolded");
400
+ assert.ok(out.some((l) => l.includes("\u001b[38;5;3m⛶")), "free cells dim");
401
+ assert.ok(out.some((l) => l.includes("\u001b[38;5;7m⛝")), "buffer cells warning");
402
+ const cat = out.find((l) => l.includes("System prompt:"))!;
403
+ assert.ok(cat.includes("\u001b[38;5;6m⛁"), "legend glyph painted with its category color");
404
+ // Narrow width: clamp applies (display clamp, not data loss).
405
+ const narrow = comp!.render(30);
406
+ const visible = (l: string) => [...l.replace(/\u001b\[[0-9;]*m/g, "")].length;
407
+ assert.ok(narrow.every((l) => visible(l) <= 30), "rows clamp to the visible width");
408
+ // Regression: escape-code inflation once shredded the grid to ~7 cells at any width.
409
+ assert.ok(visible(out[0]) >= 50, "grid + legend header fit at width 400");
410
+
411
+ // Legacy details.lines (old transcripts) keep the glyph-tint path.
412
+ const legacy = renderers["ceulen-usage-context"]!({ details: { lines: [" ⛁ System prompt: 1K tokens (1.0%)"] } }, {}, theme);
413
+ const legacyOut = legacy!.render(200);
414
+ assert.ok(legacyOut[0].includes("\u001b[38;5;6m⛁"), legacyOut[0]);
415
+ assert.ok(legacyOut[0].includes("System prompt: 1K tokens"), legacyOut[0]);
416
+ const legacyNarrow = legacy!.render(10);
417
+ assert.ok(legacyNarrow[0].includes("⛁"), "glyph survives the clamp");
418
+ assert.ok(!legacyNarrow[0].includes("System prompt"), "body beyond the width is dropped");
379
419
  });
380
420
 
381
421
  test("shortSource reduces local paths and scoped specs to a short label", () => {
@@ -12,6 +12,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
12
  import { row, type PanelGroup } from "../../lib/panel.js";
13
13
  import type { ModuleConfig } from "../../lib/registry.js";
14
14
  import { agentDirs } from "../../lib/registry.js";
15
+ import { writeSecretEnvs } from "../../lib/env.js";
15
16
  import { findEnvValue } from "./lib/config.js";
16
17
  import {
17
18
  DEFAULT_SEARXNG_BASE_URL,
@@ -21,9 +22,19 @@ import {
21
22
  import {
22
23
  ENV_TO_SETTINGS_KEY,
23
24
  readProjectWebSection,
25
+ readWebSettings,
24
26
  sectionValue,
25
27
  writeWebSection,
26
28
  } from "./lib/settings.js";
29
+ import { secretsEnvFile } from "../../lib/env.js";
30
+
31
+ function secretsEnvFilePath(): string {
32
+ return secretsEnvFile();
33
+ }
34
+
35
+ function readWebSettingsGlobal() {
36
+ return readWebSettings(process.cwd(), false);
37
+ }
27
38
 
28
39
  /** One row's definition: settings key, label, effective value, default. */
29
40
  interface WebRowSpec {
@@ -136,7 +147,7 @@ export function buildWebGroups(working: Record<string, string>): PanelGroup[] {
136
147
  } : {}),
137
148
  description: spec.description,
138
149
  ...(spec.secret
139
- ? { warning: "Stored in the settings file — prefer the env var on shared machines." }
150
+ ? { warning: "Saved to <agentDir>/.env.local (0600) — never settings.json. The matching env var overrides any settings value." }
140
151
  : {}),
141
152
  },
142
153
  ),
@@ -174,7 +185,11 @@ export function diffWebPatch(
174
185
 
175
186
  /** web's ModuleConfig for the central /config panel. cwd/trust come from the
176
187
  * save ctx (factories receive none); reads use process.cwd(), matching
177
- * munin's panel pattern. */
188
+ * munin's panel pattern. SECRET rows persist to <agentDir>/.env.local (0600)
189
+ * — never settings.json (live finding: real API keys sat in plaintext
190
+ * settings.json). Env already wins at read time, so the effective value is
191
+ * unchanged; the first save also MIGRATES any settings-stored secret into
192
+ * .env.local and scrubs it from settings.json. */
178
193
  export function webConfig(): ModuleConfig {
179
194
  const read = () => {
180
195
  const values = readWebRowValues(process.cwd(), true);
@@ -192,11 +207,55 @@ export function webConfig(): ModuleConfig {
192
207
  // written (masked rows start empty — an untouched masked row diffs to
193
208
  // no change).
194
209
  const patch = diffWebPatch(working, before);
195
- writeWebSection(patch, target);
196
- const notes = [`Web config saved to ${target} — effective immediately (read per tool call).`];
197
- // Disclose env vars that still override saved values, and a trusted
198
- // project file that shadows a field.
199
- const envOverrides = webRowSpecs().filter((s) => patch[s.key] !== undefined && process.env[s.envVar]).map((s) => s.envVar);
210
+ const specs = webRowSpecs();
211
+ const preSaveEnv = new Set(Object.keys(process.env).filter((k) => specs.some((s) => s.envVar === k)));
212
+ const secretPatch: Record<string, string> = {};
213
+ const settingsPatch: Record<string, string | number> = {};
214
+ for (const [key, value] of Object.entries(patch)) {
215
+ const spec = specs.find((s) => s.key === key);
216
+ // Secrets (typed this session) → .env.local only. A value that CLEARS a
217
+ // secret row (empty string) is dropped: deleting the env line would
218
+ // re-expose a settings-stored value or leave nothing — clearing is a
219
+ // rare deliberate act, do it by editing .env.local by hand.
220
+ if (spec?.secret && value !== "") {
221
+ secretPatch[spec.envVar] = String(value);
222
+ } else if (spec?.secret && value === "") {
223
+ continue;
224
+ } else {
225
+ settingsPatch[key] = value;
226
+ }
227
+ }
228
+ // Migration: secrets already sitting in settings.json (pre-fix saves)
229
+ // move into .env.local (onlyAbsent — env was already winning) and are
230
+ // scrubbed from settings.json. URL rows stay in settings.json untouched.
231
+ const migrate: Record<string, string> = {};
232
+ for (const spec of specs) {
233
+ if (!spec.secret) continue;
234
+ if (secretPatch[spec.envVar] !== undefined) continue;
235
+ const stored = sectionValue(readWebSettingsGlobal(), spec.key);
236
+ if (typeof stored === "string" && stored !== "") migrate[spec.envVar] = stored;
237
+ }
238
+ if (Object.keys(migrate).length > 0) writeSecretEnvs(migrate, { onlyAbsent: true });
239
+ const scrubKeys = Object.keys(migrate);
240
+ if (scrubKeys.length > 0) {
241
+ const scrubPatch: Record<string, string> = {};
242
+ for (const envName of scrubKeys) {
243
+ const spec = specs.find((s) => s.envVar === envName)!;
244
+ scrubPatch[spec.key] = ""; // writeWebSection deletes empty keys
245
+ }
246
+ writeWebSection(scrubPatch, target);
247
+ }
248
+ const written = Object.keys(secretPatch).length > 0 ? writeSecretEnvs(secretPatch) : [];
249
+ if (Object.keys(settingsPatch).length > 0) writeWebSection(settingsPatch, target);
250
+ const notes = [] as string[];
251
+ if (written.length) notes.push(`Secrets saved to ${secretsEnvFilePath()} — effective immediately (env wins at read time).`);
252
+ if (scrubKeys.length) notes.push(`Migrated ${scrubKeys.length} secret(s) out of settings.json into .env.local.`);
253
+ if (Object.keys(settingsPatch).length > 0) notes.push(`Web config saved to ${target} — effective immediately (read per tool call).`);
254
+ // Disclose env vars that PRE-EXISTED this save and still override it.
255
+ // Snapshot BEFORE writeSecretEnvs mirrors the new values into
256
+ // process.env — otherwise every edited secret row would falsely read
257
+ // as "still overridden by env" (it just became the env value).
258
+ const envOverrides = specs.filter((s) => patch[s.key] !== undefined && preSaveEnv.has(s.envVar)).map((s) => s.envVar);
200
259
  if (envOverrides.length) notes.push(`Still overridden by env: ${envOverrides.join(", ")}.`);
201
260
  // Resolve through the SAME lookup the runtime uses, so a hand-written
202
261
  // NESTED project entry (web.brave.apiKey as {brave:{apiKey}}) is
@@ -209,7 +268,7 @@ export function webConfig(): ModuleConfig {
209
268
  })
210
269
  : [];
211
270
  if (shadowed.length) notes.push(`A trusted project .pi/settings.json web section shadows: ${shadowed.join(", ")}.`);
212
- ctx.ui.notify(notes.join(" "), "info");
271
+ if (notes.length) ctx.ui.notify(notes.join(" "), "info");
213
272
  },
214
273
  };
215
274
  }
@@ -166,7 +166,9 @@ export default function piWebExtension(pi: ExtensionAPI) {
166
166
  // package.json `pi.skills` manifest — so the kill-switch gates it too:
167
167
  // disabled module ⇒ factory never runs ⇒ no web skill registered.
168
168
  pi.on("resources_discover", () => ({
169
- skillPaths: [path.join(fs.realpathSync(skillsRoot()), "web")],
169
+ // skillsRoot() is already a native absolute path (fileURLToPath) — no
170
+ // realpath needed; a throw here would kill the whole module load.
171
+ skillPaths: [path.join(skillsRoot(), "web")],
170
172
  }));
171
173
 
172
174
  // Per-tool kill-switch (ceulen.disabledTools): listed tools register
@@ -105,7 +105,7 @@ describe("axeSource", () => {
105
105
  });
106
106
  });
107
107
 
108
- describe("runner expression (via fake CDP server)", () => {
108
+ describe("runner expression (via fake CDP server)", { skip: process.platform === "linux" && !process.env.CHROME_PATH && "CI runners have no Chrome — launchCdp always spawns a real browser (the wsFactory only fakes the WS protocol)" }, () => {
109
109
  it("bootstraps axe then runs it, returning the normalized report", async () => {
110
110
  const evals: string[] = [];
111
111
  const ws = new FakeWs();
@@ -115,12 +115,16 @@ describe("web configPanel", () => {
115
115
  const notifications: string[] = [];
116
116
  const ctx = { cwd: "/nonexistent", ui: { notify: (m: string) => notifications.push(m) }, isProjectTrusted: () => false } as never;
117
117
  await cfg.save(new Set(["web.brave.apiKey", "web.crawl4ai.timeoutMs"]), ctx);
118
+ // Secrets NEVER land in settings.json — brave (a secret row) goes to
119
+ // .env.local; only the non-secret timeout hits settings.json.
120
+ const envFile = fs.readFileSync(path.join(dir, ".env.local"), "utf8");
121
+ assert.match(envFile, /BRAVE_API_KEY=panel-key/);
118
122
  const raw = JSON.parse(fs.readFileSync(path.join(dir, "settings.json"), "utf8"));
119
- assert.equal(raw.web["brave.apiKey"], "panel-key");
123
+ assert.equal(raw.web["brave.apiKey"], undefined, "secret must not be written to settings.json");
120
124
  assert.equal(raw.web["crawl4ai.timeoutMs"], 45000);
121
- assert.equal(Object.keys(raw.web).length, 2, "only changed keys written");
125
+ assert.equal(Object.keys(raw.web).length, 1, "only the non-secret changed key written to settings.json");
122
126
  const note = notifications.join(" ");
123
- assert.ok(note.includes("settings.json"), note);
127
+ assert.ok(note.includes(".env.local"), note);
124
128
  assert.ok(note.includes("BRAVE_API_KEY"), "env override disclosed");
125
129
  } finally {
126
130
  if (old === undefined) delete process.env.BRAVE_API_KEY;
@@ -22,6 +22,12 @@ function setup(): void {
22
22
  fs.mkdirSync(agentDir, { recursive: true });
23
23
  fs.mkdirSync(projectDir, { recursive: true });
24
24
  process.env.PI_CODING_AGENT_DIR = agentDir;
25
+ // env.ts ingests <real agentDir>/.env.local at import — once the secrets
26
+ // migration has run on this machine, FIRECRAWL_API_KEY etc. sit in the
27
+ // test process env and "unset everywhere" is a lie. Scrub the mapped
28
+ // vars for the suite's lifetime (the web module re-reads settings layers,
29
+ // not env, for these assertions).
30
+ for (const v of ["BRAVE_API_KEY", "FIRECRAWL_API_KEY", "CRAWL4AI_API_TOKEN", "GEMINI_WEB_SECURE_1PSID", "ZAI_API_KEY", "WEB_IMAGE_API_KEY", "WEB_CHAT_API_KEY", "SEARXNG_BASE_URL"]) delete process.env[v];
25
31
  // Trust: the real trust.json walk won't see our temp project → untrusted by
26
32
  // default. isProjectTrusted(cwd, dirs) is injected nowhere here, so trust
27
33
  // tests go through writeWebSection/readWebSettings with explicit trusted
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ceulen",
3
- "version": "0.10.1",
3
+ "version": "0.12.0",
4
4
  "description": "Ceulen — the Pi coding agent, fully dressed: one bundle extension carrying the full toolkit with a single /ceulen config command.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "homepage": "https://github.com/ceulen-dev/ceulen#readme",
41
41
  "bugs": "https://github.com/ceulen-dev/ceulen/issues",
42
42
  "scripts": {
43
- "test": "node scripts/validate-themes.mjs && node --import tsx --test extensions/lib/registry.test.ts extensions/lib/skill-path.test.ts extensions/modules/router/test/unit.test.ts extensions/modules/router/test/guard.test.ts extensions/modules/classifier/test/*.test.ts extensions/modules/advisor/test/*.test.ts extensions/modules/usage/test/*.test.ts extensions/modules/ponytail/test/*.test.ts extensions/modules/ux/test/*.test.ts extensions/modules/config/test/*.test.ts extensions/modules/composer/test/*.test.ts extensions/modules/serena/test/*.test.ts extensions/modules/fff/test/*.test.ts extensions/modules/rtk/test/*.test.js extensions/modules/munin/test/*.test.ts extensions/modules/subagent/test/*.test.ts extensions/modules/zai/test/*.test.ts extensions/modules/repair/test/*.test.ts extensions/modules/steering/test/*.test.ts extensions/modules/plan/test/*.test.ts extensions/modules/todo/test/*.test.ts extensions/modules/web/test/*.test.ts extensions/modules/rules/test/*.test.ts extensions/modules/a2a/test/*.test.ts extensions/modules/gh/test/*.test.ts",
43
+ "test": "node scripts/validate-themes.mjs && node --import tsx --test extensions/lib/env.test.ts extensions/lib/order.test.ts extensions/lib/registry.test.ts extensions/lib/skill-path.test.ts extensions/modules/router/test/unit.test.ts extensions/modules/router/test/guard.test.ts extensions/modules/classifier/test/*.test.ts extensions/modules/advisor/test/*.test.ts extensions/modules/usage/test/*.test.ts extensions/modules/ponytail/test/*.test.ts extensions/modules/ux/test/*.test.ts extensions/modules/config/test/*.test.ts extensions/modules/composer/test/*.test.ts extensions/modules/serena/test/*.test.ts extensions/modules/fff/test/*.test.ts extensions/modules/rtk/test/*.test.js extensions/modules/munin/test/*.test.ts extensions/modules/subagent/test/*.test.ts extensions/modules/zai/test/*.test.ts extensions/modules/repair/test/*.test.ts extensions/modules/steering/test/*.test.ts extensions/modules/plan/test/*.test.ts extensions/modules/todo/test/*.test.ts extensions/modules/web/test/*.test.ts extensions/modules/rules/test/*.test.ts extensions/modules/a2a/test/*.test.ts extensions/modules/gh/test/*.test.ts extensions/modules/attachments/test/*.test.ts extensions/modules/cron/test/*.test.ts extensions/modules/permission/test/*.test.ts",
44
44
  "typecheck": "tsc --noEmit"
45
45
  },
46
46
  "pi": {