ceulen 0.11.0 → 0.13.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 (70) hide show
  1. package/CHANGELOG.md +100 -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 +23 -4
  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 +2 -2
  16. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  17. package/extensions/modules/jfind/index.ts +115 -0
  18. package/extensions/modules/jfind/lib/cascade.ts +377 -0
  19. package/extensions/modules/jfind/lib/format.ts +12 -0
  20. package/extensions/modules/jfind/lib/judge.ts +74 -0
  21. package/extensions/modules/jfind/lib/lexical.ts +232 -0
  22. package/extensions/modules/jfind/lib/questions.ts +178 -0
  23. package/extensions/modules/jfind/lib/tree.ts +374 -0
  24. package/extensions/modules/jfind/test/cascade.test.ts +305 -0
  25. package/extensions/modules/notify/index.ts +33 -0
  26. package/extensions/modules/notify/lib/notify.ts +99 -0
  27. package/extensions/modules/notify/test/notify.test.ts +95 -0
  28. package/extensions/modules/plan/lib/plan-tools.ts +13 -0
  29. package/extensions/modules/repair/configPanel.ts +7 -1
  30. package/extensions/modules/repair/index.ts +158 -3
  31. package/extensions/modules/repair/lib/auto-generated.ts +89 -0
  32. package/extensions/modules/repair/lib/read-archive.ts +101 -0
  33. package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
  34. package/extensions/modules/repair/lib/settings.ts +4 -1
  35. package/extensions/modules/repair/test/freshness.test.ts +41 -1
  36. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  37. package/extensions/modules/repair/test/readers.test.ts +291 -0
  38. package/extensions/modules/repair/test/settings.test.ts +2 -1
  39. package/extensions/modules/router/configPanel.ts +4 -4
  40. package/extensions/modules/router/index.ts +1 -1
  41. package/extensions/modules/router/lib/config.ts +9 -4
  42. package/extensions/modules/router/lib/systemone.ts +17 -4
  43. package/extensions/modules/router/test/unit.test.ts +46 -1
  44. package/extensions/modules/rules/index.ts +13 -3
  45. package/extensions/modules/rules/lib/rules.ts +24 -12
  46. package/extensions/modules/rules/test/lib.test.ts +20 -0
  47. package/extensions/modules/rules/test/module.test.ts +21 -0
  48. package/extensions/modules/sg/index.ts +129 -0
  49. package/extensions/modules/sg/lib/ops.ts +144 -0
  50. package/extensions/modules/sg/lib/sg-cli.ts +104 -0
  51. package/extensions/modules/sg/test/sg.test.ts +128 -0
  52. package/extensions/modules/shells/index.ts +210 -0
  53. package/extensions/modules/shells/lib/sessions.ts +344 -0
  54. package/extensions/modules/shells/test/sessions.test.ts +275 -0
  55. package/extensions/modules/subagent/index.ts +11 -5
  56. package/extensions/modules/subagent/lib/herdr.ts +5 -0
  57. package/extensions/modules/subagent/lib/routing.ts +31 -8
  58. package/extensions/modules/subagent/lib/runner.ts +8 -2
  59. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  60. package/extensions/modules/web/configPanel.ts +67 -8
  61. package/extensions/modules/web/index.ts +34 -0
  62. package/extensions/modules/web/lib/pdf.ts +181 -0
  63. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  64. package/extensions/modules/web/test/extension.test.ts +2 -1
  65. package/extensions/modules/web/test/settings.test.ts +6 -0
  66. package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
  67. package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
  68. package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
  69. package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
  70. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,6 +1,105 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.13.0 — 2026-10-08
