ceulen 0.1.0 → 0.5.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 (56) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +103 -14
  3. package/extensions/index.ts +113 -0
  4. package/extensions/lib/env.ts +75 -0
  5. package/extensions/lib/panel.ts +1720 -0
  6. package/extensions/lib/registry.ts +182 -0
  7. package/extensions/modules/composer/index.ts +128 -0
  8. package/extensions/modules/composer/lib/settings.ts +55 -0
  9. package/extensions/modules/composer/lib/shapes.ts +436 -0
  10. package/extensions/modules/composer/test/editor.test.ts +138 -0
  11. package/extensions/modules/composer/test/module.test.ts +218 -0
  12. package/extensions/modules/composer/test/screen.test.ts +195 -0
  13. package/extensions/modules/composer/test/shapes.test.ts +175 -0
  14. package/extensions/modules/config/index.ts +298 -0
  15. package/extensions/modules/config/piSettings.ts +467 -0
  16. package/extensions/modules/config/plugins.ts +290 -0
  17. package/extensions/modules/config/test/kernel.test.ts +523 -0
  18. package/extensions/modules/config/test/kernelV4.test.ts +196 -0
  19. package/extensions/modules/config/test/menu.test.ts +226 -0
  20. package/extensions/modules/config/test/panel.test.ts +395 -0
  21. package/extensions/modules/config/test/piSettings.test.ts +185 -0
  22. package/extensions/modules/config/test/plugins.test.ts +181 -0
  23. package/extensions/modules/config/test/preview-block.test.ts +88 -0
  24. package/extensions/modules/ponytail/UPSTREAM +26 -0
  25. package/extensions/modules/ponytail/index.ts +336 -0
  26. package/extensions/modules/ponytail/lib/config.ts +149 -0
  27. package/extensions/modules/ponytail/lib/instructions.ts +98 -0
  28. package/extensions/modules/ponytail/lib/subagent.ts +31 -0
  29. package/extensions/modules/ponytail/test/extension.test.ts +422 -0
  30. package/extensions/modules/ponytail/test/helpers.test.ts +163 -0
  31. package/extensions/modules/ponytail/test/subagent.test.ts +33 -0
  32. package/extensions/modules/router/commands/commands.ts +99 -0
  33. package/extensions/modules/router/configPanel.ts +89 -0
  34. package/extensions/modules/router/index.ts +75 -0
  35. package/extensions/modules/router/lib/client.ts +390 -0
  36. package/extensions/modules/router/lib/config.ts +142 -0
  37. package/extensions/modules/router/lib/migrate.ts +92 -0
  38. package/extensions/modules/router/lib/provider.ts +138 -0
  39. package/extensions/modules/router/lib/refresh.ts +19 -0
  40. package/extensions/modules/router/test/guard.test.ts +77 -0
  41. package/extensions/modules/router/test/unit.test.ts +1126 -0
  42. package/extensions/modules/usage/index.ts +1975 -0
  43. package/extensions/modules/usage/test/context.test.ts +387 -0
  44. package/extensions/modules/usage/test/env-gating.test.ts +113 -0
  45. package/extensions/modules/usage/test/opencode-go-usage.test.ts +139 -0
  46. package/extensions/modules/usage/test/parsers.test.ts +244 -0
  47. package/extensions/modules/usage/test/stale-ctx-regression.test.ts +294 -0
  48. package/extensions/modules/usage/test/zai-anthropic-adapter.test.ts +40 -0
  49. package/package.json +15 -3
  50. package/skills/ponytail/SKILL.md +124 -0
  51. package/skills/ponytail-audit/SKILL.md +41 -0
  52. package/skills/ponytail-debt/SKILL.md +44 -0
  53. package/skills/ponytail-gain/SKILL.md +51 -0
  54. package/skills/ponytail-help/SKILL.md +73 -0
  55. package/skills/ponytail-review/SKILL.md +57 -0
  56. package/extensions/index.js +0 -42
