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.
Files changed (33) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/extensions/lib/registry.test.ts +67 -0
  3. package/extensions/lib/registry.ts +17 -7
  4. package/extensions/modules/advisor/index.ts +20 -2
  5. package/extensions/modules/advisor/lib/watcher.ts +3 -1
  6. package/extensions/modules/advisor/test/module.test.ts +64 -1
  7. package/extensions/modules/composer/test/module.test.ts +2 -2
  8. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  9. package/extensions/modules/munin/configPanel.ts +5 -2
  10. package/extensions/modules/munin/test/configPanel.test.ts +27 -2
  11. package/extensions/modules/router/configPanel.ts +24 -10
  12. package/extensions/modules/router/lib/client.ts +6 -4
  13. package/extensions/modules/router/test/unit.test.ts +83 -2
  14. package/extensions/modules/rules/index.ts +120 -0
  15. package/extensions/modules/rules/lib/rules.ts +348 -0
  16. package/extensions/modules/rules/test/lib.test.ts +263 -0
  17. package/extensions/modules/rules/test/module.test.ts +222 -0
  18. package/extensions/modules/subagent/index.ts +19 -6
  19. package/extensions/modules/subagent/lib/routing.ts +11 -6
  20. package/extensions/modules/subagent/lib/security.ts +12 -1
  21. package/extensions/modules/subagent/test/routing.test.ts +174 -0
  22. package/extensions/modules/todo/index.ts +478 -0
  23. package/extensions/modules/todo/test/todo.test.ts +252 -0
  24. package/extensions/modules/usage/index.ts +11 -0
  25. package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
  26. package/extensions/modules/web/configPanel.ts +38 -13
  27. package/extensions/modules/web/lib/settings.ts +11 -2
  28. package/extensions/modules/web/test/configPanel.test.ts +67 -1
  29. package/extensions/modules/zai/configPanel.ts +5 -2
  30. package/extensions/modules/zai/lib/signing.ts +4 -1
  31. package/extensions/modules/zai/test/configPanel.test.ts +23 -0
  32. package/extensions/modules/zai/test/signing.test.ts +19 -0
  33. package/package.json +2 -2