4
+
5
+ - **Tool-parity wave** (8h OMP/industry survey plan): 4 new modules + 4
6
+ read/write upgrades, all live-verified end-to-end (real spawns, real
7
+ classifier round-trips, real osascript):
8
+ - **shells** (new module): one `shell` tool — start/list/output/stdin/kill
9
+ over persistent background processes (dev servers, watchers, long
10
+ builds). Own process group per session (group kill via `kill(-pid)`),
11
+ 256 KB line rings (head+tail + truncation marker), 10 live/5 exited
12
+ caps, `since:"last"` output cursor, killAll on session_shutdown.
13
+ Plan-blocked.
14
+ - **read-sqlite** (repair): the wrapped read opens `db.sqlite` views —
15
+ table list, `:users` schema+rows, `:users:42` rowid, `:users:name=alice`
16
+ key lookup, `:?SELECT…` read-only query. `node:sqlite` READ-ONLY per
17
+ call; db is genuinely un-writable.
18
+ - **read-archive** (repair): `.tar`/`.tgz`/`.zip` member listing +
19
+ content through the read path; exact-then-unique-suffix member match,
20
+ 1 MB cap, binary refusal; `pkg.tgz:src/x.ts:50-80` slices the member.
21
+ - **auto-generated guard** (repair): writes/edits to lockfiles, minified
22
+ bundles, build dirs and snapshots are refused with a regenerate hint
23
+ (bash stays the deliberate override); `repair.autoGenGuard` setting,
24
+ default on, /config row on Tools → Repair.
25
+ - **read_pdf** (web, 13th tool): local PDF text via vendored pdf.js 4.10
26
+ (Apache-2.0, lazy import, workerless) — no external binaries; pages
27
+ grammar `"3"`, `"1-5"`, `"2,4,6-8"`, 10-page cap/call. Plan read-only.
28
+ - **sg** (new module): `ast_grep` (structural search, `$VAR`/`$$$ALL`
29
+ meta-variables, multi-pattern merge+dedupe) + `ast_edit` (pattern →
30
+ rewrite across files; DRY-RUN by default, staleness re-check after
31
+ apply warns on self-matching rewrites). Fail-open on a missing
32
+ ast-grep binary. Pattern-parse failures render a hint on ast-grep 0.4x
33
+ (exit 8 "Cannot parse query") as well as legacy sg. Plan read-only
34
+ search, blocked rewrite.
35
+ - **jfind** (new module): semantic code find — describe a behavior, get
36
+ files + line ranges, strongest first. OMP cascade port (lexical IDF
37
+ prior → filename judging → sketch routing → passage verification); the
38
+ judge routes through the router's System One classifier models. Plan
39
+ read-only.
40
+ - **notify** (new module): one `notify` tool — desktop notification via
41
+ osascript/notify-send, bell fallback, harmless by construction.
42
+ - Wiring: registry entries + per-tool kill-switches + plan-mode tiers, test
43
+ globs, /config tool-section count 16→20, composer disabled-list, AGENTS.md
44
+ sections, `@types/node` ^24 (node:sqlite types).
45
+ - Tests: 2750 (was 2661) — suites for shells sessions, readers, sg ops,
46
+ jfind cascade (fake-judge), notify.
47
+ - Live-verified (2026-10-08 round): shells ring/group-kill/stdin,
48
+ sqlite+archive views + guard refusal through real pi runs, pdf extraction,
49
+ sg dry-run/apply/staleness, jfind cascade vs the real classifier, notify
50
+ osascript delivery; one fix shipped (sg pattern-error detection, above).
51
+
52
+ ## 0.12.0 — 2026-10-08
53
+
54
+ - **Secrets never land in settings.json** (user policy: URLs fine, credentials
55
+ not): masked `/config` rows (web's 7 keys/cookies, a2a gateway
56
+ token/upstreamToken) persist to `<agentDir>/.env.local` (0600, ingested into
57
+ process.env at import — env already won at read time, so effective values
58
+ are unchanged); `migrateSecretsFromSettings` (bundle session_start) moves
59
+ any pre-fix plaintext secrets out of settings.json and scrubs them,
60
+ idempotently (extensions/lib/env.ts: writeSecretEnvs/readSecretEnvs; a2a's
61
+ loader gained per-gateway env fallbacks `A2A_GATEWAY_<KEY>_TOKEN` /
62
+ `_UPSTREAM_TOKEN`).
63
+ - **Live-incident fixes (8h herdr hang)**: systemoneClassify carries a default
64
+ 30s deadline (pi passes no timeoutMs — a silent endpoint parked dispatches
65
+ forever); subagent routing wraps the classify ask in a 45s race
66
+ (`deadlineMs` injectable, fail-open to the static chain); the herdr
67
+ wall-clock cap is the opt-in hard cap or 60 min — never the 3-min idle
68
+ window, which killed healthy long-running panes; timed-out panes report
69
+ that they may still complete their current write.
70
+ - **Review fixes (two subagent review waves, 13 findings)**:
71
+ - repair: the read guard no longer blocks numeric path-selector reads
72
+ (`f.ts:50-200` — it probed the raw path while the selector peels only in
73
+ execute); a successful `edit` (direct or trim-retry) now refreshes the
74
+ write-freshness baseline (read → edit → write no longer false-positives);
75
+ selector reads record the baseline too.
76
+ - rules: project RULES.md is trust-gated — an untrusted checkout's rules
77
+ never reach the system prompt or rule_get (same gate as pi's AGENTS.md);
78
+ creating a previously-missing @import target now invalidates the cache.
79
+ - router: the systemone classify URL applies the same `/v1`-append
80
+ convention as discovery (a bare-host baseUrl silently 404'd every
81
+ classify); the repo-scope overlay resolves from the session cwd, not
82
+ process.cwd().
83
+ - classifier: the bash verdict hook is bounded to a 2.5s budget (verdicts
84
+ are annotation-only in pi 1.0.0 — never park a tool call on Jev) and
85
+ pauses after 3 consecutive classify failures for 5 minutes (audited;
86
+ settings change or success re-arms).
87
+ - subagent: the dispatch verdict gates on the CHOSEN label's own
88
+ probability (a rival no longer clears the threshold for a low-confidence
89
+ choice, matching the tier rule); removeWorktree locks on the resolved
90
+ repo root (subdir-cwd dispatches no longer key the per-repo lock
91
+ differently); the tool schema no longer promises upstream's removed
92
+ 20-min lifetime cap.
93
+ - advisor: enabling the review via /config reseeds the cursor on FIRST
94
+ activation — an enable-only save no longer reviews the entire transcript.
95
+ - load order: rtk is a prompt rewriter and now loads BEFORE steering (its
96
+ note must not break the ds-anchor byte-identity); a registration-level
97
+ guard test (extensions/lib/order.test.ts) fails if any prompt rewriter
98
+ lands after steering.
99
+ - Tests: 2661 (was 2647) — new suites for the secrets store + migration, the
100
+ registration-order guard, the guard×selector interaction, edit/selector
101
+ freshness, the classifier breaker + budget, and the dispatch/deadline
102
+ routing paths.
4
103
 
5
104
  ## 0.11.0 — 2026-10-07
6
105
 
@@ -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
  });
