ceulen 0.7.0 → 0.8.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 (33) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/extensions/lib/registry.test.ts +67 -0
  3. package/extensions/lib/registry.ts +17 -7
  4. package/extensions/modules/advisor/index.ts +20 -2
  5. package/extensions/modules/advisor/lib/watcher.ts +3 -1
  6. package/extensions/modules/advisor/test/module.test.ts +64 -1
  7. package/extensions/modules/composer/test/module.test.ts +2 -2
  8. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  9. package/extensions/modules/munin/configPanel.ts +5 -2
  10. package/extensions/modules/munin/test/configPanel.test.ts +27 -2
  11. package/extensions/modules/router/configPanel.ts +24 -10
  12. package/extensions/modules/router/lib/client.ts +6 -4
  13. package/extensions/modules/router/test/unit.test.ts +83 -2
  14. package/extensions/modules/rules/index.ts +120 -0
  15. package/extensions/modules/rules/lib/rules.ts +348 -0
  16. package/extensions/modules/rules/test/lib.test.ts +263 -0
  17. package/extensions/modules/rules/test/module.test.ts +222 -0
  18. package/extensions/modules/subagent/index.ts +19 -6
  19. package/extensions/modules/subagent/lib/routing.ts +11 -6
  20. package/extensions/modules/subagent/lib/security.ts +12 -1
  21. package/extensions/modules/subagent/test/routing.test.ts +174 -0
  22. package/extensions/modules/todo/index.ts +478 -0
  23. package/extensions/modules/todo/test/todo.test.ts +252 -0
  24. package/extensions/modules/usage/index.ts +11 -0
  25. package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
  26. package/extensions/modules/web/configPanel.ts +38 -13
  27. package/extensions/modules/web/lib/settings.ts +11 -2
  28. package/extensions/modules/web/test/configPanel.test.ts +67 -1
  29. package/extensions/modules/zai/configPanel.ts +5 -2
  30. package/extensions/modules/zai/lib/signing.ts +4 -1
  31. package/extensions/modules/zai/test/configPanel.test.ts +23 -0
  32. package/extensions/modules/zai/test/signing.test.ts +19 -0
  33. package/package.json +2 -2