@@ -0,0 +1,120 @@
1
+ // rules module — sticky RULES.md + on-demand rulebook.
2
+ //
3
+ // Ported CONTRACT (not code) from OMP's sticky RULES.md + rulebook split
4
+ // (omp/docs/context-files.md "Sticky rules vs normal context",
5
+ // omp/docs/rulebook-matching-pipeline.md §5 bucket split,
6
+ // omp/packages/coding-agent/src/capability/rule.ts). The file format is
7
+ // documented at the top of ./lib/rules.ts.
8
+ //
9
+ // Surfaces:
10
+ // - ONE `before_agent_start` handler: append-only composition exactly like the
11
+ // fff module (returns `{ systemPrompt: \`${event.systemPrompt}\n\n${block}\` }`
12
+ // or undefined when no RULES.md exists anywhere — zero footprint by default).
13
+ // - ONE tool `rule_get` (name) serving a rulebook rule's body on demand.
14
+ // - `/rules` status + `/rules reload` (drops the mtime cache).
15
+ //
16
+ // Registered in a guarded()`-deduped bundle: no attempt is made to own the
17
+ // rules — dropping the module (or never wiring it) restores vanilla pi.
18
+
19
+ import type {
20
+ BeforeAgentStartEventResult,
21
+ ExtensionAPI,
22
+ ExtensionContext,
23
+ } from "@earendil-works/pi-coding-agent";
24
+ import { Type } from "typebox";
25
+ import { readDisabledTools } from "../../lib/tools";
26
+ import { clearRuleCache, loadRules, type RuleModel } from "./lib/rules";
27
+
28
+ /** Cap on a single rule body returned by rule_get (chars). */
29
+ const RULE_GET_MAX_CHARS = 20000;
30
+
31
+ function statusLines(model: RuleModel, cwd: string): string {
32
+ if (model.files.length === 0) {
33
+ return [
34
+ "Rule sources: none",
35
+ " No .pi/RULES.md found from cwd to the filesystem root, and no user-level ~/.pi/agent/RULES.md.",
36
+ " Create one to add sticky rules (append-only to the system prompt) or rulebook rules.",
37
+ ].join("\n");
38
+ }
39
+ const names = (rules: { name: string }[]) => rules.map((rule) => rule.name).join(", ") || "(none)";
40
+ return [
41
+ `Rule sources (${model.files.length}):`,
42
+ ...model.files.map((file, index) => ` ${index + 1}. ${file}`),
43
+ `Sticky rules (${model.sticky.length}): ${names(model.sticky)}`,
44
+ `Rulebook rules (${model.rulebook.length}): ${names(model.rulebook)}`,
45
+ " Bodies are served on demand by rule_get — never listed here.",
46
+ `Prompt block: ${model.blockChars} chars${model.block ? "" : " (no block emitted)"}`,
47
+ ` Sources are resolved nearest-first from ${cwd}; project files override user rules on duplicate names.`,
48
+ ].join("\n");
49
+ }
50
+
51
+ export default function rulesExtension(pi: ExtensionAPI): void {
52
+ const disabledTools = readDisabledTools();
53
+
54
+ pi.on("before_agent_start", async (event, ctx): Promise<BeforeAgentStartEventResult | undefined> => {
55
+ let model: RuleModel;
56
+ try {
57
+ model = loadRules(ctx?.cwd ?? process.cwd());
58
+ } catch {
59
+ return undefined; // never break a turn over rule discovery
60
+ }
61
+ if (!model.block) return undefined;
62
+ return { systemPrompt: `${event.systemPrompt}\n\n${model.block}` };
63
+ });
64
+
65
+ pi.registerTool({
66
+ name: "rule_get",
67
+ label: "rule_get",
68
+ description:
69
+ "Read the full body of a project rule listed in the <user-rules> rulebook (sticky rules are already in the system prompt).",
70
+ promptSnippet: "Read a rulebook rule's body by name",
71
+ parameters: Type.Object({
72
+ name: Type.String({ description: "Rule name (the `## <name>` heading) from the rulebook listing." }),
73
+ }),
74
+ defaultActive: !disabledTools.has("rule_get"),
75
+ async execute(_id: string, params: { name: string }, _signal, _onUpdate, ctx) {
76
+ const model = loadRules(ctx?.cwd ?? process.cwd());
77
+ const wanted = (params.name ?? "").trim();
78
+ const rule = model.rules.find((item) => item.name === wanted);
79
+ if (!rule) {
80
+ const available = model.rules.map((item) => item.name);
81
+ return {
82
+ content: [{
83
+ type: "text" as const,
84
+ text: available.length === 0
85
+ ? `Rule "${wanted}" not found: no RULES.md exists in this workspace (searched .pi/RULES.md from cwd to the filesystem root, plus ~/.pi/agent/RULES.md).`
86
+ : `Rule "${wanted}" not found. Available rules: ${available.join(", ")}`,
87
+ }],
88
+ details: { found: false, available },
89
+ };
90
+ }
91
+ const body = rule.sticky
92
+ ? `[sticky rule "${rule.name}" — already appended to the system prompt]\n\n${rule.body}`
93
+ : rule.body;
94
+ const clipped = body.length > RULE_GET_MAX_CHARS
95
+ ? `${body.slice(0, RULE_GET_MAX_CHARS)}\n\n[rule body truncated at ${RULE_GET_MAX_CHARS} chars]`
96
+ : body;
97
+ return {
98
+ content: [{ type: "text" as const, text: `${clipped}\n\n(rule "${rule.name}" from ${rule.source})` }],
99
+ details: { found: true, name: rule.name, source: rule.source, sticky: rule.sticky, truncated: clipped !== body },
100
+ };
101
+ },
102
+ });
103
+
104
+ pi.registerCommand("rules", {
105
+ description: "Rule sources status, or /rules reload to drop the rule-file cache.",
106
+ handler: async (args: string, ctx: ExtensionContext) => {
107
+ const arg = (args ?? "").trim().toLowerCase();
108
+ if (arg === "reload") {
109
+ clearRuleCache();
110
+ ctx.ui.notify(`[rules] cache dropped — re-reading ${loadRules(ctx.cwd).files.length} source(s)`, "info");
111
+ return;
112
+ }
113
+ if (arg !== "") {
114
+ ctx.ui.notify(`[rules] unknown argument "${arg}" — use /rules or /rules reload`, "error");
115
+ return;
116
+ }
117
+ ctx.ui.notify(statusLines(loadRules(ctx.cwd), ctx.cwd), "info");
118
+ },
119
+ });
120
+ }
@@ -0,0 +1,348 @@
1
+ // rules — RULES.md discovery, parsing, @import expansion, prompt composition.
2
+ //
3
+ // FORMAT (one rule per `## <name>` section; ported CONTRACT from OMP's
4
+ // sticky RULES.md + rulebook split):
5
+ //
6
+ // ## never-push
7
+ // Never commit or push unless the user explicitly asks.
8
+ //
9
+ // ## api-style
10
+ // description: How to write HTTP handlers in this repo.
11
+ // Always use the shared `json()` helper and return a typed error shape.
12
+ //
13
+ // - A section whose body STARTS with a `description:` line is a RULEBOOK rule:
14
+ // the prompt lists only `name — description`; the body is served on demand by
15
+ // the `rule_get` tool.
16
+ // - A section with no `description:` line is a STICKY rule: its body is always
17
+ // appended to the system prompt, under STICKY_CHAR_CAP (lowest-precedence
18
+ // rules dropped first, with a loud marker).
19
+ // - Content BEFORE the first `##` heading (i.e. a heading-less RULES.md) is one
20
+ // sticky rule named `RULES` — OMP's plain-prose RULES.md still works.
21
+ // - `# title` and `### x` are NOT rule headings; `##` inside a ``` fence is text.
22
+ // - `@path` tokens (at line start or after whitespace, outside fences) expand
23
+ // inline: relative to the RULES.md's own directory, `~/` from home, absolute
24
+ // as-is. Cycles and repeats stay literal; missing targets get a marker.
25
+ //
26
+ // SOURCES / PRECEDENCE: nearest-first walk from cwd to the filesystem root for
27
+ // `<dir>/.pi/RULES.md`, then the user-level `<agentDir>/RULES.md`. Duplicate
28
+ // rule names resolve first-wins, so a project rule overrides a user rule and a
29
+ // nearer project file overrides a farther one.
30
+ //
31
+ // DELIBERATE DEVIATIONS from OMP (documented, not accidental):
32
+ // 1. Only `##` headings split rules — no frontmatter (`description:` line
33
+ // instead) and no `alwaysApply`/TTSR condition fields. Sticky is the
34
+ // absence of a description, which keeps one parseable format.
35
+ // 2. A heading-less file is ONE sticky rule named `RULES` (OMP's plain-prose
36
+ // RULES.md); a `# Title` preamble before the first `##` is dropped.
37
+ // 3. `@token` inside a FENCED block stays literal (OMP parity), but a span
38
+ // opening with a backtick is left literal only because a backtick is not
39
+ // whitespace — no code-span parser is worth its weight here.
40
+
41
+ import { existsSync, readFileSync, statSync } from "node:fs";
42
+ import os from "node:os";
43
+ import path from "node:path";
44
+
45
+ export const STICKY_CHAR_CAP = 4000;
46
+ export const MAX_IMPORT_DEPTH = 5;
47
+ export const RULES_FILE = "RULES.md";
48
+ const PROJECT_DIR = ".pi";
49
+
50
+ const HEADING = /^##\s+(.+?)\s*$/;
51
+ const DESCRIPTION = /^description:\s*(.*)$/i;
52
+ const FENCE = /^\s*(?:```|~~~)/;
53
+ // A token only counts as an import when `@` starts a line or follows whitespace
54
+ // (so `user@example.com` and `git@github.com:o/r.git` are never imports).
55
+ const IMPORT = /(^|[ \t])@([^\s]+)/g;
56
+ const TRAILING_PUNCTUATION = /[.,;:!?)\]}"']+$/;
57
+
58
+ export interface LoadedRule {
59
+ /** The rule's slug/heading (or `RULES` for pre-heading prose). */
60
+ name: string;
61
+ /** Present = rulebook rule (body on demand); absent = sticky rule. */
62
+ description?: string;
63
+ /** Body, with `@` imports already expanded. */
64
+ body: string;
65
+ /** Absolute path of the RULES.md that defined it. */
66
+ source: string;
67
+ sticky: boolean;
68
+ }
69
+
70
+ export interface RuleModel {
71
+ /** Discovered RULES.md files, highest precedence first. */
72
+ files: string[];
73
+ /** Deduped rules in precedence order. */
74
+ rules: LoadedRule[];
75
+ sticky: LoadedRule[];
76
+ rulebook: LoadedRule[];
77
+ /** The composed prompt block, or undefined when nothing was found. */
78
+ block?: string;
79
+ /** Length of `block` (the char count /rules reports). */
80
+ blockChars: number;
81
+ }
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // Parsing
85
+ // ---------------------------------------------------------------------------
86
+
87
+ interface Section {
88
+ name: string | null;
89
+ lines: string[];
90
+ }
91
+
92
+ function splitSections(text: string): Section[] {
93
+ const sections: Section[] = [{ name: null, lines: [] }];
94
+ let fenced = false;
95
+ for (const line of text.replace(/^\uFEFF/, "").split(/\r?\n/)) {
96
+ if (FENCE.test(line)) fenced = !fenced;
97
+ const heading = fenced ? null : HEADING.exec(line);
98
+ if (heading) sections.push({ name: heading[1].trim(), lines: [] });
99
+ else sections.at(-1)!.lines.push(line);
100
+ }
101
+ return sections;
102
+ }
103
+
104
+ function makeRule(name: string, rawLines: string[], source: string): LoadedRule | null {
105
+ const lines = rawLines.slice();
106
+ while (lines.length > 0 && lines[0].trim() === "") lines.shift();
107
+ while (lines.length > 0 && lines.at(-1)!.trim() === "") lines.pop();
108
+
109
+ let description: string | undefined;
110
+ const match = lines.length > 0 ? DESCRIPTION.exec(lines[0].trim()) : null;
111
+ if (match && match[1].trim() !== "") {
112
+ description = match[1].trim();
113
+ lines.shift();
114
+ }
115
+
116
+ const body = lines.join("\n").trim();
117
+ return { name, description, body, source, sticky: description === undefined };
118
+ }
119
+
120
+ /** Parse one RULES.md into rules. A heading-less file (plain prose) is ONE sticky
121
+ * rule named `RULES`; in a sectioned file the pre-heading preamble is document
122
+ * title, not a rule, so it is dropped. */
123
+ export function parseRulesFile(text: string, source: string): LoadedRule[] {
124
+ const out: LoadedRule[] = [];
125
+ const sections = splitSections(text);
126
+ const sectioned = sections.some((section) => section.name !== null);
127
+ for (const section of sections) {
128
+ if (section.name === null && sectioned) continue;
129
+ const rule = makeRule(section.name ?? "RULES", section.lines, source);
130
+ if (rule && (rule.body !== "" || rule.description !== undefined)) out.push(rule);
131
+ }
132
+ return out;
133
+ }
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // Discovery
137
+ // ---------------------------------------------------------------------------
138
+
139
+ /** The user-level agent dir (pi relocates it with PI_CODING_AGENT_DIR). */
140
+ export function defaultUserRulesDir(): string {
141
+ return process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
142
+ }
143
+
144
+ /** `<dir>/.pi/RULES.md` from cwd up to the filesystem root, then the user file. */
145
+ export function discoverRuleFiles(cwd: string, userDir = defaultUserRulesDir()): string[] {
146
+ const files: string[] = [];
147
+ let dir = path.resolve(cwd);
148
+ for (;;) {
149
+ const candidate = path.join(dir, PROJECT_DIR, RULES_FILE);
150
+ if (existsSync(candidate)) files.push(candidate);
151
+ const parent = path.dirname(dir);
152
+ if (parent === dir) break;
153
+ dir = parent;
154
+ }
155
+ const user = path.join(userDir, RULES_FILE);
156
+ if (existsSync(user)) files.push(user);
157
+ return files;
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // @import expansion
162
+ // ---------------------------------------------------------------------------
163
+
164
+ function resolveImport(token: string, baseDir: string): string {
165
+ const raw = token.startsWith("~/") ? path.join(os.homedir(), token.slice(2)) : token;
166
+ return path.resolve(baseDir, raw);
167
+ }
168
+
169
+ interface ImportState {
170
+ /** Resolved paths already pulled into this expansion tree (cycle guard). */
171
+ seen: Set<string>;
172
+ /** Every file actually read — feeds the cache signature. */
173
+ read: Set<string>;
174
+ }
175
+
176
+ function expandImports(text: string, baseDir: string, state: ImportState, depth: number): string {
177
+ let fenced = false;
178
+ return text
179
+ .split("\n")
180
+ .map((line) => {
181
+ if (FENCE.test(line)) {
182
+ fenced = !fenced;
183
+ return line;
184
+ }
185
+ if (fenced) return line;
186
+ return line.replace(IMPORT, (whole: string, lead: string, token: string) => {
187
+ const cleaned = token.replace(TRAILING_PUNCTUATION, "");
188
+ if (cleaned === "") return whole;
189
+
190
+ const resolved = resolveImport(cleaned, baseDir);
191
+ // ponytail: repeats/cycles stay literal (OMP parity) — only a MISSING
192
+ // target gets a marker, so a real typo is loud and a repeat is silent.
193
+ if (state.seen.has(resolved)) return whole;
194
+
195
+ let content: string;
196
+ try {
197
+ content = readFileSync(resolved, "utf8");
198
+ } catch {
199
+ return `${lead}[missing import: @${cleaned}]`;
200
+ }
201
+ if (depth >= MAX_IMPORT_DEPTH) {
202
+ return `${lead}[import depth limit reached: @${cleaned}]`;
203
+ }
204
+ state.seen.add(resolved);
205
+ state.read.add(resolved);
206
+ const nested = expandImports(content.trim(), path.dirname(resolved), state, depth + 1);
207
+ return `${lead}${nested}`;
208
+ });
209
+ })
210
+ .join("\n");
211
+ }
212
+
213
+ function expandFile(raw: string, source: string, state: ImportState): string {
214
+ state.seen.add(source);
215
+ state.read.add(source);
216
+ return expandImports(raw.trim(), path.dirname(source), state, 0);
217
+ }
218
+
219
+ // ---------------------------------------------------------------------------
220
+ // Model build
221
+ // ---------------------------------------------------------------------------
222
+
223
+ /** Parse one RULES.md from disk with imports expanded (used by the loader). */
224
+ export function readRulesFile(source: string, state: ImportState = { seen: new Set(), read: new Set() }): LoadedRule[] {
225
+ let raw: string;
226
+ try {
227
+ raw = readFileSync(source, "utf8");
228
+ } catch {
229
+ return [];
230
+ }
231
+ return parseRulesFile(expandFile(raw, source, state), source);
232
+ }
233
+
234
+ function buildModel(files: string[], cwd: string): { model: RuleModel; imported: string[] } {
235
+ const state: ImportState = { seen: new Set(), read: new Set() };
236
+ const rules: LoadedRule[] = [];
237
+ const claimed = new Set<string>();
238
+
239
+ for (const file of files) {
240
+ for (const rule of readRulesFile(file, state)) {
241
+ // Name-based dedup, first-wins (precedence order = discovery order).
242
+ if (claimed.has(rule.name)) continue;
243
+ claimed.add(rule.name);
244
+ rules.push(rule);
245
+ }
246
+ }
247
+
248
+ const model: RuleModel = {
249
+ files,
250
+ rules,
251
+ sticky: rules.filter((rule) => rule.sticky),
252
+ rulebook: rules.filter((rule) => !rule.sticky),
253
+ blockChars: 0,
254
+ };
255
+ model.block = composeRulesBlock(model, cwd);
256
+ model.blockChars = model.block?.length ?? 0;
257
+ return { model, imported: [...state.read] };
258
+ }
259
+
260
+ // ---------------------------------------------------------------------------
261
+ // mtime cache (ponytail's config precedent: one stat per call, re-parse only on
262
+ // change — so edits apply without /reload)
263
+ // ---------------------------------------------------------------------------
264
+
265
+ let cache: { key: string; tracked: Set<string>; sig: string; model: RuleModel } | null = null;
266
+
267
+ function signature(files: Iterable<string>): string {
268
+ const parts: string[] = [];
269
+ for (const file of files) {
270
+ try {
271
+ const stat = statSync(file);
272
+ parts.push(`${file}:${stat.mtimeMs}:${stat.size}`);
273
+ } catch {
274
+ parts.push(`${file}:missing`);
275
+ }
276
+ }
277
+ return parts.join("|");
278
+ }
279
+
280
+ /** Drop the mtime cache (`/rules reload`, tests). */
281
+ export function clearRuleCache(): void {
282
+ cache = null;
283
+ }
284
+
285
+ export function loadRules(cwd = process.cwd(), userDir = defaultUserRulesDir()): RuleModel {
286
+ const key = `${path.resolve(cwd)}\u0000${userDir}`;
287
+ const files = discoverRuleFiles(cwd, userDir);
288
+ // Track RULES.md files AND previously imported files, so editing an imported
289
+ // doc invalidates the cache too.
290
+ const tracked = new Set([...files, ...(cache?.tracked ?? [])]);
291
+ const sig = signature(tracked);
292
+ if (cache && cache.key === key && cache.sig === sig) return cache.model;
293
+
294
+ const { model, imported } = buildModel(files, cwd);
295
+ const nextTracked = new Set([...tracked, ...imported]);
296
+ cache = { key, tracked: nextTracked, sig: signature(nextTracked), model };
297
+ return model;
298
+ }
299
+
300
+ // ---------------------------------------------------------------------------
301
+ // Prompt composition
302
+ // ---------------------------------------------------------------------------
303
+
304
+ export function displayPath(file: string, cwd: string): string {
305
+ const rel = path.relative(cwd, file);
306
+ return rel === "" || rel.startsWith("..") || path.isAbsolute(rel) ? file : rel;
307
+ }
308
+
309
+ function renderSticky(rules: LoadedRule[], cwd: string, cap = STICKY_CHAR_CAP): string {
310
+ const parts: string[] = [];
311
+ let used = 0;
312
+ let dropped = 0;
313
+
314
+ for (const rule of rules) {
315
+ const part = `### ${rule.name} (${displayPath(rule.source, cwd)})\n${rule.body}\n`;
316
+ if (used + part.length > cap) {
317
+ if (used === 0) {
318
+ // First rule alone blows the cap — truncate it rather than dump it all.
319
+ parts.push(part.slice(0, Math.max(0, cap - 80)) + "\n[rule body truncated at the sticky cap]\n");
320
+ used = cap;
321
+ }
322
+ dropped++;
323
+ continue;
324
+ }
325
+ parts.push(part);
326
+ used += part.length;
327
+ }
328
+
329
+ const marker = dropped > 0
330
+ ? `⚠ STICKY RULES TRUNCATED — ${dropped} rule(s) omitted: the always-appended block exceeded ${cap} chars. Trim RULES.md, or move detail into rulebook rules (add a \`description:\` line so the body is served on demand by rule_get).`
331
+ : "";
332
+ return [parts.join("\n"), marker].filter((text) => text !== "").join("\n").trim();
333
+ }
334
+
335
+ /** The `<user-rules>` block, or undefined when no RULES.md exists anywhere. */
336
+ export function composeRulesBlock(model: RuleModel, cwd: string): string | undefined {
337
+ if (model.rules.length === 0) return undefined;
338
+
339
+ const sections: string[] = [];
340
+ if (model.sticky.length > 0) {
341
+ sections.push(`Sticky rules — ALWAYS in effect for this session:\n\n${renderSticky(model.sticky, cwd)}`);
342
+ }
343
+ if (model.rulebook.length > 0) {
344
+ const lines = model.rulebook.map((rule) => `- ${rule.name}: ${rule.description}`).join("\n");
345
+ sections.push(`Rulebook — read the full body with rule_get("<name>") before applying one:\n${lines}`);
346
+ }
347
+ return `<user-rules>\n${sections.join("\n\n")}\n</user-rules>`;
348
+ }