@@ -50,6 +50,10 @@ import { attachmentsConfig } from "../modules/attachments/configPanel.ts";
50
50
  import cronModule from "../modules/cron/index.ts";
51
51
  import { cronConfig } from "../modules/cron/configPanel.ts";
52
52
  import permissionModule from "../modules/permission/index.ts";
53
+ import shellsModule from "../modules/shells/index.ts";
54
+ import sgModule from "../modules/sg/index.ts";
55
+ import jfindModule from "../modules/jfind/index.ts";
56
+ import notifyModule from "../modules/notify/index.ts";
53
57
  import configModule from "../modules/config/index.ts";
54
58
 
55
59
  /** A module's contribution to the central `/config` panel. */
@@ -156,11 +160,14 @@ export const MODULES: ModuleEntry[] = [
156
160
  { name: "fff", category: "Tools", describe: "FFF fuzzy file/content search (ffgrep, fffind) + @-mention completions.", load: fffModule, tools: [
157
161
  "ffgrep", "ffind", "fff_multi_grep", "resolve_file", "related_files",
158
162
  ] },
163
+ // jfind after fff: the semantic sibling of the lexical search pair (its
164
+ // judge resolves through the router's classifier models at execute time).
165
+ { name: "jfind", category: "Tools", describe: "Semantic code find: describe what code does, get files + line ranges (lexical prior + System One judge cascade).", load: jfindModule, tools: ["jfind"] },
159
166
  // Web after fff: same class of append-only before_agent_start guidance
160
167
  // (conditional on web_* tools being active) — no prompt-rewrite contract
161
168
  // beyond fff's shipped precedent.
162
169
  { 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: [
163
- "web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_interact", "web_research", "web_image", "web_chat", "web_status", "web_a11y",
170
+ "web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_interact", "web_research", "web_image", "web_chat", "web_status", "web_a11y", "read_pdf",
164
171
  ] },
165
172
  { 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"] },
166
173
  // Attachments: paste/drop files become real attachments. No tools/commands —
@@ -170,6 +177,14 @@ export const MODULES: ModuleEntry[] = [
170
177
  // gh binary (registers nothing until installed). Read-only ops only, so
171
178
  // plan mode auto-allows it (plan-tools.ts READ_ONLY_TOOLS).
172
179
  { 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"] },
180
+ // sg after gh: the same external-binary fail-open shape, for ast-grep.
181
+ { name: "sg", category: "Tools", describe: "Structural search & rewrite via the ast-grep CLI: ast_grep search, ast_edit dry-run-default rewrites. Registers nothing until ast-grep/sg is installed.", load: sgModule, tools: ["ast_grep", "ast_edit"] },
182
+ // notify: harmless desktop ping (bell fallback), herdr multi-pane ergonomics.
183
+ { name: "notify", category: "Tools", describe: "Desktop notification tool: ping the user when long work settles or input is needed (osascript / notify-send / bell).", load: notifyModule, tools: ["notify"] },
184
+ // rtk is a PROMPT REWRITER (its before_agent_start appends the RTK note), so
185
+ // it must load BEFORE steering — during a ds-anchor bootstrap, steering's
186
+ // minimal prompt replaces everything, including this note (byte-identity);
187
+ // on the normal path steering composes onto it.
173
188
  // Steering LAST of the prompt rewriters, i.e. after EVERY before_agent_start
174
189
  // composer (ponytail/plan/subagent/munin/advisor/ux/fff/serena/web/rules) and
175
190
  // before the config module (load order is load-bearing even though its
@@ -177,14 +192,18 @@ export const MODULES: ModuleEntry[] = [
177
192
  // independently): pi chains before_agent_start results, so steering must run
178
193
  // LAST for its deepseek-v4-pro anchor bootstrap to REPLACE the final prompt
179
194
  // (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.
195
+ // serena/web/rtk then append to. rtk (a prompt rewriter — it appends the
196
+ // RTK note) loads BEFORE this entry; nothing after steering touches the
197
+ // prompt — do not move rtk back after it or add a prompt rewriter here.
198
+ { name: "rtk", category: "Shell", describe: "Route shell commands through RTK for token savings.", load: rtkModule },
182
199
  { 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
200
  // ── Shell ──────────────────────────────────────────────────────────────
184
- { name: "rtk", category: "Shell", describe: "Route shell commands through RTK for token savings.", load: rtkModule },
185
201
  // Permission after rtk: persistent allow/ask/deny gating. Inert until rules
186
202
  // exist; defers to plan mode via the shared plan-bridge flag (order-free).
187
203
  { 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 },
204
+ // Background shell sessions (the bash-escape-hatch tool is BLOCKED in plan
205
+ // mode via plan-tools.ts — keep that in sync when renaming).
206
+ { name: "shells", category: "Shell", describe: "Background shell sessions: start/list/output/stdin/kill over persistent processes (dev servers, watchers). Killed on session shutdown; blocked in plan mode.", load: shellsModule, tools: ["shell"] },
188
207
  // ── Plugins ────────────────────────────────────────────────────────────
189
208
  // Config last: it owns /config and reads the contrib map. CORE: the panel is
190
209
  // the only in-app way back from a misconfiguration — it can never be the