ceulen 0.1.0 → 0.5.1

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 (56) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +103 -14
  3. package/extensions/index.ts +113 -0
  4. package/extensions/lib/env.ts +75 -0
  5. package/extensions/lib/panel.ts +1720 -0
  6. package/extensions/lib/registry.ts +182 -0
  7. package/extensions/modules/composer/index.ts +128 -0
  8. package/extensions/modules/composer/lib/settings.ts +55 -0
  9. package/extensions/modules/composer/lib/shapes.ts +436 -0
  10. package/extensions/modules/composer/test/editor.test.ts +138 -0
  11. package/extensions/modules/composer/test/module.test.ts +218 -0
  12. package/extensions/modules/composer/test/screen.test.ts +195 -0
  13. package/extensions/modules/composer/test/shapes.test.ts +175 -0
  14. package/extensions/modules/config/index.ts +298 -0
  15. package/extensions/modules/config/piSettings.ts +467 -0
  16. package/extensions/modules/config/plugins.ts +290 -0
  17. package/extensions/modules/config/test/kernel.test.ts +523 -0
  18. package/extensions/modules/config/test/kernelV4.test.ts +196 -0
  19. package/extensions/modules/config/test/menu.test.ts +226 -0
  20. package/extensions/modules/config/test/panel.test.ts +395 -0
  21. package/extensions/modules/config/test/piSettings.test.ts +185 -0
  22. package/extensions/modules/config/test/plugins.test.ts +181 -0
  23. package/extensions/modules/config/test/preview-block.test.ts +88 -0
  24. package/extensions/modules/ponytail/UPSTREAM +26 -0
  25. package/extensions/modules/ponytail/index.ts +336 -0
  26. package/extensions/modules/ponytail/lib/config.ts +149 -0
  27. package/extensions/modules/ponytail/lib/instructions.ts +98 -0
  28. package/extensions/modules/ponytail/lib/subagent.ts +31 -0
  29. package/extensions/modules/ponytail/test/extension.test.ts +422 -0
  30. package/extensions/modules/ponytail/test/helpers.test.ts +163 -0
  31. package/extensions/modules/ponytail/test/subagent.test.ts +33 -0
  32. package/extensions/modules/router/commands/commands.ts +99 -0
  33. package/extensions/modules/router/configPanel.ts +89 -0
  34. package/extensions/modules/router/index.ts +75 -0
  35. package/extensions/modules/router/lib/client.ts +390 -0
  36. package/extensions/modules/router/lib/config.ts +142 -0
  37. package/extensions/modules/router/lib/migrate.ts +92 -0
  38. package/extensions/modules/router/lib/provider.ts +138 -0
  39. package/extensions/modules/router/lib/refresh.ts +19 -0
  40. package/extensions/modules/router/test/guard.test.ts +77 -0
  41. package/extensions/modules/router/test/unit.test.ts +1126 -0
  42. package/extensions/modules/usage/index.ts +1975 -0
  43. package/extensions/modules/usage/test/context.test.ts +387 -0
  44. package/extensions/modules/usage/test/env-gating.test.ts +113 -0
  45. package/extensions/modules/usage/test/opencode-go-usage.test.ts +139 -0
  46. package/extensions/modules/usage/test/parsers.test.ts +244 -0
  47. package/extensions/modules/usage/test/stale-ctx-regression.test.ts +294 -0
  48. package/extensions/modules/usage/test/zai-anthropic-adapter.test.ts +40 -0
  49. package/package.json +15 -3
  50. package/skills/ponytail/SKILL.md +124 -0
  51. package/skills/ponytail-audit/SKILL.md +41 -0
  52. package/skills/ponytail-debt/SKILL.md +44 -0
  53. package/skills/ponytail-gain/SKILL.md +51 -0
  54. package/skills/ponytail-help/SKILL.md +73 -0
  55. package/skills/ponytail-review/SKILL.md +57 -0
  56. package/extensions/index.js +0 -42