@@ -0,0 +1,252 @@
1
+ /**
2
+ * todo module tests — the state machine, persistence rehydrate, and the
3
+ * footer indicator. Untyped harness stub: only the pi surface the module
4
+ * touches (usage/ponytail test tradition).
5
+ */
6
+
7
+ import assert from "node:assert/strict";
8
+ import { describe, it } from "node:test";
9
+
10
+ import todoModule, {
11
+ TODO_ENTRY_TYPE,
12
+ TODO_STATUS_KEY,
13
+ applyTodo,
14
+ resolveTodoPhases,
15
+ statusLine,
16
+ type TodoPhase,
17
+ } from "../index.ts";
18
+
19
+ type Params = Parameters<typeof applyTodo>[1];
20
+ const op = (o: Record<string, unknown>) => o as unknown as Params;
21
+
22
+ /** Apply an action to a list and return the resulting phases (throws on error). */
23
+ function run(current: TodoPhase[], params: Record<string, unknown>): TodoPhase[] {
24
+ const r = applyTodo(current, op(params));
25
+ assert.deepEqual(r.errors, [], `unexpected errors: ${r.errors}`);
26
+ return r.phases;
27
+ }
28
+ function fail(current: TodoPhase[], params: Record<string, unknown>): string[] {
29
+ const r = applyTodo(current, op(params));
30
+ assert.ok(r.errors.length > 0, "expected an error");
31
+ assert.equal(r.changed, false);
32
+ return r.errors;
33
+ }
34
+
35
+ const seeded = () =>
36
+ run([], {
37
+ action: "init",
38
+ phases: [{ title: "Read the repo" }, { title: "Port the tool" }, { title: "Verify" }],
39
+ });
40
+
41
+ function createPiHarness() {
42
+ const events = new Map<string, (event: unknown, ctx: unknown) => unknown>();
43
+ const commands = new Map<string, unknown>();
44
+ const tools = new Map<string, any>();
45
+ const entries: Array<{ customType: string; data: unknown }> = [];
46
+ let branchEntries: unknown[] = [];
47
+ const statusCalls: Array<[string, string | undefined]> = [];
48
+ const notifications: string[] = [];
49
+
50
+ const ui = {
51
+ notify: (m: string) => { notifications.push(m); },
52
+ setStatus: (k: string, t: string | undefined) => { statusCalls.push([k, t]); },
53
+ };
54
+ const ctx = { ui, sessionManager: { getBranch: () => branchEntries } };
55
+
56
+ const pi = {
57
+ on: (n: string, h: any) => { events.set(n, h); },
58
+ registerTool: (t: any) => { tools.set(t.name, t); },
59
+ registerCommand: (n: string, o: any) => { commands.set(n, o); },
60
+ appendEntry: (customType: string, data: unknown) => { entries.push({ customType, data }); },
61
+ };
62
+ todoModule(pi as never);
63
+
64
+ return {
65
+ events, commands, tools, entries, statusCalls, notifications, ui, ctx,
66
+ setBranch: (e: unknown[]) => { branchEntries = e; },
67
+ /** Fire the tool with params through the real execute() path. */
68
+ call: (params: Record<string, unknown>) => tools.get("todo").execute("call-1", op(params), undefined, undefined, ctx),
69
+ };
70
+ }
71
+
72
+ describe("todo state machine", () => {
73
+ it("init assigns stable ids, replaces the whole list, and auto-starts the first phase", () => {
74
+ const phases = seeded();
75
+ assert.deepEqual(phases.map((p) => [p.id, p.status]), [["p1", "in_progress"], ["p2", "pending"], ["p3", "pending"]]);
76
+ const replaced = run(phases, { action: "init", phases: [{ id: "a", title: "Only" }] });
77
+ assert.deepEqual(replaced.map((p) => p.id), ["a"]);
78
+ });
79
+
80
+ it("start marks in_progress; a second start ERRORS while one is running", () => {
81
+ // seeded() already auto-started p1 — p2 must be forced.
82
+ assert.match(fail(seeded(), { action: "start", id: "p2" })[0], /already in_progress/);
83
+ const forced = run(seeded(), { action: "start", id: "p2", force: true });
84
+ assert.deepEqual(forced.map((p) => p.status), ["pending", "in_progress", "pending"]);
85
+ // An explicit start that finishes the running phase advances the pointer by itself.
86
+ assert.equal(run(seeded(), { action: "done", id: "p1" })[1].status, "in_progress");
87
+ });
88
+
89
+ it("done marks done (idempotent) and never reopens a finished phase", () => {
90
+ const done = run(run(seeded(), { action: "done", id: "p1" }), { action: "done", id: "p3" });
91
+ // p2 auto-started when p1 completed; the out-of-order done of p3 leaves it running.
92
+ assert.deepEqual(done.map((p) => p.status), ["done", "in_progress", "done"]);
93
+ assert.equal(run(done, { action: "done", id: "p3" })[2].status, "done", "done of already-done stays done");
94
+ });
95
+
96
+ it("block/unblock set blockedBy; a blocked phase is skipped by the pointer", () => {
97
+ // p2 waits on p3 — a blocker that stays UNMET after p1 completes.
98
+ const blocked = run(seeded(), { action: "block", id: "p2", blockedBy: ["p3"] });
99
+ assert.deepEqual(blocked[1].blockedBy, ["p3"]);
100
+
101
+ // p1 completes → the pointer must SKIP blocked p2 and land on p3.
102
+ const advanced = run(blocked, { action: "done", id: "p1" });
103
+ assert.deepEqual(advanced.map((p) => p.status), ["done", "pending", "in_progress"]);
104
+ assert.equal(statusLine(advanced), "▸ 1/3 done · in_progress: Verify · 1 blocked");
105
+
106
+ // A met blocker unblocks the phase — but never steals a running pointer.
107
+ const unblocked = run(blocked, { action: "unblock", id: "p2" });
108
+ assert.deepEqual(unblocked[1].blockedBy, []);
109
+ const partial = run(run(blocked, { action: "block", id: "p2", blockedBy: ["p1"] }), { action: "unblock", id: "p2", blockedBy: ["p3"] });
110
+ assert.deepEqual(partial[1].blockedBy, ["p1"], "unblock drops only the named edge");
111
+ });
112
+
113
+ it("append adds one phase with a fresh id and rejects duplicates", () => {
114
+ const appended = run(seeded(), { action: "append", phases: [{ title: "Ship it" }] });
115
+ assert.deepEqual(appended.map((p) => p.id), ["p1", "p2", "p3", "p4"]);
116
+ assert.match(fail(appended, { action: "append", phases: [{ title: "Ship it" }] })[0], /already exists/);
117
+ });
118
+
119
+ it("rm removes a phase (and its dangling blocker edges), or clears the list", () => {
120
+ const blocked = run(seeded(), { action: "block", id: "p3", blockedBy: ["p2"] });
121
+ const removed = run(blocked, { action: "rm", id: "p2" });
122
+ assert.deepEqual(removed.map((p) => p.id), ["p1", "p3"]);
123
+ assert.deepEqual(removed[1].blockedBy, [], "the removed phase is no longer a blocker");
124
+ assert.deepEqual(run(seeded(), { action: "rm" }), [], "rm without an id clears");
125
+ });
126
+
127
+ it("errors: unknown phase, block with no blocker, unknown blocker, self-block, duplicate ids", () => {
128
+ const phases = seeded();
129
+ assert.match(fail(phases, { action: "start", id: "nope" })[0], /not found/);
130
+ assert.match(fail(phases, { action: "start" })[0], /Missing phase id/);
131
+ assert.match(fail(phases, { action: "block", id: "p1" })[0], /needs blockedBy/);
132
+ assert.match(fail(phases, { action: "block", id: "p1", blockedBy: ["ghost"] })[0], /not a phase in this list/);
133
+ assert.match(fail(phases, { action: "block", id: "p1", blockedBy: ["p1"] })[0], /cannot block itself/);
134
+ assert.match(fail(phases, { action: "init", phases: [{ id: "x", title: "A" }, { id: "x", title: "B" }] })[0], /Duplicate phase id/);
135
+ assert.match(fail(phases, { action: "init", phases: [{ title: "A", blockedBy: ["zz"] }] })[0], /unknown phase "zz"/);
136
+ });
137
+
138
+ it("view never changes the list", () => {
139
+ const phases = seeded();
140
+ const r = applyTodo(phases, op({ action: "view" }));
141
+ assert.deepEqual(r.errors, []);
142
+ assert.equal(r.changed, false);
143
+ assert.deepEqual(r.phases, phases);
144
+ });
145
+ });
146
+
147
+ describe("status indicator text", () => {
148
+ it("counts done/total, names the running phase, and clears when done", () => {
149
+ assert.equal(statusLine([]), undefined, "empty list → cleared");
150
+ assert.equal(statusLine(seeded()), "▸ 0/3 done · in_progress: Read the repo");
151
+ const allDone = run(run(run(seeded(), { action: "done", id: "p1" }), { action: "done", id: "p2" }), { action: "done", id: "p3" });
152
+ assert.equal(statusLine(allDone), undefined, "all done → cleared");
153
+ // A list whose remaining phases are all blocked names no pointer.
154
+ const blocked = run(run(seeded(), { action: "block", id: "p1", blockedBy: ["p2"] }), { action: "block", id: "p2", blockedBy: ["p3"] });
155
+ assert.equal(statusLine(blocked), "▸ 0/3 done · next: Verify · 2 blocked");
156
+ });
157
+ });
158
+
159
+ describe("module wiring", () => {
160
+ it("registers one tool and one command", () => {
161
+ const h = createPiHarness();
162
+ assert.deepEqual([...h.tools.keys()], ["todo"]);
163
+ assert.deepEqual([...h.commands.keys()], ["todo"]);
164
+ });
165
+
166
+ it("persists to ceulen-todo on every mutation, never on view", async () => {
167
+ const h = createPiHarness();
168
+ await h.call({ action: "init", phases: [{ title: "One" }, { title: "Two" }] });
169
+ await h.call({ action: "view" });
170
+ await h.call({ action: "done", id: "p1" });
171
+ assert.deepEqual(h.entries.map((e) => e.customType), [TODO_ENTRY_TYPE, TODO_ENTRY_TYPE]);
172
+ assert.deepEqual((h.entries[1].data as any).phases.map((p: TodoPhase) => p.status), ["done", "in_progress"]);
173
+ });
174
+
175
+ it("a failed op keeps the previous state and reports it as an error", async () => {
176
+ const h = createPiHarness();
177
+ await h.call({ action: "init", phases: [{ title: "One" }] });
178
+ const before = h.entries.length;
179
+ const r = await h.call({ action: "start", id: "ghost" });
180
+ assert.equal(r.isError, true);
181
+ assert.match(r.content[0].text, /not found/);
182
+ assert.match(r.content[0].text, /\[p1\] One/, "the board stays at the previous state");
183
+ assert.equal(h.entries.length, before, "no persistence on error");
184
+ });
185
+
186
+ it("mutating results restate the batch contract; a view does not", async () => {
187
+ const h = createPiHarness();
188
+ const init = await h.call({ action: "init", phases: [{ title: "One" }] });
189
+ assert.match(init.content[0].text, /never call todo alone/);
190
+ assert.match(init.content[0].text, /1\. ▸ \[p1\] One/, "the board renders glyph + id + title");
191
+ const view = await h.call({ action: "view" });
192
+ assert.doesNotMatch(view.content[0].text, /never call todo alone/);
193
+ });
194
+
195
+ it("the tool carries the batch contract as guidelines", () => {
196
+ const h = createPiHarness();
197
+ const guidelines: string[] = h.tools.get("todo").promptGuidelines;
198
+ assert.ok(guidelines.some((g) => /NEVER call todo alone/.test(g)));
199
+ assert.ok(guidelines.some((g) => /init alongside the FIRST work call/.test(g)));
200
+ assert.ok(guidelines.some((g) => /SAME call that starts the next action/.test(g)));
201
+ });
202
+
203
+ it("sets the footer indicator on mutation and clears it on shutdown", async () => {
204
+ const h = createPiHarness();
205
+ await h.call({ action: "init", phases: [{ title: "One" }] });
206
+ assert.deepEqual(h.statusCalls.at(-1), [TODO_STATUS_KEY, "▸ 0/1 done · in_progress: One"]);
207
+ await h.call({ action: "done", id: "p1" });
208
+ assert.deepEqual(h.statusCalls.at(-1), [TODO_STATUS_KEY, undefined], "all done → cleared");
209
+ await h.events.get("session_shutdown")!({}, h.ctx);
210
+ assert.deepEqual(h.statusCalls.at(-1), [TODO_STATUS_KEY, undefined]);
211
+ });
212
+
213
+ it("rehydrates the LAST ceulen-todo entry on session_start", async () => {
214
+ const h = createPiHarness();
215
+ h.setBranch([
216
+ { type: "message" },
217
+ { type: "custom", customType: TODO_ENTRY_TYPE, data: { phases: [{ id: "old", title: "Stale", status: "pending", blockedBy: [] }] } },
218
+ { type: "custom", customType: "other-entry", data: {} },
219
+ { type: "custom", customType: TODO_ENTRY_TYPE, data: { phases: [{ id: "a", title: "Resumed", status: "in_progress", blockedBy: [] }] } },
220
+ ]);
221
+ await h.events.get("session_start")!({}, h.ctx);
222
+ assert.deepEqual(h.statusCalls.at(-1), [TODO_STATUS_KEY, "▸ 0/1 done · in_progress: Resumed"]);
223
+ await h.call({ action: "done", id: "a" });
224
+ assert.deepEqual((h.entries.at(-1)!.data as any).phases[0].title, "Resumed");
225
+ });
226
+
227
+ it("resolveTodoPhases ignores malformed entries and unknown customTypes", () => {
228
+ assert.deepEqual(resolveTodoPhases(undefined), []);
229
+ assert.deepEqual(resolveTodoPhases([{ type: "custom", customType: "other", data: { phases: [{ id: "x", title: "y", status: "pending", blockedBy: [] }] } }]), []);
230
+ // Junk entries without a phases array are skipped, not fatal.
231
+ assert.deepEqual(
232
+ resolveTodoPhases([{ type: "custom", customType: TODO_ENTRY_TYPE, data: {} }, { type: "custom", customType: TODO_ENTRY_TYPE, data: { phases: [{ id: "a", title: "Good", status: "pending", blockedBy: [], junk: 1 }] } }]).map((p) => p.id),
233
+ ["a"],
234
+ );
235
+ });
236
+ });
237
+
238
+ describe("/todo command", () => {
239
+ it("bare prints the board, unknown warns, clear resets", async () => {
240
+ const h = createPiHarness();
241
+ await h.call({ action: "init", phases: [{ title: "One" }] });
242
+ const cmd = h.commands.get("todo") as any;
243
+ await cmd.handler("", h.ctx);
244
+ assert.match(h.notifications.at(-1)!, /\[p1\] One/);
245
+ await cmd.handler("bogus", h.ctx);
246
+ assert.match(h.notifications.at(-1)!, /Unknown subcommand/);
247
+ await cmd.handler("clear", h.ctx);
248
+ assert.equal(h.notifications.at(-1), "Todo list cleared.");
249
+ await cmd.handler("", h.ctx);
250
+ assert.equal(h.notifications.at(-1), "Todo list is empty.");
251
+ });
252
+ });
@@ -1870,6 +1870,17 @@ export default function (pi: ExtensionAPI) {
1870
1870
  state.ctx = ctx;
1871
1871
  resetGenRate(); // fresh session, fresh Generation Rate item
1872
1872
  resetUsageItem(); // ...and fresh usage windows
1873
+ // The cumulative figures are labelled "Session cost"/"Session avg" in
1874
+ // /usage, so they must not survive into the next session (/new, reload,
1875
+ // switch, fork). session_start fires before the new session's first
1876
+ // message_end, so an in-flight review of the old session cannot re-add
1877
+ // into these (its message_end precedes this handler).
1878
+ state.cumulativeCost = 0;
1879
+ state.cumulativeOutput = 0;
1880
+ state.cumulativeDurationMs = 0;
1881
+ state.responseStartPerf = undefined; // a request spanning the switch has no valid elapsed
1882
+ state.lastTokPerSec = undefined;
1883
+ state.lastTokPerSecLabel = undefined;
1873
1884
  updateActiveAdapter(state, ctx.model);
1874
1885
  if (state.adapter) deferRefresh(state, true);
1875
1886
  });
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Session-scoped accumulators: /usage labels these figures "Session cost" and
3
+ * "Session avg", so they must not survive session_start (/new, reload, switch,
4
+ * fork) — before the fix they were created once at module load and kept
5
+ * accumulating, so the second session reported the first session's cost.
6
+ *
7
+ * Unsupported provider ("ollama") on purpose: no adapter, so no refresh timer
8
+ * is armed (no open handles) and renderSubscriptionLine takes the tok/s branch.
9
+ */
10
+
11
+ import assert from "node:assert/strict";
12
+ import { test } from "node:test";
13
+ import extension, { renderSubscriptionLine, type State } from "../index.ts";
14
+
15
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
16
+
17
+ function harness() {
18
+ const handlers: Record<string, (event: any, ctx: any) => any> = {};
19
+ const statuses: (string | undefined)[] = [];
20
+ const pi = {
21
+ on(type: string, fn: any) {
22
+ handlers[type] = fn;
23
+ },
24
+ registerCommand() {},
25
+ registerMessageRenderer() {},
26
+ };
27
+ const ctx = {
28
+ model: { provider: "ollama", id: "llama" }, // unsupported → no adapter, no timer
29
+ isProjectTrusted: () => false,
30
+ ui: {
31
+ theme: { fg: (_c: string, s: string) => s },
32
+ setStatus(_key: string, value?: string) {
33
+ statuses.push(value);
34
+ },
35
+ notify() {},
36
+ },
37
+ getContextUsage: () => undefined,
38
+ };
39
+ const state = extension(pi as never) as State;
40
+ /** One assistant response: publishes tok/s and accumulates the session figures. */
41
+ const respond = async (cost: number) => {
42
+ await handlers.before_provider_request!({}, ctx);
43
+ await sleep(110); // clear the 100ms noise floor
44
+ await handlers.message_end!({ message: { role: "assistant", usage: { output: 1000, reasoning: 400, cost: { total: cost } } } }, ctx);
45
+ };
46
+ return { handlers, ctx, state, statuses, respond };
47
+ }
48
+
49
+ test("session_start resets the session cost/avg accumulators (a second session never inherits the first)", async () => {
50
+ const h = harness();
51
+ await h.handlers.session_start!({ reason: "startup" }, h.ctx);
52
+ assert.equal(h.state.cumulativeCost, 0, "fresh session starts at zero cost");
53
+
54
+ await h.respond(0.05);
55
+ assert.ok(h.state.cumulativeCost > 0, "cost accumulates within the session");
56
+ assert.ok(h.state.cumulativeOutput > 0 && h.state.cumulativeDurationMs > 0, "tok/s samples accumulate the session average");
57
+ assert.ok(h.state.lastTokPerSec !== undefined, "last response rate published");
58
+
59
+ // The /usage footer/session-avg surface reads these fields directly.
60
+ renderSubscriptionLine(h.state);
61
+ assert.match(String(h.statuses.at(-1)), /tok\/s/, "last response rate rendered before the switch");
62
+
63
+ // /new (or reload/switch/fork): the accumulators must reset with the session.
64
+ await h.handlers.session_start!({ reason: "new" }, h.ctx);
65
+ assert.equal(h.state.cumulativeCost, 0, "session cost reset — not the previous session's total");
66
+ assert.equal(h.state.cumulativeOutput, 0, "session output reset");
67
+ assert.equal(h.state.cumulativeDurationMs, 0, "session duration reset");
68
+ assert.equal(h.state.lastTokPerSec, undefined, "last-response rate cleared with the session");
69
+ assert.equal(h.state.lastTokPerSecLabel, undefined, "last-response label cleared too (it belongs to the old session)");
70
+ assert.equal(h.state.responseStartPerf, undefined, "no half-measured request carried across the switch");
71
+
72
+ renderSubscriptionLine(h.state);
73
+ assert.equal(h.state.cumulativeCost, 0);
74
+ const last = String(h.statuses.at(-1));
75
+ assert.ok(!/Session avg|tok\/s/.test(last), `session-scoped tok/s surfaces gone after the switch (got ${JSON.stringify(last)})`);
76
+
77
+ // Positive control: the reset is per SESSION, not per message — the new
78
+ // session accumulates its own figures normally. (No separate lifetime/aggregate
79
+ // counter exists in State, so the reset has nothing else to clobber: cost,
80
+ // output, duration and the last-response rate are all session-scoped.)
81
+ await h.respond(0.01);
82
+ assert.ok(h.state.cumulativeCost > 0 && h.state.cumulativeCost < 0.02, "the new session counts only its own cost");
83
+ await h.respond(0.01);
84
+ assert.ok(h.state.cumulativeCost > 0.015, "messages within one session still accumulate");
85
+ });
@@ -20,7 +20,8 @@ import {
20
20
  } from "./lib/config.js";
