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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,53 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.0 — 2026-10-04
4
+
5
+ - **todo**: new module (OMP port) — phased task tracking: one `todo` tool
6
+ (`init/start/done/rm/block/unblock/append/view`) over an ordered phase list.
7
+ Blocked is derived from unmet `blockedBy` edges (finishing a blocker
8
+ auto-unblocks dependents); the earliest pending unblocked phase auto-starts
9
+ after every mutation; `start` errors while another phase is in progress
10
+ unless `force`. Every mutation persists (`ceulen-todo` entries, rehydrated
11
+ on session start) and updates a `▸ n/m done · in_progress: …` status
12
+ segment. `/todo` prints the board, `/todo clear` resets.
13
+ - **rules**: new module (OMP port) — sticky RULES.md + rulebook. Sources:
14
+ nearest-first walk from cwd to root for `.pi/RULES.md`, then
15
+ `~/.pi/agent/RULES.md`; project names override user. One rule per
16
+ `## name` section — a `description:` first line makes it a rulebook rule
17
+ (listed in the prompt, body served on demand by the `rule_get` tool);
18
+ otherwise the body is sticky (appended to every request inside
19
+ `<user-rules>…</user-rules>`, 4000-char cap with a loud truncation marker).
20
+ `@path` imports expand at load (cycle-guarded); files cached by mtime so
21
+ edits apply without `/reload`. `/rules` = status, `/rules reload` = drop
22
+ the cache. Zero footprint when no RULES.md exists anywhere.
23
+ - **subagent**: `subagent.idleTimeoutMins` now actually reaches the timeout
24
+ resolver (it was dead config — children always died on the env default);
25
+ a typo'd `@alias` fails the dispatch loud on BOTH runners instead of
26
+ silently running the child on the parent model; the classifier tier gates
27
+ on the chosen label's own probability, not the max across all labels.
28
+ - **router**: `/config` saves re-register the provider from the EFFECTIVE
29
+ (trust-aware) snapshot — a trusted-project endpoint is no longer clobbered
30
+ and the catalog refresh can no longer send the API key to a saved-but-
31
+ shadowed URL; `combo/*` thinking `off` now OMITS `reasoning_effort`
32
+ (the upstream 422s on the literal value — found by live-testing).
33
+ - **steering**: registry reorder — steering is now genuinely the LAST
34
+ `before_agent_start` rewriter (serena/web loaded after it and appended to
35
+ the ds-anchor bootstrap prompt, breaking byte-identity on request #1).
36
+ - **advisor**: the "paused after 3 consecutive failures" notice actually
37
+ reaches the user (it was defeated by its own pause flag); the cursor
38
+ reseed fires when enable + chain are saved in one `/config` write.
39
+ - **usage**: session cost / tok-s accumulators reset on `session_start` —
40
+ "Session cost" no longer reports whole-process totals after `/new` or
41
+ reload.
42
+ - **zai**: config panel baseline honors project trust; the 401 ladder clears
43
+ its signed-request marker on success so unsigned 401s no longer count
44
+ toward signing bypass.
45
+ - **web**: garbage input on a number row is skipped instead of persisted as
46
+ `0`; nested-shaped project `web` entries are disclosed as save shadows.
47
+ - **munin**: config panel baseline honors project trust.
48
+ - **registry**: `isProjectTrusted` walks each agent dir from cwd (a mutated
49
+ cursor made the second dir probe at `/`).
50
+
3
51
  ## 0.7.0 — 2026-10-04
4
52
 
5
53
  - **web**: new module — the 11 unified web tools ported from `@bacnh85/pi-web`
@@ -0,0 +1,67 @@
1
+ // Registry helpers: the trust walk must restart from cwd for EVERY candidate
2
+ // agent dir (the walk mutates its cursor up to `/`, so a shared cursor made
3
+ // dir #2 probe the filesystem root and fail closed).
4
+
5
+ import { describe, it, before, after } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+
11
+ const ROOT = join(tmpdir(), "ceulen-registry-test-" + process.pid);
12
+ // project = <ROOT>/proj; dirs probed in order dirA (no matching entry) → dirB.
13
+ const PROJECT = join(ROOT, "proj");
14
+ const DIR_A = join(ROOT, "agentA");
15
+ const DIR_B = join(ROOT, "agentB");
16
+
17
+ before(() => {
18
+ rmSync(ROOT, { recursive: true, force: true });
19
+ for (const d of [PROJECT, DIR_A, DIR_B]) mkdirSync(d, { recursive: true });
20
+ });
21
+ after(() => { rmSync(ROOT, { recursive: true, force: true }); });
22
+
23
+ describe("isProjectTrusted", () => {
24
+ it("second agent dir is probed from cwd, not from the first dir's walk root", async () => {
25
+ const { isProjectTrusted } = await import("./registry.js");
26
+ // dirA carries a trust.json that says NOTHING about PROJECT — its walk
27
+ // reaches '/' and must not leak that cursor into dirB's probe.
28
+ writeFileSync(join(DIR_A, "trust.json"), JSON.stringify({ "/somewhere/else": true }));
29
+ writeFileSync(join(DIR_B, "trust.json"), JSON.stringify({ [PROJECT]: true }));
30
+ assert.equal(isProjectTrusted(PROJECT, [DIR_A, DIR_B]), true, "declared boolean for the entry in dir #2");
31
+
32
+ writeFileSync(join(DIR_B, "trust.json"), JSON.stringify({ [PROJECT]: false }));
33
+ assert.equal(isProjectTrusted(PROJECT, [DIR_A, DIR_B]), false, "explicit false honoured too");
34
+ });
35
+
36
+ it("single-dir behaviour unchanged: parent-walk hit, miss, unreadable → false", async () => {
37
+ const { isProjectTrusted } = await import("./registry.js");
38
+ const nested = join(PROJECT, "a", "b");
39
+ mkdirSync(nested, { recursive: true });
40
+ writeFileSync(join(DIR_A, "trust.json"), JSON.stringify({ [PROJECT]: true }));
41
+ assert.equal(isProjectTrusted(nested, [DIR_A]), true, "walk finds the ancestor entry");
42
+ assert.equal(isProjectTrusted(join(ROOT, "nope"), [DIR_A]), false, "no entry → fail closed");
43
+ assert.equal(isProjectTrusted(PROJECT, [join(ROOT, "missing-dir")]), false, "absent trust.json → false");
44
+ const bad = join(ROOT, "bad");
45
+ mkdirSync(bad, { recursive: true });
46
+ writeFileSync(join(bad, "trust.json"), "{not json");
47
+ assert.equal(isProjectTrusted(PROJECT, [bad]), false, "malformed json → false");
48
+ });
49
+ });
50
+
51
+ describe("MODULES load order", () => {
52
+ // The steering entry must stay behind every before_agent_start prompt
53
+ // rewriter (its ds-anchor bootstrap REPLACES the final prompt; a rewriter
54
+ // loaded after it would append to the byte-identical minimal prompt, which
55
+ // is exactly what serena/web used to do) and ahead of the non-rewriters
56
+ // (rtk/config). Modules registering before_agent_start and loading BEFORE
57
+ // steering: munin, advisor, ux, ponytail, subagent, plan, fff, serena, web
58
+ // — web is the last of them, hence the anchor below.
59
+ it("steering is the last prompt rewriter, before rtk/config", async () => {
60
+ const { MODULES } = await import("./registry.js");
61
+ const at = (name: string) => MODULES.findIndex((m) => m.name === name);
62
+ assert.ok(at("steering") > at("web"), "steering loads after the last rewriter (web)");
63
+ assert.ok(at("steering") > at("serena") && at("steering") > at("plan"));
64
+ assert.ok(at("steering") < at("rtk"), "rtk (no prompt rewrite) loads after steering");
65
+ assert.equal(MODULES.at(-1)!.name, "config", "config stays last");
66
+ });
67
+ });
@@ -26,6 +26,7 @@ import subagentModule from "../modules/subagent/index.ts";
26
26
  import { subagentConfig } from "../modules/subagent/configPanel.js";
27
27
  import planModule from "../modules/plan/index.ts";
28
28
  import { planConfig } from "../modules/plan/configPanel.js";
29
+ import todoModule from "../modules/todo/index.ts";
29
30
  import steeringModule from "../modules/steering/index.ts";
30
31
  import { steeringConfig } from "../modules/steering/configPanel.js";
31
32
  import repairModule from "../modules/repair/index.ts";
@@ -38,6 +39,7 @@ import muninModule from "../modules/munin/index.ts";
38
39
  import { muninConfig } from "../modules/munin/configPanel.ts";
39
40
  import webModule from "../modules/web/index.ts";
40
41
  import { webConfig } from "../modules/web/configPanel.ts";
42
+ import rulesModule from "../modules/rules/index.ts";
41
43
  import configModule from "../modules/config/index.ts";
42
44
 
43
45
  /** A module's contribution to the central `/config` panel. */
@@ -120,12 +122,7 @@ export const MODULES: ModuleEntry[] = [
120
122
  // (sandbox: read-only) and its before_agent_start must compose BEFORE
121
123
  // steering (the last prompt rewriter — see its entry below).
122
124
  { name: "plan", category: "Tasks", describe: "Read-only plan mode: /plan toggle, tool gating, write_plan + ask_user_question, plan model/thinking, approval handoff.", load: planModule, config: planConfig, tools: ["write_plan", "ask_user_question"] },
123
- // Steering LAST before the config module (load order is load-bearing even
124
- // though its /config rows live on the Model tab, which PI_TAB_ORDER sorts
125
- // independently): its before_agent_start handler must run AFTER ponytail's
126
- // and subagent's so the deepseek-v4-pro anchor bootstrap REPLACES the final
127
- // prompt (byte-identical minimal prompt) instead of being re-appended to.
128
- { name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): first-tool hints, reasoning strip, leak cleaning, error recovery hints, DeepSeek guidance + v4-pro minimal-mode anchor.", load: steeringModule, config: steeringConfig },
125
+ { name: "todo", category: "Tasks", describe: "Phased task board: the `todo` tool (init/start/done/block/unblock) with session persistence, blockers, and a status-segment progress readout.", load: todoModule, tools: ["todo"] },
129
126
  // ── Tools ─────────────────────────────────────────────────────────────
130
127
  // Repair first in the section: it wraps the built-in tools; serena/fff ride
131
128
  // on top (no load-order dependency — hooks resolve at call time).
@@ -148,6 +145,17 @@ export const MODULES: ModuleEntry[] = [
148
145
  { name: "web", category: "Tools", describe: "Unified web tools: search (SearXNG/Brave/Firecrawl), extract & crawl (JSDOM/Firecrawl/Crawl4AI/agy), screenshot/PDF, CDP browser interaction, Gemini research, image generation, one-off chat.", load: webModule, config: webConfig, tools: [
149
146
  "web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_interact", "web_research", "web_image", "web_chat", "web_status",
150
147
  ] },
148
+ { name: "rules", category: "Context", describe: "Sticky RULES.md constraints carried in every request + a rulebook of on-demand rules served by rule_get. Nearest-first project walk over user-level.", load: rulesModule, tools: ["rule_get"] },
149
+ // Steering LAST of the prompt rewriters, i.e. after EVERY before_agent_start
150
+ // composer (ponytail/plan/subagent/munin/advisor/ux/fff/serena/web/rules) and
151
+ // before the config module (load order is load-bearing even though its
152
+ // /config rows live on the Model tab, which PI_TAB_ORDER sorts
153
+ // independently): pi chains before_agent_start results, so steering must run
154
+ // LAST for its deepseek-v4-pro anchor bootstrap to REPLACE the final prompt
155
+ // (byte-identical minimal prompt) instead of appending to a prompt that
156
+ // serena/web then append to. Nothing after this entry (rtk, config) touches
157
+ // the prompt — do not move it earlier or add a prompt rewriter after it.
158
+ { name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): first-tool hints, reasoning strip, leak cleaning, error recovery hints, DeepSeek guidance + v4-pro minimal-mode anchor.", load: steeringModule, config: steeringConfig },
151
159
  // ── Shell ──────────────────────────────────────────────────────────────
152
160
  { name: "rtk", category: "Shell", describe: "Route shell commands through RTK for token savings.", load: rtkModule },
153
161
  // ── Plugins ────────────────────────────────────────────────────────────
@@ -247,8 +255,10 @@ export function writeDisabled(list: string[], cwd = process.cwd()): string {
247
255
  * walking up the tree like pi's ProjectTrustStore. Unreadable/absent →
248
256
  * false (fail closed). */
249
257
  export function isProjectTrusted(cwd: string, dirs: string[] = agentDirs()): boolean {
250
- let current = path.resolve(cwd);
251
258
  for (const dir of dirs) {
259
+ // Per-dir walk start — the walk below mutates `current` up to the root, so
260
+ // a second agent dir must restart from cwd, not inherit the first's root.
261
+ let current = path.resolve(cwd);
252
262
  const file = path.join(dir, "trust.json");
253
263
  if (!existsSync(file)) continue;
254
264
  try {
@@ -34,6 +34,12 @@ export function __setIsolatedForTest(fn: IsolatedCall | undefined): void {
34
34
  testIsolated = fn;
35
35
  }
36
36
 
37
+ // ponytail: test-only read of the newest module instance's runtime (cursor/wiring assertions).
38
+ let testRuntime: (() => WatcherRuntime | undefined) | undefined;
39
+ export function __getRuntimeForTest(): WatcherRuntime | undefined {
40
+ return testRuntime?.();
41
+ }
42
+
37
43
  interface NoteData {
38
44
  severity: Severity;
39
45
  note: string;
@@ -61,6 +67,7 @@ function renderNoteCard(raw: NoteData | undefined, expanded: boolean, theme: The
61
67
 
62
68
  export default function advisorModule(pi: ExtensionAPI): void {
63
69
  let runtime: WatcherRuntime | undefined;
70
+ testRuntime = () => runtime;
64
71
  let runtimeSessionId: string | undefined;
65
72
  /** Effective settings as last loaded/applied — the base for partial writes. */
66
73
  let settings: AdvisorConfig = DEFAULTS;
@@ -75,6 +82,12 @@ export default function advisorModule(pi: ExtensionAPI): void {
75
82
  function applySettings(next: AdvisorConfig, ctx: ExtensionContext): void {
76
83
  const masterChanged = next.enabled !== settings.enabled;
77
84
  settings = next;
85
+ // The session watch state this save TARGETS — computed before the reseed
86
+ // below: an explicit master change re-arms/disarms the session, an unchanged
87
+ // master leaves a /advisor watch-off override in place. Reading watchEnabled
88
+ // directly would miss a save that sets enabled + chain together, because
89
+ // watchEnabled is only updated at the end of this function.
90
+ const willWatch = masterChanged ? next.enabled : watchEnabled;
78
91
  const rt = runtime;
79
92
  const wasEmpty = !rt || rt.models.length === 0;
80
93
  if (rt) {
@@ -86,7 +99,7 @@ export default function advisorModule(pi: ExtensionAPI): void {
86
99
  rt.failures = 0;
87
100
  }
88
101
  // Enabling mid-session must not replay history.
89
- if (wasEmpty && next.models.length > 0 && watchEnabled) reseedCursor(rt, ctx);
102
+ if (wasEmpty && next.models.length > 0 && willWatch) reseedCursor(rt, ctx);
90
103
  }
91
104
  // An explicit master change re-arms/disarms the session; otherwise a
92
105
  // /advisor watch-off override stays in place.
@@ -178,11 +191,16 @@ export default function advisorModule(pi: ExtensionAPI): void {
178
191
  // watch-off flips the flag, repeated failures pause — a review in flight
179
192
  // across any of these must deliver nothing.
180
193
  const live = () => runtime === rt && watchEnabled && rt.models.length > 0 && !rt.stats.paused;
194
+ // Reviews/notes additionally require "not paused": the 3-strike pause exists
195
+ // precisely because the review just failed, so a notify behind live() could
196
+ // never tell the user the watch stopped. Passed as a separate predicate — the
197
+ // pause flag still suppresses outbound notes and further reviews.
198
+ const alive = () => runtime === rt && watchEnabled && rt.models.length > 0;
181
199
  void reviewTurn(rt, ctx, {
182
200
  sendMessage: (message, options) => { if (live()) pi.sendMessage(message, options as never); },
183
201
  sendUserMessage: (content, options) => { if (live()) pi.sendUserMessage(content, options); },
184
202
  appendEntry: (customType, data) => { if (live()) pi.appendEntry(customType, data); },
185
- notify: (message) => { if (live()) ctx.ui.notify(message, "error"); },
203
+ notify: (message) => { if (alive()) ctx.ui.notify(message, "error"); },
186
204
  }, testIsolated).catch((err) => { if (live()) ctx.ui.notify(`Advisor review failed: ${String(err)}`, "error"); });
187
205
  });
188
206
 
@@ -171,7 +171,9 @@ export interface WatcherHost {
171
171
  sendUserMessage(content: string, options?: { deliverAs?: "steer" | "followUp" }): void;
172
172
  /** Display-only immediate card (session entry; never enters LLM context). */
173
173
  appendEntry<T = unknown>(customType: string, data?: T): void;
174
- /** Error/status toast, liveness-gated by the caller (never leaks into a replaced session). */
174
+ /** Error/status toast, liveness-gated by the caller (never leaks into a replaced session).
175
+ * The pause notice is the ONE message that must survive the runtime's own
176
+ * `stats.paused` flag — the caller gates it on liveness WITHOUT the pause term. */
175
177
  notify(message: string): void;
176
178
  }
177
179
 
@@ -3,7 +3,7 @@ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { after, beforeEach, describe, it } from "node:test";
6
- import advisorModule, { __setIsolatedForTest } from "../index.js";
6
+ import advisorModule, { __getRuntimeForTest, __setIsolatedForTest } from "../index.js";
7
7
  import { advisorConfig } from "../configPanel.js";
8
8
  import { writeAdvisorSettings } from "../lib/config.js";
9
9
 
@@ -229,6 +229,38 @@ describe("advisor module wiring", () => {
229
229
  await cmd.handler("on", ctx);
230
230
  assert.ok(state.activeTools.has("advisor"), "tool re-activated by /advisor on without waiting for session_start");
231
231
  });
232
+
233
+ it("session_start(review off, no chain) + /config save enabling both reseeds the cursor (no history replay)", async () => {
234
+ const { pi, state } = createFakePi();
235
+ advisorModule(pi);
236
+ writeSettings({ advisor: { enabled: false } });
237
+ // Session opens with the review OFF and NO chain → runtime cursor stays undefined.
238
+ let ctx = available(fakeCtx(toolCalls(4)));
239
+ await fire(pi, state, "session_start", ctx);
240
+ const rt = __getRuntimeForTest();
241
+ assert.ok(rt, "runtime created for the session");
242
+ assert.equal(rt!.cursor, undefined, "no chain + review off → nothing reviewed yet");
243
+ assert.equal(rt!.models.length, 0, "no advisor model configured at start");
244
+
245
+ // ONE /config save sets enabled:true AND the chain. The reseed must key on
246
+ // the target watch state (willWatch), not on the not-yet-updated watchEnabled.
247
+ const entries = toolCalls(4);
248
+ ctx = available(fakeCtx(entries));
249
+ const m = advisorConfig();
250
+ m.groups()[0]!.rows[0]!.set(true);
251
+ m.groups()[0]!.rows[1]!.set(MODEL);
252
+ await m.save(new Set(["advisor.enabled", "advisor.model"]), ctx);
253
+
254
+ assert.deepEqual(readSettings().advisor, { enabled: true, models: [MODEL], watch: { minToolCalls: 3, immuneTurns: 3 } }, "enabled + chain written in one save");
255
+ assert.equal(rt!.cursor, entries.at(-1).id, "cursor reseeded to the transcript tail — the pre-existing history is not replayed");
256
+
257
+ // And the watch actually reviews only NEW work: the settled turn adds
258
+ // nothing, so the reseeded cursor leaves the existing 4 tool calls unseen.
259
+ let calls = 0;
260
+ __setIsolatedForTest(async (_c, models) => { calls++; return { text: "", model: models[0], usage: NO_USAGE }; });
261
+ await fire(pi, state, "agent_settled", step(available(fakeCtx(entries)), "tui"));
262
+ assert.equal(calls, 0, "nothing new since the reseed → no review of the pre-existing turn");
263
+ });
232
264
  });
233
265
 
234
266
  describe("advisor review flow", () => {
@@ -389,6 +421,37 @@ describe("advisor review flow", () => {
389
421
  assert.equal(calls, 0, "no isolated call without a model");
390
422
  assert.equal(state.entries.length, 0);
391
423
  });
424
+
425
+ it("the 3-strike pause notice reaches the user exactly once through the real wiring", async () => {
426
+ const { pi, state } = await arm({ advisor: { models: [MODEL], watch: { minToolCalls: 0, immuneTurns: 1 } } });
427
+ __setIsolatedForTest(async () => { throw new Error("429 rate limited"); });
428
+ const base = toolCalls(1);
429
+ const ctx = step(available(fakeCtx(base)), "tui");
430
+ // Three consecutive failing reviews — each its own settled turn with new work.
431
+ for (const extra of [toolCalls(1), toolCalls(1), toolCalls(1)]) {
432
+ ctx.sessionManager = { ...ctx.sessionManager, getEntries: () => [...base, ...extra] };
433
+ await fire(pi, state, "agent_settled", ctx);
434
+ }
435
+ const pause = ctx.notes.filter((n: any) => n.message.includes("Advisor watch paused"));
436
+ assert.equal(pause.length, 1, "the pause toast lands (previously dead code behind the paused flag)");
437
+ assert.equal(pause[0].level, "error", "delivered as an error toast");
438
+ assert.equal(__getRuntimeForTest()!.stats.paused, true, "the watch is still paused");
439
+ assert.equal(state.userMessages.length, 0, "no note delivered by the failed reviews");
440
+
441
+ // Paused means NO further reviews until /advisor on — the next turn skips.
442
+ let calls = 0;
443
+ __setIsolatedForTest(async (_c, models) => { calls++; return { text: "", model: models[0], usage: NO_USAGE }; });
444
+ ctx.sessionManager = { ...ctx.sessionManager, getEntries: () => [...base, ...toolCalls(1), ...toolCalls(1)] };
445
+ await fire(pi, state, "agent_settled", ctx);
446
+ assert.equal(calls, 0, "paused watch issues no further review");
447
+
448
+ // …and /advisor on resumes, as the notice promises: no duplicate toast.
449
+ await state.commands.get("advisor").handler("on", ctx);
450
+ assert.equal(__getRuntimeForTest()!.stats.paused, false, "resumed");
451
+ await fire(pi, state, "agent_settled", ctx);
452
+ assert.equal(calls, 1, "reviews resume after /advisor on");
453
+ assert.equal(ctx.notes.filter((n: any) => n.message.includes("Advisor watch paused")).length, 1, "still exactly one pause notice");
454
+ });
392
455
  });
393
456
 
394
457
  describe("/advisor command surface", () => {
@@ -305,8 +305,8 @@ describe("core module contract", () => {
305
305
  it("nextDisabled excludes core modules; withEnableRow adds no row for them", async () => {
306
306
  const { nextDisabled, withEnableRow } = await import("../../config/index.js");
307
307
  // working = enabled set; nextDisabled lists the NOT-enabled non-core modules.
308
- assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "steering", "repair", "serena", "fff", "web", "rtk"]);
309
- assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "steering", "zai", "serena", "fff", "web", "repair", "rtk", "config"])), [], "all-on → nothing disabled");
308
+ assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "todo", "repair", "serena", "fff", "web", "rules", "steering", "rtk"]);
309
+ assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "todo", "repair", "serena", "fff", "web", "rules", "steering", "zai", "rtk", "config"])), [], "all-on → nothing disabled");
310
310
  for (const core of ["composer", "advisor", "router", "classifier", "usage", "ux", "config"]) {
311
311
  assert.ok(!nextDisabled(new Set()).includes(core), `core (${core}) is never disableable`);
312
312
  }
@@ -34,7 +34,7 @@ function toolGroups(): PanelGroup[] {
34
34
  describe("render smoke — ported modules' /config sections", () => {
35
35
  it("renders Enable + per-tool rows inside the boxed frame with zero overflow", () => {
36
36
  const groups = toolGroups();
37
- assert.equal(groups.length, 10, "serena + fff + ux + munin + classifier + advisor + subagent + repair + plan + web (rtk has no tools)");
37
+ assert.equal(groups.length, 12, "serena + fff + ux + munin + classifier + advisor + subagent + repair + plan + todo + web + rules (rtk has no tools)");
38
38
  const m = new ConfigPanelModel(groups, theme, "Settings");
39
39
  m.getHeight = () => 40;
40
40
  for (const w of [110, 100, 80, 60]) {
@@ -7,7 +7,7 @@
7
7
 
8
8
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
9
9
  import { row, type PanelGroup } from "../../lib/panel.js";
10
- import type { ModuleConfig } from "../../lib/registry.js";
10
+ import { isProjectTrusted, type ModuleConfig } from "../../lib/registry.js";
11
11
  import {
12
12
  DEFAULT_MUNIN_BASE_URL,
13
13
  getMuninConfig,
@@ -76,7 +76,10 @@ const OWNED_PREFIX = "munin.";
76
76
  * from the save ctx (factories receive none); reads use process.cwd(),
77
77
  * matching router's panel pattern. */
78
78
  export function muninConfig(): ModuleConfig {
79
- const before = readMuninSettings(process.cwd(), true);
79
+ // Baseline = what the tools resolve: the factory has no ctx, so the shared
80
+ // trust helper decides (the same rule the save ctx applies) — an untrusted
81
+ // checkout must not show phantom project values.
82
+ const before = readMuninSettings(process.cwd(), isProjectTrusted(process.cwd()));
80
83
  const working = structuredClone(before);
81
84
  return {
82
85
  groups: () => buildMuninGroups(working),
@@ -1,7 +1,7 @@
1
1
  // NEW for the ceulen port — panel groups shape, effective-value display, and
2
2
  // the project-level save path (write target, patch diffing, trust + env notes).
3
3
 
4
- import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync } from "node:fs";
4
+ import { mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync, readFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { describe, it, beforeEach, afterEach } from "node:test";
@@ -9,7 +9,7 @@ import assert from "node:assert/strict";
9
9
  import { projectSettingsPath } from "../lib/helpers.js";
10
10
  import { buildMuninGroups, muninConfig, readMuninSettings, type MuninSettings } from "../configPanel.js";
11
11
 
12
- const ENV_KEYS = ["MUNIN_API_KEY", "MUNIN_PROJECT", "MUNIN_BASE_URL"] as const;
12
+ const ENV_KEYS = ["MUNIN_API_KEY", "MUNIN_PROJECT", "MUNIN_BASE_URL", "PI_CODING_AGENT_DIR"] as const;
13
13
 
14
14
  describe("buildMuninGroups", () => {
15
15
  it("renders the Memory tab with masked apiKey row", () => {
@@ -68,6 +68,31 @@ describe("readMuninSettings", () => {
68
68
  const none = readMuninSettings(join(cwd, "nowhere"), false);
69
69
  assert.deepEqual(none, { project: "", baseUrl: "https://munin.kalera.ai", apiKey: "" });
70
70
  });
71
+
72
+ it("muninConfig resolves the trust flag itself (no phantom project values untrusted)", () => {
73
+ // The factory gets no ctx, so the baseline must resolve trust through the
74
+ // shared helper — a hardcoded `true` shows a trusted-project value in an
75
+ // UNTRUSTED checkout (the phantom-value bug class).
76
+ const agentDir = mkdtempSync(join(tmpdir(), "munin-agent-"));
77
+ const cwd = mkdtempSync(join(tmpdir(), "munin-trust-"));
78
+ dirs.push(agentDir, cwd);
79
+ process.env.PI_CODING_AGENT_DIR = agentDir;
80
+ process.env.MUNIN_API_KEY = "env-key"; // keep getMuninConfig from throwing
81
+ process.env.MUNIN_PROJECT = "env-id";
82
+ mkdirSync(join(cwd, ".pi"), { recursive: true });
83
+ writeFileSync(projectSettingsPath(cwd), JSON.stringify({ munin: { baseUrl: "https://project.test" } }));
84
+ const prevCwd = process.cwd();
85
+ process.chdir(cwd);
86
+ const baseUrlRow = () => muninConfig().groups()[0]!.rows[1]!.value;
87
+ try {
88
+ writeFileSync(join(agentDir, "trust.json"), JSON.stringify({ [process.cwd()]: true }));
89
+ assert.equal(baseUrlRow(), "https://project.test", "trusted → project value shown");
90
+ writeFileSync(join(agentDir, "trust.json"), JSON.stringify({ [process.cwd()]: false }));
91
+ assert.equal(baseUrlRow(), "https://munin.kalera.ai", "untrusted → project value ignored");
92
+ } finally {
93
+ process.chdir(prevCwd);
94
+ }
95
+ });
71
96
  });
72
97
 
73
98
  describe("muninConfig save", () => {
@@ -5,12 +5,20 @@
5
5
  */
6
6
 
7
7
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
8
- import type { ModuleConfig } from "../../lib/registry.js";
8
+ import { isProjectTrusted, type ModuleConfig } from "../../lib/registry.js";
9
9
  import { row, type PanelGroup } from "../../lib/panel.js";
10
10
  import { getSettings, writeRouterSection, type RouterSettings } from "./lib/config.js";
11
11
  import { registerProvider, maybeRefreshCatalog } from "./lib/provider.js";
12
12
  import { refreshActiveModel } from "./lib/refresh.js";
13
13
 
14
+ /** Read the panel's working copy: the EFFECTIVE values (env/project overrides
15
+ * shown), so the panel never hides what the next request will actually use.
16
+ * `trusted` is required — the caller decides, mirroring the rule the save-time
17
+ * ctx applies (see zai's precedent). */
18
+ export function readRouterSettings(trusted: boolean): RouterSettings {
19
+ return getSettings({ trustProject: trusted });
20
+ }
21
+
14
22
  /** Build the router panel groups over a working copy (mutated by row setters).
15
23
  * ONE group — the OMP "Providers" tab carries a single "Router" section
16
24
  * (its Enable kill-switch row is prepended by the config module). Exported
@@ -40,12 +48,14 @@ export function buildRouterGroups(cfg: RouterSettings): PanelGroup[] {
40
48
  ];
41
49
  }
42
50
 
43
- /** Persist the working copy + apply it live: re-register the provider so its
44
- * closure picks up the new values, force a catalog refresh (new endpoint or
45
- * reasoning flag must take effect immediately — bypass TTL, supersede any
46
- * in-flight fetch), then keep the active model valid. Notifies effective vs
47
- * saved values (env/repo precedence can shadow the persisted ones) — one
48
- * save path, no drift. */
51
+ /** Persist the working copy + apply it live: re-register the provider from the
52
+ * EFFECTIVE settings (so a trusted repo's `router.baseUrl` is what the next
53
+ * request and the forced catalog refresh actually use — re-registering the raw
54
+ * saved copy would redirect the endpoint while `ROUTER_BASE_URL` set), force a
55
+ * catalog refresh (new endpoint or reasoning flag must take effect immediately
56
+ * — bypass TTL, supersede any in-flight fetch), then keep the active model
57
+ * valid. Notifies effective vs saved values (env/repo precedence can shadow
58
+ * the persisted ones) — one save path, no drift. */
49
59
  export async function saveRouterConfig(pi: ExtensionAPI, before: RouterSettings, working: RouterSettings, ctx: ExtensionContext): Promise<void> {
50
60
  if (working.baseUrl === before.baseUrl && working.enableReasoning === before.enableReasoning) {
51
61
  ctx.ui.notify("No changes.", "info");
@@ -55,12 +65,13 @@ export async function saveRouterConfig(pi: ExtensionAPI, before: RouterSettings,
55
65
  baseUrl: working.baseUrl !== before.baseUrl ? working.baseUrl : undefined,
56
66
  enableReasoning: working.enableReasoning !== before.enableReasoning ? working.enableReasoning : undefined,
57
67
  });
58
- registerProvider(pi, working);
68
+ const trusted = ctx.isProjectTrusted?.() === true;
69
+ const effective = readRouterSettings(trusted);
70
+ registerProvider(pi, effective);
59
71
  try {
60
72
  await maybeRefreshCatalog(ctx, { force: true });
61
73
  } catch { /* refresh errors are surfaced by Pi elsewhere */ }
62
74
  await refreshActiveModel(pi, ctx);
63
- const effective = getSettings();
64
75
  const overridden =
65
76
  (working.baseUrl !== effective.baseUrl && working.baseUrl !== "") ||
66
77
  working.enableReasoning !== effective.enableReasoning;
@@ -77,7 +88,10 @@ const OWNED_KEYS = ["router.baseUrl", "router.enableReasoning"];
77
88
 
78
89
  /** Router's ModuleConfig for the central /config panel. */
79
90
  export function routerConfig(pi: ExtensionAPI): ModuleConfig {
80
- const before = getSettings();
91
+ // Baseline = what the next request resolves: the factory gets no ctx, so the
92
+ // shared trust helper decides (same rule save-time ctx.isProjectTrusted
93
+ // applies) — an untrusted checkout must not show phantom project values.
94
+ const before = readRouterSettings(isProjectTrusted(process.cwd()));
81
95
  const working = structuredClone(before);
82
96
  return {
83
97
  groups: () => buildRouterGroups(working),
@@ -276,10 +276,12 @@ const FORMAT_TO_LEVEL_MAP: Record<string, Record<string, string | null>> = {
276
276
  // (GLM's single thinking-on tier), max→"max"; xhigh/minimal unsupported (hidden).
277
277
  "zai": { off:"none", minimal:null, low:"high", medium:"high", high:"high", xhigh:null, max:"max" },
278
278
  "minimax": { off:"none", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"xhigh", max:"xhigh" },
279
- // Yardmaster CC-enum backends (combo/, live-probed): valid effort values are
280
- // exactly off|low|medium|high|xhigh|max — "none"/"minimal" 400. "off" is
281
- // honored (omitting it leaves the upstream defaulting to thinking ON).
282
- "cc-enum": { off:"off", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"xhigh", max:"max" },
279
+ // Yardmaster CC-enum backends (combo/, live-probed): "none"/"minimal" 400,
280
+ // and the literal "off" 422s too (reasoning_effort: unknown variant 'off',
281
+ // observed live on combo/deepseek-v4.1-flash 2026-10-04 — an earlier probe
282
+ // claiming off was honored was wrong). off → null omits the parameter
283
+ // entirely (SDK no-level branch); the upstream then applies its own default.
284
+ "cc-enum": { off:null, minimal:null, low:"low", medium:"medium", high:"high", xhigh:"xhigh", max:"max" },
283
285
  };
284
286
 
285
287
  function getThinkingLevelMap(modelId: string): Record<string, string | null> {
@@ -105,6 +105,85 @@ describe("config", () => {
105
105
  });
106
106
  });
107
107
 
108
+ // ── /config Router save: re-register from the EFFECTIVE settings ─────────
109
+ // With a trusted project endpoint P shadowing global G, saving any /config
110
+ // change must leave the provider on P (registering the raw saved copy would
111
+ // clobber it with G); the disclosure must report the effective values.
112
+ describe("saveRouterConfig re-registers from effective settings", () => {
113
+ const repoPath = () => join(process.cwd(), ".pi", "settings.json");
114
+
115
+ async function withRepoSettings(router: unknown, fn: () => Promise<void>): Promise<void> {
116
+ const prev = existsSync(repoPath()) ? readFileSync(repoPath(), "utf8") : null;
117
+ mkdirSync(join(process.cwd(), ".pi"), { recursive: true });
118
+ writeFileSync(repoPath(), JSON.stringify({ router }));
119
+ try {
120
+ await fn();
121
+ } finally {
122
+ if (prev === null) unlinkSync(repoPath());
123
+ else writeFileSync(repoPath(), prev);
124
+ }
125
+ }
126
+
127
+ function makeSaveHarness(trusted: boolean) {
128
+ const registered: string[] = [];
129
+ const notes: { text: string; level: string }[] = [];
130
+ const pi = {
131
+ registerProvider: (_n: string, config: { baseUrl: string }) => { registered.push(config.baseUrl); },
132
+ };
133
+ const ctx = {
134
+ ui: { notify: (text: string, level: string) => { notes.push({ text, level }); } },
135
+ model: undefined,
136
+ modelRegistry: { refresh: async () => ({}), find: () => undefined },
137
+ isProjectTrusted: () => trusted,
138
+ };
139
+ return { pi, ctx, registered, notes };
140
+ }
141
+
142
+ it("trusted project endpoint wins over the saved copy", async () => {
143
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
144
+ writeSettings({ baseUrl: "http://global" });
145
+ const { saveRouterConfig } = await import("../configPanel.js");
146
+ const h = makeSaveHarness(true);
147
+ await withRepoSettings({ baseUrl: "http://trusted-repo" }, async () => {
148
+ // The panel baseline/working copy is the effective (project) value…
149
+ const before = { baseUrl: "http://trusted-repo", enableReasoning: true };
150
+ await saveRouterConfig(h.pi as never, before, { ...before, enableReasoning: false }, h.ctx as never);
151
+ });
152
+ assert.deepEqual(h.registered, ["http://trusted-repo"], "provider re-registered with the project endpoint, not the saved global one");
153
+ assert.equal(h.notes.at(-1)!.level, "info", "no phantom override when saved and effective agree");
154
+ assert.match(h.notes.at(-1)!.text, /http:\/\/trusted-repo/);
155
+ });
156
+
157
+ it("untrusted project endpoint is ignored — the saved value is registered", async () => {
158
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
159
+ writeSettings({ baseUrl: "http://global" });
160
+ const { saveRouterConfig } = await import("../configPanel.js");
161
+ const h = makeSaveHarness(false);
162
+ await withRepoSettings({ baseUrl: "http://trusted-repo" }, async () => {
163
+ const before = { baseUrl: "http://global", enableReasoning: true };
164
+ await saveRouterConfig(h.pi as never, before, { ...before, enableReasoning: false }, h.ctx as never);
165
+ });
166
+ assert.deepEqual(h.registered, ["http://global"], "untrusted repo scope never owns the endpoint");
167
+ });
168
+
169
+ it("env ROUTER_BASE_URL shadows the save: disclosed + provider follows env", async () => {
170
+ try { unlinkSync(settingsPath()); } catch { /* ignore */ }
171
+ writeSettings({ baseUrl: "http://global" });
172
+ process.env.ROUTER_BASE_URL = "http://from-env/";
173
+ try {
174
+ const { saveRouterConfig } = await import("../configPanel.js");
175
+ const h = makeSaveHarness(false);
176
+ const before = { baseUrl: "", enableReasoning: true };
177
+ await saveRouterConfig(h.pi as never, before, { ...before, baseUrl: "http://panel-typed" }, h.ctx as never);
178
+ assert.deepEqual(h.registered, ["http://from-env"], "catalog refresh + requests hit the effective env endpoint");
179
+ assert.equal(h.notes.at(-1)!.level, "warning");
180
+ assert.match(h.notes.at(-1)!.text, /ROUTER_BASE_URL/);
181
+ } finally {
182
+ delete process.env.ROUTER_BASE_URL;
183
+ }
184
+ });
185
+ });
186
+
108
187
  it("legacy NINE_ROUTER_BASE_URL still works", async () => {
109
188
  try { unlinkSync(settingsPath()); } catch { /* ignore */ }
110
189
  process.env.NINE_ROUTER_BASE_URL = "http://legacy-env";
@@ -398,13 +477,15 @@ describe("client", () => {
398
477
  }
399
478
  });
400
479
 
401
- it("combo/ backends map onto the CC enum (off honored, none/minimal never sent)", async () => {
480
+ it("combo/ backends map onto the CC enum (nothing invalid is ever sent)", async () => {
402
481
  const { mapModel } = await import("../lib/client.js");
403
482
  const tlm = (id: string) => mapModel({ id }, true).thinkingLevelMap ?? {};
404
483
  // The deepseek family map would send off→"none" — the yardmaster combo
405
484
  // backend 400s on it (live-probed 2026-10-03). cc-enum must win.
406
485
  const m = tlm("combo/deepseek-v4.1-flash");
407
- assert.equal(m.off, "off");
486
+ // The literal "off" 422s upstream too (reasoning_effort: unknown variant
487
+ // 'off', live 2026-10-04) — off must OMIT the parameter, not send "off".
488
+ assert.equal(m.off, null);
408
489
  assert.equal(m.low, "low");
409
490
  assert.equal(m.medium, "medium");
410
491
  assert.equal(m.max, "max");