@@ -0,0 +1,395 @@
1
+ import { describe, it, before, after } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ // Isolation: PI_CODING_AGENT_DIR → temp dir; cwd is the repo root (tests run
8
+ // from the package root), whose .pi/settings.json must never be touched —
9
+ // project-scope tests below use a temp cwd instead of chdir.
10
+ const TMP_HOME = join(tmpdir(), "ceulen-config-test-" + process.pid);
11
+ before(() => {
12
+ mkdirSync(TMP_HOME, { recursive: true });
13
+ process.env.PI_CODING_AGENT_DIR = TMP_HOME;
14
+ });
15
+ after(() => {
16
+ delete process.env.PI_CODING_AGENT_DIR;
17
+ try { rmSync(TMP_HOME, { recursive: true, force: true }); } catch { /* ignore */ }
18
+ });
19
+
20
+ const settingsPath = () => join(TMP_HOME, "settings.json");
21
+
22
+ // ── registry: kill-switch read/write + layer precedence ─────────────────────
23
+
24
+ describe("registry kill-switch", () => {
25
+ it("readDisabled returns [] when no settings file exists", async () => {
26
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
27
+ const { readDisabled } = await import("../../../lib/registry.js");
28
+ assert.deepEqual(readDisabled(), []);
29
+ });
30
+
31
+ it("writeDisabled round-trips through the same file readDisabled resolves", async () => {
32
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
33
+ const { readDisabled, writeDisabled, disabledSource } = await import("../../../lib/registry.js");
34
+ const written = writeDisabled(["usage"]);
35
+ assert.equal(written, settingsPath());
36
+ assert.deepEqual(readDisabled(), ["usage"]);
37
+ assert.equal(disabledSource().isProject, false);
38
+ });
39
+
40
+ it("writeDisabled merges — unrelated keys survive, tmp residue cleaned", async () => {
41
+ writeFileSync(settingsPath(), JSON.stringify({ theme: "dark", ceulen: { disabled: ["usage"] } }));
42
+ const inoBefore = statSync(settingsPath()).ino;
43
+ const { writeDisabled } = await import("../../../lib/registry.js");
44
+ writeDisabled(["ponytail"]);
45
+ const json = JSON.parse(readFileSync(settingsPath(), "utf8"));
46
+ assert.equal(json.theme, "dark");
47
+ assert.deepEqual(json.ceulen.disabled, ["ponytail"]);
48
+ assert.notEqual(inoBefore, statSync(settingsPath()).ino); // tmp+rename atomic
49
+ assert.ok(!existsSync(settingsPath() + ".tmp"));
50
+ });
51
+
52
+ it("writeDisabled refuses to clobber a corrupt settings.json", async () => {
53
+ writeFileSync(settingsPath(), '{ "ceulen": { "disabled": ["usage"] }\nOOPS');
54
+ const before = readFileSync(settingsPath(), "utf8");
55
+ const { writeDisabled } = await import("../../../lib/registry.js");
56
+ assert.throws(() => writeDisabled(["ponytail"]), /not valid JSON/);
57
+ assert.equal(readFileSync(settingsPath(), "utf8"), before);
58
+ assert.ok(!existsSync(settingsPath() + ".tmp"));
59
+ });
60
+
61
+ it("deprecated \"sub\" alias reads as \"usage\"", async () => {
62
+ writeFileSync(settingsPath(), JSON.stringify({ ceulen: { disabled: ["sub"] } }));
63
+ const { readDisabled } = await import("../../../lib/registry.js");
64
+ assert.deepEqual(readDisabled(), ["usage"]);
65
+ });
66
+
67
+ // Project scope: temp cwd + trust.json in the agent dir. readDisabled(cwd)/
68
+ // writeDisabled are cwd-parameterized, so no chdir needed.
69
+ describe("trusted project precedence", () => {
70
+ const projectCwd = join(TMP_HOME, "project");
71
+ const projectSettings = join(projectCwd, ".pi", "settings.json");
72
+
73
+ before(() => {
74
+ mkdirSync(join(projectCwd, ".pi"), { recursive: true });
75
+ writeFileSync(join(TMP_HOME, "trust.json"), JSON.stringify({ [projectCwd]: true }));
76
+ });
77
+
78
+ it("project ceulen section wins the read AND captures the write", async () => {
79
+ writeFileSync(settingsPath(), JSON.stringify({ ceulen: { disabled: ["usage"] } }));
80
+ writeFileSync(projectSettings, JSON.stringify({ ceulen: { disabled: ["ponytail"] } }));
81
+ const { readDisabled, writeDisabled, disabledSource } = await import("../../../lib/registry.js");
82
+
83
+ assert.deepEqual(readDisabled(projectCwd), ["ponytail"]); // project wins
84
+ const source = disabledSource(projectCwd);
85
+ assert.equal(source.path, projectSettings);
86
+ assert.equal(source.isProject, true);
87
+
88
+ const written = writeDisabled(["config"], projectCwd);
89
+ assert.equal(written, projectSettings, "write lands where the read resolves — never shadowed");
90
+ assert.deepEqual(readDisabled(projectCwd), ["config"]);
91
+ // Global file untouched by the project-scoped write.
92
+ assert.deepEqual(JSON.parse(readFileSync(settingsPath(), "utf8")).ceulen.disabled, ["usage"]);
93
+ });
94
+
95
+ it("project file WITHOUT a ceulen section does not capture the write", async () => {
96
+ writeFileSync(projectSettings, JSON.stringify({ router: { baseUrl: "http://x" } }));
97
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
98
+ const { writeDisabled, disabledSource } = await import("../../../lib/registry.js");
99
+ assert.equal(disabledSource(projectCwd).isProject, false);
100
+ assert.equal(writeDisabled(["usage"], projectCwd), settingsPath());
101
+ });
102
+ });
103
+ });
104
+
105
+ // ── config module: group assembly + save dispatch ───────────────────────────
106
+
107
+ describe("config module", () => {
108
+ const ctxStub = () => {
109
+ const notes: string[] = [];
110
+ return {
111
+ notes,
112
+ // cwd is required by the pi-settings SettingsManager instance the
113
+ // /config handler creates; use the isolated temp home as the project.
114
+ // ui/modelRegistry carry the runtime menu lookups (themes, models).
115
+ ctx: {
116
+ cwd: TMP_HOME,
117
+ ui: {
118
+ notify: (m: string) => notes.push(m),
119
+ getAllThemes: () => [{ name: "dark", path: undefined }, { name: "light", path: undefined }],
120
+ getTheme: () => undefined,
121
+ setTheme: () => ({ success: true }),
122
+ },
123
+ modelRegistry: { getAvailable: () => [] },
124
+ } as never,
125
+ };
126
+ };
127
+
128
+ it("moduleEnableRow toggles mutate the working set; nextDisabled inverts it", async () => {
129
+ const { moduleEnableRow, nextDisabled } = await import("../index.js");
130
+ const { MODULES } = await import("../../../lib/registry.js");
131
+ const working = new Set(MODULES.map((m) => m.name));
132
+ const enable = moduleEnableRow("usage", "Usage footer.", working);
133
+ assert.equal(enable.key, "ceulen.disabled.usage");
134
+ assert.equal(enable.defaultValue, true);
135
+
136
+ // Toggle "usage" off via its row setter.
137
+ assert.equal(enable.value, true);
138
+ enable.set(false);
139
+ assert.equal(working.has("usage"), false);
140
+ assert.deepEqual(nextDisabled(working), ["usage"]);
141
+
142
+ enable.set(true);
143
+ assert.deepEqual(nextDisabled(working), []);
144
+ });
145
+
146
+ it("withEnableRow prepends the Enable row to the module's FIRST section only", async () => {
147
+ const { withEnableRow } = await import("../index.js");
148
+ const { MODULES } = await import("../../../lib/registry.js");
149
+ const working = new Set(MODULES.map((m) => m.name));
150
+ const groups = [
151
+ { key: "a", label: "Router", tab: "Providers", rows: [{ key: "router.baseUrl" }] },
152
+ { key: "b", label: "Models", tab: "Providers", rows: [{ key: "router.enableReasoning" }] },
153
+ ] as never;
154
+ const out = withEnableRow(groups, "router", "Routes requests.", working);
155
+ assert.deepEqual(out[0]!.rows.map((r) => r.key), ["ceulen.disabled.router", "router.baseUrl"]);
156
+ assert.deepEqual(out[1]!.rows.map((r) => r.key), ["router.enableReasoning"], "second section untouched");
157
+ });
158
+
159
+ it("saveContributions: only edited-key owners are invoked, and a thrower doesn't block siblings", async () => {
160
+ const { saveContributions } = await import("../index.js");
161
+ const calls: string[] = [];
162
+ const contribution = (name: string, keys: string[], boom = false) => ({
163
+ name,
164
+ cfg: {
165
+ groups: () => [],
166
+ save: async (edited: Set<string>) => {
167
+ if (!keys.some((k) => edited.has(k))) return;
168
+ calls.push(name);
169
+ if (boom) throw new Error("boom");
170
+ },
171
+ },
172
+ });
173
+ const { ctx, notes } = ctxStub();
174
+ await saveContributions(
175
+ [contribution("router", ["router.baseUrl"]), contribution("ponytail", ["ponytail.defaultMode"], true), contribution("late", ["late.key"])],
176
+ new Set(["router.baseUrl", "ponytail.defaultMode", "late.key"]),
177
+ ctx,
178
+ );
179
+ // router + late ran despite ponytail throwing between them; error surfaced.
180
+ assert.deepEqual(calls, ["router", "ponytail", "late"]);
181
+ assert.ok(notes.some((n) => n.includes("ponytail: save failed")));
182
+ });
183
+
184
+ it("saveContributions: a save() that no-ops for unedited keys is the contract, dispatch still calls it once", async () => {
185
+ const { saveContributions } = await import("../index.js");
186
+ const { ctx } = ctxStub();
187
+ let invoked = 0;
188
+ let savedWith: string[] = [];
189
+ await saveContributions(
190
+ [{
191
+ name: "router",
192
+ cfg: {
193
+ groups: () => [],
194
+ save: async (edited: Set<string>) => {
195
+ invoked++;
196
+ if (!edited.has("router.baseUrl")) return; // module's own guard
197
+ savedWith = [...edited];
198
+ },
199
+ },
200
+ }],
201
+ new Set(["ponytail.defaultMode"]),
202
+ ctx,
203
+ );
204
+ assert.equal(invoked, 1); // dispatch is unconditional; the module guards
205
+ assert.deepEqual(savedWith, []);
206
+ });
207
+
208
+ it("piMenuLookup: theme preview captures the live theme once, restores on Esc, clears after commit", async () => {
209
+ const { piMenuLookup } = await import("../index.js");
210
+ const live = { name: "live-instance" };
211
+ const calls: unknown[] = [];
212
+ const ctx = {
213
+ ui: {
214
+ theme: live,
215
+ getAllThemes: () => [{ name: "dark" }, { name: "light" }],
216
+ getTheme: (n: string) => ({ name: `theme:${n}` }),
217
+ setTheme: (t: unknown) => { calls.push(t); return { success: true }; },
218
+ },
219
+ modelRegistry: { getAvailable: () => [] },
220
+ } as never;
221
+ const lk = piMenuLookup(ctx);
222
+ assert.deepEqual(lk.themes!(), ["dark", "light"]);
223
+ lk.previewTheme!("dark");
224
+ lk.previewTheme!("light");
225
+ // Capture happens ONCE (first preview), not per move.
226
+ assert.deepEqual(calls, [{ name: "theme:dark" }, { name: "theme:light" }]);
227
+ lk.restoreTheme!();
228
+ assert.deepEqual(calls[2], live, "Esc restores the pre-browse live instance");
229
+ // After a restore the capture is re-armed for the next browse session.
230
+ lk.previewTheme!("dark");
231
+ lk.restoreTheme!();
232
+ assert.equal(calls.length, 5);
233
+ assert.deepEqual(calls[4], live);
234
+ // Commit clears the capture: a following Esc must not clobber the commit.
235
+ calls.length = 0;
236
+ lk.previewTheme!("dark"); // capture = live
237
+ lk.applyTheme!("light"); // commit (live + persist), capture cleared
238
+ lk.restoreTheme!(); // stray cancel — must be a no-op
239
+ assert.equal(calls.length, 2, "only preview + apply happened; restore no-oped");
240
+ });
241
+
242
+ it("/config show assembles pi + module + plugin sections in OMP taxonomy order", async () => {
243
+ // Stub pi that records the registered command so the real handler runs.
244
+ let handler: ((args: string, ctx: never) => Promise<void>) | undefined;
245
+ const pi = {
246
+ registerCommand: (_name: string, opts: { handler: typeof handler }) => { handler = opts.handler; },
247
+ } as never;
248
+ const factories = new Map<string, () => never>();
249
+ const { default: configModule } = await import("../index.js");
250
+ configModule(pi, { configContribs: factories } as never);
251
+ assert.ok(handler, "handler registered");
252
+ const { notes, ctx } = ctxStub();
253
+ // Non-TUI branch takes the textual summary over the same assembly.
254
+ await (handler as never as (a: string, c: unknown) => Promise<void>)("show", ctx);
255
+ const text = notes.join("\n");
256
+ assert.ok(text.includes("[Appearance]"), `pi settings present: ${text.slice(0, 200)}`);
257
+ assert.ok(text.includes("[Providers]") && text.includes("Router"), "router section categorized");
258
+ assert.ok(text.includes("[Tasks]") && text.includes("Ponytail"), "ponytail section categorized");
259
+ assert.ok(text.includes("[Plugins]"), "plugins tab present");
260
+ assert.ok(!text.includes("[Modules]"), "standalone Modules tab is gone");
261
+ // Order follows PI_TAB_ORDER: Appearance before Model before Interaction…
262
+ assert.ok(text.indexOf("[Appearance]") < text.indexOf("[Model]"), "taxonomy order");
263
+ assert.ok(text.indexOf("[Model]") < text.indexOf("[Interaction]"));
264
+ });
265
+ });
266
+
267
+ // ── router contribution ─────────────────────────────────────────────────────
268
+
269
+ describe("router config contribution", () => {
270
+ it("buildRouterGroups has prefixed row keys and mutates the working copy", async () => {
271
+ const { buildRouterGroups } = await import("../../router/configPanel.js");
272
+ const cfg = { baseUrl: "http://a", enableReasoning: true };
273
+ const groups = buildRouterGroups(cfg);
274
+ const rows = groups.flatMap((g) => g.rows);
275
+ assert.deepEqual(rows.map((r) => r.key), ["router.baseUrl", "router.enableReasoning"]);
276
+ // ONE section under OMP's Providers tab (the Enable row is prepended by
277
+ // the config module at assembly time).
278
+ assert.equal(groups.length, 1);
279
+ assert.equal(groups[0]!.tab, "Providers");
280
+ assert.equal(groups[0]!.label, "Router");
281
+
282
+ rows[0]!.set("http://b/");
283
+ assert.equal(cfg.baseUrl, "http://b/"); // setter mutates the copy the module handed over
284
+ rows[1]!.set(false);
285
+ assert.equal(cfg.enableReasoning, false);
286
+ });
287
+
288
+ it("routerConfig().save ignores non-router keys (no write, no notify)", async () => {
289
+ const { routerConfig } = await import("../../router/configPanel.js");
290
+ const settingsBefore = existsSync(settingsPath()) ? readFileSync(settingsPath(), "utf8") : null;
291
+ let notified = 0;
292
+ const ctx = { ui: { notify: () => { notified++; } } } as never;
293
+ const cfg = routerConfig({} as never);
294
+ await cfg.save(new Set(["ponytail.defaultMode"]), ctx);
295
+ assert.equal(notified, 0);
296
+ assert.equal(existsSync(settingsPath()) ? readFileSync(settingsPath(), "utf8") : null, settingsBefore);
297
+ });
298
+ });
299
+
300
+ // ── openConfigPanel: fullscreen overlay contract ──────────────────────────
301
+
302
+ describe("openConfigPanel overlay launch", () => {
303
+ it("passes overlay:true + full-viewport options to ctx.ui.custom and resolves on done()", async () => {
304
+ const { openConfigPanel } = await import("../../../lib/panel.js");
305
+ let captured: { overlay?: boolean; overlayOptions?: unknown } | undefined;
306
+ let factory: ((...a: unknown[]) => unknown) | undefined;
307
+ let finish: ((v?: unknown) => void) | undefined;
308
+ const ctx = {
309
+ mode: "tui",
310
+ hasUI: true,
311
+ ui: {
312
+ notify: () => {},
313
+ custom: (f: (...a: unknown[]) => unknown, options?: { overlay?: boolean; overlayOptions?: unknown }) => {
314
+ captured = options;
315
+ factory = f;
316
+ return new Promise((resolve) => { finish = resolve; });
317
+ },
318
+ },
319
+ } as never;
320
+ const p = openConfigPanel({
321
+ ctx,
322
+ cfg: {},
323
+ build: () => [],
324
+ onSave: () => {},
325
+ });
326
+ // The options are resolved synchronously at custom() time; the factory is
327
+ // invoked by the real TUI — here we only contract-check what was passed.
328
+ await new Promise((r) => setImmediate(r));
329
+ assert.ok(captured, "ctx.ui.custom received options");
330
+ assert.equal(captured!.overlay, true);
331
+ const resolved = (captured!.overlayOptions as () => Record<string, unknown>)();
332
+ assert.deepEqual(resolved, { anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0 });
333
+ // done() (the model's close path) resolves the panel promise.
334
+ finish?.();
335
+ await p;
336
+ void factory;
337
+ });
338
+
339
+ it("non-TUI mode still notifies and resolves without opening", async () => {
340
+ const { openConfigPanel } = await import("../../../lib/panel.js");
341
+ const notes: string[] = [];
342
+ let opened = false;
343
+ const ctx = {
344
+ mode: "rpc",
345
+ hasUI: false,
346
+ ui: { notify: (m: string) => notes.push(m), custom: () => { opened = true; } },
347
+ } as never;
348
+ await openConfigPanel({ ctx, cfg: {}, build: () => [] });
349
+ assert.equal(opened, false);
350
+ assert.ok(notes.some((n) => n.includes("TUI")));
351
+ });
352
+ });
353
+
354
+ // ── ponytail contribution ───────────────────────────────────────────────────
355
+
356
+ describe("ponytail config contribution", () => {
357
+ const ponytailHome = join(TMP_HOME, "ponytail-xdg");
358
+
359
+ it("buildPonytailGroups has prefixed keys, enum values + row metadata", async () => {
360
+ const { buildPonytailGroups } = await import("../../ponytail/index.js");
361
+ const cfg = { defaultMode: "full", quietStartup: false, hideStatus: false };
362
+ const groups = buildPonytailGroups(cfg);
363
+ assert.equal(groups[0]!.tab, "Tasks", "ponytail is a task/mode setting in OMP's taxonomy");
364
+ const rows = groups.flatMap((g) => g.rows);
365
+ assert.deepEqual(rows.map((r) => r.key), ["ponytail.defaultMode", "ponytail.quietStartup", "ponytail.hideStatus"]);
366
+ // Closed value set + declared default: the panel cycles these, no free text.
367
+ assert.deepEqual(rows[0]!.values, ["off", "lite", "full", "ultra"]);
368
+ assert.equal(rows[0]!.defaultValue, "full");
369
+ assert.ok(rows.every((r) => r.description), "every ponytail row carries a description");
370
+ rows[1]!.set(true);
371
+ assert.equal(cfg.quietStartup, true);
372
+ });
373
+
374
+ it("save writes defaultMode + bool flags into the ponytail config file", async () => {
375
+ const prevXdg = process.env.XDG_CONFIG_HOME;
376
+ process.env.XDG_CONFIG_HOME = ponytailHome;
377
+ try {
378
+ const { writeDefaultMode } = await import("../../ponytail/lib/config.js");
379
+ writeDefaultMode("lite"); // seed
380
+ const { ponytailConfig } = await import("../../ponytail/index.js");
381
+ const ctx = { ui: { notify: () => {} } } as never;
382
+ const cfg = ponytailConfig();
383
+ for (const r of cfg.groups().flatMap((g) => g.rows)) {
384
+ if (r.key === "ponytail.hideStatus") r.set(true);
385
+ }
386
+ await cfg.save(new Set(["ponytail.hideStatus"]), ctx);
387
+ const written = JSON.parse(readFileSync(join(ponytailHome, "ponytail", "config.json"), "utf8"));
388
+ assert.equal(written.hideStatus, true);
389
+ assert.equal(written.defaultMode, "lite"); // untouched fields preserved
390
+ } finally {
391
+ if (prevXdg === undefined) delete process.env.XDG_CONFIG_HOME;
392
+ else process.env.XDG_CONFIG_HOME = prevXdg;
393
+ }
394
+ });
395
+ });
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Pi-settings contribution tests — all against `SettingsManager.inMemory`,
3
+ * so no file I/O and no dependence on the developer's real settings.
4
+ */
5
+
6
+ import { describe, it } from "node:test";
7
+ import assert from "node:assert/strict";
8
+ import { SettingsManager } from "@earendil-works/pi-coding-agent";
9
+ import { buildPiSettingsGroups, isPiKey, PI_TAB_ORDER } from "../piSettings.js";
10
+
11
+ const rowsOf = (m: SettingsManager) => buildPiSettingsGroups(m).flatMap((g) => g.rows);
12
+ const rowAt = (m: SettingsManager, key: string) => rowsOf(m).find((r) => r.key === key)!;
13
+
14
+ describe("pi settings contribution", () => {
15
+ it("builds OMP-taxonomy tabs with unique keys and sections", () => {
16
+ const groups = buildPiSettingsGroups(SettingsManager.inMemory());
17
+ const keys = groups.flatMap((g) => g.rows.map((r) => r.key));
18
+ assert.equal(new Set(keys).size, keys.length, "row keys are unique");
19
+ // Tab names all belong to OMP's taxonomy.
20
+ for (const g of groups) {
21
+ assert.ok(PI_TAB_ORDER.includes(g.tab as (typeof PI_TAB_ORDER)[number]), `known tab: ${g.tab}`);
22
+ assert.ok(g.rows.every((r) => r.key.startsWith("pi.")), "pi-prefixed keys");
23
+ }
24
+ // The tabs the panel relies on are present.
25
+ const tabs = new Set(groups.map((g) => g.tab));
26
+ for (const t of ["Appearance", "Model", "Interaction", "Context", "Shell"]) {
27
+ assert.ok(tabs.has(t), `tab present: ${t}`);
28
+ }
29
+ });
30
+
31
+ it("isPiKey matches only pi-core keys", () => {
32
+ assert.ok(isPiKey("pi.steeringMode"));
33
+ assert.ok(!isPiKey("ceulen.disabled.router"));
34
+ assert.ok(!isPiKey("router.baseUrl"));
35
+ });
36
+
37
+ it("reads EFFECTIVE values from the manager (defaults included)", () => {
38
+ const m = SettingsManager.inMemory({ steeringMode: "all", hideThinkingBlock: true });
39
+ assert.equal(rowAt(m, "pi.steeringMode").value, "all");
40
+ assert.equal(rowAt(m, "pi.followUpMode").value, "one-at-a-time", "built-in default");
41
+ assert.equal(rowAt(m, "pi.hideThinkingBlock").value, true);
42
+ assert.equal(rowAt(m, "pi.compaction.enabled").value, true, "default auto-compact on");
43
+ });
44
+
45
+ it("changed-from-default is expressed via defaultValue for every settable row", () => {
46
+ // Rows WITHOUT a declared default can never render as changed — the panel
47
+ // only warns when defaultValue is present and differs.
48
+ const rows = rowsOf(SettingsManager.inMemory());
49
+ const noDefault = rows.filter((r) => r.defaultValue === undefined).map((r) => r.key);
50
+ // Free-text rows (theme, default model/provider, shell paths, lists) are
51
+ // intentionally defaultless; everything else must declare one.
52
+ assert.deepEqual(noDefault.sort(), [
53
+ "pi.defaultModel",
54
+ "pi.defaultProvider",
55
+ "pi.enabledModels",
56
+ "pi.npmCommand",
57
+ "pi.shellCommandPrefix",
58
+ "pi.shellPath",
59
+ "pi.theme",
60
+ ].sort());
61
+ });
62
+
63
+ it("setters persist through the manager and are observable via getters", () => {
64
+ const m = SettingsManager.inMemory();
65
+ rowAt(m, "pi.steeringMode").set("all");
66
+ assert.equal(m.getSteeringMode(), "all");
67
+ rowAt(m, "pi.compaction.enabled").set(false);
68
+ assert.equal(m.getCompactionEnabled(), false);
69
+ rowAt(m, "pi.quietStartup").set(true);
70
+ assert.equal(m.getQuietStartup(), true);
71
+ rowAt(m, "pi.defaultProjectTrust").set("never");
72
+ assert.equal(m.getDefaultProjectTrust(), "never");
73
+ rowAt(m, "pi.tuiMode").set("fullscreen");
74
+ assert.equal(m.getTuiMode(), "fullscreen");
75
+ });
76
+
77
+ it("number rows coerce and clamp through the typed setters", () => {
78
+ const m = SettingsManager.inMemory();
79
+ rowAt(m, "pi.editorPaddingX").set(2);
80
+ assert.equal(m.getEditorPaddingX(), 2);
81
+ rowAt(m, "pi.editorPaddingX").set(9); // clamped 0–3 by pi
82
+ assert.equal(m.getEditorPaddingX(), 3);
83
+ rowAt(m, "pi.autocompleteMaxVisible").set(1); // clamped 3–20
84
+ assert.equal(m.getAutocompleteMaxVisible(), 3);
85
+ });
86
+
87
+ it("number rows IGNORE unparseable input instead of throwing (the panel passes typed text)", () => {
88
+ const m = SettingsManager.inMemory();
89
+ const before = m.getHttpIdleTimeoutMs();
90
+ // kindValue returns the raw string when it does not parse; pi's
91
+ // setHttpIdleTimeoutMs THROWS on NaN — the guard must swallow it.
92
+ assert.doesNotThrow(() => rowAt(m, "pi.httpIdleTimeoutMs").set("abc"));
93
+ assert.equal(m.getHttpIdleTimeoutMs(), before, "value unchanged on garbage input");
94
+ // Negative is clamped to 0 (pi throws on < 0).
95
+ assert.doesNotThrow(() => rowAt(m, "pi.httpIdleTimeoutMs").set(-5));
96
+ assert.equal(m.getHttpIdleTimeoutMs(), 0);
97
+ });
98
+
99
+ it("list rows join on read and split on write", () => {
100
+ const m = SettingsManager.inMemory({ enabledModels: ["anthropic/*", "zai/glm-*"] });
101
+ const r = rowAt(m, "pi.enabledModels");
102
+ assert.equal(r.value, "anthropic/* zai/glm-*");
103
+ r.set("openai/gpt-5 router/*");
104
+ assert.deepEqual(m.getEnabledModels(), ["openai/gpt-5", "router/*"]);
105
+ r.set("");
106
+ assert.equal(m.getEnabledModels(), undefined, "empty clears the scope");
107
+ });
108
+
109
+ it("warnings merge into the existing object instead of replacing it", () => {
110
+ const m = SettingsManager.inMemory({ warnings: { anthropicExtraUsage: false } });
111
+ rowAt(m, "pi.warnings.anthropicExtraUsage").set(true);
112
+ assert.deepEqual(m.getWarnings(), { anthropicExtraUsage: true });
113
+ });
114
+
115
+ it("rows carry descriptions and enum rows declare closed value sets", () => {
116
+ const rows = rowsOf(SettingsManager.inMemory());
117
+ assert.ok(rows.every((r) => (r.description ?? "").length > 0), "every pi row is described");
118
+ const steering = rowAt(SettingsManager.inMemory(), "pi.steeringMode");
119
+ assert.deepEqual(steering.values, ["one-at-a-time", "all"], "closed value set cycles");
120
+ const trust = rowAt(SettingsManager.inMemory(), "pi.defaultProjectTrust");
121
+ assert.deepEqual(trust.values, ["ask", "always", "never"]);
122
+ assert.ok(trust.warning, "auto-trust carries a risk note");
123
+ });
124
+
125
+ it("without a lookup the Theme and Default model rows stay plain text rows", () => {
126
+ const m = SettingsManager.inMemory({ theme: "dark", defaultProvider: "zai", defaultModel: "glm-5" });
127
+ const theme = rowAt(m, "pi.theme");
128
+ assert.equal(theme.menu, undefined);
129
+ assert.equal(theme.preview, undefined);
130
+ theme.set("light");
131
+ assert.equal(m.getThemeSetting(), "light", "plain setter still persists");
132
+ const model = rowAt(m, "pi.defaultModel");
133
+ assert.equal(model.menu, undefined);
134
+ model.set("gpt-5");
135
+ assert.equal(m.getDefaultModel(), "gpt-5");
136
+ });
137
+
138
+ it("theme lookup: menu lists themes (+ the unlisted current value first), preview cancels via the row hook", () => {
139
+ const m = SettingsManager.inMemory();
140
+ const previewed: string[] = [];
141
+ const applied: string[] = [];
142
+ let restores = 0;
143
+ const rows = buildPiSettingsGroups(m, {
144
+ themes: () => ["dark", "light"],
145
+ previewTheme: (n) => previewed.push(n),
146
+ restoreTheme: () => { restores++; },
147
+ applyTheme: (n) => applied.push(n),
148
+ }).flatMap((g) => g.rows);
149
+ const theme = rows.find((r) => r.key === "pi.theme")!;
150
+ assert.ok(theme.menu, "theme row gained a menu");
151
+ assert.deepEqual(theme.menu!().map((o) => o.value), ["dark", "light"]);
152
+ // A current setting outside the list is offered first so it stays visible.
153
+ m.setTheme("custom-x");
154
+ assert.deepEqual(theme.menu!().map((o) => o.value), ["custom-x", "dark", "light"]);
155
+ theme.preview!("light");
156
+ assert.deepEqual(previewed, ["light"], "preview routed to the non-persisting hook");
157
+ assert.equal(m.getThemeSetting(), "custom-x", "preview never writes the manager");
158
+ theme.previewCancel!();
159
+ assert.equal(restores, 1, "cancel routed to the restore hook");
160
+ theme.set("light");
161
+ assert.equal(m.getThemeSetting(), "light", "commit persists through the manager");
162
+ assert.deepEqual(applied, ["light"], "commit also live-applies");
163
+ });
164
+
165
+ it("model lookup: menu is provider/id, commit writes the pair atomically", () => {
166
+ const m = SettingsManager.inMemory({ defaultProvider: "zai", defaultModel: "glm-5" });
167
+ const rows = buildPiSettingsGroups(m, {
168
+ models: () => [
169
+ { provider: "zai", id: "glm-5", description: "GLM-5" },
170
+ { provider: "openai", id: "gpt-5" },
171
+ ],
172
+ }).flatMap((g) => g.rows);
173
+ const model = rows.find((r) => r.key === "pi.defaultModel")!;
174
+ assert.equal(model.value, "zai/glm-5", "value renders as provider/id");
175
+ assert.deepEqual(model.menu!().map((o) => o.value), ["zai/glm-5", "openai/gpt-5"]);
176
+ assert.equal(model.menu!()[1]!.description, undefined, "no description when the model has none");
177
+ model.set("openai/gpt-5");
178
+ assert.equal(m.getDefaultProvider(), "openai");
179
+ assert.equal(m.getDefaultModel(), "gpt-5");
180
+ // Malformed values keep the previous pair instead of writing garbage.
181
+ model.set("no-slash");
182
+ assert.equal(m.getDefaultProvider(), "openai");
183
+ assert.equal(m.getDefaultModel(), "gpt-5");
184
+ });
185
+ });