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
@@ -0,0 +1,230 @@
1
+ // Worktree sandbox lifecycle — lock serialization, owner marker, GC sweep,
2
+ // CoW clone construction, baseline carry (READ-ONLY on the parent), and
3
+ // .worktreeinclude copying. Git state is exercised through a scripted exec
4
+ // fake (the module's established seam) so no assertion depends on the host's
5
+ // git version; on-disk effects use real temp dirs.
6
+
7
+ import assert from "node:assert/strict";
8
+ import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { after, describe, it } from "node:test";
12
+ import {
13
+ applyBaselineToWorktree,
14
+ captureParentBaseline,
15
+ copyWorktreeIncludes,
16
+ createWorktree,
17
+ pidAlive,
18
+ sweepStaleWorktrees,
19
+ withRepoLock,
20
+ WORKTREE_DIR_NAME,
21
+ } from "../lib/runner.ts";
22
+
23
+ const dirs: string[] = [];
24
+ after(async () => {
25
+ await Promise.all(dirs.map((d) => rm(d, { recursive: true, force: true })));
26
+ });
27
+
28
+ async function tempDir(prefix: string): Promise<string> {
29
+ const dir = await mkdtemp(join(tmpdir(), prefix));
30
+ dirs.push(dir);
31
+ return dir;
32
+ }
33
+
34
+ type Exec = (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>;
35
+
36
+ /** Scripted exec: records every (command, args, cwd) and answers from a map of
37
+ * predicate → response (first match wins). Unmatched git calls succeed empty. */
38
+ function fakeExec(handlers: Array<{ match: (command: string, args: string[], cwd?: string) => boolean; code?: number; stdout?: string; stderr?: string }>): Exec & { calls: { command: string; args: string[]; cwd?: string }[] } {
39
+ const calls: { command: string; args: string[]; cwd?: string }[] = [];
40
+ const fn = async (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => {
41
+ calls.push({ command, args, cwd: options?.cwd });
42
+ const hit = handlers.find((h) => h.match(command, args, options?.cwd));
43
+ if (!hit && command === "git") return { code: 0, stdout: "", stderr: "" };
44
+ if (!hit) return { code: 1, stdout: "", stderr: `unexpected command: ${command} ${args.join(" ")}` };
45
+ return { code: hit.code ?? 0, stdout: hit.stdout ?? "", stderr: hit.stderr ?? "" };
46
+ };
47
+ (fn as Exec & { calls: typeof calls }).calls = calls;
48
+ return fn as Exec & { calls: typeof calls };
49
+ }
50
+
51
+ // ── withRepoLock: serialization + error isolation ──────────────────────────
52
+
53
+ describe("withRepoLock", () => {
54
+ it("serializes same-repo blocks and releases the key when idle", async () => {
55
+ const order: string[] = [];
56
+ let release1: (() => void) | undefined;
57
+ const gate = new Promise<void>((r) => { release1 = r; });
58
+ const p1 = withRepoLock("/repo", async () => { order.push("a-start"); await gate; order.push("a-end"); });
59
+ const p2 = withRepoLock("/repo", async () => { order.push("b-start"); });
60
+ await new Promise((r) => setTimeout(r, 10));
61
+ assert.deepEqual(order, ["a-start"]); // b must be waiting
62
+ release1!();
63
+ await Promise.all([p1, p2]);
64
+ assert.deepEqual(order, ["a-start", "a-end", "b-start"]);
65
+ });
66
+
67
+ it("a failing block does not poison the queue and still propagates to its caller", async () => {
68
+ await assert.rejects(withRepoLock("/repo2", async () => { throw new Error("boom"); }), /boom/);
69
+ const out = await withRepoLock("/repo2", async () => "clean");
70
+ assert.equal(out, "clean");
71
+ });
72
+
73
+ it("different repos do not block each other", async () => {
74
+ const order: string[] = [];
75
+ await Promise.all([
76
+ withRepoLock("/repoA", async () => { await new Promise((r) => setTimeout(r, 20)); order.push("A"); }),
77
+ withRepoLock("/repoB", async () => { order.push("B"); }),
78
+ ]);
79
+ assert.deepEqual(order, ["B", "A"]);
80
+ });
81
+ });
82
+
83
+ // ── Owner marker + pid liveness ─────────────────────────────────────────────
84
+
85
+ describe("owner marker + pid liveness", () => {
86
+ it("pidAlive: current process alive, pid 2^22 dead", () => {
87
+ assert.equal(pidAlive(process.pid), true);
88
+ // A pid that cannot exist on any supported host (max pid < 2^22 everywhere
89
+ // practical; on Linux pid_max default caps at 32768/4194304).
90
+ assert.equal(pidAlive(16 * 1024 * 1024), false);
91
+ });
92
+ });
93
+
94
+ // ── GC sweep decisions ──────────────────────────────────────────────────────
95
+
96
+ describe("sweepStaleWorktrees", () => {
97
+ it("removes dead-pid and marker-less sandboxes, keeps live ones, uses worktree remove for registered dirs", async () => {
98
+ const repo = await tempDir("wt-sweep-repo-");
99
+ const base = join(repo, WORKTREE_DIR_NAME);
100
+ await mkdir(join(base, "dead"), { recursive: true });
101
+ await mkdir(join(base, "live"), { recursive: true });
102
+ await mkdir(join(base, "legacy"), { recursive: true });
103
+ await writeFile(join(base, "dead.owner.json"), JSON.stringify({ pid: 16 * 1024 * 1024, id: "dead", createdAt: 1 }));
104
+ await writeFile(join(base, "live.owner.json"), JSON.stringify({ pid: process.pid, id: "live", createdAt: Date.now() }));
105
+ const wtList = `worktree ${repo}\nHEAD abc\n\nworktree ${join(base, "dead")}\nHEAD def\n\n`;
106
+ const exec = fakeExec([
107
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
108
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "list", stdout: wtList },
109
+ ]);
110
+ const result = await sweepStaleWorktrees(repo, exec);
111
+ assert.deepEqual(result.removed.map((r) => r.split("/").pop()).sort(), ["dead", "legacy"]);
112
+ assert.equal(result.kept, 1);
113
+ const removeCalls = exec.calls.filter((c) => c.args[0] === "worktree" && c.args[1] === "remove");
114
+ assert.equal(removeCalls.length, 1); // only the registered one via git
115
+ assert.ok(removeCalls[0].args[3].includes("dead"));
116
+ await assert.rejects(stat(join(base, "dead")));
117
+ await assert.rejects(stat(join(base, "legacy")));
118
+ await stat(join(base, "live")); // still there
119
+ });
120
+
121
+ it("no .pi-worktrees dir → zero cost, no git calls beyond rev-parse", async () => {
122
+ const repo = await tempDir("wt-sweep-empty-");
123
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` }]);
124
+ const result = await sweepStaleWorktrees(repo, exec);
125
+ assert.deepEqual(result, { removed: [], kept: 0 });
126
+ assert.equal(exec.calls.length, 1);
127
+ });
128
+ });
129
+
130
+ // ── Baseline capture: PURE READS on the parent ─────────────────────────────
131
+
132
+ describe("captureParentBaseline", () => {
133
+ it("composes staged + unstaged + untracked diffs; ZERO parent-mutating git args", async () => {
134
+ const repo = "/fake/repo";
135
+ const exec = fakeExec([
136
+ { match: (_c, args) => args[0] === "diff" && args.includes("--cached"), stdout: "STAGED-PATCH\n" },
137
+ { match: (_c, args) => args[0] === "diff" && args.includes("--no-index"), stdout: "UNTRACKED-PATCH\n" },
138
+ { match: (_c, args) => args[0] === "diff", stdout: "UNSTAGED-PATCH\n" },
139
+ { match: (_c, args) => args[0] === "ls-files", stdout: "new1.txt\nnew2.txt\n" },
140
+ ]);
141
+ const result = await captureParentBaseline(repo, exec);
142
+ assert.ok(result.ok);
143
+ // Order mirrors working-tree construction: staged, unstaged, untracked.
144
+ assert.equal(result.patch, "STAGED-PATCH\n\nUNSTAGED-PATCH\n\nUNTRACKED-PATCH\n\nUNTRACKED-PATCH\n");
145
+ const mutators = exec.calls.filter((c) =>
146
+ c.args.includes("add") || c.args.includes("stash") || c.args.includes("commit") || c.args.includes("apply"));
147
+ assert.deepEqual(mutators, []); // parent purity — the advisor-reviewed invariant
148
+ // Untracked diffs are new-file no-index diffs against /dev/null.
149
+ const noIndex = exec.calls.filter((c) => c.args.includes("--no-index"));
150
+ assert.equal(noIndex.length, 2);
151
+ assert.deepEqual(noIndex[0].args.slice(-2), ["/dev/null", "new1.txt"]);
152
+ });
153
+
154
+ it("256 MiB budget: oversized baseline is skipped with an error, not buffered", async () => {
155
+ const repo = "/fake/repo2";
156
+ const big = "x".repeat(300 * 1024 * 1024);
157
+ const exec = fakeExec([
158
+ { match: (_c, args) => args[0] === "diff" && args.includes("--cached"), stdout: big },
159
+ { match: (_c, args) => args[0] === "diff" && !args.includes("--cached"), stdout: "" },
160
+ { match: (_c, args) => args[0] === "ls-files", stdout: "" },
161
+ ]);
162
+ const result = await captureParentBaseline(repo, exec);
163
+ assert.equal(result.ok, false);
164
+ assert.match(result.error!, /budget/);
165
+ });
166
+ });
167
+
168
+ // ── Baseline apply: runs INSIDE the worktree cwd ────────────────────────────
169
+
170
+ describe("applyBaselineToWorktree", () => {
171
+ it("writes the patch to a temp file and applies it in the worktree cwd", async () => {
172
+ let seen: { args: string[]; cwd?: string } | undefined;
173
+ const exec = fakeExec([]);
174
+ const orig = exec;
175
+ const wrapped: Exec = async (command, args, options) => {
176
+ if (command === "git" && args[0] === "apply") seen = { args, cwd: options?.cwd };
177
+ return orig(command, args, options);
178
+ };
179
+ const result = await applyBaselineToWorktree("/wt/dir", "PATCH\n", wrapped);
180
+ assert.ok(result.ok);
181
+ assert.equal(seen!.cwd, "/wt/dir");
182
+ assert.deepEqual(seen!.args.slice(0, 3), ["apply", "--binary", "--whitespace=nowarn"]);
183
+ });
184
+
185
+ it("apply failure surfaces the error (caller skips carry)", async () => {
186
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "apply", code: 1, stderr: "error: patch does not apply" }]);
187
+ const result = await applyBaselineToWorktree("/wt/dir", "PATCH\n", exec);
188
+ assert.equal(result.ok, false);
189
+ assert.match(result.error!, /does not apply/);
190
+ });
191
+ });
192
+
193
+ // ── .worktreeinclude ────────────────────────────────────────────────────────
194
+
195
+ describe("copyWorktreeIncludes", () => {
196
+ it("copies gitignored files matching the include globs into the worktree", async () => {
197
+ const repo = await tempDir("wt-include-repo-");
198
+ const wt = await tempDir("wt-include-dst-");
199
+ await writeFile(join(repo, ".worktreeinclude"), "# env and config\n.env\nconfig/*.local\n");
200
+ await mkdir(join(repo, "config"), { recursive: true });
201
+ await writeFile(join(repo, ".env"), "SECRET=1\n");
202
+ await writeFile(join(repo, "config", "dev.local"), "x=1\n");
203
+ await writeFile(join(repo, "config", "keep.txt"), "not matched\n");
204
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "ls-files", stdout: ".env\nconfig/dev.local\nconfig/keep.txt\n" }]);
205
+ const copied = await copyWorktreeIncludes(repo, wt, exec);
206
+ assert.equal(copied, 2);
207
+ assert.equal(await readFile(join(wt, ".env"), "utf8"), "SECRET=1\n");
208
+ assert.equal(await readFile(join(wt, "config", "dev.local"), "utf8"), "x=1\n");
209
+ await assert.rejects(stat(join(wt, "config", "keep.txt"))); // not gitignored-matched
210
+ });
211
+
212
+ it("no .worktreeinclude → no git calls, returns 0", async () => {
213
+ const repo = await tempDir("wt-include-none-");
214
+ const exec = fakeExec([]);
215
+ assert.equal(await copyWorktreeIncludes(repo, "/wt", exec), 0);
216
+ assert.equal(exec.calls.length, 0);
217
+ });
218
+ });
219
+
220
+ // ── createWorktree: CoW construction + fallback ─────────────────────────────
221
+
222
+ describe("createWorktree", () => {
223
+ it("not-a-repo fails cleanly", async () => {
224
+ const dir = await tempDir("wt-create-norepo-");
225
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "rev-parse", code: 128, stderr: "not a git repository" }]);
226
+ const result = await createWorktree(dir, exec);
227
+ assert.equal(result.ok, false);
228
+ assert.match(result.error!, /not a git repo/);
229
+ });
230
+ });
@@ -1516,51 +1516,105 @@ export function formatCtxPercent(tokens: number, contextWindow: number): string
1516
1516
 
1517
1517
  /** Waffle-chart glyphs, matching OMP's vocabulary. */
1518
1518
  const WAFFLE_FILLED = "⛁";
1519
+ const WAFFLE_MESSAGES = "⛃";
1519
1520
  const WAFFLE_FREE = "⛶";
1520
1521
  const WAFFLE_BUFFER = "⛝";
1521
1522
 
1522
- /** OMP's signature waffle grid: `rows × cols` cells over the window, painted in
1523
- * slice order (used categories → free → autocompact buffer).
1524
- *
1525
- * Cells are allocated by share of the window, with a **minimum of one cell per
1526
- * slice worth ≥0.5%** — deliberate visibility scaling, the same choice OMP
1527
- * makes (their 2%-used grid still lights up a third of the cells). Any
1528
- * shortfall or overflow is absorbed by the largest slice, so the grid always
1529
- * fills exactly `rows × cols` cells. */
1530
- export function ctxWaffle(
1531
- slices: { tokens: number; glyph: string }[],
1523
+ /** OMP grid geometry: 20×10 = 200 space-joined cells beside the legend. */
1524
+ export const CTX_GRID_COLS = 20;
1525
+ export const CTX_GRID_ROWS = 10;
1526
+ const CTX_GUTTER = " ";
1527
+
1528
+ /** One planned cell: glyph + the ThemeColor (or "strong") to paint it with. */
1529
+ export interface CtxCell {
1530
+ glyph: string;
1531
+ color: "accent" | "warning" | "success" | "userMessageText" | "customMessageLabel" | "dim";
1532
+ }
1533
+
1534
+ /** OMP's category→color map (all tokens exist in pi's ThemeColor). */
1535
+ const CTX_CATEGORY_STYLE: Record<string, { glyph: string; color: CtxCell["color"] }> = {
1536
+ "System prompt": { glyph: WAFFLE_FILLED, color: "accent" },
1537
+ "System tools": { glyph: WAFFLE_FILLED, color: "warning" },
1538
+ "System context": { glyph: WAFFLE_FILLED, color: "customMessageLabel" },
1539
+ Skills: { glyph: WAFFLE_FILLED, color: "success" },
1540
+ Messages: { glyph: WAFFLE_MESSAGES, color: "userMessageText" },
1541
+ "Free space": { glyph: WAFFLE_FREE, color: "dim" },
1542
+ "Autocompact buffer": { glyph: WAFFLE_BUFFER, color: "warning" },
1543
+ };
1544
+
1545
+ /** OMP's cell planner over the disjoint categories: cells are allocated by
1546
+ * share of the window, every nonzero category keeps at least one visible cell
1547
+ * (visibility scaling — OMP's ratioCells has no lower share gate). Overflow
1548
+ * trims from the largest category first, never below one cell; the remainder
1549
+ * is painted free, then the autocompact buffer hatches the tail. Always
1550
+ * exactly cols × rows cells. */
1551
+ export function planCtxCells(
1552
+ categories: { label: string; tokens: number }[],
1532
1553
  contextWindow: number,
1533
- cols = 10,
1534
- rows = 4,
1535
- ): string[] {
1554
+ cols = CTX_GRID_COLS,
1555
+ rows = CTX_GRID_ROWS,
1556
+ ): CtxCell[] {
1536
1557
  const cells = cols * rows;
1537
- if (!(contextWindow > 0)) return Array.from({ length: rows }, () => WAFFLE_FREE.repeat(cols));
1538
- const MIN_SHARE = 0.005;
1539
- const alloc = slices.map((s) => {
1540
- const tokens = Math.max(0, s.tokens);
1541
- if (tokens <= 0) return 0;
1542
- const share = tokens / contextWindow;
1543
- return share < MIN_SHARE ? 1 : Math.max(1, Math.round(share * cells));
1544
- });
1545
- // Overflow swallows from the largest slice first (never below one cell).
1546
- let total = alloc.reduce((a, b) => a + b, 0);
1547
- while (total > cells) {
1548
- const biggest = alloc.indexOf(Math.max(...alloc));
1549
- if (alloc[biggest] <= 1) break;
1550
- alloc[biggest] -= 1;
1551
- total -= 1;
1558
+ if (!(contextWindow > 0)) {
1559
+ return Array.from({ length: cells }, () => ({ glyph: WAFFLE_FREE, color: "dim" as const }));
1552
1560
  }
1553
- // Underflow pads the LARGEST slice — with a well-formed breakdown that is free
1554
- // space. Never the last slice: that would inflate the autocompact buffer (a
1555
- // fixed reserve) whenever a category figure is underestimated.
1556
- if (total < cells && alloc.length > 0) {
1557
- const biggest = alloc.indexOf(Math.max(...alloc));
1558
- alloc[biggest] += cells - total;
1561
+ const tokensPerCell = contextWindow / cells;
1562
+ const count = (tokens: number) => (tokens > 0 ? Math.max(1, Math.round(tokens / tokensPerCell)) : 0);
1563
+ const planned = categories.map((c) => ({ style: CTX_CATEGORY_STYLE[c.label] ?? { glyph: WAFFLE_FILLED, color: "accent" as const }, n: count(c.tokens) }));
1564
+ let used = planned.reduce((a, p) => a + p.n, 0);
1565
+ if (used > cells) {
1566
+ // Trim from the largest allocations first, preserving visibility for small ones.
1567
+ const order = [...planned].sort((a, b) => b.n - a.n);
1568
+ let overflow = used - cells;
1569
+ for (const p of order) {
1570
+ while (overflow > 0 && p.n > 1) {
1571
+ p.n -= 1;
1572
+ overflow -= 1;
1573
+ }
1574
+ }
1575
+ used = planned.reduce((a, p) => a + p.n, 0);
1559
1576
  }
1560
- const glyphs = alloc.flatMap((count, i) => Array.from({ length: count }, () => slices[i].glyph));
1561
- const out: string[] = [];
1562
- for (let r = 0; r < rows; r++) out.push(glyphs.slice(r * cols, (r + 1) * cols).join(""));
1563
- return out;
1577
+ const freeCount = Math.max(0, cells - used);
1578
+ const out: CtxCell[] = [];
1579
+ for (const p of planned) for (let i = 0; i < p.n; i++) out.push({ glyph: p.style.glyph, color: p.style.color });
1580
+ for (let i = 0; i < freeCount; i++) out.push({ glyph: WAFFLE_FREE, color: "dim" });
1581
+ while (out.length < cells) out.push({ glyph: WAFFLE_FREE, color: "dim" });
1582
+ return out.slice(0, cells);
1583
+ }
1584
+
1585
+ /** Styled legend runs (OMP's LegendPart shape): `s` is a ThemeColor, "strong"
1586
+ * (bold), or undefined (plain). Plain data — the renderer applies the live
1587
+ * theme at display time. */
1588
+ export type CtxLegendPart = { t: string; s?: CtxCell["color"] | "muted" | "strong" };
1589
+
1590
+ /** Legend lines for the /context panel, mirroring OMP's buildLegendParts:
1591
+ * model header, totals, then the per-category block and free/buffer rows. */
1592
+ export function buildCtxLegend(b: ContextBreakdown): CtxLegendPart[][] {
1593
+ const k = formatCtxTokens;
1594
+ const pct = (n: number) => formatCtxPercent(n, b.contextWindow);
1595
+ const windowLabel = b.contextWindow > 0 ? k(b.contextWindow) : "?";
1596
+ const lines: CtxLegendPart[][] = [];
1597
+ if (b.modelName) lines.push([{ t: b.modelName, s: "strong" }, ...(b.contextWindow > 0 ? [{ t: ` (${windowLabel} context)`, s: "dim" as const }] : [])]);
1598
+ if (b.modelLabel) lines.push([{ t: `${b.modelLabel.split("/").pop()}${b.contextWindow > 0 ? `[${windowLabel}]` : ""}`, s: "muted" as const }]);
1599
+ const used = b.usedTokens ?? b.systemPrompt.total + b.tools.total + b.messages.total;
1600
+ lines.push([
1601
+ { t: k(used), s: "strong" },
1602
+ { t: `/${windowLabel} tokens`, s: "dim" },
1603
+ { t: ` (${formatCtxPercent(used, b.contextWindow)})`, s: "muted" as const },
1604
+ ]);
1605
+ lines.push([]);
1606
+ lines.push([{ t: "Estimated usage by category", s: "muted" as const }]);
1607
+ for (const c of b.categories) {
1608
+ const style = CTX_CATEGORY_STYLE[c.label];
1609
+ lines.push([
1610
+ { t: c.glyph, s: style?.color ?? "accent" },
1611
+ { t: ` ${c.label}: ` },
1612
+ { t: k(c.tokens), s: "strong" },
1613
+ { t: c.tokens === 1 ? " token " : " tokens ", s: "dim" },
1614
+ { t: `(${pct(c.tokens)})`, s: "dim" },
1615
+ ]);
1616
+ }
1617
+ return lines;
1564
1618
  }
1565
1619
 
1566
1620
  /** Token cost of one tool as the prompt carries it: description + JSON
@@ -1758,7 +1812,7 @@ export function computeContextBreakdown(input: ContextBreakdownInput): ContextBr
1758
1812
  { label: "System tools", tokens: toolsTotal, glyph: "⛁" },
1759
1813
  { label: "System context", tokens: contextTokens, glyph: "⛁" },
1760
1814
  { label: "Skills", tokens: skillsTokens, glyph: "⛁" },
1761
- { label: "Messages", tokens: messagesRow, glyph: WAFFLE_FILLED },
1815
+ { label: "Messages", tokens: messagesRow, glyph: WAFFLE_MESSAGES },
1762
1816
  { label: "Free space", tokens: freeSpace, glyph: WAFFLE_FREE },
1763
1817
  // The reserve is the LAST slice of the window (pi compacts at
1764
1818
  // `tokens > window - reserve`), so it renders after free space.
@@ -1789,9 +1843,10 @@ export function computeContextBreakdown(input: ContextBreakdownInput): ContextBr
1789
1843
  };
1790
1844
  }
1791
1845
 
1792
- /** Render the /context panel in OMP's layout: waffle grid + model info to its
1793
- * right, then a disjoint "Estimated usage by category" block, then detail
1794
- * lists and pruning recommendations. */
1846
+ /** Render the /context panel in OMP's layout: 20×10 cell grid paired with the
1847
+ * legend beside it (3-space gutter), then detail lists and pruning
1848
+ * recommendations. Returns plain lines for the transcript fallback; the
1849
+ * structured grid+legend for the themed renderer rides in `details`. */
1795
1850
  export function renderContextPanel(b: ContextBreakdown): string[] {
1796
1851
  const k = formatCtxTokens;
1797
1852
  const pct = (n: number) => ` (${formatCtxPercent(n, b.contextWindow)})`;
@@ -1806,28 +1861,34 @@ export function renderContextPanel(b: ContextBreakdown): string[] {
1806
1861
  }
1807
1862
  const used = b.usedTokens ?? b.systemPrompt.total + b.tools.total + b.messages.total;
1808
1863
 
1809
- // ── Header: waffle on the left (10 cols), model + totals on the right ──
1810
- // Painted in window order: used categories → free → autocompact buffer.
1811
- const waffleSlices = b.categories.map((c) => ({ tokens: c.tokens, glyph: c.glyph }));
1812
- const grid = ctxWaffle(waffleSlices, b.contextWindow, 10, 4);
1813
- const right = [
1814
- b.modelName ? `${b.modelName}${b.contextWindow > 0 ? ` (${k(b.contextWindow)} context)` : ""}` : undefined,
1815
- // OMP shows the bare model id with the window bracketed: `glm-5.3[1m]`.
1816
- b.modelLabel ? `${b.modelLabel.split("/").pop()}${b.contextWindow > 0 ? `[${k(b.contextWindow)}]` : ""}` : undefined,
1817
- `${k(used)}/${k(b.contextWindow)} tokens (${formatCtxPercent(used, b.contextWindow)})`,
1818
- "Estimated usage by category",
1819
- ];
1820
- for (let r = 0; r < grid.length; r++) {
1821
- const rightText = right[r];
1822
- lines.push(rightText ? `${grid[r]} ${rightText}` : grid[r]);
1864
+ // ── Header: 20×10 cell grid on the left, legend on the right ──
1865
+ const cells = planCtxCells(b.categories, b.contextWindow);
1866
+ const gridRows: string[] = [];
1867
+ for (let r = 0; r < CTX_GRID_ROWS; r++) {
1868
+ gridRows.push(cells.slice(r * CTX_GRID_COLS, (r + 1) * CTX_GRID_COLS).map((c) => c.glyph).join(" "));
1823
1869
  }
1824
- for (const extra of right.slice(grid.length)) if (extra) lines.push(" " + extra);
1825
- lines.push("");
1826
-
1827
- // ── Disjoint category block (glyph-prefixed, OMP style) ──
1870
+ // Legend lines share the per-category color map; build them as plain text here.
1871
+ const legend: string[] = [];
1872
+ if (b.modelName) legend.push(`${b.modelName}${b.contextWindow > 0 ? ` (${k(b.contextWindow)} context)` : ""}`);
1873
+ // OMP shows the bare model id with the window bracketed: `glm-5.3[1m]`.
1874
+ if (b.modelLabel) legend.push(`${b.modelLabel.split("/").pop()}${b.contextWindow > 0 ? `[${k(b.contextWindow)}]` : ""}`);
1875
+ legend.push(`${k(used)}/${k(b.contextWindow)} tokens (${formatCtxPercent(used, b.contextWindow)})`);
1876
+ legend.push("");
1877
+ legend.push("Estimated usage by category");
1828
1878
  for (const c of b.categories) {
1829
- lines.push(` ${c.glyph} ${c.label}: ${k(c.tokens)} token${c.tokens === 1 ? "" : "s"}${pct(c.tokens)}`);
1879
+ legend.push(`${c.glyph} ${c.label}: ${k(c.tokens)} token${c.tokens === 1 ? "" : "s"}${pct(c.tokens)}`);
1880
+ }
1881
+
1882
+ const bodyLines = Math.max(CTX_GRID_ROWS, legend.length);
1883
+ const blankGrid = " ".repeat(gridRows[0]?.length ?? 0);
1884
+ for (let r = 0; r < bodyLines; r++) {
1885
+ const g = r < gridRows.length ? gridRows[r] : blankGrid;
1886
+ const l = legend[r] ?? "";
1887
+ lines.push(l.length > 0 ? `${g}${CTX_GUTTER}${l}` : g);
1830
1888
  }
1889
+ lines.push("");
1890
+
1891
+ // The autocompact row lives in the legend; a disabled compaction still needs its note.
1831
1892
  if (b.compactionDisabled) lines.push(" ⛶ Autocompact buffer: disabled (compaction.enabled=false)");
1832
1893
 
1833
1894
  // ── Detail: system-prompt sections, top tools, per-package attribution ──
@@ -1980,21 +2041,76 @@ export default function (pi: ExtensionAPI) {
1980
2041
 
1981
2042
  // Transcript renderer for /context: pi renders this inline in the scrollback
1982
2043
  // (above the editor), like OMP's panel, instead of a dismissable overlay. The
1983
- // renderer receives the live theme, so the category glyphs keep their colors
1984
- // and the panel stays visible while you keep working.
2044
+ // renderer receives the live theme, so grid cells and legend runs keep their
2045
+ // category colors and the panel stays visible while you keep working.
2046
+ // v2 details carry the structured grid + legend as PLAIN data (colors applied
2047
+ // here, at render time — the theme can change between send and render);
2048
+ // legacy entries stored `details.lines` keep the glyph-tint path.
1985
2049
  // Optional-call guard: matches pi-a2a/pi-subagent/pi-advisor, and keeps older
1986
2050
  // SDK builds (and minimal test harnesses) loadable.
1987
- pi.registerMessageRenderer?.<{ lines: string[] }>(MESSAGE_TYPE_CONTEXT, (message, _opts, theme) => {
2051
+ pi.registerMessageRenderer?.<{ grid?: CtxCell[][]; legend?: CtxLegendPart[][]; lines?: string[] }>(MESSAGE_TYPE_CONTEXT, (message, _opts, theme) => {
1988
2052
  try {
1989
2053
  const fg = theme?.fg ? (c: string, s: string) => theme.fg(c as never, s) : (s: string) => s;
1990
- const body = (message.details as { lines?: string[] } | undefined)?.lines
1991
- ?? (typeof message.content === "string" ? message.content.split("\n") : []);
2054
+ const bold = theme?.bold ? (s: string) => theme.bold(s) : (s: string) => s;
2055
+ const details = message.details as { grid?: CtxCell[][]; legend?: CtxLegendPart[][]; lines?: string[] } | undefined;
2056
+ const ANSI_RE = /\u001b\[[0-9;]*m/g;
2057
+ const visibleWidth = (s: string) => [...s.replace(ANSI_RE, "")].length;
1992
2058
  const clamp = (line: string, width: number) => {
1993
- if (width <= 0 || [...line].length <= width) return line;
2059
+ if (width <= 0 || visibleWidth(line) <= width) return line;
1994
2060
  // Ellipsis rather than a mid-word slice — this is a display clamp, not data loss.
1995
- const chars = [...line];
1996
- return chars.length <= width ? line : chars.slice(0, Math.max(0, width - 1)).join("") + "…";
2061
+ const chars = [...line.replace(ANSI_RE, "")];
2062
+ return chars.slice(0, Math.max(0, width - 1)).join("") + "…";
1997
2063
  };
2064
+ if (details?.grid && details?.legend) {
2065
+ // v2: assemble rows as spans (plain text + style), clamp by VISIBLE
2066
+ // width, and only then paint — the ANSI form's codepoint count is
2067
+ // ~12× the visible width and would shred the grid at real widths.
2068
+ // Cells join with a space like OMP's grid (20 cells → 39 columns).
2069
+ const gridSpans = details.grid.map((row) =>
2070
+ row.flatMap((c, i) => {
2071
+ const cell = { t: c.glyph, s: c.color as string };
2072
+ return i === 0 ? [cell] : [{ t: " ", s: "" }, cell];
2073
+ }),
2074
+ );
2075
+ const blankSpans = details.grid[0]?.length
2076
+ ? Array.from({ length: details.grid[0].length * 2 - 1 }, () => ({ t: " ", s: "" }))
2077
+ : [];
2078
+ const bodyLines = Math.max(details.grid.length, details.legend.length);
2079
+ return {
2080
+ render: (width: number) =>
2081
+ Array.from({ length: bodyLines }, (_, r) => {
2082
+ const g = r < gridSpans.length ? gridSpans[r] : blankSpans;
2083
+ const l = details.legend![r] ?? [];
2084
+ // Gutter (3 spaces) rides only when a legend line follows.
2085
+ const gutter: Array<{ t: string; s: string }> = l.length > 0 ? [{ t: CTX_GUTTER, s: "" }] : [];
2086
+ const spans = [...g, ...gutter, ...l.map((p) => ({ t: p.t, s: (p.s ?? "") as string }))];
2087
+ // Emit spans up to the VISIBLE budget; ellipsize the span that
2088
+ // crosses it. Painting happens per span, so escape codes never
2089
+ // inflate the measure.
2090
+ let budget = Math.max(0, width);
2091
+ let out = "";
2092
+ let lastStyle: string | undefined;
2093
+ for (const sp of spans) {
2094
+ if (budget <= 0) break;
2095
+ let t = sp.t;
2096
+ if (visibleWidth(t) > budget) {
2097
+ t = [...t].slice(0, Math.max(0, budget - 1)).join("") + "…";
2098
+ }
2099
+ if (sp.s !== lastStyle) {
2100
+ lastStyle = sp.s;
2101
+ out += sp.s === "strong" ? bold(t) : sp.s ? fg(sp.s as never, t) : t;
2102
+ } else {
2103
+ out += t;
2104
+ }
2105
+ budget -= visibleWidth(t);
2106
+ }
2107
+ return out;
2108
+ }),
2109
+ invalidate: () => {},
2110
+ };
2111
+ }
2112
+ const body = details?.lines
2113
+ ?? (typeof message.content === "string" ? message.content.split("\n") : []);
1998
2114
  return {
1999
2115
  render: (width: number) => body.map((l) => clamp(l, width)).map((line) => {
2000
2116
  // Tint the category glyph; keep the numeric body plain for contrast.
@@ -2017,10 +2133,16 @@ export default function (pi: ExtensionAPI) {
2017
2133
  // contexts (ExtensionCommandContext) do not expose them.
2018
2134
  const b = computeContextBreakdown({ ctx, allTools: pi.getAllTools(), activeTools: pi.getActiveTools(), model: ctx.model as ContextBreakdownInput["model"], settings: readCompactionSettings() });
2019
2135
  const lines = renderContextPanel(b);
2136
+ // Structured v2 details: grid cells + legend runs as plain data — the
2137
+ // transcript renderer applies the live theme (which may differ at replay).
2138
+ const legend = buildCtxLegend(b);
2139
+ const grid: CtxCell[][] = [];
2140
+ const cells = planCtxCells(b.categories, b.contextWindow);
2141
+ for (let r = 0; r < cells.length; r += CTX_GRID_COLS) grid.push(cells.slice(r, r + CTX_GRID_COLS));
2020
2142
  // display:true → shown in the transcript (above the editor, like OMP).
2021
2143
  // `content` is the plain-text fallback for renderer-less builds and
2022
- // non-TUI modes; `details.lines` feeds the themed transcript renderer.
2023
- pi.sendMessage({ customType: MESSAGE_TYPE_CONTEXT, content: lines.join("\n"), display: true, details: { lines } });
2144
+ // non-TUI modes; `details` feeds the themed transcript renderer.
2145
+ pi.sendMessage({ customType: MESSAGE_TYPE_CONTEXT, content: lines.join("\n"), display: true, details: { grid, legend, lines } });
2024
2146
  },
2025
2147
  });
2026
2148