ceulen 0.20.0 → 0.23.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.
- package/CHANGELOG.md +111 -0
- package/extensions/lib/env.test.ts +45 -0
- package/extensions/lib/env.ts +56 -3
- package/extensions/lib/skill-path.test.ts +1 -1
- package/extensions/modules/a2a/lib/gateway.ts +3 -0
- package/extensions/modules/a2a/lib/persistence.ts +3 -2
- package/extensions/modules/a2a/test/persistence.test.ts +12 -0
- package/extensions/modules/classifier/index.ts +12 -1
- package/extensions/modules/classifier/lib/settings.ts +21 -0
- package/extensions/modules/classifier/lib/think-gate.ts +211 -0
- package/extensions/modules/classifier/test/classifier.test.ts +285 -1
- package/extensions/modules/cron/index.ts +1 -0
- package/extensions/modules/cron/lib/jobs.ts +2 -1
- package/extensions/modules/cron/test/cwd-repro.test.ts +10 -1
- package/extensions/modules/jfind/index.ts +13 -4
- package/extensions/modules/jfind/lib/cascade.ts +5 -2
- package/extensions/modules/jfind/lib/tree.ts +8 -3
- package/extensions/modules/jfind/test/cascade.test.ts +28 -1
- package/extensions/modules/munin/configPanel.ts +13 -3
- package/extensions/modules/munin/index.ts +7 -4
- package/extensions/modules/munin/test/configPanel.test.ts +9 -3
- package/extensions/modules/munin/test/extension.test.ts +31 -0
- package/extensions/modules/permission/index.ts +20 -9
- package/extensions/modules/permission/test/permission.test.ts +33 -1
- package/extensions/modules/plan/index.ts +36 -7
- package/extensions/modules/plan/lib/shell-gate.ts +93 -26
- package/extensions/modules/plan/test/module.test.ts +114 -1
- package/extensions/modules/plan/test/shell-gate.test.ts +64 -0
- package/extensions/modules/repair/lib/guards.ts +4 -1
- package/extensions/modules/repair/test/guards.test.ts +9 -0
- package/extensions/modules/router/lib/client.ts +24 -0
- package/extensions/modules/router/test/unit.test.ts +33 -3
- package/extensions/modules/sg/index.ts +3 -3
- package/extensions/modules/sg/lib/ops.ts +15 -1
- package/extensions/modules/sg/test/sg.test.ts +16 -2
- package/extensions/modules/subagent/index.ts +12 -1
- package/extensions/modules/subagent/lib/herdr.ts +37 -3
- package/extensions/modules/subagent/lib/history.ts +6 -2
- package/extensions/modules/subagent/lib/settings.ts +2 -1
- package/extensions/modules/subagent/test/extension.test.ts +31 -0
- package/extensions/modules/subagent/test/file-modes.test.ts +40 -0
- package/extensions/modules/subagent/test/herdr-stalled.test.ts +39 -0
- package/extensions/modules/web/lib/chatgpt.ts +2 -1
- package/extensions/scripts/probe-thinking.mjs +108 -0
- package/package.json +1 -1
- package/skills/review/SKILL.md +45 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,116 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.23.0 — 2026-10-19
|
|
4
|
+
|
|
5
|
+
Thinking-mode gaps closed — GLM-5.3 gets its real effort ladder on the router,
|
|
6
|
+
and the main session's thinking level is classifier-routed per turn.
|
|
7
|
+
|
|
8
|
+
Research basis: GLM-5.3/5.3-Flash accept only `reasoning_effort: low|high|max`
|
|
9
|
+
(forced thinking — `none`/`off` are accepted but silently think at max depth;
|
|
10
|
+
live probe 2026-10-19), `high` ≈ 93% of `max` quality at ~⅔ the tokens
|
|
11
|
+
(Z.ai Code Bench), and overthinking hurts on easy tasks (arXiv 2601.21418,
|
|
12
|
+
2604.10739).
|
|
13
|
+
|
|
14
|
+
- **Router `zai53` map** (`router/lib/client.ts`): GLM-5.3 family split out of
|
|
15
|
+
the GLM-5.2-shaped `zai` map — `off` now OMITS the parameter (never sends
|
|
16
|
+
`"none"`, which would think at max depth), and the native `low` tier is
|
|
17
|
+
reachable (`low/medium→low`, `xhigh→max` via pi's clamp). `combo/` routes keep
|
|
18
|
+
the CC enum; glm-5.2 keeps the old map. Probe script shipped:
|
|
19
|
+
`extensions/scripts/probe-thinking.mjs` (value × route status matrix).
|
|
20
|
+
- **`classifier.thinkGate`** (new, `classifier/lib/think-gate.ts`): one Jev
|
|
21
|
+
score question per user turn sets the session thinking level; baseline
|
|
22
|
+
restored at settle. planGate pattern — default fully OFF, observe-first, 2.5s
|
|
23
|
+
budget, fail-open everywhere, every verdict audited to `classifier.log`
|
|
24
|
+
(`ceulen-think-gate` tag; missing-model fail-opens audit once per session).
|
|
25
|
+
Stands down for the session when the user touches the thinking dial; skips
|
|
26
|
+
plan mode, custom messages, and herdr children (`CEULEN_THINK_GATE_OFF=1`
|
|
27
|
+
injected by the subagent module — covers `thinking_level_select` too, so
|
|
28
|
+
child panes are fully inert). Live-verified in herdr: parent pane full
|
|
29
|
+
cycle (trivial → `off`(→minimal), architecture → `xhigh`), child panes zero
|
|
30
|
+
gate events.
|
|
31
|
+
- Pitfalls encoded as tests: pi emits `thinking_level_select` synchronously
|
|
32
|
+
off the set call site with CLAMPED values (ownership = pre-call timestamp
|
|
33
|
+
arm + effective-level re-read); level-capped models clamp DOWN (xhigh→high
|
|
34
|
+
regression case covered).
|
|
35
|
+
|
|
36
|
+
## 0.22.0 — 2026-10-17
|
|
37
|
+
|
|
38
|
+
Post-completion review gate — the research-backed practice (Codex Auto-review,
|
|
39
|
+
Anthropic verification guidance) shipped as a convention skill, not a hook:
|
|
40
|
+
after a plan finishes executing or a substantial task ends, capture the diff
|
|
41
|
+
scope + acceptance criteria and dispatch the bundled `reviewer` subagent
|
|
42
|
+
(fresh context, evidence-required findings) before claiming done.
|
|
43
|
+
|
|
44
|
+
- **`review` skill** (new, `skills/review/SKILL.md`): one reviewer pass per
|
|
45
|
+
gate (never parallel fans), review AGAINST plan acceptance criteria not
|
|
46
|
+
open-ended style, fix critical/high/blocking only, ONE revision loop, human
|
|
47
|
+
reviews last. Advisor owns per-turn review; this owns task-end — never
|
|
48
|
+
stacked on the same turn.
|
|
49
|
+
- **Registration**: subagent module contributes the skill via
|
|
50
|
+
`resources_discover` (munin/cron pattern) — the module kill-switch gates it,
|
|
51
|
+
since the skill dispatches that module's reviewer agent.
|
|
52
|
+
- **Tests**: skill-path existence list covers `cron` + `review`; new
|
|
53
|
+
subagent `extension.test.ts` asserts the registration (typo/dropped-handler
|
|
54
|
+
mutation-verified). AGENTS.md layout + subagent sections updated.
|
|
55
|
+
|
|
56
|
+
## 0.21.0 — 2026-10-17
|
|
57
|
+
|
|
58
|
+
Security-review pass — 18 findings (1 critical, 5 high, 7 medium, 5 low),
|
|
59
|
+
all verified against code and now fixed. Every finding carries a regression
|
|
60
|
+
test; the plan-mode shell gate also gained live-tested hardening after the
|
|
61
|
+
F1 exploit class was executed against a real session during the review
|
|
62
|
+
(the home-wipe incident — see the shell-gate entry).
|
|
63
|
+
|
|
64
|
+
- **plan/shell-gate (F1, critical)**: backslash handling in the quote
|
|
65
|
+
scanners created a *phantom-quote* bypass — `ls \" ; rm …` classified
|
|
66
|
+
`read` and **auto-ran in plan mode**. One shared bash-faithful helper
|
|
67
|
+
(`quoteCloses`: single quotes close on any `'`; double quotes on an EVEN
|
|
68
|
+
backslash run) now drives all four scanners; escaped quotes outside
|
|
69
|
+
quotes never open spans; `$()`/backticks inside double quotes still scan
|
|
70
|
+
as live; dangling quotes classify confirm, never read.
|
|
71
|
+
- **plan gating (F2/F3/F11/F13/F15)**: a session allow ("npm test") can no
|
|
72
|
+
longer auto-run a RISKY command on the same first token ("npm publish");
|
|
73
|
+
subagent auto-allow resolves at the scope the tool actually runs (a
|
|
74
|
+
read-only project agent can no longer shadow a full-write bundled
|
|
75
|
+
namesake); the planGate static pre-check also tests a de-quoted copy
|
|
76
|
+
(`curl … | 'b''a''s''h'` never reaches Jev; `cargo publish`, `twine
|
|
77
|
+
upload`, `gem push` join the classifier RISKY list); the textconv
|
|
78
|
+
diff-driver probe is awaited before bash classification (kills the `git
|
|
79
|
+
log -p` read race); `session_tree` resets the ask-loop dampener.
|
|
80
|
+
- **shell tool parity (F4)**: a `shell action:"start"` is a shell command —
|
|
81
|
+
permission `bash` rules now apply to it (deny blocks, ask shows the
|
|
82
|
+
command, session promotions key under bash) and the classifier risky hook
|
|
83
|
+
annotates it like bash.
|
|
84
|
+
- **file modes (F5/F6/F12)**: permission allowlist persist, subagent
|
|
85
|
+
settings, cron jobs.json + run logs, and a2a transcripts (dir 0700) write
|
|
86
|
+
0600; subagent history switched to atomic tmp+rename 0600.
|
|
87
|
+
- **munin apiKey (F7)**: the API key never lands in the git-trackable
|
|
88
|
+
project `.pi/settings.json` — the /config save diverts to
|
|
89
|
+
`<agentDir>/.env.local` (0600, mirrored live into the session env), and
|
|
90
|
+
the startup secret migration scrubs a plaintext key from a trusted
|
|
91
|
+
project file.
|
|
92
|
+
- **jfind containment (F8)**: symlink entries are never followed
|
|
93
|
+
(lstat + skip in both walk branches, single-file symlink scopes yield
|
|
94
|
+
nothing) and the `path` scope must stay inside the workspace — file
|
|
95
|
+
contents ship to the classifier, so the scope is a content boundary.
|
|
96
|
+
- **sg path validation (F9)**: flag-shaped paths (`paths:["-U"]` turned a
|
|
97
|
+
dry-run into a silent write) and cwd escapes are rejected; a `--`
|
|
98
|
+
separator guards every path list.
|
|
99
|
+
- **herdr evidence + resources (F10/F16)**: a pane echoing the submitted
|
|
100
|
+
prompt back no longer counts as completion evidence (echo-stripped tails
|
|
101
|
+
must carry a remainder); report reads cap before buffering (256 KB);
|
|
102
|
+
evidence polls back off 1s→2s→5s; the herdr tool's prompt-wait timeout is
|
|
103
|
+
clamped to the documented 60-min ceiling.
|
|
104
|
+
- **smaller fixes (F14/F17/F18)**: munin validation runs before the loop
|
|
105
|
+
dampener (invalid calls return validation errors, not loop guidance);
|
|
106
|
+
the ChatGPT OAuth refresh fetch gets a 15s timeout; the a2a gateway
|
|
107
|
+
reverse-channel dispatch gets a 120s timeout.
|
|
108
|
+
- **test hygiene (home-wipe incident)**: shell-gate exploit fixtures now
|
|
109
|
+
target sacrificial `/tmp` paths (never `~`/`$HOME`), a meta-test keeps the
|
|
110
|
+
fixture file free of home-pointing `rm` lines, and the repair bash guard
|
|
111
|
+
treats `~`, `$HOME`, `${HOME}` as absolute paths in its recursive-force
|
|
112
|
+
delete refusal (live-verified: the pre-fix guard waved `rm -rf ~` through).
|
|
113
|
+
|
|
3
114
|
## 0.20.0 — 2026-10-16
|
|
4
115
|
|
|
5
116
|
pi 1.3.0 compatibility pass (verified by diffing the 1.2.0 and 1.3.0
|
|
@@ -114,6 +114,51 @@ test("migrate: missing/corrupt settings.json is a silent no-op", () => {
|
|
|
114
114
|
}
|
|
115
115
|
});
|
|
116
116
|
|
|
117
|
+
test("migrate: trusted project munin.apiKey moves to .env.local and is scrubbed (F7)", () => {
|
|
118
|
+
const dir = tmpDir();
|
|
119
|
+
const prevCwd = process.cwd();
|
|
120
|
+
const project = fs.mkdtempSync(path.join(os.tmpdir(), "ceulen-env-proj-"));
|
|
121
|
+
try {
|
|
122
|
+
// Isolation: a pi session that imported env.ts with a REAL ~/.pi/agent/.env.local
|
|
123
|
+
// has MUNIN_API_KEY already in process.env — onlyAbsent would keep it and the
|
|
124
|
+
// asserts below would see the ambient value, not the migrated one.
|
|
125
|
+
delete process.env.MUNIN_API_KEY;
|
|
126
|
+
// Trust the project cwd (keyed on the REAL path process.cwd() returns
|
|
127
|
+
// after chdir — path.resolve does not resolve symlinks), then give it a
|
|
128
|
+
// plaintext munin key.
|
|
129
|
+
process.chdir(project);
|
|
130
|
+
fs.writeFileSync(path.join(dir, "trust.json"), JSON.stringify({ [process.cwd()]: true }));
|
|
131
|
+
fs.mkdirSync(path.join(project, ".pi"), { recursive: true });
|
|
132
|
+
fs.writeFileSync(path.join(project, ".pi", "settings.json"), JSON.stringify({
|
|
133
|
+
munin: { apiKey: "proj-secret", project: "my-bank" },
|
|
134
|
+
other: { keep: true },
|
|
135
|
+
}));
|
|
136
|
+
migrateSecretsFromSettings();
|
|
137
|
+
|
|
138
|
+
const envText = fs.readFileSync(path.join(dir, ".env.local"), "utf8");
|
|
139
|
+
assert.match(envText, /MUNIN_API_KEY=proj-secret/, "project key migrated");
|
|
140
|
+
assert.equal(process.env.MUNIN_API_KEY, "proj-secret");
|
|
141
|
+
|
|
142
|
+
const raw = JSON.parse(fs.readFileSync(path.join(project, ".pi", "settings.json"), "utf8"));
|
|
143
|
+
assert.equal(raw.munin.apiKey, undefined, "the key is scrubbed");
|
|
144
|
+
assert.equal(raw.munin.project, "my-bank", "non-secret munin config stays");
|
|
145
|
+
assert.deepEqual(raw.other, { keep: true }, "sibling keys stay");
|
|
146
|
+
|
|
147
|
+
// Untrusted cwd: the key stays (an untrusted checkout's settings.json is
|
|
148
|
+
// never read at all — scrubbing it would change nothing effective).
|
|
149
|
+
fs.writeFileSync(path.join(dir, "trust.json"), JSON.stringify({ [process.cwd()]: false }));
|
|
150
|
+
fs.writeFileSync(path.join(project, ".pi", "settings.json"), JSON.stringify({ munin: { apiKey: "untrusted-secret" } }));
|
|
151
|
+
migrateSecretsFromSettings();
|
|
152
|
+
assert.equal(JSON.parse(fs.readFileSync(path.join(project, ".pi", "settings.json"), "utf8")).munin.apiKey, "untrusted-secret", "untrusted file untouched");
|
|
153
|
+
} finally {
|
|
154
|
+
process.chdir(prevCwd);
|
|
155
|
+
delete process.env.MUNIN_API_KEY;
|
|
156
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
157
|
+
fs.rmSync(project, { recursive: true, force: true });
|
|
158
|
+
delete process.env.PI_CODING_AGENT_DIR;
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
|
|
117
162
|
test("writeSecretEnvs: upsert + create + onlyAbsent semantics, 0600", () => {
|
|
118
163
|
const dir = tmpDir();
|
|
119
164
|
try {
|
package/extensions/lib/env.ts
CHANGED
|
@@ -95,6 +95,52 @@ function agentDirsForSecrets(): string[] {
|
|
|
95
95
|
: [path.join(os.homedir(), ".pi", "agent"), path.join(os.homedir(), ".pi", "agents")];
|
|
96
96
|
}
|
|
97
97
|
|
|
98
|
+
/** Trust walk for the cwd's .pi/settings.json (registry.isProjectTrusted
|
|
99
|
+
* inlined — env.ts stays a leaf). */
|
|
100
|
+
function isTrustedCwd(cwd: string): boolean {
|
|
101
|
+
const resolved = path.resolve(cwd);
|
|
102
|
+
for (const dir of agentDirsForSecrets()) {
|
|
103
|
+
const file = path.join(dir, "trust.json");
|
|
104
|
+
if (!fs.existsSync(file)) continue;
|
|
105
|
+
try {
|
|
106
|
+
const data = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
107
|
+
let current = resolved;
|
|
108
|
+
for (;;) {
|
|
109
|
+
const v = data[current];
|
|
110
|
+
if (typeof v === "boolean") return v;
|
|
111
|
+
const parent = path.dirname(current);
|
|
112
|
+
if (parent === current) break;
|
|
113
|
+
current = parent;
|
|
114
|
+
}
|
|
115
|
+
} catch { /* unreadable trust.json → not trusted */ }
|
|
116
|
+
}
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** F7 (security review 2026-10-17): munin.apiKey must not sit in the
|
|
121
|
+
* git-trackable project .pi/settings.json. When the cwd is trusted, move its
|
|
122
|
+
* munin.apiKey into `migrate` FIRST (project beats global at read time, so
|
|
123
|
+
* its value must win the onlyAbsent write) and scrub the file atomically. */
|
|
124
|
+
function migrateProjectMuninKey(migrate: Record<string, string>): boolean {
|
|
125
|
+
try {
|
|
126
|
+
const cwd = process.cwd();
|
|
127
|
+
if (!isTrustedCwd(cwd)) return false;
|
|
128
|
+
const projectFile = path.join(cwd, ".pi", "settings.json");
|
|
129
|
+
const settings = JSON.parse(fs.readFileSync(projectFile, "utf8"));
|
|
130
|
+
const munin = settings?.munin;
|
|
131
|
+
if (!munin || typeof munin !== "object" || typeof munin.apiKey !== "string" || munin.apiKey === "") return false;
|
|
132
|
+
migrate.MUNIN_API_KEY = munin.apiKey;
|
|
133
|
+
delete munin.apiKey;
|
|
134
|
+
if (Object.keys(munin).length === 0) delete settings.munin;
|
|
135
|
+
const tmp = projectFile + ".tmp";
|
|
136
|
+
fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
|
|
137
|
+
fs.renameSync(tmp, projectFile);
|
|
138
|
+
return true;
|
|
139
|
+
} catch {
|
|
140
|
+
return false; // absent/corrupt/unwritable project file — nothing to do
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
98
144
|
/** Read the current secrets file as parsed entries ({} when absent). */
|
|
99
145
|
export function readSecretEnvs(agentDir?: string): Record<string, string> {
|
|
100
146
|
return readEnvFile(secretsEnvFile(agentDir));
|
|
@@ -156,16 +202,23 @@ const WEB_SECRET_ENV_BY_KEY: Record<string, string> = {
|
|
|
156
202
|
* Never throws — a failed migration leaves the (working) status quo. */
|
|
157
203
|
export function migrateSecretsFromSettings(): void {
|
|
158
204
|
try {
|
|
205
|
+
const migrate: Record<string, string> = {};
|
|
206
|
+
const scrubWeb: string[] = [];
|
|
207
|
+
// Project munin key FIRST (F7): it must also run when the GLOBAL
|
|
208
|
+
// settings.json is absent/corrupt — its early return below still has to
|
|
209
|
+
// flush this env write.
|
|
210
|
+
migrateProjectMuninKey(migrate);
|
|
159
211
|
const dir = agentDirsForSecrets()[0]!;
|
|
160
212
|
const settingsFile = path.join(dir, "settings.json");
|
|
161
213
|
let settings: Record<string, any>;
|
|
162
214
|
try {
|
|
163
215
|
settings = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
|
|
164
216
|
} catch {
|
|
165
|
-
|
|
217
|
+
// Absent/corrupt — nothing else to migrate, but a project-file find
|
|
218
|
+
// above still lands in .env.local.
|
|
219
|
+
if (Object.keys(migrate).length > 0) writeSecretEnvs(migrate, { agentDir: dir, onlyAbsent: true });
|
|
220
|
+
return;
|
|
166
221
|
}
|
|
167
|
-
const migrate: Record<string, string> = {};
|
|
168
|
-
const scrubWeb: string[] = [];
|
|
169
222
|
// web section: flat or nested secret keys.
|
|
170
223
|
const web = settings.web && typeof settings.web === "object" ? settings.web : {};
|
|
171
224
|
for (const [key, envName] of Object.entries(WEB_SECRET_ENV_BY_KEY)) {
|
|
@@ -24,7 +24,7 @@ describe("skillsRoot", () => {
|
|
|
24
24
|
});
|
|
25
25
|
|
|
26
26
|
it("joins to this package's own skill dirs", () => {
|
|
27
|
-
for (const name of ["web", "munin", "a2a", "ponytail", "ux-design"]) {
|
|
27
|
+
for (const name of ["web", "munin", "a2a", "ponytail", "ux-design", "cron", "review"]) {
|
|
28
28
|
assert.ok(existsSync(join(skillsRoot(), name)), `skill dir exists: ${name}`);
|
|
29
29
|
}
|
|
30
30
|
});
|
|
@@ -835,6 +835,9 @@ export class ChannelClient {
|
|
|
835
835
|
method: env.method,
|
|
836
836
|
headers,
|
|
837
837
|
body: ["GET", "HEAD"].includes(env.method) ? undefined : binary,
|
|
838
|
+
// F18: the reverse-channel dispatch must not leak an inflight promise
|
|
839
|
+
// when the local server never answers.
|
|
840
|
+
signal: AbortSignal.timeout(120_000),
|
|
838
841
|
});
|
|
839
842
|
const buf = new Uint8Array(await res.arrayBuffer());
|
|
840
843
|
if (buf.length > MAX_CHANNEL_BODY) {
|
|
@@ -44,8 +44,9 @@ export function persistMessage(opts: {
|
|
|
44
44
|
peer: opts.peer,
|
|
45
45
|
};
|
|
46
46
|
const p = fileFor(opts.piDir, opts.contextId);
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
// 0700/0600: transcripts are private peer conversations (F12).
|
|
48
|
+
mkdirSync(dir(opts.piDir), { recursive: true, mode: 0o700 });
|
|
49
|
+
appendFileSync(p, JSON.stringify(rec) + "\n", { encoding: "utf-8", mode: 0o600 });
|
|
49
50
|
} catch {
|
|
50
51
|
/* best-effort persistence */
|
|
51
52
|
}
|
|
@@ -10,6 +10,18 @@ function tmpDir(): string {
|
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
describe("persistence", () => {
|
|
13
|
+
it("writes transcripts 0600 into a 0700 dir (F12)", () => {
|
|
14
|
+
const dir = tmpDir();
|
|
15
|
+
persistMessage({ piDir: dir, contextId: "ctx-sec", role: "user", text: "secret" });
|
|
16
|
+
const p = childTranscriptDir(dir) === dir ? dir : path.join(dir, "a2a_sessions");
|
|
17
|
+
// Find the transcript file wherever fileFor put it.
|
|
18
|
+
const walk = (d: string): string[] =>
|
|
19
|
+
fs.existsSync(d) ? fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)]) : [];
|
|
20
|
+
const files = walk(dir).filter((f) => f.endsWith(".jsonl"));
|
|
21
|
+
assert.lengthOf(files, 1);
|
|
22
|
+
assert.equal(fs.statSync(files[0]!).mode & 0o777, 0o600, "transcript file is 0600");
|
|
23
|
+
});
|
|
24
|
+
|
|
13
25
|
it("round-trips messages to JSONL", () => {
|
|
14
26
|
const dir = tmpDir();
|
|
15
27
|
persistMessage({ piDir: dir, contextId: "ctx-1", role: "user", text: "hello" });
|
|
@@ -32,6 +32,7 @@ import { join } from "node:path";
|
|
|
32
32
|
import { Type } from "typebox";
|
|
33
33
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
34
34
|
import { getClassifierSettings } from "./lib/settings.js";
|
|
35
|
+
import { registerThinkGate } from "./lib/think-gate.js";
|
|
35
36
|
import { setClassifierRegistry } from "./configPanel.js";
|
|
36
37
|
|
|
37
38
|
// ── Risk gate (static, before Jev ever sees a command) ──────────────────────
|
|
@@ -42,6 +43,7 @@ const RISKY = [
|
|
|
42
43
|
/\bgit\s+push\b[^|;&]*--force/, /\bgit\s+push\s+-f\b/, /\bgit\s+reset\s+--hard\b/,
|
|
43
44
|
/curl[^|;&]*\|\s*(ba)?sh/, /wget[^|;&]*\|\s*(ba)?sh/, // pipe-to-shell
|
|
44
45
|
/\b(npm|pnpm|yarn|bun)\s+publish\b/, /\bgh\s+release\s+(create|upload)\b/,
|
|
46
|
+
/\bcargo\s+publish\b/, /\btwine\s+upload\b/, /\bgem\s+push\b/,
|
|
45
47
|
/\bterraform\s+(apply|destroy)\b/, /\bkubectl\s+(delete|apply)\b/,
|
|
46
48
|
/(^|\s)~?\/?\.?(ssh|aws|gnupg|kube)(\/|$)/, /id_rsa|\.pem\b|credentials\b/i,
|
|
47
49
|
];
|
|
@@ -166,6 +168,12 @@ export function getLastTask(): string {
|
|
|
166
168
|
}
|
|
167
169
|
|
|
168
170
|
export default function (pi: ExtensionAPI) {
|
|
171
|
+
// Main-session per-turn thinking gate (classifier.thinkGate, default off —
|
|
172
|
+
// planGate pattern). Register the handlers even while off: settings are read
|
|
173
|
+
// per turn, so a settings.json flip needs no /reload. Returns undefined —
|
|
174
|
+
// never touches systemPrompt (steering load-order contract).
|
|
175
|
+
registerThinkGate(pi);
|
|
176
|
+
|
|
169
177
|
// The /config contribution reads discovered decision models at open time;
|
|
170
178
|
// config factories get no ctx, so the module stashes the live registry
|
|
171
179
|
// here (the panel always opens after a session exists). Cleared on shutdown
|
|
@@ -263,7 +271,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
263
271
|
const CLASSIFIER_HOOK_BUDGET_MS = 2_500;
|
|
264
272
|
|
|
265
273
|
pi.on("tool_call", async (event, ctx) => {
|
|
266
|
-
|
|
274
|
+
// F4: a shell tool START runs a shell command with shell:true — the same
|
|
275
|
+
// exposure as bash, so it gets the same risky-hook annotation.
|
|
276
|
+
const isShellStart = event.toolName === "shell" && event.input?.action === "start";
|
|
277
|
+
if (event.toolName !== "bash" && !isShellStart) return undefined;
|
|
267
278
|
const command = String(event.input?.command || "");
|
|
268
279
|
if (!command) return undefined;
|
|
269
280
|
|
|
@@ -18,6 +18,14 @@
|
|
|
18
18
|
// "observe": false, // log-only audit pass — verdicts land in classifier.log, nothing changes
|
|
19
19
|
// "threshold": 0.9 // p(reversible) must clear it for an auto-run
|
|
20
20
|
// }
|
|
21
|
+
//
|
|
22
|
+
// `thinkGate` (ceulen; main-session per-turn thinking level):
|
|
23
|
+
//
|
|
24
|
+
// "thinkGate": {
|
|
25
|
+
// "enabled": false, // let the gate SET the session thinking level per user turn
|
|
26
|
+
// "observe": false, // log-only audit pass — verdicts land in classifier.log
|
|
27
|
+
// "threshold": 0.6 // the score answer's confidence must clear it
|
|
28
|
+
// }
|
|
21
29
|
|
|
22
30
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
23
31
|
import { homedir } from "node:os";
|
|
@@ -36,6 +44,11 @@ export interface ClassifierSettings {
|
|
|
36
44
|
observe: boolean;
|
|
37
45
|
threshold: number;
|
|
38
46
|
};
|
|
47
|
+
thinkGate: {
|
|
48
|
+
enabled: boolean;
|
|
49
|
+
observe: boolean;
|
|
50
|
+
threshold: number;
|
|
51
|
+
};
|
|
39
52
|
}
|
|
40
53
|
|
|
41
54
|
function agentDir(): string {
|
|
@@ -62,6 +75,7 @@ export function getClassifierSettings(): ClassifierSettings {
|
|
|
62
75
|
const c = raw.classifier && typeof raw.classifier === "object" ? (raw.classifier as Record<string, unknown>) : {};
|
|
63
76
|
const perm = c.permission && typeof c.permission === "object" ? (c.permission as Record<string, unknown>) : {};
|
|
64
77
|
const gate = c.planGate && typeof c.planGate === "object" ? (c.planGate as Record<string, unknown>) : {};
|
|
78
|
+
const think = c.thinkGate && typeof c.thinkGate === "object" ? (c.thinkGate as Record<string, unknown>) : {};
|
|
65
79
|
return {
|
|
66
80
|
model: typeof c.model === "string" ? c.model.trim() : "",
|
|
67
81
|
permission: {
|
|
@@ -77,6 +91,13 @@ export function getClassifierSettings(): ClassifierSettings {
|
|
|
77
91
|
observe: gate.observe === true,
|
|
78
92
|
threshold: typeof gate.threshold === "number" && gate.threshold > 0 && gate.threshold < 1 ? gate.threshold : 0.9,
|
|
79
93
|
},
|
|
94
|
+
// Default 0.6 = subagent-routing effort precedent (the dial is reversible
|
|
95
|
+
// mid-turn via /think; planGate's 0.9 is for destructive auto-run).
|
|
96
|
+
thinkGate: {
|
|
97
|
+
enabled: think.enabled === true,
|
|
98
|
+
observe: think.observe === true,
|
|
99
|
+
threshold: typeof think.threshold === "number" && think.threshold > 0 && think.threshold < 1 ? think.threshold : 0.6,
|
|
100
|
+
},
|
|
80
101
|
};
|
|
81
102
|
}
|
|
82
103
|
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
// think-gate.ts — main-session per-turn thinking gate (classifier.thinkGate).
|
|
2
|
+
//
|
|
3
|
+
// One Jev score question per USER turn ("how much reasoning does this turn
|
|
4
|
+
// need?") sets the session thinking level; the baseline is restored at settle.
|
|
5
|
+
// planGate precedent: default fully OFF, observe-first rollout, 2.5s budget,
|
|
6
|
+
// fail-open everywhere, every verdict audited to classifier.log.
|
|
7
|
+
//
|
|
8
|
+
// Scope guards (each returns without classifying):
|
|
9
|
+
// - custom/triggerTurn messages (cron fires, subagent receipts) — only
|
|
10
|
+
// messageType "user" turns are gated;
|
|
11
|
+
// - plan mode (extensions/lib/plan-bridge.ts — the plan module owns the dial);
|
|
12
|
+
// - CEULEN_THINK_GATE_OFF=1 (herdr pane children — they get dispatch-routed
|
|
13
|
+
// thinking already; a per-turn gate would double-classify and fight it);
|
|
14
|
+
// - stood-down sessions: ANY thinking_level_select event we did not cause
|
|
15
|
+
// (user /think, level cycling, a model switch whose clamp differs) disables
|
|
16
|
+
// the gate until restart — a user who touches the dial owns the dial.
|
|
17
|
+
//
|
|
18
|
+
// Ownership of our own set: pi emits thinking_level_select only when the level
|
|
19
|
+
// actually changes (agent-session.js setThinkingLevel isChanging gate), with
|
|
20
|
+
// {level, previousLevel} — our set always yields level===ours.to &&
|
|
21
|
+
// previousLevel===ours.from; a <1.5s window guards the pathological late emit.
|
|
22
|
+
// Both must hold, else the event reads as manual.
|
|
23
|
+
|
|
24
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
25
|
+
import { askJev, audit } from "../index.js";
|
|
26
|
+
import { getClassifierSettings } from "./settings.js";
|
|
27
|
+
import { isPlanActive } from "../../../lib/plan-bridge.js";
|
|
28
|
+
|
|
29
|
+
const TAG = "ceulen-think-gate";
|
|
30
|
+
const BUDGET_MS = 2_500;
|
|
31
|
+
/** Guards against a pathologically late event being misread as ours (pi emits
|
|
32
|
+
* synchronously off setThinkingLevel, so real ownership arrives in ms). */
|
|
33
|
+
const OWNERSHIP_WINDOW_MS = 1_500;
|
|
34
|
+
|
|
35
|
+
/** Keep in sync with extensions/modules/subagent/lib/routing.ts EFFORT_LADDER
|
|
36
|
+
* (same 5 rungs; a local copy so the classifier module stays dependency-free). */
|
|
37
|
+
const EFFORT_LADDER: readonly string[] = [
|
|
38
|
+
"off: mechanical lookup or trivial edit, no reasoning needed",
|
|
39
|
+
"low: simple, well-specified change; fix already identified",
|
|
40
|
+
"medium: normal multi-step implementation or verification",
|
|
41
|
+
"high: cross-file reasoning, subtle interactions, careful refactor",
|
|
42
|
+
"xhigh: architecture, design tradeoffs, consequential planning",
|
|
43
|
+
];
|
|
44
|
+
const LEVELS = ["off", "low", "medium", "high", "xhigh"] as const;
|
|
45
|
+
type Level = (typeof LEVELS)[number];
|
|
46
|
+
|
|
47
|
+
interface Ours {
|
|
48
|
+
setAt: number;
|
|
49
|
+
from: Level;
|
|
50
|
+
to: Level;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Armed BEFORE a setThinkingLevel call: pi's thinking_level_select arrives
|
|
54
|
+
* synchronously off the call site (live-verified 2026-10-19 — the event lands
|
|
55
|
+
* before the line after the call executes), so post-call attribution is too
|
|
56
|
+
* late. The arm is consumed by the next event, whatever its (clamped) values.
|
|
57
|
+
* A no-change set emits nothing; the arm then lingers windowed (5s) and only
|
|
58
|
+
* risks mis-attributing a pathological same-second manual change — fail-open
|
|
59
|
+
* direction: the gate keeps running. */
|
|
60
|
+
let expectEventAt = 0;
|
|
61
|
+
const EXPECT_EVENT_WINDOW_MS = 5_000;
|
|
62
|
+
|
|
63
|
+
export function registerThinkGate(pi: ExtensionAPI): void {
|
|
64
|
+
let ours: Ours | undefined;
|
|
65
|
+
let stoodDown = false;
|
|
66
|
+
let reportedNoModel = false;
|
|
67
|
+
|
|
68
|
+
const reset = () => {
|
|
69
|
+
ours = undefined;
|
|
70
|
+
stoodDown = false;
|
|
71
|
+
reportedNoModel = false;
|
|
72
|
+
expectEventAt = 0;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
pi.on("session_start", () => reset());
|
|
76
|
+
pi.on("session_shutdown", () => reset());
|
|
77
|
+
|
|
78
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
79
|
+
if (event.messageType !== "user" || !event.prompt) return undefined;
|
|
80
|
+
if (process.env.CEULEN_THINK_GATE_OFF) return undefined;
|
|
81
|
+
if (stoodDown || isPlanActive()) return undefined;
|
|
82
|
+
const { thinkGate } = getClassifierSettings();
|
|
83
|
+
if (!thinkGate.enabled && !thinkGate.observe) return undefined;
|
|
84
|
+
|
|
85
|
+
const current = pi.getThinkingLevel() as Level;
|
|
86
|
+
const model = ctx.model;
|
|
87
|
+
const head = event.prompt.slice(0, 4000);
|
|
88
|
+
const finish = (entry: Record<string, unknown>) =>
|
|
89
|
+
// Awaited by the caller: one append per turn is ~1ms and makes the
|
|
90
|
+
// audit-vs-settle ordering deterministic. (The bash hook keeps
|
|
91
|
+
// fire-and-forget — that one is a per-tool-call hot path.)
|
|
92
|
+
audit({ tag: TAG, prompt_head: head.slice(0, 80), model: model?.id, current_level: current, ...entry });
|
|
93
|
+
|
|
94
|
+
let score: number | undefined;
|
|
95
|
+
let confidence: number | undefined;
|
|
96
|
+
let reason: string | undefined;
|
|
97
|
+
try {
|
|
98
|
+
const budget = AbortSignal.timeout(BUDGET_MS);
|
|
99
|
+
const answers = (await Promise.race([
|
|
100
|
+
askJev(
|
|
101
|
+
ctx,
|
|
102
|
+
{ prompt: head, model: model?.id, current_level: current },
|
|
103
|
+
{
|
|
104
|
+
effort: {
|
|
105
|
+
type: "score",
|
|
106
|
+
instructions: "How much reasoning does this turn need?",
|
|
107
|
+
criteria: [...EFFORT_LADDER],
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
budget,
|
|
111
|
+
),
|
|
112
|
+
new Promise<never>((_, reject) => budget.addEventListener("abort", () => reject(new Error("think gate budget exceeded")), { once: true })),
|
|
113
|
+
])) as Record<string, unknown>;
|
|
114
|
+
const effort = answers.effort as { score?: unknown; confidence?: unknown } | undefined;
|
|
115
|
+
if (effort && typeof effort.score === "number" && Number.isFinite(effort.score)) {
|
|
116
|
+
score = effort.score;
|
|
117
|
+
confidence = typeof effort.confidence === "number" ? effort.confidence : undefined;
|
|
118
|
+
} else {
|
|
119
|
+
reason = "malformed answer";
|
|
120
|
+
}
|
|
121
|
+
} catch (e) {
|
|
122
|
+
reason = e instanceof Error ? e.message.slice(0, 80) : "classifier error";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (score === undefined) {
|
|
126
|
+
// Circuit-breaker for the log: a missing classifier model fail-opens on
|
|
127
|
+
// EVERY turn — one audit line per turn is noise, one per session is a
|
|
128
|
+
// trace. First miss writes the line and arms the flag; later misses are
|
|
129
|
+
// silent (a malformed answer re-reports once via its own branch).
|
|
130
|
+
if (reason?.includes("no classifier model")) {
|
|
131
|
+
if (!reportedNoModel) {
|
|
132
|
+
reportedNoModel = true;
|
|
133
|
+
await finish({ applied: false, reason });
|
|
134
|
+
}
|
|
135
|
+
} else {
|
|
136
|
+
await finish({ applied: false, reason });
|
|
137
|
+
}
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
if (confidence !== undefined && confidence < thinkGate.threshold) {
|
|
141
|
+
await finish({ applied: false, reason: `confidence ${confidence} < ${thinkGate.threshold}`, verdict_score: score });
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const idx = Math.min(Math.max(Math.round(score), 0), LEVELS.length - 1);
|
|
146
|
+
const verdict = LEVELS[idx];
|
|
147
|
+
if (thinkGate.observe || verdict === current) {
|
|
148
|
+
await finish({ applied: false, reason: thinkGate.observe ? "observe" : "same", verdict, confidence });
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Arm BEFORE the set: pi emits synchronously off the call site (live
|
|
153
|
+
// 2026-10-19) — `ours` and the event arm must be complete when the
|
|
154
|
+
// handler runs.
|
|
155
|
+
ours = { setAt: Date.now(), from: current, to: verdict };
|
|
156
|
+
expectEventAt = Date.now();
|
|
157
|
+
pi.setThinkingLevel(verdict);
|
|
158
|
+
// pi CLAMPS the requested level (GLM-5.3 has no real "off": off→minimal
|
|
159
|
+
// via the zai53 map) — keep the EFFECTIVE level as ours.to so the settle
|
|
160
|
+
// check compares against reality. (Live lesson 2026-10-19: verdict "off"
|
|
161
|
+
// clamped to "minimal"; the raw-verdict comparison restored nothing.)
|
|
162
|
+
ours.to = pi.getThinkingLevel() as Level;
|
|
163
|
+
if (ours.to === ours.from) ours = undefined;
|
|
164
|
+
await finish({ applied: true, verdict, confidence, baseline: current });
|
|
165
|
+
return undefined;
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
pi.on("agent_settled", async () => {
|
|
169
|
+
if (!ours) return;
|
|
170
|
+
const current = pi.getThinkingLevel() as Level;
|
|
171
|
+
const o = ours;
|
|
172
|
+
ours = undefined;
|
|
173
|
+
if (current === o.to) {
|
|
174
|
+
expectEventAt = Date.now();
|
|
175
|
+
pi.setThinkingLevel(o.from);
|
|
176
|
+
// Re-read: the restore is also subject to the clamp — log what actually
|
|
177
|
+
// happened, and skip the audit on a no-op (a no-op emits no event; the
|
|
178
|
+
// lingering arm is windowed and harmless).
|
|
179
|
+
const restoredTo = pi.getThinkingLevel() as Level;
|
|
180
|
+
if (restoredTo !== o.to) {
|
|
181
|
+
await audit({ tag: TAG, restored: restoredTo, verdict: o.to });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// Level moved by someone else mid-turn: thinking_level_select already
|
|
185
|
+
// stood the gate down; nothing to restore here.
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
pi.on("thinking_level_select", async (event) => {
|
|
189
|
+
// Kill-switch first: a herdr child's pi INIT fires this event (model default
|
|
190
|
+
// re-apply) before any turn — without this guard the child logs a spurious
|
|
191
|
+
// stoodDown even though its gate is env-disabled (live herdr test
|
|
192
|
+
// 2026-10-19). Inert means fully inert.
|
|
193
|
+
if (process.env.CEULEN_THINK_GATE_OFF) return;
|
|
194
|
+
// Our own forward set or settle-restore (armed at the call site; pi emits
|
|
195
|
+
// the CLAMPED values, which we cannot predict — the arm is the attribution).
|
|
196
|
+
if (expectEventAt && Date.now() - expectEventAt < EXPECT_EVENT_WINDOW_MS) {
|
|
197
|
+
expectEventAt = 0;
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const isOurs = ours !== undefined
|
|
201
|
+
&& event.level === ours.to
|
|
202
|
+
&& event.previousLevel === ours.from
|
|
203
|
+
&& Date.now() - ours.setAt < OWNERSHIP_WINDOW_MS;
|
|
204
|
+
if (isOurs) return;
|
|
205
|
+
if (!stoodDown) {
|
|
206
|
+
stoodDown = true;
|
|
207
|
+
ours = undefined;
|
|
208
|
+
await audit({ tag: TAG, stoodDown: true, level: event.level, previousLevel: event.previousLevel });
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
}
|