ceulen 0.10.1 → 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 (69) hide show
  1. package/CHANGELOG.md +107 -1
  2. package/README.md +56 -1
  3. package/extensions/index.ts +5 -1
  4. package/extensions/lib/env.test.ts +147 -0
  5. package/extensions/lib/env.ts +180 -0
  6. package/extensions/lib/order.test.ts +74 -0
  7. package/extensions/lib/plan-bridge.ts +18 -0
  8. package/extensions/lib/registry.test.ts +8 -5
  9. package/extensions/lib/registry.ts +22 -3
  10. package/extensions/modules/a2a/configPanel.ts +42 -1
  11. package/extensions/modules/a2a/index.ts +4 -2
  12. package/extensions/modules/a2a/lib/config.ts +8 -3
  13. package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
  14. package/extensions/modules/advisor/index.ts +6 -3
  15. package/extensions/modules/advisor/test/module.test.ts +31 -0
  16. package/extensions/modules/attachments/configPanel.ts +91 -0
  17. package/extensions/modules/attachments/index.ts +274 -0
  18. package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
  19. package/extensions/modules/attachments/lib/pastes.ts +45 -0
  20. package/extensions/modules/attachments/lib/paths.ts +74 -0
  21. package/extensions/modules/attachments/lib/registry.ts +70 -0
  22. package/extensions/modules/attachments/lib/settings.ts +99 -0
  23. package/extensions/modules/attachments/lib/tray.ts +74 -0
  24. package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
  25. package/extensions/modules/attachments/test/index.test.ts +870 -0
  26. package/extensions/modules/attachments/test/module.test.ts +53 -0
  27. package/extensions/modules/classifier/index.ts +55 -1
  28. package/extensions/modules/classifier/test/classifier.test.ts +62 -0
  29. package/extensions/modules/composer/test/module.test.ts +2 -2
  30. package/extensions/modules/config/index.ts +3 -0
  31. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  32. package/extensions/modules/cron/configPanel.ts +103 -0
  33. package/extensions/modules/cron/index.ts +638 -0
  34. package/extensions/modules/cron/lib/jobs.ts +201 -0
  35. package/extensions/modules/cron/lib/schedule.ts +161 -0
  36. package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
  37. package/extensions/modules/cron/test/index.test.ts +859 -0
  38. package/extensions/modules/cron/test/schedule.test.ts +93 -0
  39. package/extensions/modules/munin/index.ts +3 -1
  40. package/extensions/modules/permission/index.ts +567 -0
  41. package/extensions/modules/permission/test/permission.test.ts +789 -0
  42. package/extensions/modules/plan/index.ts +5 -0
  43. package/extensions/modules/repair/index.ts +160 -5
  44. package/extensions/modules/repair/test/freshness.test.ts +209 -0
  45. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  46. package/extensions/modules/router/configPanel.ts +4 -4
  47. package/extensions/modules/router/index.ts +1 -1
  48. package/extensions/modules/router/lib/config.ts +9 -4
  49. package/extensions/modules/router/lib/systemone.ts +17 -4
  50. package/extensions/modules/router/test/unit.test.ts +46 -1
  51. package/extensions/modules/rules/index.ts +13 -3
  52. package/extensions/modules/rules/lib/rules.ts +24 -12
  53. package/extensions/modules/rules/test/lib.test.ts +20 -0
  54. package/extensions/modules/rules/test/module.test.ts +21 -0
  55. package/extensions/modules/subagent/index.ts +49 -10
  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 +356 -14
  59. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  60. package/extensions/modules/subagent/test/worktree.test.ts +230 -0
  61. package/extensions/modules/usage/index.ts +193 -71
  62. package/extensions/modules/usage/test/context.test.ts +160 -120
  63. package/extensions/modules/web/configPanel.ts +67 -8
  64. package/extensions/modules/web/index.ts +3 -1
  65. package/extensions/modules/web/test/a11y.test.ts +1 -1
  66. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  67. package/extensions/modules/web/test/settings.test.ts +6 -0
  68. package/package.json +2 -2
  69. package/skills/cron/SKILL.md +58 -0
