ceulen 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +51 -1
  2. package/extensions/index.ts +5 -1
  3. package/extensions/lib/env.test.ts +147 -0
  4. package/extensions/lib/env.ts +180 -0
  5. package/extensions/lib/order.test.ts +74 -0
  6. package/extensions/lib/registry.test.ts +8 -5
  7. package/extensions/lib/registry.ts +8 -3
  8. package/extensions/modules/a2a/configPanel.ts +42 -1
  9. package/extensions/modules/a2a/lib/config.ts +8 -3
  10. package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
  11. package/extensions/modules/advisor/index.ts +6 -3
  12. package/extensions/modules/advisor/test/module.test.ts +31 -0
  13. package/extensions/modules/classifier/index.ts +55 -1
  14. package/extensions/modules/classifier/test/classifier.test.ts +62 -0
  15. package/extensions/modules/composer/test/module.test.ts +1 -1
  16. package/extensions/modules/repair/index.ts +26 -2
  17. package/extensions/modules/repair/test/freshness.test.ts +41 -1
  18. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  19. package/extensions/modules/router/configPanel.ts +4 -4
  20. package/extensions/modules/router/index.ts +1 -1
  21. package/extensions/modules/router/lib/config.ts +9 -4
  22. package/extensions/modules/router/lib/systemone.ts +17 -4
  23. package/extensions/modules/router/test/unit.test.ts +46 -1
  24. package/extensions/modules/rules/index.ts +13 -3
  25. package/extensions/modules/rules/lib/rules.ts +24 -12
  26. package/extensions/modules/rules/test/lib.test.ts +20 -0
  27. package/extensions/modules/rules/test/module.test.ts +21 -0
  28. package/extensions/modules/subagent/index.ts +11 -5
  29. package/extensions/modules/subagent/lib/herdr.ts +5 -0
  30. package/extensions/modules/subagent/lib/routing.ts +31 -8
  31. package/extensions/modules/subagent/lib/runner.ts +8 -2
  32. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  33. package/extensions/modules/web/configPanel.ts +67 -8
  34. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  35. package/extensions/modules/web/test/settings.test.ts +6 -0
  36. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,6 +1,56 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.12.0 — 2026-10-08