@@ -0,0 +1,182 @@
1
+ /**
2
+ * ceulen module registry + shared settings access.
3
+ *
4
+ * Lives outside extensions/index.ts so the config module can iterate the
5
+ * registry without a circular import (index imports the config module
6
+ * statically; the config module imports this list).
7
+ */
8
+
9
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import type { PanelGroup } from "./panel.js";
14
+ import routerModule from "../modules/router/index.ts";
15
+ import { routerConfig } from "../modules/router/configPanel.ts";
16
+ import usageModule from "../modules/usage/index.ts";
17
+ import composerModule, { composerConfig } from "../modules/composer/index.ts";
18
+ import ponytailModule, { ponytailConfig } from "../modules/ponytail/index.ts";
19
+ import configModule from "../modules/config/index.ts";
20
+
21
+ /** A module's contribution to the central `/config` panel. */
22
+ export interface ModuleConfig {
23
+ /** Panel groups over a fresh working copy; called once per /config open.
24
+ * Row keys MUST be prefixed `<module>.` so editedKeys route to the owner. */
25
+ groups: () => PanelGroup[];
26
+ /** Persist + apply. Only called when an owned key was edited. */
27
+ save: (edited: Set<string>, ctx: ExtensionContext) => Promise<void>;
28
+ }
29
+
30
+ /** Per-load dependencies handed to a module factory (second arg). Only the
31
+ * config module reads it: the map holds one config-contribution factory per
32
+ * enabled module, each closing over THAT module's guarded pi — so a runtime
33
+ * re-registration (router's provider) stays the owner's claim, never config's. */
34
+ export interface ModuleLoadDeps {
35
+ configContribs: Map<string, () => ModuleConfig>;
36
+ }
37
+
38
+ export interface ModuleEntry {
39
+ name: string;
40
+ /** Core modules are always loaded — the kill-switch can't disable them and
41
+ * /config shows no Enable row (composer owns the editor surface: a
42
+ * half-configured composer is worse than none). */
43
+ core?: boolean;
44
+ /** OMP-taxonomy tab the module's /config sections live in — the single
45
+ * source for tab placement, synthesized Enable-only sections, and /ceulen
46
+ * status grouping (the {section, icon} pretty-names stay in the config
47
+ * module's local map). */
48
+ category: string;
49
+ /** One-line module purpose — rendered as the kill-switch row's description
50
+ * and reused by /ceulen status output. */
51
+ describe?: string;
52
+ load: (pi: ExtensionAPI, deps?: ModuleLoadDeps) => void;
53
+ /** Central-config contribution factory, called with the module's OWN guarded
54
+ * pi once per /config open. Optional — purely additive. */
55
+ config?: (pi: ExtensionAPI) => ModuleConfig;
56
+ }
57
+
58
+ // ponytail: module registry grows by append — one object per module, loader
59
+ // stays ~10 lines forever, no plugin framework
60
+ export const MODULES: ModuleEntry[] = [
61
+ // ── Providers ──────────────────────────────────────────────────────────
62
+ // Router first: usage reads the `router` provider for usage display.
63
+ { name: "router", category: "Providers", describe: "Route requests to a yardmaster/OmniRoute endpoint and expose its models.", load: routerModule, config: routerConfig },
64
+ // ── Appearance ─────────────────────────────────────────────────────────
65
+ { name: "usage", category: "Appearance", describe: "Subscription-usage footer (5h/weekly/monthly windows + credits).", load: usageModule },
66
+ { name: "composer", core: true, category: "Appearance", describe: "Composer shape for the input editor — pick one in /config with a live preview. Core: always on.", load: composerModule, config: composerConfig },
67
+ // ── Tasks ──────────────────────────────────────────────────────────────
68
+ { name: "ponytail", category: "Tasks", describe: "Lazy-senior-dev mode: prompts, status, skills, subagent instructions.", load: ponytailModule, config: ponytailConfig },
69
+ // ── Plugins ────────────────────────────────────────────────────────────
70
+ // Config last: it owns /config and reads the contrib map.
71
+ { name: "config", category: "Plugins", describe: "This panel — /config central settings for every module.", load: configModule },
72
+ ];
73
+
74
+ // ── Kill-switch settings ─────────────────────────────────────────────────────
75
+
76
+ /** True when the module is core (always loaded, never kill-switchable). */
77
+ export function isCore(name: string): boolean {
78
+ return MODULES.some((m) => m.name === name && m.core === true);
79
+ }
80
+
81
+ /** Candidate settings files in read precedence: trusted project scope first
82
+ * (when trusted), then agent dirs. */
83
+ function settingsCandidates(cwd = process.cwd()): string[] {
84
+ return [
85
+ ...(isProjectTrusted(cwd) ? [path.join(cwd, ".pi", "settings.json")] : []),
86
+ ...agentDirs().map((d) => path.join(d, "settings.json")),
87
+ ];
88
+ }
89
+
90
+ export function agentDirs(): string[] {
91
+ return process.env.PI_CODING_AGENT_DIR
92
+ ? [process.env.PI_CODING_AGENT_DIR]
93
+ : [path.join(os.homedir(), ".pi", "agent"), path.join(os.homedir(), ".pi", "agents")];
94
+ }
95
+
96
+ /** The file `readDisabled`/`writeDisabled` resolve: the first candidate that
97
+ * exists and carries a `ceulen` section (a project file configuring only other
98
+ * keys must not shadow the kill-switch). Falls back to the agent-dir file
99
+ * (`~/.pi/agent/settings.json`), the documented home for `ceulen.disabled`,
100
+ * when no file claims it. */
101
+ export function disabledSource(cwd = process.cwd()): { path: string; isProject: boolean } {
102
+ const projectPath = path.join(cwd, ".pi", "settings.json");
103
+ for (const file of settingsCandidates(cwd)) {
104
+ if (!existsSync(file)) continue;
105
+ try {
106
+ const json = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
107
+ if (json && typeof json.ceulen === "object" && json.ceulen !== null) {
108
+ return { path: file, isProject: file === projectPath };
109
+ }
110
+ } catch {
111
+ // malformed → not claiming (readDisabled falls back the same way)
112
+ }
113
+ }
114
+ return { path: path.join(agentDirs()[0]!, "settings.json"), isProject: false };
115
+ }
116
+
117
+ /** Read the `ceulen.disabled` module list. The project scope is only eligible
118
+ * when trusted (an untrusted checkout must not re-enable or disable modules).
119
+ * Resolves through `disabledSource` — the same file `writeDisabled` targets. */
120
+ export function readDisabled(cwd = process.cwd()): string[] {
121
+ const { path: file } = disabledSource(cwd);
122
+ if (!existsSync(file)) return [];
123
+ try {
124
+ const raw = (JSON.parse(readFileSync(file, "utf8"))?.ceulen ?? {}) as { disabled?: unknown };
125
+ if (!Array.isArray(raw.disabled)) return [];
126
+ // ponytail: deprecated "sub" alias — the module was renamed to "usage"; drop when no settings ship it
127
+ // Core modules are never disableable — a stale/foreign entry is ignored.
128
+ return raw.disabled
129
+ .map((n) => (n === "sub" ? "usage" : n))
130
+ .filter((n): n is string => typeof n === "string" && !isCore(n));
131
+ } catch {
132
+ return []; // malformed → defaults (all modules on)
133
+ }
134
+ }
135
+
136
+ /** Write `ceulen.disabled` into the SAME file readDisabled resolves, so a
137
+ * toggle can never be shadowed by a project-level section. Atomic (tmp +
138
+ * rename); a corrupt file refuses to clobber (same data-loss guard as
139
+ * writeRouterSection). Returns the written path for the caller's disclosure. */
140
+ export function writeDisabled(list: string[], cwd = process.cwd()): string {
141
+ const { path: file } = disabledSource(cwd);
142
+ let settings: Record<string, unknown> = {};
143
+ if (existsSync(file)) {
144
+ try {
145
+ settings = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
146
+ } catch {
147
+ throw new Error(`${file} is not valid JSON — fix or remove it before saving.`);
148
+ }
149
+ }
150
+ const ceulen = (settings.ceulen ?? {}) as Record<string, unknown>;
151
+ ceulen.disabled = list.filter((n) => !isCore(n));
152
+ settings.ceulen = ceulen;
153
+ mkdirSync(path.dirname(file), { recursive: true });
154
+ const tmp = file + ".tmp";
155
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
156
+ renameSync(tmp, file);
157
+ return file;
158
+ }
159
+
160
+ /** Project trust: read <agentDir>/trust.json ({ "<path>": true|false }),
161
+ * walking up the tree like pi's ProjectTrustStore. Unreadable/absent →
162
+ * false (fail closed). */
163
+ export function isProjectTrusted(cwd: string, dirs: string[] = agentDirs()): boolean {
164
+ let current = path.resolve(cwd);
165
+ for (const dir of dirs) {
166
+ const file = path.join(dir, "trust.json");
167
+ if (!existsSync(file)) continue;
168
+ try {
169
+ const data = JSON.parse(readFileSync(file, "utf8"));
170
+ for (;;) {
171
+ const v = data[current];
172
+ if (typeof v === "boolean") return v;
173
+ const parent = path.dirname(current);
174
+ if (parent === current) break;
175
+ current = parent;
176
+ }
177
+ } catch {
178
+ return false;
179
+ }
180
+ }
181
+ return false;
182
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * composer module — Composer Shape for the input editor. CORE: always on,
3
+ * not kill-switchable (it owns the editor surface; a half-configured composer
4
+ * is worse than none).
5
+ *
6
+ * Pick a shape in /config (Appearance → Composer Shape) with a live preview
7
+ * window in the panel; Enter applies it to the running editor immediately and
8
+ * persists `composer.shape` to the global settings.json. Browsing only moves
9
+ * the panel's preview block — it never mutates the live editor (OMP previews
10
+ * in-window and commits on Enter).
11
+ *
12
+ * Session lifecycle: `session_start` is the only hook needed — it fires for
13
+ * startup/new/resume/fork/reload, and pi's beforeSessionInvalidate clears
14
+ * custom editors before the replacement session's session_start re-arms this
15
+ * handler (same reliance as the usage module's ctx grab).
16
+ */
17
+
18
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
19
+ import type { ModuleConfig } from "../../lib/registry.js";
20
+ import { row, type PanelGroup, type PanelMenuOption } from "../../lib/panel.js";
21
+ import { DEFAULT_SHAPE, IDENTITY_THEME, isShapeId, previewShape, ShapeEditor, shapeById, shapeTheme, SHAPES, type BandData, type ShapeTheme } from "./lib/shapes.ts";
22
+ import { readComposerShape, writeComposerSection } from "./lib/settings.ts";
23
+
24
+ /** Live band/status data from the freshest session ctx; blank rather than stale. */
25
+ let liveCtx: ExtensionContext | undefined;
26
+
27
+ function shapeData(ctx: ExtensionContext | undefined): BandData {
28
+ if (!ctx) return {};
29
+ try {
30
+ return {
31
+ model: ctx.model?.name,
32
+ cwd: ctx.cwd ? ctx.cwd.split(/[\\/]/).filter(Boolean).pop() : undefined,
33
+ pct: ctx.getContextUsage()?.percent ?? null,
34
+ };
35
+ } catch {
36
+ return {};
37
+ }
38
+ }
39
+
40
+ /** Theme styling read LIVE per call: pi's theme object is a Proxy over a
41
+ * globalThis slot, so every render/preview picks up the current theme. */
42
+ function currentTheme(ctx: ExtensionContext | undefined): ShapeTheme {
43
+ try {
44
+ const t = ctx?.ui?.theme;
45
+ return t ? shapeTheme(t) : IDENTITY_THEME;
46
+ } catch {
47
+ return IDENTITY_THEME;
48
+ }
49
+ }
50
+
51
+ /** Apply the shape to the RUNNING editor. Guards the TUI-only API and
52
+ * feature-detects `setEditorComponent` (peer-range floor predates it).
53
+ * Exported for tests. */
54
+ export function applyShape(shape: string, ctx: ExtensionContext): void {
55
+ if (ctx.mode !== "tui" || !ctx.hasUI || typeof ctx.ui.setEditorComponent !== "function") return;
56
+ const def = shapeById(isShapeId(shape) ? shape : DEFAULT_SHAPE);
57
+ ctx.ui.setEditorComponent(
58
+ (tui, theme, keybindings) =>
59
+ new ShapeEditor(def, { theme: () => currentTheme(liveCtx), data: () => shapeData(liveCtx) }, tui, theme, keybindings, {
60
+ embedWorkingStatus: true,
61
+ }),
62
+ );
63
+ }
64
+
65
+ /** The /config menu options — OMP's label + description per shape (the
66
+ * description is the whole point of the selection screen). */
67
+ export function shapeOptions(): PanelMenuOption[] {
68
+ return SHAPES.map((s) => ({ value: s.id, label: s.label, description: s.description }));
69
+ }
70
+
71
+ /** Build the composer panel groups over a working value (mutated by the row
72
+ * setter). Exported for tests. */
73
+ export function buildComposerGroups(working: { shape: string }): PanelGroup[] {
74
+ return [
75
+ {
76
+ key: "composer",
77
+ label: "Composer Shape",
78
+ tab: "Appearance",
79
+ icon: "🎨",
80
+ rows: [
81
+ row("composer.shape", "Shape", "string", working.shape, (v) => {
82
+ working.shape = isShapeId(v) ? String(v) : DEFAULT_SHAPE;
83
+ }, {
84
+ menu: shapeOptions,
85
+ defaultValue: DEFAULT_SHAPE,
86
+ description: "Visual layout of the input editor and status line. Browsing previews below; Enter applies to the running editor.",
87
+ // OMP's preview window: rendered through the SAME chrome builders
88
+ // the live editor uses (no-drift), at the body's inner width, with
89
+ // live session data. Never mutates the live editor (see module doc).
90
+ previewLines: (v, width) => {
91
+ try {
92
+ return previewShape(isShapeId(v) ? v : DEFAULT_SHAPE, Math.max(20, width), currentTheme(liveCtx), shapeData(liveCtx));
93
+ } catch {
94
+ return [];
95
+ }
96
+ },
97
+ }),
98
+ ],
99
+ },
100
+ ];
101
+ }
102
+
103
+ const OWNED_KEYS = ["composer.shape"];
104
+
105
+ /** Composer's ModuleConfig for the central /config panel. */
106
+ export function composerConfig(_pi?: ExtensionAPI): ModuleConfig {
107
+ const working = { shape: readComposerShape() };
108
+ return {
109
+ groups: () => buildComposerGroups(working),
110
+ save: async (edited, ctx) => {
111
+ if (!OWNED_KEYS.some((k) => edited.has(k))) return;
112
+ writeComposerSection({ shape: working.shape });
113
+ liveCtx = ctx;
114
+ applyShape(working.shape, ctx);
115
+ ctx.ui.notify(`Composer shape saved — ${shapeById(working.shape).label} applied.`, "info");
116
+ },
117
+ };
118
+ }
119
+
120
+ export default function composerModule(pi: ExtensionAPI): void {
121
+ pi.on("session_start", async (_event, ctx) => {
122
+ liveCtx = ctx;
123
+ applyShape(readComposerShape(), ctx);
124
+ });
125
+ pi.on("session_shutdown", async () => {
126
+ liveCtx = undefined;
127
+ });
128
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `composer.shape` persistence in the agent-dir settings.json — copied from
3
+ * router/lib/config.ts (read-modify-write merge, atomic tmp+rename, refuse to
4
+ * clobber a corrupt file).
5
+ */
6
+
7
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join, dirname } from "node:path";
10
+ import { DEFAULT_SHAPE, isShapeId } from "./shapes.ts";
11
+
12
+ function agentDir(): string {
13
+ return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
14
+ }
15
+
16
+ function settingsPath(): string {
17
+ return join(agentDir(), "settings.json");
18
+ }
19
+
20
+ export function readComposerShape(): string {
21
+ try {
22
+ if (!existsSync(settingsPath())) return DEFAULT_SHAPE;
23
+ const shape = (JSON.parse(readFileSync(settingsPath(), "utf8")) as { composer?: { shape?: unknown } }).composer?.shape;
24
+ return isShapeId(shape) ? shape : DEFAULT_SHAPE;
25
+ } catch {
26
+ return DEFAULT_SHAPE;
27
+ }
28
+ }
29
+
30
+ /** Merge `patch` into the global settings.json `composer` section. Atomic
31
+ * (tmp+rename); a corrupt file refuses to clobber (same data-loss guard as
32
+ * writeRouterSection). */
33
+ export function writeComposerSection(patch: { shape?: string }): void {
34
+ const file = settingsPath();
35
+ let settings: Record<string, unknown> | null = {};
36
+ try {
37
+ if (existsSync(file)) {
38
+ settings = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
39
+ }
40
+ } catch {
41
+ // Corrupt ≠ missing: a {} fallback would make the rename below overwrite
42
+ // the file with ONLY the composer section, destroying every other key.
43
+ settings = null;
44
+ }
45
+ if (settings === null) {
46
+ throw new Error(`${file} is not valid JSON — fix or remove it before saving.`);
47
+ }
48
+ const composer = (settings.composer ?? {}) as Record<string, unknown>;
49
+ if (patch.shape !== undefined) composer.shape = patch.shape;
50
+ settings.composer = composer;
51
+ mkdirSync(dirname(file), { recursive: true });
52
+ const tmp = file + ".tmp";
53
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
54
+ renameSync(tmp, file);
55
+ }