ceulen 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/extensions/lib/registry.test.ts +67 -0
- package/extensions/lib/registry.ts +17 -7
- package/extensions/modules/advisor/index.ts +20 -2
- package/extensions/modules/advisor/lib/watcher.ts +3 -1
- package/extensions/modules/advisor/test/module.test.ts +64 -1
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/munin/configPanel.ts +5 -2
- package/extensions/modules/munin/test/configPanel.test.ts +27 -2
- package/extensions/modules/router/configPanel.ts +24 -10
- package/extensions/modules/router/lib/client.ts +6 -4
- package/extensions/modules/router/test/unit.test.ts +83 -2
- package/extensions/modules/rules/index.ts +120 -0
- package/extensions/modules/rules/lib/rules.ts +348 -0
- package/extensions/modules/rules/test/lib.test.ts +263 -0
- package/extensions/modules/rules/test/module.test.ts +222 -0
- package/extensions/modules/subagent/index.ts +19 -6
- package/extensions/modules/subagent/lib/routing.ts +11 -6
- package/extensions/modules/subagent/lib/security.ts +12 -1
- package/extensions/modules/subagent/test/routing.test.ts +174 -0
- package/extensions/modules/todo/index.ts +478 -0
- package/extensions/modules/todo/test/todo.test.ts +252 -0
- package/extensions/modules/usage/index.ts +11 -0
- package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
- package/extensions/modules/web/configPanel.ts +38 -13
- package/extensions/modules/web/lib/settings.ts +11 -2
- package/extensions/modules/web/test/configPanel.test.ts +67 -1
- package/extensions/modules/zai/configPanel.ts +5 -2
- package/extensions/modules/zai/lib/signing.ts +4 -1
- package/extensions/modules/zai/test/configPanel.test.ts +23 -0
- package/extensions/modules/zai/test/signing.test.ts +19 -0
- package/package.json +2 -2
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rules lib tests: parsing (sticky vs rulebook), @import expansion (cycle guard,
|
|
3
|
+
* missing marker, fence skip), prompt-block composition (marker, cap + truncation
|
|
4
|
+
* marker), and the mtime cache. Fixture files live in temp dirs.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { after, describe, it } from "node:test";
|
|
8
|
+
import assert from "node:assert/strict";
|
|
9
|
+
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
|
|
10
|
+
import os from "node:os";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
MAX_IMPORT_DEPTH,
|
|
15
|
+
STICKY_CHAR_CAP,
|
|
16
|
+
clearRuleCache,
|
|
17
|
+
composeRulesBlock,
|
|
18
|
+
discoverRuleFiles,
|
|
19
|
+
loadRules,
|
|
20
|
+
parseRulesFile,
|
|
21
|
+
} from "../lib/rules";
|
|
22
|
+
|
|
23
|
+
const temps: string[] = [];
|
|
24
|
+
after(() => {
|
|
25
|
+
for (const dir of temps) rmSync(dir, { recursive: true, force: true });
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
function tmp(prefix: string): string {
|
|
29
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), prefix));
|
|
30
|
+
temps.push(dir);
|
|
31
|
+
return dir;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function write(file: string, text: string): string {
|
|
35
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
36
|
+
writeFileSync(file, text, "utf8");
|
|
37
|
+
return file;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** cwd nested inside an empty temp root — no ancestor can hold a .pi/RULES.md. */
|
|
41
|
+
function workspace(): { cwd: string; userDir: string } {
|
|
42
|
+
const root = tmp("rules-lib-");
|
|
43
|
+
return { cwd: path.join(root, "a", "b"), userDir: path.join(root, "agent") };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
describe("parseRulesFile", () => {
|
|
47
|
+
it("classifies a description-led section as rulebook and the rest as sticky", () => {
|
|
48
|
+
const rules = parseRulesFile(
|
|
49
|
+
[
|
|
50
|
+
"## never-push",
|
|
51
|
+
"Never commit or push.",
|
|
52
|
+
"",
|
|
53
|
+
"## api-style",
|
|
54
|
+
"description: How to write HTTP handlers here.",
|
|
55
|
+
"Always use the shared json() helper.",
|
|
56
|
+
].join("\n"),
|
|
57
|
+
"/x/.pi/RULES.md",
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
assert.deepEqual(rules.map((r) => [r.name, r.sticky, r.description]), [
|
|
61
|
+
["never-push", true, undefined],
|
|
62
|
+
["api-style", false, "How to write HTTP handlers here."],
|
|
63
|
+
]);
|
|
64
|
+
assert.equal(rules[0].body, "Never commit or push.");
|
|
65
|
+
// The description line is metadata, never part of the body.
|
|
66
|
+
assert.equal(rules[1].body, "Always use the shared json() helper.");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("treats pre-heading prose as one sticky rule named RULES", () => {
|
|
70
|
+
const rules = parseRulesFile("Never edit generated files.\nDo not commit without asking.\n", "/x/RULES.md");
|
|
71
|
+
assert.deepEqual(rules.map((r) => [r.name, r.sticky, r.body]), [
|
|
72
|
+
["RULES", true, "Never edit generated files.\nDo not commit without asking."],
|
|
73
|
+
]);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("does not parse headings inside fenced code blocks or non-## headings", () => {
|
|
77
|
+
const rules = parseRulesFile(
|
|
78
|
+
["# Title", "## real", "```md", "## not-a-rule", "```", "### also-not-a-rule"].join("\n"),
|
|
79
|
+
"/x/RULES.md",
|
|
80
|
+
);
|
|
81
|
+
assert.deepEqual(rules.map((r) => r.name), ["real"]);
|
|
82
|
+
assert.ok(rules[0].body.includes("## not-a-rule"));
|
|
83
|
+
assert.ok(rules[0].body.includes("### also-not-a-rule"));
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("ignores empty sections and a description line with no value", () => {
|
|
87
|
+
assert.deepEqual(parseRulesFile("## empty\n\n## also-empty\n", "/x/RULES.md"), []);
|
|
88
|
+
const [rule] = parseRulesFile("## x\ndescription:\nbody here\n", "/x/RULES.md");
|
|
89
|
+
assert.equal(rule.sticky, true, "an empty description must not turn a sticky rule into a rulebook entry");
|
|
90
|
+
assert.equal(rule.body, "description:\nbody here");
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe("@import expansion", () => {
|
|
95
|
+
it("expands relative to the importing RULES.md (not cwd), recursively", () => {
|
|
96
|
+
const { cwd, userDir } = workspace();
|
|
97
|
+
const rulesFile = write(
|
|
98
|
+
path.join(cwd, ".pi/RULES.md"),
|
|
99
|
+
["## a", "top", "@inc/one.md"].join("\n"),
|
|
100
|
+
);
|
|
101
|
+
write(path.join(cwd, ".pi/inc/one.md"), "one\n@sibling/two.md\n");
|
|
102
|
+
write(path.join(cwd, ".pi/inc/sibling/two.md"), "two\n");
|
|
103
|
+
|
|
104
|
+
const model = loadRules(cwd, userDir);
|
|
105
|
+
assert.equal(model.rules.length, 1);
|
|
106
|
+
assert.ok(model.rules[0].body.includes("top"));
|
|
107
|
+
assert.ok(model.rules[0].body.includes("one"));
|
|
108
|
+
assert.ok(model.rules[0].body.includes("two"), "nested imports expand relative to their own file");
|
|
109
|
+
assert.equal(model.rules[0].source, rulesFile);
|
|
110
|
+
assert.deepEqual(discoverRuleFiles(cwd, userDir), [rulesFile]);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("leaves cycles and repeats literal and never crashes", () => {
|
|
114
|
+
const { cwd, userDir } = workspace();
|
|
115
|
+
write(path.join(cwd, ".pi/RULES.md"), "## a\n@a.md\n@b.md\n@b.md\n");
|
|
116
|
+
write(path.join(cwd, ".pi/a.md"), "AAA\n@b.md\n");
|
|
117
|
+
write(path.join(cwd, ".pi/b.md"), "BBB\n@a.md\n");
|
|
118
|
+
|
|
119
|
+
const body = loadRules(cwd, userDir).rules[0].body;
|
|
120
|
+
assert.ok(body.includes("AAA"));
|
|
121
|
+
assert.ok(body.includes("BBB"));
|
|
122
|
+
// a.md already pulled b.md, so b.md's own @a.md back-reference stays literal.
|
|
123
|
+
assert.ok(body.includes("@a.md"));
|
|
124
|
+
// Second mention of b.md is a repeat → literal, not a second expansion.
|
|
125
|
+
assert.equal(body.match(/BBB/g)?.length, 1);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("marks a missing import in one line instead of failing", () => {
|
|
129
|
+
const { cwd, userDir } = workspace();
|
|
130
|
+
write(path.join(cwd, ".pi/RULES.md"), "## a\nsee @nope/missing.md for details\n");
|
|
131
|
+
assert.ok(loadRules(cwd, userDir).rules[0].body.includes("[missing import: @nope/missing.md]"));
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("stops expanding past the depth limit", () => {
|
|
135
|
+
const { cwd, userDir } = workspace();
|
|
136
|
+
const chain = Array.from({ length: MAX_IMPORT_DEPTH + 2 }, (_, i) => `level-${i}`);
|
|
137
|
+
write(path.join(cwd, ".pi/RULES.md"), `## a\n@f0.md\n`);
|
|
138
|
+
chain.forEach((text, i) => write(path.join(cwd, `.pi/f${i}.md`), `${text}\n@f${i + 1}.md\n`));
|
|
139
|
+
|
|
140
|
+
const body = loadRules(cwd, userDir).rules[0].body;
|
|
141
|
+
assert.ok(body.includes(`level-${MAX_IMPORT_DEPTH - 1}`));
|
|
142
|
+
assert.ok(body.includes(`[import depth limit reached: @f${MAX_IMPORT_DEPTH}.md]`));
|
|
143
|
+
assert.ok(!body.includes(`level-${MAX_IMPORT_DEPTH + 1}`));
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("does not expand @tokens inside fences, or email/git tokens", () => {
|
|
147
|
+
const { cwd, userDir } = workspace();
|
|
148
|
+
write(path.join(cwd, ".pi/doc.md"), "EXPANDED\n");
|
|
149
|
+
write(
|
|
150
|
+
path.join(cwd, ".pi/RULES.md"),
|
|
151
|
+
["## a", "```", "@doc.md", "```", "mail me at user@example.com", "clone git@github.com:o/r.git", "also `@nope.ts`"].join("\n"),
|
|
152
|
+
);
|
|
153
|
+
const body = loadRules(cwd, userDir).rules[0].body;
|
|
154
|
+
assert.ok(!body.includes("EXPANDED"), "fenced @tokens stay literal");
|
|
155
|
+
assert.ok(body.includes("user@example.com"));
|
|
156
|
+
assert.ok(body.includes("git@github.com:o/r.git"));
|
|
157
|
+
// A `@token` opening an inline code span follows a backtick, so the
|
|
158
|
+
// "line start or whitespace" gate leaves it literal — span and fence alike.
|
|
159
|
+
assert.ok(body.includes("`@nope.ts`"), "inline code spans stay literal");
|
|
160
|
+
assert.ok(!body.includes("[missing import: @nope.ts]"));
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
describe("precedence", () => {
|
|
165
|
+
it("resolves sources nearest-first and projects override the user file", () => {
|
|
166
|
+
const { cwd, userDir } = workspace();
|
|
167
|
+
const near = write(path.join(cwd, ".pi/RULES.md"), "## shared\nnear\n## near-only\nN\n");
|
|
168
|
+
const far = write(path.join(cwd, "..", ".pi/RULES.md"), "## shared\nfar\n## far-only\nF\n");
|
|
169
|
+
const user = write(path.join(userDir, "RULES.md"), "## shared\nuser\n## user-only\nU\n");
|
|
170
|
+
|
|
171
|
+
assert.deepEqual(discoverRuleFiles(cwd, userDir), [near, far, user]);
|
|
172
|
+
|
|
173
|
+
const model = loadRules(cwd, userDir);
|
|
174
|
+
assert.deepEqual(model.rules.map((r) => r.name), ["shared", "near-only", "far-only", "user-only"]);
|
|
175
|
+
assert.equal(model.rules[0].body, "near", "nearest project file wins the duplicate name");
|
|
176
|
+
assert.deepEqual(
|
|
177
|
+
model.rules.map((r) => r.source),
|
|
178
|
+
[near, near, far, user],
|
|
179
|
+
);
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
describe("composeRulesBlock", () => {
|
|
184
|
+
it("is undefined when no RULES.md exists anywhere (zero footprint)", () => {
|
|
185
|
+
const { cwd, userDir } = workspace();
|
|
186
|
+
const model = loadRules(cwd, userDir);
|
|
187
|
+
assert.equal(model.block, undefined);
|
|
188
|
+
assert.deepEqual(model.files, []);
|
|
189
|
+
assert.equal(composeRulesBlock(model, cwd), undefined);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("marks the block and lists rulebook names with descriptions only", () => {
|
|
193
|
+
const { cwd, userDir } = workspace();
|
|
194
|
+
write(
|
|
195
|
+
path.join(cwd, ".pi/RULES.md"),
|
|
196
|
+
["## sticky-one", "S body", "", "## book-one", "description: B description", "B body secret"].join("\n"),
|
|
197
|
+
);
|
|
198
|
+
const model = loadRules(cwd, userDir);
|
|
199
|
+
const block = model.block!;
|
|
200
|
+
|
|
201
|
+
assert.ok(block.startsWith("<user-rules>"));
|
|
202
|
+
assert.ok(block.endsWith("</user-rules>"));
|
|
203
|
+
assert.ok(block.includes("S body"));
|
|
204
|
+
assert.ok(block.includes("- book-one: B description"));
|
|
205
|
+
assert.ok(!block.includes("B body secret"), "the rulebook body is served on demand, never inlined");
|
|
206
|
+
assert.equal(model.blockChars, block.length);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it("caps the sticky block and drops the lowest-precedence files first, loudly", () => {
|
|
210
|
+
const { cwd, userDir } = workspace();
|
|
211
|
+
const big = (name: string) => `## ${name}\n${name.repeat(1500)}\n`;
|
|
212
|
+
write(path.join(cwd, ".pi/RULES.md"), big("near"));
|
|
213
|
+
write(path.join(userDir, "RULES.md"), big("user"));
|
|
214
|
+
|
|
215
|
+
const model = loadRules(cwd, userDir);
|
|
216
|
+
const block = model.block!;
|
|
217
|
+
assert.equal(model.sticky.length, 2);
|
|
218
|
+
assert.ok(block.includes("near"), "the nearest file survives");
|
|
219
|
+
assert.ok(!block.includes("user".repeat(1500)), "the user file is dropped first");
|
|
220
|
+
assert.ok(block.includes("STICKY RULES TRUNCATED"));
|
|
221
|
+
assert.ok(block.includes(`exceeded ${STICKY_CHAR_CAP} chars`));
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it("truncates a single oversized sticky rule instead of dumping it whole", () => {
|
|
225
|
+
const { cwd, userDir } = workspace();
|
|
226
|
+
write(path.join(cwd, ".pi/RULES.md"), `## huge\n${"x".repeat(STICKY_CHAR_CAP * 2)}\n`);
|
|
227
|
+
const block = loadRules(cwd, userDir).block!;
|
|
228
|
+
assert.ok(block.includes("[rule body truncated at the sticky cap]"));
|
|
229
|
+
assert.ok(block.length < STICKY_CHAR_CAP + 500);
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
describe("mtime cache", () => {
|
|
234
|
+
it("re-reads after an edit and after an edit to an imported file", async () => {
|
|
235
|
+
const { cwd, userDir } = workspace();
|
|
236
|
+
const imported = write(path.join(cwd, ".pi/snippet.md"), "OLD-IMPORT\n");
|
|
237
|
+
write(path.join(cwd, ".pi/RULES.md"), "## a\n@snippet.md\n");
|
|
238
|
+
assert.ok(loadRules(cwd, userDir).rules[0].body.includes("OLD-IMPORT"));
|
|
239
|
+
|
|
240
|
+
// Same mtimeMs/size would hide the change — bump mtime explicitly.
|
|
241
|
+
const bump = (file: string, text: string) => {
|
|
242
|
+
writeFileSync(file, text, "utf8");
|
|
243
|
+
const future = new Date(Date.now() + 5000);
|
|
244
|
+
utimesSync(file, future, future);
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
bump(imported, "NEW-IMPORT\n");
|
|
248
|
+
assert.ok(loadRules(cwd, userDir).rules[0].body.includes("NEW-IMPORT"), "imported-file edits invalidate the cache");
|
|
249
|
+
|
|
250
|
+
bump(path.join(cwd, ".pi/RULES.md"), "## a\nBODY-V2\n@missing.md\n");
|
|
251
|
+
assert.ok(loadRules(cwd, userDir).rules[0].body.includes("BODY-V2"));
|
|
252
|
+
|
|
253
|
+
clearRuleCache();
|
|
254
|
+
assert.ok(loadRules(cwd, userDir).rules[0].body.includes("BODY-V2"));
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it("returns the cached model unchanged when nothing on disk moved", () => {
|
|
258
|
+
const { cwd, userDir } = workspace();
|
|
259
|
+
write(path.join(cwd, ".pi/RULES.md"), "## a\nstable\n");
|
|
260
|
+
const first = loadRules(cwd, userDir);
|
|
261
|
+
assert.equal(loadRules(cwd, userDir), first, "same mtime+size → the same model object");
|
|
262
|
+
});
|
|
263
|
+
});
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rules module tests: the before_agent_start composer (append-only, no-op with
|
|
3
|
+
* zero rules), the rule_get tool (found / not-found / sticky), the /rules
|
|
4
|
+
* command (status hides rulebook bodies; reload drops the cache), and the
|
|
5
|
+
* per-tool kill-switch.
|
|
6
|
+
*
|
|
7
|
+
* The `pi` stub is deliberately loose (only the surface the module touches) —
|
|
8
|
+
* pi's real SDK types require a full context object.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { after, describe, it } from "node:test";
|
|
12
|
+
import assert from "node:assert/strict";
|
|
13
|
+
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
|
|
14
|
+
import os from "node:os";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
|
|
17
|
+
import rulesExtension from "../index.ts";
|
|
18
|
+
import { readDisabledTools } from "../../../lib/tools";
|
|
19
|
+
|
|
20
|
+
const temps: string[] = [];
|
|
21
|
+
const envBackup = process.env.PI_CODING_AGENT_DIR;
|
|
22
|
+
const agentDir = tmp("rules-agent-"); // empty agent dir: an inherited one adds a live user RULES.md
|
|
23
|
+
mkdirSync(agentDir, { recursive: true });
|
|
24
|
+
process.env.PI_CODING_AGENT_DIR = agentDir;
|
|
25
|
+
|
|
26
|
+
after(() => {
|
|
27
|
+
for (const dir of temps) rmSync(dir, { recursive: true, force: true });
|
|
28
|
+
if (envBackup !== undefined) process.env.PI_CODING_AGENT_DIR = envBackup;
|
|
29
|
+
else delete process.env.PI_CODING_AGENT_DIR;
|
|
30
|
+
clearDisabled();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
function tmp(prefix: string): string {
|
|
34
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), prefix));
|
|
35
|
+
temps.push(dir);
|
|
36
|
+
return dir;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function write(file: string, text: string): string {
|
|
40
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
41
|
+
writeFileSync(file, text, "utf8");
|
|
42
|
+
return file;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Isolated workspace; cwd has no ancestor .pi/RULES.md (temp dir under os.tmpdir). */
|
|
46
|
+
function workspace(files: Record<string, string> = {}): string {
|
|
47
|
+
const cwd = path.join(tmp("rules-mod-"), "a", "b");
|
|
48
|
+
mkdirSync(cwd, { recursive: true });
|
|
49
|
+
for (const [rel, text] of Object.entries(files)) write(path.join(cwd, rel), text);
|
|
50
|
+
return cwd;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Empty dir used as PI_CODING_AGENT_DIR — set at the top of this file. */
|
|
54
|
+
|
|
55
|
+
interface Harness {
|
|
56
|
+
events: Map<string, (event: any, ctx: any) => any>;
|
|
57
|
+
tools: Map<string, any>;
|
|
58
|
+
commands: Map<string, any>;
|
|
59
|
+
notes: { message: string; level?: string }[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function harness(): Harness {
|
|
63
|
+
const events = new Map();
|
|
64
|
+
const tools = new Map();
|
|
65
|
+
const commands = new Map();
|
|
66
|
+
const notes: Harness["notes"] = [];
|
|
67
|
+
const pi = {
|
|
68
|
+
on(name: string, handler: any) { events.set(name, handler); },
|
|
69
|
+
registerTool(tool: any) { tools.set(tool.name, tool); },
|
|
70
|
+
registerCommand(name: string, options: any) { commands.set(name, options); },
|
|
71
|
+
};
|
|
72
|
+
rulesExtension(pi as any);
|
|
73
|
+
return { events, tools, commands, notes };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function context(cwd: string, notes: Harness["notes"] = []): any {
|
|
77
|
+
return { cwd, ui: { notify: (message: string, level?: string) => notes.push({ message, level }) }, isProjectTrusted: () => true };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Point the kill-switch at the temp agent dir (readDisabledTools has no cwd arg). */
|
|
81
|
+
function disableTools(names: string[]): void {
|
|
82
|
+
process.env.PI_CODING_AGENT_DIR = agentDir;
|
|
83
|
+
writeFileSync(path.join(agentDir, "settings.json"), JSON.stringify({ ceulen: { disabledTools: names } }), "utf8");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function clearDisabled(): void {
|
|
87
|
+
rmSync(path.join(agentDir, "settings.json"), { force: true });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function startBlock(cwd: string, base = "BASE"): Promise<string | undefined> {
|
|
91
|
+
const { events } = harness();
|
|
92
|
+
const result = await events.get("before_agent_start")!({ systemPrompt: base, prompt: "p" }, context(cwd));
|
|
93
|
+
return result?.systemPrompt;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
describe("rules module — before_agent_start", () => {
|
|
97
|
+
it("is a no-op when no RULES.md exists anywhere (zero footprint)", async () => {
|
|
98
|
+
const cwd = workspace();
|
|
99
|
+
const { events } = harness();
|
|
100
|
+
const result = await events.get("before_agent_start")!({ systemPrompt: "BASE", prompt: "p" }, context(cwd));
|
|
101
|
+
assert.equal(result, undefined);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("appends the block to the existing system prompt, never replacing it", async () => {
|
|
105
|
+
const cwd = workspace({ ".pi/RULES.md": "## sticky\nS body\n\n## book\ndescription: B desc\nB body\n" });
|
|
106
|
+
const out = (await startBlock(cwd))!;
|
|
107
|
+
assert.ok(out.startsWith("BASE\n\n<user-rules>"));
|
|
108
|
+
assert.ok(out.includes("S body"));
|
|
109
|
+
assert.ok(out.includes("- book: B desc"));
|
|
110
|
+
assert.ok(!out.includes("B body"));
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("does not gate on the tool set (the fff pattern minus the active-tool check)", async () => {
|
|
114
|
+
const cwd = workspace({ ".pi/RULES.md": "## sticky\nS body\n" });
|
|
115
|
+
disableTools(["rule_get"]);
|
|
116
|
+
try {
|
|
117
|
+
assert.equal(readDisabledTools().has("rule_get"), true);
|
|
118
|
+
assert.ok((await startBlock(cwd))!.includes("S body"));
|
|
119
|
+
} finally {
|
|
120
|
+
clearDisabled();
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
describe("rules module — rule_get", () => {
|
|
126
|
+
it("registers the canonical tool name, active by default", () => {
|
|
127
|
+
const { tools } = harness();
|
|
128
|
+
assert.deepEqual([...tools.keys()], ["rule_get"]);
|
|
129
|
+
assert.equal(tools.get("rule_get").defaultActive, true);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("returns the body (imports expanded) for a found rule and lists names when not found", async () => {
|
|
133
|
+
const cwd = workspace({
|
|
134
|
+
".pi/RULES.md": "## book\ndescription: B desc\nsee @detail.md\n",
|
|
135
|
+
".pi/detail.md": "DETAIL-BODY\n",
|
|
136
|
+
});
|
|
137
|
+
const { tools } = harness();
|
|
138
|
+
const tool = tools.get("rule_get");
|
|
139
|
+
|
|
140
|
+
const found = await tool.execute("id", { name: "book" }, undefined, undefined, context(cwd));
|
|
141
|
+
assert.ok(found.content[0].text.includes("DETAIL-BODY"));
|
|
142
|
+
assert.ok(found.content[0].text.includes("from " + path.join(cwd, ".pi/RULES.md")));
|
|
143
|
+
|
|
144
|
+
const missing = await tool.execute("id", { name: "nope" }, undefined, undefined, context(cwd));
|
|
145
|
+
assert.ok(missing.content[0].text.includes('Rule "nope" not found'));
|
|
146
|
+
assert.ok(missing.content[0].text.includes("book"));
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("labels a sticky rule as already present in the prompt", async () => {
|
|
150
|
+
const cwd = workspace({ ".pi/RULES.md": "## sticky\nS body\n" });
|
|
151
|
+
const { tools } = harness();
|
|
152
|
+
const result = await tools.get("rule_get").execute("id", { name: "sticky" }, undefined, undefined, context(cwd));
|
|
153
|
+
assert.ok(result.content[0].text.includes('already appended to the system prompt'));
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("reports an empty workspace distinctly", async () => {
|
|
157
|
+
const cwd = workspace();
|
|
158
|
+
const { tools } = harness();
|
|
159
|
+
const result = await tools.get("rule_get").execute("id", { name: "anything" }, undefined, undefined, context(cwd));
|
|
160
|
+
assert.ok(result.content[0].text.includes("no RULES.md exists in this workspace"));
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("registers inactive when listed in ceulen.disabledTools", () => {
|
|
164
|
+
disableTools(["rule_get"]);
|
|
165
|
+
try {
|
|
166
|
+
assert.equal(harness().tools.get("rule_get").defaultActive, false);
|
|
167
|
+
} finally {
|
|
168
|
+
clearDisabled();
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
describe("rules module — /rules command", () => {
|
|
174
|
+
it("reports sources, counts, names, and char count without leaking rulebook bodies", async () => {
|
|
175
|
+
const cwd = workspace({
|
|
176
|
+
".pi/RULES.md": "## sticky\nS body\n\n## book\ndescription: B desc\nSECRET-BODY-TEXT\n",
|
|
177
|
+
});
|
|
178
|
+
const notes: Harness["notes"] = [];
|
|
179
|
+
const { commands } = harness();
|
|
180
|
+
await commands.get("rules").handler("", context(cwd, notes));
|
|
181
|
+
|
|
182
|
+
const text = notes[0].message;
|
|
183
|
+
assert.equal(notes[0].level, "info");
|
|
184
|
+
assert.ok(text.includes(path.join(cwd, ".pi/RULES.md")));
|
|
185
|
+
assert.ok(text.includes("Sticky rules (1): sticky"));
|
|
186
|
+
assert.ok(text.includes("Rulebook rules (1): book"));
|
|
187
|
+
assert.ok(text.includes("Bodies are served on demand"));
|
|
188
|
+
assert.ok(!text.includes("SECRET-BODY-TEXT"), "rulebook bodies are on-demand only");
|
|
189
|
+
assert.ok(!text.includes("S body"), "sticky bodies are not echoed either");
|
|
190
|
+
assert.ok(/Prompt block: \d+ chars/.test(text));
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it("says so when nothing was found", async () => {
|
|
194
|
+
const notes: Harness["notes"] = [];
|
|
195
|
+
const { commands } = harness();
|
|
196
|
+
await commands.get("rules").handler("", context(workspace(), notes));
|
|
197
|
+
assert.ok(notes[0].message.includes("Rule sources: none"));
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("drops the cache on /rules reload so edits apply without a restart", async () => {
|
|
201
|
+
const cwd = workspace({ ".pi/RULES.md": "## a\nV1\n" });
|
|
202
|
+
const { commands } = harness();
|
|
203
|
+
const notes: Harness["notes"] = [];
|
|
204
|
+
assert.ok((await startBlock(cwd))!.includes("V1"));
|
|
205
|
+
|
|
206
|
+
const file = path.join(cwd, ".pi/RULES.md");
|
|
207
|
+
writeFileSync(file, "## a\nV2\n", "utf8");
|
|
208
|
+
const future = new Date(Date.now() + 5000);
|
|
209
|
+
utimesSync(file, future, future);
|
|
210
|
+
|
|
211
|
+
await commands.get("rules").handler("reload", context(cwd, notes));
|
|
212
|
+
assert.ok(notes[0].message.includes("cache dropped"));
|
|
213
|
+
assert.ok((await startBlock(cwd))!.includes("V2"));
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it("rejects an unknown argument", async () => {
|
|
217
|
+
const notes: Harness["notes"] = [];
|
|
218
|
+
const { commands } = harness();
|
|
219
|
+
await commands.get("rules").handler("bogus", context(workspace(), notes));
|
|
220
|
+
assert.equal(notes[0].level, "error");
|
|
221
|
+
});
|
|
222
|
+
});
|
|
@@ -1002,7 +1002,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1002
1002
|
task: string,
|
|
1003
1003
|
solutionSpace?: string,
|
|
1004
1004
|
precomputed?: RoutingVerdict,
|
|
1005
|
-
): Promise<{ chain: ExpandedCandidates; defaultThinking: SubagentThinkingLevel | undefined }> {
|
|
1005
|
+
): Promise<{ chain: ExpandedCandidates; defaultThinking: SubagentThinkingLevel | undefined; error?: string }> {
|
|
1006
1006
|
let tierOverride: string[] | undefined;
|
|
1007
1007
|
let classifierThinking: SubagentThinkingLevel | undefined;
|
|
1008
1008
|
// A precomputed verdict already carries tier/effort (single-mode
|
|
@@ -1019,7 +1019,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
1019
1019
|
const chain = tierOverride
|
|
1020
1020
|
? expandModelCandidates(tierOverride, rolesCfg.roles)
|
|
1021
1021
|
: resolveAgentModelChain(agent, rolesCfg);
|
|
1022
|
-
return {
|
|
1022
|
+
return {
|
|
1023
|
+
chain,
|
|
1024
|
+
defaultThinking: classifierThinking ?? effectiveAgentThinking(agent, rolesCfg),
|
|
1025
|
+
// A typo'd `@alias` must FAIL LOUD: an empty candidate list would
|
|
1026
|
+
// otherwise read as "use the parent model" (resolveModel's fallback)
|
|
1027
|
+
// and silently dispatch the child on the parent model. Only when
|
|
1028
|
+
// NOTHING resolves — one bad entry beside a resolvable chain is a
|
|
1029
|
+
// diagnostic, not a dispatch failure. Both runners share this path.
|
|
1030
|
+
error: chain.unresolved.length > 0 && chain.candidates.length === 0
|
|
1031
|
+
? `Unresolved model role(s): ${chain.unresolved.join(", ")} — fix the agent frontmatter or subagent.roles.`
|
|
1032
|
+
: undefined,
|
|
1033
|
+
};
|
|
1023
1034
|
}
|
|
1024
1035
|
|
|
1025
1036
|
// Helper (herdr runner): validate + create topology + start the child pi,
|
|
@@ -1035,14 +1046,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
1035
1046
|
): Promise<{ handle: HerdrHandle; timeoutMs: number; startedAt: number } | { error: string }> {
|
|
1036
1047
|
const agent = agents.find((a) => a.name === agentName);
|
|
1037
1048
|
if (!agent) return { error: `Unknown agent: "${agentName}".` };
|
|
1038
|
-
const { chain: agentChain, defaultThinking } = await routedChain(agent, task, solutionSpace, verdict);
|
|
1049
|
+
const { chain: agentChain, defaultThinking, error: chainError } = await routedChain(agent, task, solutionSpace, verdict);
|
|
1050
|
+
if (chainError) return { error: chainError };
|
|
1039
1051
|
const resolved = await resolveModelWithColdStartRetry(ctx, agentChain.candidates);
|
|
1040
1052
|
if (!resolved.model) {
|
|
1041
1053
|
return { error: `No model resolved for agent "${agentName}" (tried: ${resolved.attempted.join(", ") || "none"}).` };
|
|
1042
1054
|
}
|
|
1043
1055
|
// herdr children run full pi — they need SOME lifetime cap so an
|
|
1044
1056
|
// unattended pane can't run forever; fall back to the idle window.
|
|
1045
|
-
const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, hardTimeoutMins: subSettings.hardTimeoutMins });
|
|
1057
|
+
const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, idleTimeoutMins: subSettings.idleTimeoutMins, hardTimeoutMins: subSettings.hardTimeoutMins });
|
|
1046
1058
|
if (timeouts.error) return { error: timeouts.error };
|
|
1047
1059
|
const hardTimeoutMs = timeouts.hardTimeoutMs ?? timeouts.timeoutMs ?? 0;
|
|
1048
1060
|
if (!hardTimeoutMs) return { error: "Invalid herdr timeout configuration." };
|
|
@@ -1147,7 +1159,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1147
1159
|
return makeErrorResult(agentName, task, `Unknown agent: "${agentName}". Available: ${available}.`);
|
|
1148
1160
|
}
|
|
1149
1161
|
|
|
1150
|
-
const { chain: agentChain, defaultThinking } = await routedChain(agent, task, solutionSpace);
|
|
1162
|
+
const { chain: agentChain, defaultThinking, error: chainError } = await routedChain(agent, task, solutionSpace);
|
|
1163
|
+
if (chainError) return makeErrorResult(agentName, task, chainError);
|
|
1151
1164
|
const resolved = await resolveModelWithColdStartRetry(ctx, agentChain.candidates);
|
|
1152
1165
|
if (!resolved.model) {
|
|
1153
1166
|
const tried = resolved.attempted.join(", ") || "none";
|
|
@@ -1171,7 +1184,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1171
1184
|
// Precedence: per-call timeout > agent frontmatter default > global
|
|
1172
1185
|
// default; hard cap from settings (0 = OFF — a child producing events
|
|
1173
1186
|
// is never hard-killed; the idle window is the hang detector).
|
|
1174
|
-
const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, globalTimeout: params.timeout, hardTimeoutMins: subSettings.hardTimeoutMins });
|
|
1187
|
+
const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, globalTimeout: params.timeout, idleTimeoutMins: subSettings.idleTimeoutMins, hardTimeoutMins: subSettings.hardTimeoutMins });
|
|
1175
1188
|
if (timeouts.error) throw new Error(timeouts.error);
|
|
1176
1189
|
effectiveTimeoutMs = timeouts.timeoutMs;
|
|
1177
1190
|
effectiveHardMs = timeouts.hardTimeoutMs;
|
|
@@ -11,8 +11,9 @@
|
|
|
11
11
|
// 2. `agentModels` pin → disables BOTH overrides (no classify call is made)
|
|
12
12
|
// 3. `agentThinking` pin → disables the effort override only
|
|
13
13
|
// 4. classifier (tier + effort): tier gates on the WINNING LABEL'S probability
|
|
14
|
-
// (
|
|
15
|
-
//
|
|
14
|
+
// (`probabilities[choice]`, NOT the max across labels — a high-probability
|
|
15
|
+
// rival must not clear the threshold for a low-confidence choice), effort
|
|
16
|
+
// on the score answer's `confidence`; both must be >= threshold
|
|
16
17
|
// 5. agent frontmatter defaults (what the classifier amends; what applies
|
|
17
18
|
// when routing is off / the call fails / confidence is low)
|
|
18
19
|
//
|
|
@@ -33,7 +34,7 @@ export interface RoutingSettings {
|
|
|
33
34
|
/** Optional classifier model override (provider/id or id); empty = first available. */
|
|
34
35
|
model: string;
|
|
35
36
|
/** Minimum certainty to act on an answer: tier = winning label's
|
|
36
|
-
* probability, effort = the score answer's `confidence` field. */
|
|
37
|
+
* OWN probability, effort = the score answer's `confidence` field. */
|
|
37
38
|
threshold: number;
|
|
38
39
|
}
|
|
39
40
|
|
|
@@ -188,9 +189,13 @@ export async function classifyTask(
|
|
|
188
189
|
const tierAnswer = result.answers.tier as { choice?: string; probabilities?: Record<string, number> } | undefined;
|
|
189
190
|
let tier: Tier | undefined;
|
|
190
191
|
if (wantTier && tierAnswer?.choice && (TIERS as readonly string[]).includes(tierAnswer.choice)) {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
tier
|
|
192
|
+
// Gate on the CHOSEN label's own probability. A label the classifier did
|
|
193
|
+
// not report (or a non-numeric / out-of-range value) means no usable
|
|
194
|
+
// certainty → no tier, exactly like below-threshold (fail open).
|
|
195
|
+
const prob = tierAnswer.probabilities?.[tierAnswer.choice];
|
|
196
|
+
tier = typeof prob === "number" && Number.isFinite(prob) && prob >= 0 && prob <= 1 && prob >= settings.threshold
|
|
197
|
+
? (tierAnswer.choice as Tier)
|
|
198
|
+
: undefined;
|
|
194
199
|
}
|
|
195
200
|
|
|
196
201
|
let effort: string | undefined;
|
|
@@ -478,6 +478,13 @@ export interface ResolveChildTimeoutsOptions {
|
|
|
478
478
|
* ceulen delta: 0 disables the cap (upstream had no off switch).
|
|
479
479
|
*/
|
|
480
480
|
hardTimeoutMins?: number;
|
|
481
|
+
/**
|
|
482
|
+
* Idle (inactivity) window in minutes from `subagent.idleTimeoutMins`.
|
|
483
|
+
* > 0 REPLACES the env-derived default (PI_SUBAGENT_INACTIVITY_TIMEOUT_MINS);
|
|
484
|
+
* 0/undefined keeps the current behaviour. It is a DEFAULT, so an explicit
|
|
485
|
+
* per-call `requested` or frontmatter `agentTimeoutMins` still wins.
|
|
486
|
+
*/
|
|
487
|
+
idleTimeoutMins?: number;
|
|
481
488
|
}
|
|
482
489
|
|
|
483
490
|
export interface ResolveChildTimeoutsResult {
|
|
@@ -495,13 +502,17 @@ export interface ResolveChildTimeoutsResult {
|
|
|
495
502
|
*
|
|
496
503
|
* Precedence: per-call timeout > agent frontmatter `timeout:` > global/caller
|
|
497
504
|
* timeout. The idle window IS the hang detector (every SDK event resets it).
|
|
505
|
+
* `idleTimeoutMins` (> 0) supplies that window as the default; 0/undefined
|
|
506
|
+
* falls back to the env-derived default (3 min).
|
|
498
507
|
* When the hard cap is enabled (hardTimeoutMins > 0), it is clamped up to the
|
|
499
508
|
* idle window — a lifetime cap smaller than the idle window is nonsensical.
|
|
500
509
|
* 0/undefined ⇒ undefined: a child producing events is never hard-killed.
|
|
501
510
|
*/
|
|
502
511
|
export function resolveChildTimeouts(options: ResolveChildTimeoutsOptions): ResolveChildTimeoutsResult {
|
|
503
512
|
const agentMs = options.agentTimeoutMins ? options.agentTimeoutMins * 60_000 : undefined;
|
|
504
|
-
const
|
|
513
|
+
const idleMins = options.idleTimeoutMins ?? 0;
|
|
514
|
+
const defaultValue = idleMins > 0 ? Math.min(idleMins, MAX_TIMEOUT_MINS) * 60_000 : DEFAULT_TIMEOUT_MS;
|
|
515
|
+
const result = normalizeTimeout({ requested: options.requested ?? agentMs ?? options.globalTimeout, defaultValue });
|
|
505
516
|
if (result.error) return { error: result.error };
|
|
506
517
|
const capMins = options.hardTimeoutMins ?? 0;
|
|
507
518
|
if (capMins <= 0) return { timeoutMs: result.timeoutMs, hardTimeoutMs: undefined };
|