4
+
5
+ - **Secrets never land in settings.json** (user policy: URLs fine, credentials
6
+ not): masked `/config` rows (web's 7 keys/cookies, a2a gateway
7
+ token/upstreamToken) persist to `<agentDir>/.env.local` (0600, ingested into
8
+ process.env at import — env already won at read time, so effective values
9
+ are unchanged); `migrateSecretsFromSettings` (bundle session_start) moves
10
+ any pre-fix plaintext secrets out of settings.json and scrubs them,
11
+ idempotently (extensions/lib/env.ts: writeSecretEnvs/readSecretEnvs; a2a's
12
+ loader gained per-gateway env fallbacks `A2A_GATEWAY_<KEY>_TOKEN` /
13
+ `_UPSTREAM_TOKEN`).
14
+ - **Live-incident fixes (8h herdr hang)**: systemoneClassify carries a default
15
+ 30s deadline (pi passes no timeoutMs — a silent endpoint parked dispatches
16
+ forever); subagent routing wraps the classify ask in a 45s race
17
+ (`deadlineMs` injectable, fail-open to the static chain); the herdr
18
+ wall-clock cap is the opt-in hard cap or 60 min — never the 3-min idle
19
+ window, which killed healthy long-running panes; timed-out panes report
20
+ that they may still complete their current write.
21
+ - **Review fixes (two subagent review waves, 13 findings)**:
22
+ - repair: the read guard no longer blocks numeric path-selector reads
23
+ (`f.ts:50-200` — it probed the raw path while the selector peels only in
24
+ execute); a successful `edit` (direct or trim-retry) now refreshes the
25
+ write-freshness baseline (read → edit → write no longer false-positives);
26
+ selector reads record the baseline too.
27
+ - rules: project RULES.md is trust-gated — an untrusted checkout's rules
28
+ never reach the system prompt or rule_get (same gate as pi's AGENTS.md);
29
+ creating a previously-missing @import target now invalidates the cache.
30
+ - router: the systemone classify URL applies the same `/v1`-append
31
+ convention as discovery (a bare-host baseUrl silently 404'd every
32
+ classify); the repo-scope overlay resolves from the session cwd, not
33
+ process.cwd().
34
+ - classifier: the bash verdict hook is bounded to a 2.5s budget (verdicts
35
+ are annotation-only in pi 1.0.0 — never park a tool call on Jev) and
36
+ pauses after 3 consecutive classify failures for 5 minutes (audited;
37
+ settings change or success re-arms).
38
+ - subagent: the dispatch verdict gates on the CHOSEN label's own
39
+ probability (a rival no longer clears the threshold for a low-confidence
40
+ choice, matching the tier rule); removeWorktree locks on the resolved
41
+ repo root (subdir-cwd dispatches no longer key the per-repo lock
42
+ differently); the tool schema no longer promises upstream's removed
43
+ 20-min lifetime cap.
44
+ - advisor: enabling the review via /config reseeds the cursor on FIRST
45
+ activation — an enable-only save no longer reviews the entire transcript.
46
+ - load order: rtk is a prompt rewriter and now loads BEFORE steering (its
47
+ note must not break the ds-anchor byte-identity); a registration-level
48
+ guard test (extensions/lib/order.test.ts) fails if any prompt rewriter
49
+ lands after steering.
50
+ - Tests: 2661 (was 2647) — new suites for the secrets store + migration, the
51
+ registration-order guard, the guard×selector interaction, edit/selector
52
+ freshness, the classifier breaker + budget, and the dispatch/deadline
53
+ routing paths.
4
54
 
5
55
  ## 0.11.0 — 2026-10-07
6
56
 
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
- import { loadCwdEnvFilesIfTrusted } from "./lib/env.js";
13
+ import { loadCwdEnvFilesIfTrusted, migrateSecretsFromSettings } from "./lib/env.js";
14
14
  import { MODULES, readDisabled, type ModuleConfig, type ModuleLoadDeps } from "./lib/registry.js";
15
15
 
16
16
  // Guards the ONE namespace bundle modules share: pi merges every module's
@@ -89,6 +89,10 @@ export default function ceulen(pi: ExtensionAPI) {
89
89
  // its own idempotent call as a safety net when this entry is bypassed.
90
90
  pi.on("session_start", async (_event, ctx) => {
91
91
  loadCwdEnvFilesIfTrusted(ctx);
92
+ // One-time migration: secrets saved pre-fix sit in PLAINTEXT settings.json
93
+ // — move them into <agentDir>/.env.local (0600) and scrub. Env was already
94
+ // winning at read time, so effective values are unchanged.
95
+ migrateSecretsFromSettings();
92
96
  });
93
97
 
94
98
  // One ownership map for the whole loop — this is what makes guarded() able
@@ -0,0 +1,147 @@
1
+ // migrateSecretsFromSettings: plaintext secrets leave settings.json for
2
+ // <agentDir>/.env.local, idempotently, without touching non-secret rows.
3
+
4
+ import assert from "node:assert/strict";
5
+ import { test } from "node:test";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import os from "node:os";
9
+
10
+ import { migrateSecretsFromSettings, writeSecretEnvs, readSecretEnvs } from "./env.ts";
11
+
12
+ function tmpDir(): string {
13
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ceulen-env-test-"));
14
+ process.env.PI_CODING_AGENT_DIR = dir;
15
+ return dir;
16
+ }
17
+
18
+ test("migrate: web + a2a secrets move to .env.local; URLs stay; idempotent", () => {
19
+ const dir = tmpDir();
20
+ try {
21
+ fs.writeFileSync(path.join(dir, "settings.json"), JSON.stringify({
22
+ web: {
23
+ "brave.apiKey": "brave-secret",
24
+ "firecrawl.baseUrl": "https://firecrawl.example",
25
+ "firecrawl.apiKey": "fc-secret",
26
+ "crawl4ai.timeoutMs": 30000,
27
+ },
28
+ a2a: {
29
+ server: { enabled: false, port: 9900 },
30
+ discovery: {
31
+ gateways: {
32
+ remote: { enabled: true, url: "http://gw:9920", token: "agw-plain", heartbeatSec: 60 },
33
+ },
34
+ },
35
+ },
36
+ theme: "default",
37
+ }));
38
+
39
+ migrateSecretsFromSettings();
40
+
41
+ const envText = fs.readFileSync(path.join(dir, ".env.local"), "utf8");
42
+ assert.match(envText, /BRAVE_API_KEY=brave-secret/);
43
+ assert.match(envText, /FIRECRAWL_API_KEY=fc-secret/);
44
+ assert.match(envText, /A2A_GATEWAY_REMOTE_TOKEN=agw-plain/);
45
+
46
+ const raw = JSON.parse(fs.readFileSync(path.join(dir, "settings.json"), "utf8"));
47
+ assert.equal(raw.web["brave.apiKey"], undefined, "brave key scrubbed");
48
+ assert.equal(raw.web["firecrawl.apiKey"], undefined, "firecrawl key scrubbed");
49
+ assert.equal(raw.web["firecrawl.baseUrl"], "https://firecrawl.example", "URL stays");
50
+ assert.equal(raw.web["crawl4ai.timeoutMs"], 30000, "timeout stays");
51
+ assert.equal(raw.a2a.discovery.gateways.remote.url, "http://gw:9920", "gateway URL stays");
52
+ assert.equal(raw.a2a.discovery.gateways.remote.token, undefined, "gateway token scrubbed");
53
+ assert.equal(raw.a2a.server.port, 9900, "server config stays");
54
+ assert.equal(raw.theme, "default", "unrelated keys stay");
55
+
56
+ // Idempotent: second run is a no-op (nothing left to migrate).
57
+ migrateSecretsFromSettings();
58
+ const raw2 = JSON.parse(fs.readFileSync(path.join(dir, "settings.json"), "utf8"));
59
+ assert.deepEqual(raw2, raw);
60
+ const env2 = fs.readFileSync(path.join(dir, ".env.local"), "utf8");
61
+ assert.equal(env2, envText, "no duplicate env lines");
62
+
63
+ // Nested hand-written web secrets also migrate (onlyAbsent: the first
64
+ // BRAVE_API_KEY already written wins — correct env precedence — but the
65
+ // nested settings copy is still scrubbed to one source of truth).
66
+ fs.writeFileSync(path.join(dir, "settings.json"), JSON.stringify({
67
+ web: { brave: { apiKey: "nested-secret" } },
68
+ }));
69
+ migrateSecretsFromSettings();
70
+ assert.doesNotMatch(fs.readFileSync(path.join(dir, ".env.local"), "utf8"), /nested-secret/, "first migrated value wins (onlyAbsent)");
71
+ assert.equal(JSON.parse(fs.readFileSync(path.join(dir, "settings.json"), "utf8")).web, undefined,
72
+ "empty nested web section removed — secret gone from settings.json");
73
+ } finally {
74
+ delete process.env.BRAVE_API_KEY;
75
+ delete process.env.FIRECRAWL_API_KEY;
76
+ delete process.env.A2A_GATEWAY_REMOTE_TOKEN;
77
+ fs.rmSync(dir, { recursive: true, force: true });
78
+ delete process.env.PI_CODING_AGENT_DIR;
79
+ }
80
+ });
81
+
82
+ test("migrate: onlyAbsent honors a hand-placed .env.local value", () => {
83
+ const dir = tmpDir();
84
+ try {
85
+ fs.writeFileSync(path.join(dir, ".env.local"), "BRAVE_API_KEY=hand-placed\n");
86
+ fs.writeFileSync(path.join(dir, "settings.json"), JSON.stringify({ web: { "brave.apiKey": "from-settings" } }));
87
+
88
+ migrateSecretsFromSettings();
89
+
90
+ const envText = fs.readFileSync(path.join(dir, ".env.local"), "utf8");
91
+ assert.match(envText, /BRAVE_API_KEY=hand-placed/, "hand-placed value wins");
92
+ assert.doesNotMatch(envText, /from-settings/);
93
+ // The settings copy is still scrubbed — one source of truth (the web
94
+ // section disappears entirely when the secret was its only key).
95
+ const after = JSON.parse(fs.readFileSync(path.join(dir, "settings.json"), "utf8"));
96
+ assert.ok(!(after.web && after.web["brave.apiKey"]), "settings copy scrubbed");
97
+ } finally {
98
+ delete process.env.BRAVE_API_KEY;
99
+ fs.rmSync(dir, { recursive: true, force: true });
100
+ delete process.env.PI_CODING_AGENT_DIR;
101
+ }
102
+ });
103
+
104
+ test("migrate: missing/corrupt settings.json is a silent no-op", () => {
105
+ const dir = tmpDir();
106
+ try {
107
+ assert.doesNotThrow(() => migrateSecretsFromSettings()); // no file at all
108
+ fs.writeFileSync(path.join(dir, "settings.json"), "{not json");
109
+ assert.doesNotThrow(() => migrateSecretsFromSettings());
110
+ assert.ok(!fs.existsSync(path.join(dir, ".env.local")), "corrupt file wrote nothing");
111
+ } finally {
112
+ fs.rmSync(dir, { recursive: true, force: true });
113
+ delete process.env.PI_CODING_AGENT_DIR;
114
+ }
115
+ });
116
+
117
+ test("writeSecretEnvs: upsert + create + onlyAbsent semantics, 0600", () => {
118
+ const dir = tmpDir();
119
+ try {
120
+ fs.writeFileSync(path.join(dir, ".env.local"), "EXISTING=old\n# comment\n");
121
+ const written = writeSecretEnvs({ NEW: "v1" }, { agentDir: dir });
122
+ assert.deepEqual(written, ["NEW"]);
123
+ writeSecretEnvs({ NEW: "v2" }, { agentDir: dir });
124
+ const text = fs.readFileSync(path.join(dir, ".env.local"), "utf8");
125
+ assert.match(text, /EXISTING=old/, "other lines preserved");
126
+ assert.match(text, /NEW=v2/, "upsert replaces in place");
127
+ assert.doesNotMatch(text, /NEW=v1/);
128
+ // onlyAbsent keeps the existing value.
129
+ writeSecretEnvs({ NEW: "v3", FRESH: "x" }, { agentDir: dir, onlyAbsent: true });
130
+ const text2 = fs.readFileSync(path.join(dir, ".env.local"), "utf8");
131
+ assert.match(text2, /NEW=v2/);
132
+ assert.match(text2, /FRESH=x/);
133
+ assert.equal(process.env.NEW, "v2", "process.env mirrors the surviving value");
134
+ // Mode check.
135
+ const mode = fs.statSync(path.join(dir, ".env.local")).mode & 0o777;
136
+ assert.equal(mode, 0o600);
137
+ assert.deepEqual(readSecretEnvs(dir).NEW, "v2");
138
+ // Newline-bearing values are rejected, not written corrupt.
139
+ writeSecretEnvs({ BAD: "line1\nline2" }, { agentDir: dir });
140
+ assert.doesNotMatch(fs.readFileSync(path.join(dir, ".env.local"), "utf8"), /BAD=/);
141
+ } finally {
142
+ delete process.env.NEW;
143
+ delete process.env.FRESH;
144
+ fs.rmSync(dir, { recursive: true, force: true });
145
+ delete process.env.PI_CODING_AGENT_DIR;
146
+ }
147
+ });
@@ -73,3 +73,183 @@ export function loadCwdEnvFilesIfTrusted(ctx: { isProjectTrusted?: () => boolean
73
73
  }
74
74
  }
75
75
  }
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // Secret store: <agentDir>/.env.local — secrets NEVER land in settings.json
79
+ // ---------------------------------------------------------------------------
80
+
81
+ /** The secrets file next to the global settings.json. 0600, git-ignored by
82
+ * design (agent dir is never a repo), ingested into process.env at import by
83
+ * loadGlobalEnvFiles above — so env resolution, which already WINS over the
84
+ * settings layers in every module, serves these values unchanged. */
85
+ export function secretsEnvFile(agentDir?: string): string {
86
+ const dir = agentDir ?? agentDirsForSecrets()[0]!;
87
+ return path.join(dir, ".env.local");
88
+ }
89
+
90
+ function agentDirsForSecrets(): string[] {
91
+ // Local import to avoid a cycle: registry.ts imports env.ts helpers? No —
92
+ // env.ts is a leaf. Inline the same resolution (keeps env.ts import-free).
93
+ return process.env.PI_CODING_AGENT_DIR
94
+ ? [process.env.PI_CODING_AGENT_DIR]
95
+ : [path.join(os.homedir(), ".pi", "agent"), path.join(os.homedir(), ".pi", "agents")];
96
+ }
97
+
98
+ /** Read the current secrets file as parsed entries ({} when absent). */
99
+ export function readSecretEnvs(agentDir?: string): Record<string, string> {
100
+ return readEnvFile(secretsEnvFile(agentDir));
101
+ }
102
+
103
+ /** Upsert KEY=VALUE lines into <agentDir>/.env.local (other lines preserved),
104
+ * write atomically at 0600, and mirror into process.env so the LIVE session
105
+ * resolves the new secret immediately (file ingestion only runs at import).
106
+ * `onlyAbsent` keeps any existing value (migration semantics). */
107
+ export function writeSecretEnvs(entries: Record<string, string>, opts: { agentDir?: string; onlyAbsent?: boolean } = {}): string[] {
108
+ const file = secretsEnvFile(opts.agentDir);
109
+ let text = "";
110
+ try {
111
+ text = fs.readFileSync(file, "utf8");
112
+ } catch { /* absent — start fresh */ }
113
+ const written: string[] = [];
114
+ for (const [key, value] of Object.entries(entries)) {
115
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue; // env-safe names only
116
+ // A newline in the value would corrupt the line-based .env format (the
117
+ // next read silently parses the remainder as garbage lines) — reject
118
+ // rather than write a broken file. API keys/tokens/cookies never contain
119
+ // newlines; a multiline PEM would need a different store anyway.
120
+ if (/[\r\n]/.test(value)) continue;
121
+ const line = `${key}=${value}`;
122
+ const re = new RegExp(`^${key}=.*$`, "m");
123
+ if (re.test(text)) {
124
+ if (opts.onlyAbsent) continue;
125
+ text = text.replace(re, line);
126
+ } else {
127
+ text += (text.endsWith("\n") || text === "" ? "" : "\n") + line + "\n";
128
+ }
129
+ written.push(key);
130
+ if (process.env[key] === undefined || !opts.onlyAbsent) process.env[key] = value;
131
+ }
132
+ if (written.length === 0) return written;
133
+ fs.mkdirSync(path.dirname(file), { recursive: true });
134
+ const tmp = file + ".tmp";
135
+ fs.writeFileSync(tmp, text, { mode: 0o600 });
136
+ fs.renameSync(tmp, file);
137
+ return written;
138
+ }
139
+
140
+ /** web-module secret rows: settings key → env var (mirrors webRowSpecs'
141
+ * secret:true entries; keep in sync). */
142
+ const WEB_SECRET_ENV_BY_KEY: Record<string, string> = {
143
+ "brave.apiKey": "BRAVE_API_KEY",
144
+ "firecrawl.apiKey": "FIRECRAWL_API_KEY",
145
+ "crawl4ai.apiToken": "CRAWL4AI_API_TOKEN",
146
+ "gemini.cookie": "GEMINI_WEB_SECURE_1PSID",
147
+ "image.zaiKey": "ZAI_API_KEY",
148
+ "image.customKey": "WEB_IMAGE_API_KEY",
149
+ "chat.apiKey": "WEB_CHAT_API_KEY",
150
+ };
151
+
152
+ /** One-time plaintext-secret migration out of the GLOBAL settings.json into
153
+ * <agentDir>/.env.local (env already wins at read time, so effective values
154
+ * are unchanged). Idempotent: a scrubbed key is absent next session, and
155
+ * onlyAbsent keeps any value the user hand-placed in .env.local first.
156
+ * Never throws — a failed migration leaves the (working) status quo. */
157
+ export function migrateSecretsFromSettings(): void {
158
+ try {
159
+ const dir = agentDirsForSecrets()[0]!;
160
+ const settingsFile = path.join(dir, "settings.json");
161
+ let settings: Record<string, any>;
162
+ try {
163
+ settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
164
+ } catch {
165
+ return; // absent/corrupt — nothing to migrate
166
+ }
167
+ const migrate: Record<string, string> = {};
168
+ const scrubWeb: string[] = [];
169
+ // web section: flat or nested secret keys.
170
+ const web = settings.web && typeof settings.web === "object" ? settings.web : {};
171
+ for (const [key, envName] of Object.entries(WEB_SECRET_ENV_BY_KEY)) {
172
+ let value: unknown = (web as Record<string, unknown>)[key];
173
+ if (value === undefined && key.includes(".")) {
174
+ let cur: unknown = web;
175
+ for (const p of key.split(".")) {
176
+ if (!cur || typeof cur !== "object") { cur = undefined; break; }
177
+ cur = (cur as Record<string, unknown>)[p];
178
+ }
179
+ value = cur;
180
+ }
181
+ if (typeof value === "string" && value !== "") {
182
+ migrate[envName] = value;
183
+ scrubWeb.push(key);
184
+ }
185
+ }
186
+ // a2a section: gateway tokens (legacy block + gateways map).
187
+ const a2a = settings.a2a && typeof settings.a2a === "object" ? settings.a2a : {};
188
+ const discovery = a2a.discovery && typeof a2a.discovery === "object" ? a2a.discovery : {};
189
+ let a2aChanged = false;
190
+ const gw = discovery.gateway && typeof discovery.gateway === "object" ? discovery.gateway : undefined;
191
+ if (gw && typeof gw.token === "string" && gw.token !== "") {
192
+ migrate.A2A_GATEWAY_TOKEN = gw.token;
193
+ delete gw.token;
194
+ a2aChanged = true;
195
+ }
196
+ if (gw && typeof gw.upstreamToken === "string" && gw.upstreamToken !== "") {
197
+ migrate.A2A_GATEWAY_UPSTREAM_TOKEN = gw.upstreamToken;
198
+ delete gw.upstreamToken;
199
+ a2aChanged = true;
200
+ }
201
+ const gws = discovery.gateways && typeof discovery.gateways === "object" ? discovery.gateways : undefined;
202
+ if (gws) {
203
+ for (const [key, raw] of Object.entries(gws as Record<string, any>)) {
204
+ if (!raw || typeof raw !== "object") continue;
205
+ const keyEnv = key.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
206
+ if (typeof raw.token === "string" && raw.token !== "") {
207
+ migrate[`A2A_GATEWAY_${keyEnv}_TOKEN`] = raw.token;
208
+ delete raw.token;
209
+ a2aChanged = true;
210
+ }
211
+ if (typeof raw.upstreamToken === "string" && raw.upstreamToken !== "") {
212
+ migrate[`A2A_GATEWAY_${keyEnv}_UPSTREAM_TOKEN`] = raw.upstreamToken;
213
+ delete raw.upstreamToken;
214
+ a2aChanged = true;
215
+ }
216
+ }
217
+ }
218
+ if (Object.keys(migrate).length === 0) return;
219
+ // Ordering: env write FIRST, settings scrub second. If the process dies
220
+ // between them the secret exists in both places — harmless (env wins at
221
+ // read time) and the next session's migration scrubs again (idempotent).
222
+ // The reverse order could LOSE a secret (scrubbed but never written).
223
+ writeSecretEnvs(migrate, { agentDir: dir, onlyAbsent: true });
224
+ // Scrub: rewrite settings.json WITHOUT the migrated secrets, atomically.
225
+ if (scrubWeb.length > 0) {
226
+ for (const key of scrubWeb) {
227
+ delete (web as Record<string, unknown>)[key];
228
+ const parts = key.split(".");
229
+ if (parts.length < 2) continue;
230
+ let cur: any = web;
231
+ for (const p of parts.slice(0, -1)) {
232
+ if (!cur[p] || typeof cur[p] !== "object") { cur = null; break; }
233
+ cur = cur[p];
234
+ }
235
+ if (cur) delete cur[parts[parts.length - 1]!];
236
+ }
237
+ const prune = (node: Record<string, unknown>) => {
238
+ for (const [k, v] of Object.entries(node)) {
239
+ if (v && typeof v === "object" && !Array.isArray(v)) {
240
+ prune(v as Record<string, unknown>);
241
+ if (Object.keys(v as Record<string, unknown>).length === 0) delete node[k];
242
+ }
243
+ }
244
+ };
245
+ prune(web as Record<string, unknown>);
246
+ if (Object.keys(web).length === 0) delete settings.web;
247
+ }
248
+ if (scrubWeb.length === 0 && !a2aChanged) return;
249
+ const tmp = settingsFile + ".tmp";
250
+ fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
251
+ fs.renameSync(tmp, settingsFile);
252
+ } catch {
253
+ /* never break startup over a migration */
254
+ }
255
+ }
@@ -0,0 +1,74 @@
1
+ // Load-order guard at the REGISTRATION level: the MODULES array order is the
2
+ // contract's proxy, but the real invariant is "no module that registers a
3
+ // before_agent_start handler loads after steering". This test loads every
4
+ // module against a recording fake pi (all pi methods no-op; .on records) and
5
+ // asserts the registration order directly — a module added to MODULES after
6
+ // steering with a prompt-rewriting handler fails HERE even if nobody updates
7
+ // the array-order assertions in registry.test.ts.
8
+ //
9
+ // Live incident class (reviewer 2026-10-06): rtk loaded after steering and
10
+ // its before_agent_start appended the RTK note to the ds-anchor's
11
+ // byte-identical minimal prompt, silently defeating the anchor.
12
+
13
+ import { describe, it, before, after } from "node:test";
14
+ import assert from "node:assert/strict";
15
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+
19
+ describe("before_agent_start registration order (steering contract)", () => {
20
+ let dir: string;
21
+ before(() => {
22
+ dir = mkdtempSync(join(tmpdir(), "ceulen-order-"));
23
+ process.env.PI_CODING_AGENT_DIR = dir;
24
+ // Neutral settings: all modules enabled, no ceulen section.
25
+ writeFileSync(join(dir, "settings.json"), "{}");
26
+ });
27
+ after(() => {
28
+ rmSync(dir, { recursive: true, force: true });
29
+ delete process.env.PI_CODING_AGENT_DIR;
30
+ });
31
+
32
+ it("no module registering before_agent_start loads after steering", async () => {
33
+ const { MODULES } = await import("./registry.js");
34
+ const registrations: { module: string; event: string }[] = [];
35
+ const failures: string[] = [];
36
+
37
+ const makePi = (mod: string) =>
38
+ new Proxy({} as Record<string, unknown>, {
39
+ get(_t, prop: string) {
40
+ if (prop === "on") {
41
+ return (event: string) => { registrations.push({ module: mod, event }); };
42
+ }
43
+ if (prop === "then") return undefined; // not a thenable
44
+ return () => undefined; // no-op every other load-time pi call
45
+ },
46
+ });
47
+
48
+ for (const m of MODULES) {
49
+ try {
50
+ (m.load as (pi: unknown, deps?: unknown) => void)(makePi(m.name), { configContribs: new Map() });
51
+ } catch (err) {
52
+ // A module needing more than the stub offers still REGISTERED its
53
+ // handlers before failing (pi.on is called first); record and move on.
54
+ failures.push(`${m.name}: ${err instanceof Error ? err.message : String(err)}`);
55
+ }
56
+ }
57
+
58
+ const at = MODULES.findIndex((m) => m.name === "steering");
59
+ const rewroteAfter = registrations.filter(
60
+ (r) => r.event === "before_agent_start" && MODULES.findIndex((m) => m.name === r.module) > at,
61
+ );
62
+ assert.deepEqual(
63
+ rewroteAfter.map((r) => r.module),
64
+ [],
65
+ `before_agent_start registered AFTER steering by: ${rewroteAfter.map((r) => r.module).join(", ")} — ` +
66
+ "steering must be the last prompt rewriter (ds-anchor byte-identity). " +
67
+ `(load failures tolerated: ${failures.length})`,
68
+ );
69
+ // Sanity: the harness captured real registrations from many modules.
70
+ assert.ok(registrations.length > 30, `expected many registrations, saw ${registrations.length}`);
71
+ assert.ok(registrations.some((r) => r.module === "rtk" && r.event === "before_agent_start"),
72
+ "rtk's before_agent_start must be visible to this guard");
73
+ });
74
+ });
@@ -53,15 +53,18 @@ describe("MODULES load order", () => {
53
53
  // rewriter (its ds-anchor bootstrap REPLACES the final prompt; a rewriter
54
54
  // loaded after it would append to the byte-identical minimal prompt, which
55
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 () => {
56
+ // (config). Modules registering before_agent_start and loading BEFORE
57
+ // steering: munin, advisor, ux, ponytail, subagent, plan, fff, serena, web,
58
+ // rules, rtk — web is the last of them, hence the anchor below. rtk IS a
59
+ // prompt rewriter (its before_agent_start appends the RTK note), so it must
60
+ // sit before steering or the ds-anchor bootstrap loses byte-identity.
61
+ it("steering is the last prompt rewriter, after rtk, before config", async () => {
60
62
  const { MODULES } = await import("./registry.js");
61
63
  const at = (name: string) => MODULES.findIndex((m) => m.name === name);
62
64
  assert.ok(at("steering") > at("web"), "steering loads after the last rewriter (web)");
63
65
  assert.ok(at("steering") > at("serena") && at("steering") > at("plan"));
64
- assert.ok(at("steering") < at("rtk"), "rtk (no prompt rewrite) loads after steering");
66
+ assert.ok(at("steering") > at("rtk"), "rtk (a prompt rewriter) loads before steering");
67
+ assert.ok(at("steering") > at("rules"), "rules (prompt composer) loads before steering");
65
68
  assert.equal(MODULES.at(-1)!.name, "config", "config stays last");
66
69
  });
67
70
  });
@@ -170,6 +170,10 @@ export const MODULES: ModuleEntry[] = [
170
170
  // gh binary (registers nothing until installed). Read-only ops only, so
171
171
  // plan mode auto-allows it (plan-tools.ts READ_ONLY_TOOLS).
172
172
  { name: "gh", category: "Tools", describe: "GitHub tool over the gh CLI: repo/file/PR views, PR diff, five search flavors, Actions run_watch. Read-only; mutating flows stay on bash gh.", load: ghModule, config: ghConfig, tools: ["github"] },
173
+ // rtk is a PROMPT REWRITER (its before_agent_start appends the RTK note), so
174
+ // it must load BEFORE steering — during a ds-anchor bootstrap, steering's
175
+ // minimal prompt replaces everything, including this note (byte-identity);
176
+ // on the normal path steering composes onto it.
173
177
  // Steering LAST of the prompt rewriters, i.e. after EVERY before_agent_start
174
178
  // composer (ponytail/plan/subagent/munin/advisor/ux/fff/serena/web/rules) and
175
179
  // before the config module (load order is load-bearing even though its
@@ -177,11 +181,12 @@ export const MODULES: ModuleEntry[] = [
177
181
  // independently): pi chains before_agent_start results, so steering must run
178
182
  // LAST for its deepseek-v4-pro anchor bootstrap to REPLACE the final prompt
179
183
  // (byte-identical minimal prompt) instead of appending to a prompt that
180
- // serena/web then append to. Nothing after this entry (rtk, config) touches
181
- // the prompt — do not move it earlier or add a prompt rewriter after it.
184
+ // serena/web/rtk then append to. rtk (a prompt rewriter — it appends the
185
+ // RTK note) loads BEFORE this entry; nothing after steering touches the
186
+ // prompt — do not move rtk back after it or add a prompt rewriter here.
187
+ { name: "rtk", category: "Shell", describe: "Route shell commands through RTK for token savings.", load: rtkModule },
182
188
  { 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, tools: ["think"] },
183
189
  // ── Shell ──────────────────────────────────────────────────────────────
184
- { name: "rtk", category: "Shell", describe: "Route shell commands through RTK for token savings.", load: rtkModule },
185
190
  // Permission after rtk: persistent allow/ask/deny gating. Inert until rules
186
191
  // exist; defers to plan mode via the shared plan-bridge flag (order-free).
187
192
  { name: "permission", category: "Shell", describe: "Persistent allow/ask/deny permission rules per tool (wildcards, external-directory boundary, doom-loop guard) — opt-in via the `permission` settings section; inert until configured.", load: permissionModule },
@@ -29,6 +29,13 @@ import {
29
29
  type Peer,
30
30
  } from "./lib/config.js";
31
31
  import { a2aServerRunning as a2aServerRunningIndex, restartA2AServer as restartA2AServerIndex } from "./index.js";
32
+ import { writeSecretEnvs } from "../../lib/env.js";
33
+
34
+ /** Env var name for one gateway secret (per-key diversion). */
35
+ function gatewayTokenEnv(key: string, field: "token" | "upstreamToken"): string {
36
+ const keyEnv = key.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
37
+ return field === "token" ? `A2A_GATEWAY_${keyEnv}_TOKEN` : `A2A_GATEWAY_${keyEnv}_UPSTREAM_TOKEN`;
38
+ }
32
39
 
33
40
  /** Restart bridge — defaults to the index.ts exports; tests inject via
34
41
  * __setRestartBridgeForTests (the panel must not spin real servers). */
@@ -380,10 +387,43 @@ export function a2aConfig(pi: ExtensionAPI): ModuleConfig {
380
387
  gatewayChanged,
381
388
  editedGatewayKeys,
382
389
  });
390
+ // SECRETS DIVERSION: gateway tokens never persist in settings.json.
391
+ // Tokens the user actually edited → .env.local (0600, ingested at
392
+ // startup, env wins at read time); the loader's per-key env fallback
393
+ // (config.ts) resolves them at read time. The settings patch keeps
394
+ // every non-secret field (URL, name, heartbeat, enabled).
395
+ const secretEnvs: Record<string, string> = {};
396
+ const diverted = (patch: (a2a: any) => any): (a2a: any) => any => (a2a: any) => {
397
+ const out = patch(a2a);
398
+ if (out?.discovery && typeof out.discovery === "object") {
399
+ const scrub = (entry: Record<string, any>, key: string | null, editedToken: boolean, editedUpstream: boolean) => {
400
+ if (editedToken && entry.token) {
401
+ secretEnvs[key ? gatewayTokenEnv(key, "token") : "A2A_GATEWAY_TOKEN"] = String(entry.token);
402
+ entry.token = "";
403
+ }
404
+ if (editedUpstream && entry.upstreamToken) {
405
+ secretEnvs[key ? gatewayTokenEnv(key, "upstreamToken") : "A2A_GATEWAY_UPSTREAM_TOKEN"] = String(entry.upstreamToken);
406
+ entry.upstreamToken = undefined;
407
+ }
408
+ };
409
+ if (out.discovery.gateway && typeof out.discovery.gateway === "object") {
410
+ scrub(out.discovery.gateway, null, editedGatewayKeys.has("gateway.token"), editedGatewayKeys.has("gateway.upstreamToken"));
411
+ }
412
+ if (out.discovery.gateways && typeof out.discovery.gateways === "object") {
413
+ for (const [k, entry] of Object.entries(out.discovery.gateways as Record<string, any>)) {
414
+ if (entry && typeof entry === "object") {
415
+ scrub(entry, k, editedGatewayKeys.has(`gw.${k}.token`), editedGatewayKeys.has(`gw.${k}.upstreamToken`));
416
+ }
417
+ }
418
+ }
419
+ }
420
+ return out;
421
+ };
383
422
  const written = writeSettingsA2A({
384
423
  cwd: ctx.cwd,
385
- patch: builtPatch,
424
+ patch: diverted(builtPatch),
386
425
  });
426
+ const savedSecrets = Object.keys(secretEnvs).length > 0 ? writeSecretEnvs(secretEnvs) : [];
387
427
 
388
428
  // Live apply — config is read per call; no /reload needed.
389
429
  setConfigOverrides({
@@ -395,6 +435,7 @@ export function a2aConfig(pi: ExtensionAPI): ModuleConfig {
395
435
  });
396
436
 
397
437
  const notes = [`A2A config saved to ${written} — applied live.`];
438
+ if (savedSecrets.length) notes.push(`Gateway token(s) saved to .env.local (${savedSecrets.length}) — never settings.json.`);
398
439
  // Env overrides still shadowing edited fields.
399
440
  const envOverrides = [...edited]
400
441
  .map((k) => (k.startsWith("a2a.") ? ENV_SHADOW[k.slice("a2a.".length)] : undefined))
@@ -503,7 +503,9 @@ export function loadConfig(opts: {
503
503
  url: gwUrl,
504
504
  token: gwToken,
505
505
  name: dg.name ? String(dg.name) : undefined,
506
- upstreamToken: dg.upstreamToken ? String(dg.upstreamToken) : undefined,
506
+ // Secrets live in .env.local (panel diversion) — env fallback keeps
507
+ // settings.json free of tokens while the value still resolves.
508
+ upstreamToken: dg.upstreamToken != null ? String(dg.upstreamToken) : (env.A2A_GATEWAY_UPSTREAM_TOKEN || undefined),
507
509
  heartbeatSec: num(dg.heartbeatSec, 60),
508
510
  channel: dg.channel === undefined ? undefined : bool(dg.channel, true),
509
511
  };
@@ -518,15 +520,18 @@ export function loadConfig(opts: {
518
520
  if (!GATEWAY_KEY_RE.test(key)) continue;
519
521
  if (!raw || typeof raw !== "object") continue;
520
522
  const g = raw as Record<string, any>;
523
+ // Per-gateway secret env names (panel diversion — tokens never persist
524
+ // in settings.json): A2A_GATEWAY_<KEY>_TOKEN / _UPSTREAM_TOKEN.
525
+ const keyEnv = key.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
521
526
  const u = String(g.url ?? "");
522
- const t = String(g.token ?? "");
527
+ const t = String(g.token ?? env[`A2A_GATEWAY_${keyEnv}_TOKEN`] ?? "");
523
528
  const enabled = g.enabled !== undefined ? bool(g.enabled, true) : Boolean(u && t);
524
529
  gateways[key] = {
525
530
  enabled,
526
531
  url: u,
527
532
  token: t,
528
533
  name: g.name ? String(g.name) : undefined,
529
- upstreamToken: g.upstreamToken ? String(g.upstreamToken) : undefined,
534
+ upstreamToken: g.upstreamToken != null ? String(g.upstreamToken) : (env[`A2A_GATEWAY_${keyEnv}_UPSTREAM_TOKEN`] || undefined),
530
535
  heartbeatSec: num(g.heartbeatSec, 60),
531
536
  channel: g.channel === undefined ? undefined : bool(g.channel, true),
532
537
  };