21
21
  import {
22
22
  ENV_TO_SETTINGS_KEY,
23
- readWebSettings,
23
+ readProjectWebSection,
24
+ sectionValue,
24
25
  writeWebSection,
25
26
  } from "./lib/settings.js";
26
27
 
@@ -146,6 +147,31 @@ export function buildWebGroups(working: Record<string, string>): PanelGroup[] {
146
147
 
147
148
  const OWNED_PREFIX = "web.";
148
149
 
150
+ /** The save patch for the rows edited since the pre-edit snapshot. Number rows
151
+ * persist as numbers (timeoutMs semantics), strings as strings, and an empty
152
+ * string clears the key (writeWebSection semantics). Free text that is not a
153
+ * finite number is SKIPPED — writing 0 would clobber the stored cap with a
154
+ * value the consumer then clamps (or bricks the timeout loaders). Exported
155
+ * for tests. */
156
+ export function diffWebPatch(
157
+ working: Record<string, string>,
158
+ before: Record<string, string>,
159
+ ): Record<string, string | number> {
160
+ const patch: Record<string, string | number> = {};
161
+ for (const spec of webRowSpecs()) {
162
+ if (working[spec.key] === before[spec.key]) continue;
163
+ const raw = working[spec.key] ?? "";
164
+ if (spec.kind === "number" && raw !== "") {
165
+ const n = Number.parseInt(raw, 10);
166
+ if (!Number.isFinite(n)) continue; // garbage → leave the stored value alone
167
+ patch[spec.key] = n;
168
+ } else {
169
+ patch[spec.key] = raw;
170
+ }
171
+ }
172
+ return patch;
173
+ }
174
+
149
175
  /** web's ModuleConfig for the central /config panel. cwd/trust come from the
150
176
  * save ctx (factories receive none); reads use process.cwd(), matching
151
177
  * munin's panel pattern. */
@@ -165,24 +191,23 @@ export function webConfig(): ModuleConfig {
165
191
  // Diff against the pre-edit effective values: only changed keys are
166
192
  // written (masked rows start empty — an untouched masked row diffs to
167
193
  // no change).
168
- const patch: Record<string, string | number> = {};
169
- for (const spec of webRowSpecs()) {
170
- if (working[spec.key] !== before[spec.key]) {
171
- // number rows persist as numbers (timeoutMs semantics), strings as
172
- // strings; empty string clears the key (writeWebSection semantics).
173
- patch[spec.key] = spec.kind === "number" && working[spec.key] !== ""
174
- ? (Number.parseInt(working[spec.key], 10) || 0)
175
- : working[spec.key];
176
- }
177
- }
194
+ const patch = diffWebPatch(working, before);
178
195
  writeWebSection(patch, target);
179
196
  const notes = [`Web config saved to ${target} — effective immediately (read per tool call).`];
180
197
  // Disclose env vars that still override saved values, and a trusted
181
198
  // project file that shadows a field.
182
199
  const envOverrides = webRowSpecs().filter((s) => patch[s.key] !== undefined && process.env[s.envVar]).map((s) => s.envVar);
183
200
  if (envOverrides.length) notes.push(`Still overridden by env: ${envOverrides.join(", ")}.`);
184
- const project = readWebSettings(ctx.cwd, ctx.isProjectTrusted?.() === true);
185
- const shadowed = Object.keys(patch).filter((k) => project[k] !== undefined && project[k] !== "");
201
+ // Resolve through the SAME lookup the runtime uses, so a hand-written
202
+ // NESTED project entry (web.brave.apiKey as {brave:{apiKey}}) is
203
+ // disclosed instead of shadowing the save silently. The PROJECT layer
204
+ // alone — a merged read reports the just-written global key as a shadow.
205
+ const shadowed = ctx.isProjectTrusted?.() === true
206
+ ? Object.keys(patch).filter((k) => {
207
+ const v = sectionValue(readProjectWebSection(ctx.cwd), k);
208
+ return v !== undefined && v !== null && v !== "";
209
+ })
210
+ : [];
186
211
  if (shadowed.length) notes.push(`A trusted project .pi/settings.json web section shadows: ${shadowed.join(", ")}.`);
187
212
  ctx.ui.notify(notes.join(" "), "info");
188
213
  },
@@ -54,10 +54,19 @@ export function readWebSettings(cwd = process.cwd(), trusted = isProjectTrusted(
54
54
  return { ...global, ...readSection(path.join(path.resolve(cwd), ".pi", "settings.json")) };
55
55
  }
56
56
 
57
+ /** The project `.pi/settings.json` `web` section ALONE (no global merge) — the
58
+ * only layer that can shadow a GLOBAL /config save. Used for shadow disclosure
59
+ * (a merged read would report the just-written global key as a shadow). */
60
+ export function readProjectWebSection(cwd: string): WebSettings {
61
+ return readSection(path.join(path.resolve(cwd), ".pi", "settings.json"));
62
+ }
63
+
57
64
  /** Read one value from a `web` section by settings key. Accepts BOTH the
58
65
  * flat panel form (`"brave.apiKey"`) and a nested form (`brave.apiKey` as
59
- * { brave: { apiKey } } path) so hand-written settings of either shape work. */
60
- function sectionValue(section: WebSettings, key: string): unknown {
66
+ * { brave: { apiKey } } path) so hand-written settings of either shape work.
67
+ * Exported so the /config panel resolves shadow disclosure the same way the
68
+ * runtime does. */
69
+ export function sectionValue(section: WebSettings, key: string): unknown {
61
70
  if (key in section) return section[key];
62
71
  const parts = key.split(".");
63
72
  let cur: unknown = section;
@@ -7,7 +7,7 @@ import fs from "node:fs";
7
7
  import os from "node:os";
8
8
  import path from "node:path";
9
9
 
10
- import { buildWebGroups, readWebRowValues, webConfig } from "../configPanel";
10
+ import { buildWebGroups, diffWebPatch, readWebRowValues, webConfig } from "../configPanel";
11
11
  import { writeWebSection } from "../lib/settings";
12
12
 
13
13
  function tmpAgentDir(): string {
@@ -129,4 +129,70 @@ describe("web configPanel", () => {
129
129
  delete process.env.PI_CODING_AGENT_DIR;
130
130
  }
131
131
  });
132
+
133
+ it("diffWebPatch: free-text garbage on a number row leaves the key untouched", () => {
134
+ // Live-found regression: parseInt('abc') || 0 wrote a 0 cap to disk, which
135
+ // the consumer then clamped — silently clobbering the user's real value.
136
+ const before = { "image.dailyCap": "20", "crawl4ai.timeoutMs": "60000", "brave.apiKey": "old" };
137
+ assert.deepEqual(diffWebPatch({ ...before, "image.dailyCap": "abc" }, before), {}, "garbage number row skipped, never 0");
138
+ // A real number still persists as a number; empty string still clears.
139
+ assert.deepEqual(diffWebPatch({ ...before, "crawl4ai.timeoutMs": "45000" }, before), { "crawl4ai.timeoutMs": 45000 });
140
+ assert.deepEqual(diffWebPatch({ ...before, "image.dailyCap": "" }, before), { "image.dailyCap": "" });
141
+ });
142
+
143
+ it("save keeps the stored cap when the panel edit is garbage ('abc' → no write)", async () => {
144
+ const dir = tmpAgentDir();
145
+ try {
146
+ writeWebSection({ "image.dailyCap": 20 }, path.join(dir, "settings.json"));
147
+ const cfg = webConfig();
148
+ cfg.groups()[0]!.rows.find((r) => r.key === "web.image.dailyCap")!.set("abc");
149
+ const ctx = { cwd: "/nonexistent", ui: { notify: () => {} }, isProjectTrusted: () => false } as never;
150
+ await cfg.save(new Set(["web.image.dailyCap"]), ctx);
151
+ const raw = JSON.parse(fs.readFileSync(path.join(dir, "settings.json"), "utf8"));
152
+ assert.equal(raw.web["image.dailyCap"], 20, "stored cap survives a garbage edit");
153
+ } finally {
154
+ fs.rmSync(dir, { recursive: true, force: true });
155
+ delete process.env.PI_CODING_AGENT_DIR;
156
+ }
157
+ });
158
+
159
+ it("discloses a NESTED project web entry that shadows the save", async () => {
160
+ const dir = tmpAgentDir();
161
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "web-nested-"));
162
+ try {
163
+ // Hand-written nested shape: the flat panel key is NOT a top-level key.
164
+ fs.mkdirSync(path.join(cwd, ".pi"), { recursive: true });
165
+ fs.writeFileSync(path.join(cwd, ".pi", "settings.json"), JSON.stringify({ web: { brave: { apiKey: "nested-project-key" } } }));
166
+ const cfg = webConfig();
167
+ cfg.groups()[0]!.rows.find((r) => r.key === "web.brave.apiKey")!.set("panel-key");
168
+ const notifications: string[] = [];
169
+ const ctx = { cwd, ui: { notify: (m: string) => notifications.push(m) }, isProjectTrusted: () => true } as never;
170
+ await cfg.save(new Set(["web.brave.apiKey"]), ctx);
171
+ const note = notifications.join(" ");
172
+ assert.match(note, /shadows: brave\.apiKey/, note);
173
+ } finally {
174
+ fs.rmSync(dir, { recursive: true, force: true });
175
+ fs.rmSync(cwd, { recursive: true, force: true });
176
+ delete process.env.PI_CODING_AGENT_DIR;
177
+ }
178
+ });
179
+
180
+ it("trusted save with no project web section reports no phantom shadow", async () => {
181
+ const dir = tmpAgentDir();
182
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "web-noproj-"));
183
+ try {
184
+ const cfg = webConfig();
185
+ cfg.groups()[0]!.rows.find((r) => r.key === "web.brave.apiKey")!.set("panel-key");
186
+ const notifications: string[] = [];
187
+ const ctx = { cwd, ui: { notify: (m: string) => notifications.push(m) }, isProjectTrusted: () => true } as never;
188
+ await cfg.save(new Set(["web.brave.apiKey"]), ctx);
189
+ // Disclosure reads the PROJECT layer alone: a merged read would see the
190
+ // key just written to global and call it a shadow.
191
+ assert.doesNotMatch(notifications.join(" "), /shadows:/);
192
+ } finally {
193
+ fs.rmSync(dir, { recursive: true, force: true });
194
+ fs.rmSync(cwd, { recursive: true, force: true });
195
+ delete process.env.PI_CODING_AGENT_DIR;
196
+ }
197
+ });
132
198
  });
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
- import type { ModuleConfig } from "../../lib/registry.js";
12
+ import { isProjectTrusted, type ModuleConfig } from "../../lib/registry.js";
13
13
  import { row, type PanelGroup } from "../../lib/panel.js";