package/CHANGELOG.md CHANGED
@@ -1,6 +1,112 @@
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.
54
+
55
+ ## 0.11.0 — 2026-10-07
56
+
57
+ - **Worktree sandbox hardening + multi-session repo safety** (subagent module;
58
+ OMP/Claude-Code mechanisms ported at ponytail scale — no new deps, no new
59
+ settings):
60
+ - **Per-repo lock** (`withRepoLock`, keyed by resolved repo root):
61
+ serializes the parent-mutating git calls — `worktree add`, `worktree
62
+ remove`, and the `git apply --3way` merge — which previously raced on
63
+ git's no-waiter O_EXCL locks when parallel children finished together.
64
+ - **Owner marker + GC sweep**: each sandbox records a sibling
65
+ `<id>.owner.json` (`{pid, id, createdAt}`, 0600) OUTSIDE the sandbox dir
66
+ so it can never leak into the captured diff (an in-sandbox marker made
67
+ two parallel merges add/add-conflict — caught by the live race test);
68
+ `sweepStaleWorktrees` runs fire-and-forget on `session_start` and removes
69
+ dead-owner sandboxes (registration-aware: `worktree remove` for
70
+ registered entries, `rm -rf` for CoW copies). `/subagent worktrees
71
+ [clean]` lists or forces the sweep.
72
+ - **`<repoRoot>/.pi-worktrees/.gitignore`** (content `*`) auto-created so
73
+ sandboxes never pollute the parent's `git status` or the untracked
74
+ baseline capture — no user-file edits.
75
+ - **CoW backend (darwin)**: `createWorktree` prefers a per-top-level-entry
76
+ `cp -cR` clone staged OUTSIDE the copied tree (sibling temp dir, skip
77
+ `.pi-worktrees`), then atomic-renames into place — BSD cp lacks GNU's
78
+ self-copy guard, and whole-tree copies would compound prior sandboxes.
79
+ The copy IS the working tree (uncommitted state, node_modules, .env come
80
+ free; the copied `.git` is fully independent). Any failure/EXDEV falls
81
+ back to the detached `git worktree add`. Linux is deliberately
82
+ worktree-only (`--reflink=auto` silently full-copies big trees).
83
+ - **Baseline carry** (git-worktree fallback): `captureParentBaseline`
84
+ composes the parent's WIP as PURE READS — `git diff --cached --binary` +
85
+ `git diff --binary` + per-untracked-file `git diff --no-index --binary
86
+ /dev/null <f>` — never `git add`/`stash create` on the parent (both
87
+ mutate it). 256 MiB cap (constant; OMP #8939 lesson). The child's delta
88
+ then 3-way-merges cleanly onto a parent holding the same baseline.
89
+ - **`.worktreeinclude`**: repo-root gitignore-style lines; matching
90
+ gitignored files (zero-dep glob matcher, 500-file cap) copied into
91
+ git-worktree sandboxes. Fail-open per file.
92
+ - **repair module — multi-session guards** (always-on, deterministic):
93
+ - **Conflict-marker footer**: full-file reads append a footer naming
94
+ detected `<<<<<<<`/`=======`/`>>>>>>>` blocks (OMP conflict-detect
95
+ workflow; zero extra I/O; `:conflicts` stays the explicit listing path).
96
+ - **Write freshness guard**: reads record each file's mtime (capped map);
97
+ a `write` to a file changed since this session last read it fails BEFORE
98
+ writing with a re-read-first error — no more blind clobbering of a
99
+ foreign session's edit. `apply_patch`/`str_replace_editor` refresh the
100
+ baseline via a `refreshMtime` seam; `edit` needs no guard (its
101
+ exact-match anchor already fails loudly).
102
+ - **README**: documents every module in the bundle (subagent, repair,
103
+ steering, zai, a2a, todo, rules, gh, attachments, cron, permission were
104
+ missing) — the subagent section leads with the multi-session safety work.
105
+ - Live-verified end to end on this machine: baseline carry through a real
106
+ `sandbox:"worktree"` child, GC sweep in a fresh headless `pi -p` session,
107
+ herdr-pane load, both repair guards through real wrapped tools, and a
108
+ concurrent two-child `merge:"3way"` race (both patches landed, no
109
+ conflicts, no lock leftovers). 23 new tests; suite at 2639 green.
4
110
 
5
111
  ## 0.10.1 — 2026-10-07
6
112
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **The Pi coding agent, fully dressed.**
4
4
 
5
- One extension bundle that turns [Pi](https://github.com/earendil-works/pi) into a fully equipped coding agent: a router provider, a second-model reviewer, long-term memory, usage display, themes, and a central settings panel — one install, one command surface, most modules individually switchable.
5
+ One extension bundle that turns [Pi](https://github.com/earendil-works/pi) into a fully equipped coding agent: a router provider, a second-model reviewer, long-term memory, subagent delegation with multi-session repo safety, usage display, themes, and a central settings panel — one install, one command surface, most modules individually switchable.
6
6
 
7
7
  Named for Ludolph van Ceulen, who computed π to 35 digits — they're carved on his tombstone.
8
8
 
@@ -75,6 +75,33 @@ Pick the input editor's look from `/config` → Appearance → Composer Shape: S
75
75
 
76
76
  `/ponytail off|lite|full|ultra` switches an over-engineering discipline: simplest solution that works, stdlib first, no speculative abstraction. Also ships `/ponytail-review`, `/ponytail-audit`, `/ponytail-debt`, `/ponytail-gain` skills. Deactivate with `stop ponytail`.
77
77
 
78
+ ### subagent — delegate work, safely
79
+
80
+ One `subagent` tool fans work out to specialized agents — `scout` (recon), `tester`, `worker`, `planner`, `reviewer` — in three modes: single, parallel (up to 8 tasks), or chained pipelines. Background tasks report liveness (`operation:"status"/"wait"/"cancel"`); when Pi runs inside herdr, tasks can delegate to visible interactive panes instead. Model tier and thinking effort are routed per task by the classifier module; `/subagent` manages roles, `/agent` inspects threads.
81
+
82
+ Multi-session repo safety (isolated children never clobber you or each other):
83
+
84
+ - **Worktree sandbox** — `sandbox:"worktree"` runs the child in a copy-on-write clone of your working tree (macOS `clonefile` — near-zero time and disk; carries your uncommitted changes, `node_modules`, and `.env` for free), falling back to a detached git worktree elsewhere. The child's changes come back as a patch; `merge:"3way"` applies it to your checkout with conflicts **reported, never silently resolved**.
85
+ - **Baseline carry** — on the worktree fallback the parent's uncommitted state is composed as pure reads (`git diff`/`--no-index`) and seeded into the sandbox, so children never work a stale tree and patches merge cleanly.
86
+ - **`.worktreeinclude`** — gitignore-style file listing copied into fresh worktrees (env files, configs).
87
+ - **Repo lock + GC** — parent-mutating git operations serialize per repo (no `index.lock` races between parallel children); crashed runs' sandboxes are swept on session start. `/subagent worktrees [clean]` lists or forces the sweep.
88
+ - **Write freshness guard** (repair module) — a `write` to a file another session changed since you last read it fails with a re-read-first error instead of clobbering.
89
+ - **Conflict footer** (repair module) — full-file reads surface unresolved `<<<<<<<` conflict markers automatically.
90
+
91
+ Config: `/config` → Tasks → Subagents (model pools, routing, timeouts).
92
+
93
+ ### repair — tool-call hardening
94
+
95
+ Wraps the built-in read/write/edit/grep/find/ls/bash once each: schema argument repair, edit-mismatch trim-tolerant retry with `apply_patch` escalation, destructive-bash + guessed-path guards, and read path suffixes — `file.ts:50`, `:50-200`, `:50+150`, `:-60` (tail), comma-joined ranges, `:raw`, and `:conflicts` (list merge-conflict blocks). Registers `apply_patch` (Codex-style V4D diffs) and `str_replace_editor` as standalone tools. Config: `/config` → Tools → Repair.
96
+
97
+ ### steering — model-family guidance
98
+
99
+ Provider-agnostic deepseek/glm family detection with first-tool hints, reasoning stripping, error categorization + recovery hints, and the ds-anchor two-phase bootstrap for DeepSeek minimal mode. `/steering` shows status.
100
+
101
+ ### zai — Z.AI provider (GLM)
102
+
103
+ Registers a `zai-anthropic` provider serving GLM through Z.ai's Anthropic endpoint: explicit prompt caching, `speed:"fast"` serving tier, effort-based reasoning, a cross-process rate-limit throttle, and optional ZCode request signing. `/zai` = status; config in `/config` → Providers.
104
+
78
105
  ### ux — anti-slop UI discipline
79
106
 
80
107
  `/ux off|lite|strict` injects a UI design method (tokens only, full interaction states, no AI-slop tells) for any UI work; `strict` blocks handoff until the deterministic `ux_audit` tool passes (APCA contrast, token, and state gates — no model needed). Ships the `ux-*` skills. Deactivate with `stop ux`.
@@ -90,6 +117,34 @@ Pick the input editor's look from `/config` → Appearance → Composer Shape: S
90
117
  - Config: `/config` → Tools → **Web** — 16 provider rows (endpoints, keys, timeouts, Gemini cookie, image/chat providers). Written to the global `web` settings section and read per tool call, so saves apply without `/reload`; `BRAVE_API_KEY`, `SEARXNG_BASE_URL`, `FIRECRAWL_*`, `CRAWL4AI_*`, `GEMINI_WEB_*`, `ZAI_API_KEY`, `WEB_IMAGE_*`, `WEB_CHAT_*` env vars still win. Secrets are masked. Individual tools toggle from the same section.
91
118
  - Static extraction uses vendored readability/turndown (no extra install); `jsdom` and `gemini-reverse` are the module's only runtime dependencies.
92
119
 
120
+ ### a2a — Agent2Agent protocol
121
+
122
+ Talk to remote agents (Hermes, ADK, LangChain, CrewAI, any A2A peer): 7 outbound tools (`a2a_call` with async dispatch, `a2a_status`, `a2a_discover`, `a2a_list`, `a2a_history`, `a2a_orchestrate` fan-out, `a2a_peers`) and an opt-in inbound server that serves isolated child sessions. Discovery spans a local registry, mDNS, and a2a-switchboard gateways. `/a2a-help` for everything; config in `/config` → Tasks → A2A.
123
+
124
+ ### todo — phased task board
125
+
126
+ One `todo` tool tracks an ordered phase list with `blockedBy` edges, auto-start, and a live TUI HUD; `/todo` prints the board. Follows the batch contract (call it alongside real work, never alone).
127
+
128
+ ### rules — sticky rules + rulebook
129
+
130
+ `<dir>/.pi/RULES.md` files (walking to repo root, plus a user-level file) inject sticky rules into every request; `## name` sections with a `description:` line become an on-demand rulebook served by the `rule_get` tool. Edits apply without `/reload`; `/rules` = status.
131
+
132
+ ### gh — GitHub (read-only)
133
+
134
+ One `github` tool over the `gh` CLI: `repo_view`, `file_read`, `pr_view`, `pr_diff`, issue/PR/code/commit/repo search with date qualifiers, and `run_watch` for Actions runs with failed-job log tails. Zero npm deps; fails open when `gh` is absent. Mutating flows stay with bash `gh` — which keeps the tool auto-allowed in plan mode.
135
+
136
+ ### attachments — paste files into prompts
137
+
138
+ Pasting file paths (or big text) collapses to `[[attach:name]]` tokens with a tray widget; on submit they become real image parts, path chips, or inline file blocks. `alt+shift+v` pastes clipboard file references. Config: `/config` → Files → Attachments.
139
+
140
+ ### cron — scheduled jobs
141
+
142
+ The `cron` tool + `/cron` manage recurring prompts in `<agentDir>/cron/jobs.json` (vixie-cron schedules, hand-rolled matcher — zero deps). Jobs fire as follow-up turns; pinned jobs run headless in their own Pi process. `/cron test` previews fire times; config in `/config` → Tasks → Cron.
143
+
144
+ ### permission — config-driven tool permissions
145
+
146
+ Opt-in `permission` settings section: allow/ask/deny rules per tool with wildcards, an `external_directory` deny boundary, and a doom-loop guard on repeated identical calls. No section = no opinion. Headless asks fail closed; `--yolo`/`--auto` auto-approve.
147
+
93
148
  ### serena / fff / rtk — code navigation & search (bundled tools)
94
149
 
95
150
  - **serena** — semantic code tools (find symbol, references, rename, diagnostics) via a persistent language-server worker
@@ -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
+ });
@@ -0,0 +1,18 @@
1
+ // Cross-module contract: the plan module publishes whether plan mode is
2
+ // currently active; the permission module reads it to stay silent while plan
3
+ // mode owns tool gating (otherwise both fire tool_call prompts on the same
4
+ // call — double prompting). Flag, not event chaining, so registration order
5
+ // never matters. Inert unless both modules are loaded: with plan disabled the
6
+ // flag simply never becomes true.
7
+ let planActive = false;
8
+
9
+ /** True while plan mode is on (plan module writes, permission module reads). */
10
+ export function isPlanActive(): boolean {
11
+ return planActive;
12
+ }
13
+
14
+ /** Publish the plan-mode state. Called by the plan module at every
15
+ * `planModeEnabled` assignment site (toggle, restore, exit-for-execution). */
16
+ export function setPlanActive(active: boolean): void {
17
+ planActive = active;
18
+ }