14
14
  import { DEFAULT_BASE_URL, KNOWN_BASE_URLS } from "./lib/anthropic.js";
15
15
  import { DEFAULT_MIN_INTERVAL_MS } from "./lib/throttle.js";
@@ -139,7 +139,10 @@ function changed(before: ZaiSettings, working: ZaiSettings, key: string): boolea
139
139
 
140
140
  /** zai's ModuleConfig for the central /config panel. */
141
141
  export function zaiConfig(pi: ExtensionAPI): ModuleConfig {
142
- const before = readZaiSettings(process.cwd(), true);
142
+ // Baseline = what the next request resolves: the factory gets no ctx, so the
143
+ // shared trust helper decides (same rule save-time ctx.isProjectTrusted
144
+ // applies) — an untrusted checkout must not show phantom project values.
145
+ const before = readZaiSettings(process.cwd(), isProjectTrusted(process.cwd()));
143
146
  const working = structuredClone(before);
144
147
  return {
145
148
  groups: () => buildZaiGroups(working),
@@ -444,10 +444,13 @@ export class ClientSigningManager {
444
444
  this.lastSignedKey = "";
445
445
  }
446
446
 
447
- /** Called on any non-401 response: a success between 401s keeps them from counting as consecutive. */
447
+ /** Called on any non-401 response: a success between 401s keeps them from counting as consecutive.
448
+ * Also drops the pending signed-key marker — a later UNSIGNED request's 401 must not be
449
+ * attributed to the (successful) signed request before it. */
448
450
  noteResponseOk(): void {
449
451
  const state = this.states.get(this.lastSignedKey);
450
452
  if (state) state.consecutive401s = 0;
453
+ this.lastSignedKey = "";
451
454
  }
452
455
 
453
456
  private async buildSignedHeaders(
@@ -204,4 +204,27 @@ describe("zaiConfig save", () => {
204
204
  assert.equal(notifications[0]!.level, "info");
205
205
  assert.match(notifications[0]!.message, /NOT trusted/);
206
206
  });
207
+
208
+ it("baseline honors the trust helper (no phantom project values untrusted)", () => {
209
+ const agentDir = tempDir("zai-trust-agent-");
210
+ process.env.PI_CODING_AGENT_DIR = agentDir;
211
+ const cwd = tempDir("zai-trust-cwd-");
212
+ mkdirSync(join(cwd, ".pi"), { recursive: true });
213
+ writeFileSync(join(cwd, ".pi", "settings.json"), JSON.stringify({ zai: { baseUrl: "https://open.bigmodel.cn/api/anthropic" } }));
214
+ const trustFile = join(agentDir, "trust.json");
215
+ const prevCwd = process.cwd();
216
+ process.chdir(cwd);
217
+ try {
218
+ writeFileSync(trustFile, JSON.stringify({ [process.cwd()]: true }));
219
+ assert.equal(
220
+ zaiConfig(fakePi().pi).groups()[0]!.rows[0]!.value,
221
+ "https://open.bigmodel.cn/api/anthropic",
222
+ "trusted → project value shown",
223
+ );
224
+ writeFileSync(trustFile, JSON.stringify({ [process.cwd()]: false }));
225
+ assert.equal(zaiConfig(fakePi().pi).groups()[0]!.rows[0]!.value, DEFAULT_BASE_URL, "untrusted → project value ignored");
226
+ } finally {
227
+ process.chdir(prevCwd);
228
+ }
229
+ });
207
230
  });
@@ -302,6 +302,25 @@ describe("zcode-signing", () => {
302
302
  await signedHeaders(manager, URL_ULTRA); // must still sign
303
303
  });
304
304
 
305
+ it("401 ladder: a success clears the signed-request marker (later unsigned 401 is not attributed)", async () => {
306
+ const { fetchImpl, calls } = makeFetch({ gateEnabled: true });
307
+ const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
308
+ await signedHeaders(manager); // signed #1
309
+ manager.noteResponseOk(); // 200 — marker cleared
310
+ manager.noteResponse401(); // 401 on an UNSIGNED request: must be a no-op
311
+ // State untouched: the next sign reuses the handshake key (no re-handshake)
312
+ // and no bypass kicked in.
313
+ assert.equal(calls.handshakeCount, 1);
314
+ const headers = await signedHeaders(manager, URL_ULTRA);
315
+ assert.equal(calls.handshakeCount, 1, "no invalidation from the stale marker");
316
+ assert.ok(headers["X-Client-Sig"], "a stale marker must not invalidate the handshake key");
317
+ // And it did not count toward the ladder: two real signed 401s are still required.
318
+ manager.noteResponse401();
319
+ await signedHeaders(manager, URL_ULTRA); // re-handshake, count 1 → still signs
320
+ manager.noteResponse401(); // count 2 → bypass
321
+ assert.equal(await manager.sign(URL_ULTRA, baseHeaders(), CRED), false, "bypass needs two SIGNED 401s");
322
+ });
323
+
305
324
  it("origin allowlist: non-z.ai base URL → unsigned, zero network (no credential egress)", async () => {
306
325
  const { fetchImpl, calls } = makeFetch({ gateEnabled: true });
307
326
  const manager = new ClientSigningManager({ identity: IDENTITY, fetchImpl });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ceulen",
3
- "version": "0.7.0",
3
+ "version": "0.8.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/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/web/test/*.test.ts",
43
+ "test": "node scripts/validate-themes.mjs && node --import tsx --test extensions/lib/registry.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",
44
44
  "typecheck": "tsc --noEmit"
45
45
  },
46
46
  "pi": {