repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

refactor: use pi settings for extension config

6a199a6714b7b486aa53900ce5c43fc1589cdd4f

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (20)

docs/super/plans/2026-07-03-extension-settings-only.md

Added
new file mode 100644
1 +# Extension Settings-Only Implementation Plan
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
5 +**Goal:** Move extension configuration to Pi settings only: global `~/.pi/agent/settings.json` and project `.pi/settings.json`; remove custom config files and workspace-root `settings.json` fallbacks.
7 +**Architecture:** Use Pi's merged settings (`pi.settingsManager.getSettings()` or `SettingsManager`) for extension config. Keep non-config state/artifacts such as tune session JSONL, locks, hooks, dashboards, workflow specs, and logs. Add a static regression guard so future extensions cannot reintroduce custom config files.
9 +**Tech Stack:** TypeScript Pi extensions, Vitest, Node stdlib, `mise` tasks.
11 +**Roadmap:** None
13 +**Phase:** Single-plan implementation
15 +---
17 +## Scope rules
19 +- In scope: extension config only.
20 +- Out of scope: `ultra` workflow specs under `.pi/workflows` and `~/.pi/agent/workflows`; these are resources, not config.
21 +- Out of scope: tune state/artifacts under `.pi/tune/` except `.pi/tune/config.json` reads.
22 +- No legacy fallback: old `settings.json` at workspace root, `.pi/tune/config.json`, and `~/.pi/agent/extensions/tune.json` stop being read.
23 +- Do not delete user files. Ignore old config files.
24 +- Preserve unrelated dirty work. Stage only files touched by this plan.
26 +## Files
28 +- Modify: `scripts/extensions.mjs` — add static config-file guard.
29 +- Modify: `scripts/test_extensions_static_check.mjs` — red tests for forbidden config patterns.
30 +- Modify: `extensions/angel/index.ts` — use runtime settings only.
31 +- Create: `extensions/angel/__tests__/settings.test.ts` — settings regression tests.
32 +- Modify: `extensions/lazy/src/config.ts` — use runtime settings only; remove file reads and `cwd/settings.json` fallback.
33 +- Modify: `extensions/lazy/__tests__/unit.test.ts` — update config tests.
34 +- Modify: `extensions/ultra/settings.ts` — use runtime settings only; remove file reads.
35 +- Modify: `extensions/ultra/index.ts` — stop passing settings files.
36 +- Modify: `extensions/ultra/__tests__/settings.test.ts` — update settings tests.
37 +- Modify: `extensions/leaks/src/pi.ts` — read merged `leaks` settings from Pi runtime settings.
38 +- Modify: `extensions/leaks/__tests__/pi-direct.test.ts` — add runtime settings to fake Pi.
39 +- Modify: `extensions/neko/index.ts` — read merged `neko.enabled` and `editorPaddingX` from Pi runtime settings.
40 +- Modify: `extensions/neko/__tests__/lifecycle.test.ts` — cover merged settings behavior.
41 +- Modify: `extensions/tune/index.ts` — replace `.pi/tune/config.json` reads with `settings.tune` reads.
42 +- Modify: `extensions/tune/shortcuts.ts` — replace `~/.pi/agent/extensions/tune.json` with `settings.tune.shortcuts` parser.
43 +- Modify: `extensions/tune/__tests__/unit.test.ts` — update auto-resume/max-iteration tests.
44 +- Modify: `extensions/tune/__tests__/remaining.test.ts` — update shortcut tests.
45 +- Modify: READMEs/CHANGELOGs for touched extensions only when they document old config paths.
47 +---
49 +### Task 1: Static guard against custom extension config files
51 +**Files:**
53 +- Modify: `scripts/test_extensions_static_check.mjs`
54 +- Modify: `scripts/extensions.mjs`
56 +- [x] **Step 1: Write failing static-check tests**
58 +Add this block near the existing `withTemp` static-check tests in `scripts/test_extensions_static_check.mjs`:
60 +```js
61 +withTemp((root) => {
62 + const ext = writeExtension(
63 + root,
64 + "bad-config",
65 + { devDependencies: { [HARNESS]: "^0.6.1" } },
66 + [
67 + "import path from \"node:path\";",
68 + "const a = path.join(process.cwd(), \"settings.json\");",
69 + "const b = path.join(process.cwd(), \".pi\", \"tune\", \"config.json\");",
70 + "const c = \"tune.json\";",
71 + "void [a, b, c];",
72 + ].join("\n"),
73 + );
74 + const errors = staticCheck(ext, { root });
75 + assert(errors.some((e) => e.includes("workspace-root settings.json")));
76 + assert(errors.some((e) => e.includes("custom tune config file")));
77 + assert(errors.some((e) => e.includes("agent extension config file")));
78 +});
79 +```
81 +- [x] **Step 2: Run test to verify it fails**
83 +Run:
85 +```bash
86 +cd pi-ext && mise run check
87 +```
89 +Expected: `scripts/test_extensions_static_check.mjs` fails because `staticCheck()` does not yet report the three config errors.
91 +- [x] **Step 3: Implement minimal static guard**
93 +In `scripts/extensions.mjs`, before `export function staticCheck`, add:
95 +```js
96 +const FORBIDDEN_EXTENSION_CONFIG_PATTERNS = [
97 + {
98 + re:
99 + /(?:path\.)?join\(\s*(?:process\.cwd\(\)|\bcwd\b)\s*,\s*["']settings\.json["']\s*\)/,
100 + message:
101 + "workspace-root settings.json is not a Pi settings file; use merged Pi settings",
102 + },
104 + re: /(?:\.pi["'][^\n]{0,80}tune[^\n]{0,80}config\.json|tuneConfigPath)/,
105 + message:
106 + "custom tune config file is forbidden; use settings.tune in Pi settings",
107 + },
109 + re: /["']tune\.json["']/,
110 + message:
111 + "agent extension config file is forbidden; use settings.tune in Pi settings",
112 + },
114 +```
116 +Inside the existing `for (const file of tsFiles(ext))` loop, after `const text = readFileSync(file, "utf8");`, add:
118 +```js
119 +for (const pattern of FORBIDDEN_EXTENSION_CONFIG_PATTERNS) {
120 + if (pattern.re.test(text)) {
121 + err(errors, ext, `${pattern.message} in ${rel(file, ext)}`);
124 +```
126 +- [x] **Step 4: Run static-check tests**
128 +Run:
130 +```bash
131 +cd pi-ext && node scripts/test_extensions_static_check.mjs
132 +```
134 +Expected: prints `OK static-check tests`.
136 +---
138 +### Task 2: Angel uses runtime Pi settings only
140 +**Files:**
142 +- Modify: `extensions/angel/index.ts`
143 +- Create: `extensions/angel/__tests__/settings.test.ts`
145 +- [x] **Step 1: Write failing Angel settings test**
147 +Create `extensions/angel/__tests__/settings.test.ts`:
149 +```ts
150 +import { describe, expect, it } from "vitest";
151 +import { __test } from "../index.ts";
153 +describe("angel settings", () => {
154 + it("loads only the merged Pi settings angel block", () => {
155 + expect(
156 + __test.loadSettings({
157 + settingsManager: {
158 + getSettings: () => ({
159 + angel: { enabled: false, maxCallsPerTask: 4 },
160 + }),
161 + },
162 + } as never),
163 + ).toMatchObject({ enabled: false, maxCallsPerTask: 4 });
164 + });
166 + it("defaults when runtime settings are missing", () => {
167 + expect(__test.loadSettings({} as never)).toEqual({});
168 + });
169 +});
170 +```
172 +- [x] **Step 2: Run test to verify it fails**
174 +Run:
176 +```bash
177 +cd pi-ext && npm run test -- extensions/angel/__tests__/settings.test.ts
178 +```
180 +Expected: FAIL because `__test` is not exported.
182 +- [x] **Step 3: Remove file-based settings from Angel**
184 +In `extensions/angel/index.ts`:
186 +- Change the imports from:
188 +```ts
189 +import { existsSync, readFileSync } from "node:fs";
190 +import * as fs from "node:fs/promises";
191 +import * as path from "node:path";
192 +```
194 +To:
196 +```ts
197 +import * as fs from "node:fs/promises";
198 +import * as path from "node:path";
199 +```
201 +- Change the Pi import from:
203 +```ts
204 +import {
205 + convertToLlm,
206 + getAgentDir,
207 + serializeConversation,
208 +} from "@earendil-works/pi-coding-agent";
209 +```
211 +To:
213 +```ts
214 +import {
215 + convertToLlm,
216 + serializeConversation,
217 +} from "@earendil-works/pi-coding-agent";
218 +```
220 +- Delete `readSettings(file: string)`.
221 +- Replace `loadSettings` with:
223 +```ts
224 +function loadSettings(pi: ExtensionAPI): Settings {
225 + const allSettings = (pi as SettingsAPI).settingsManager?.getSettings();
226 + return isPlainObject(allSettings?.angel)
227 + ? (allSettings.angel as Settings)
228 + : {};
230 +```
232 +- Add at the end of the file:
234 +```ts
235 +export const __test = { loadSettings };
236 +```
238 +- [x] **Step 4: Run Angel tests**
240 +Run:
242 +```bash
243 +cd pi-ext && npm run test -- extensions/angel/__tests__/settings.test.ts extensions/angel/__tests__/harness.test.ts
244 +```
246 +Expected: PASS.
248 +---
250 +### Task 3: Lazy and Ultra remove workspace-root `settings.json` fallback
252 +**Files:**
254 +- Modify: `extensions/lazy/src/config.ts`
255 +- Modify: `extensions/lazy/__tests__/unit.test.ts`
256 +- Modify: `extensions/ultra/settings.ts`
257 +- Modify: `extensions/ultra/index.ts`
258 +- Modify: `extensions/ultra/__tests__/settings.test.ts`
260 +- [x] **Step 1: Write failing Lazy regression test**
262 +In `extensions/lazy/__tests__/unit.test.ts`, replace the current `it("loads files before runtime"...)` test with:
264 +```ts
265 +it("loads runtime Pi settings and ignores workspace-root settings.json", async () => {
266 + const dir = await tempDir();
267 + writeFileSync(
268 + path.join(dir, "settings.json"),
269 + JSON.stringify({ lazy: { defaultMode: "lite" } }),
270 + );
272 + expect(
273 + loadLazySettingsForCwd(dir, {
274 + settingsManager: {
275 + getSettings: () => ({ lazy: { defaultMode: "ultra" } }),
276 + },
277 + }).defaultMode,
278 + ).toBe("ultra");
280 + expect(
281 + loadLazySettingsForCwd(dir, {
282 + settingsManager: { getSettings: () => ({}) },
283 + }).defaultMode,
284 + ).toBe("full");
285 +});
286 +```
288 +- [x] **Step 2: Write failing Ultra regression test**
290 +In `extensions/ultra/__tests__/settings.test.ts`:
292 +- Delete `describe("readUltraSettings", ...)`.
293 +- Replace the `loadUltraSettings` precedence test with:
295 +```ts
296 +it("uses runtime Pi settings over defaults", () => {
297 + const merged = loadUltraSettings({
298 + runtime: { ultra: { concurrency: 10, maxRetries: 9 } },
299 + });
301 + expect(merged).toEqual({
302 + enabled: true,
303 + concurrency: 10,
304 + maxRetries: 9,
305 + defaultTimeoutMs: 180000,
306 + subagentExtensions: "all",
307 + });
308 +});
309 +```
311 +- [x] **Step 3: Run tests to verify they fail**
313 +Run:
315 +```bash
316 +cd pi-ext && npm run test -- extensions/lazy/__tests__/unit.test.ts extensions/ultra/__tests__/settings.test.ts
317 +```
319 +Expected: Lazy fails because workspace-root `settings.json` still affects config; Ultra fails until the old file-based API is removed from the test/imports.
321 +- [x] **Step 4: Implement Lazy runtime-only settings**
323 +In `extensions/lazy/src/config.ts`:
325 +- Remove imports from `node:fs`, `node:path`, and `getAgentDir`.
326 +- Delete `SettingsSource`, `readLazySettings`, and file merging.
327 +- Replace `loadLazySettings` and `loadLazySettingsForCwd` with:
329 +```ts
330 +export function loadLazySettings(runtime?: unknown): LazySettings {
331 + return mergeLazySettings(pickLazy(runtime));
334 +export function loadLazySettingsForCwd(
335 + _cwd: string,
336 + pi: SettingsAPI,
337 +): LazySettings {
338 + return loadLazySettings(pi.settingsManager?.getSettings());
340 +```
342 +- [x] **Step 5: Implement Ultra runtime-only settings**
344 +In `extensions/ultra/settings.ts`:
346 +- Remove `existsSync/readFileSync` import.
347 +- Delete `readUltraSettings`.
348 +- Change `SettingsSources` to:
350 +```ts
351 +export interface SettingsSources {
352 + runtime?: unknown;
354 +```
356 +- Change `loadUltraSettings` to:
358 +```ts
359 +export function loadUltraSettings(sources: SettingsSources): UltraSettings {
360 + return mergeUltraSettings(pickUltra(sources.runtime));
362 +```
364 +In `extensions/ultra/index.ts`:
366 +- Remove `getAgentDir` and `path` imports if unused after this change.
367 +- Replace the settings loader with:
369 +```ts
370 +const settings = (): UltraSettings =>
371 + loadUltraSettings({
372 + runtime: (
373 + pi as { settingsManager?: { getSettings(): unknown } }
374 + ).settingsManager?.getSettings(),
375 + });
376 +```
378 +- [x] **Step 6: Run Lazy and Ultra tests**
380 +Run:
382 +```bash
383 +cd pi-ext && npm run test -- extensions/lazy/__tests__/unit.test.ts extensions/ultra/__tests__/settings.test.ts extensions/ultra/__tests__/harness.test.ts
384 +```
386 +Expected: PASS.
388 +---
390 +### Task 4: Leaks and Neko read merged Pi settings
392 +**Files:**
394 +- Modify: `extensions/leaks/src/pi.ts`
395 +- Modify: `extensions/leaks/__tests__/pi-direct.test.ts`
396 +- Modify: `extensions/neko/index.ts`
397 +- Modify: `extensions/neko/__tests__/lifecycle.test.ts`
399 +- [x] **Step 1: Write failing Leaks runtime-settings test**
401 +In `extensions/leaks/__tests__/pi-direct.test.ts`, update `fakePi()` so `pi` includes runtime settings:
403 +```ts
404 +pi: {
405 + settingsManager: {
406 + getSettings: () => ({
407 + leaks: { regex: [{ pattern: "TOKEN_[0-9]+", label: "TOKEN" }] },
408 + }),
409 + },
410 + on(name: string, handler: Handler) {
411 +```
413 +Then add an assertion after `session_start` and before provider redaction checks:
415 +```ts
416 +const custom = await runtime.handlers.get("before_provider_request")?.(
417 + { payload: { text: "TOKEN_123" } },
418 + view.ctx,
420 +expect(JSON.stringify(custom)).not.toContain("TOKEN_123");
421 +```
423 +- [x] **Step 2: Write failing Neko merged-settings test**
425 +In `extensions/neko/__tests__/lifecycle.test.ts`, change `createHarness()` to accept runtime settings:
427 +```ts
428 +function createHarness(
429 + runtimeSettings: Record<string, unknown> = {
430 + neko: { enabled: true },
431 + editorPaddingX: 1,
432 + },
433 +) {
434 +```
436 +Add this field to the fake `pi` object:
438 +```ts
439 +settingsManager: {
440 + getSettings: () => runtimeSettings,
442 +```
444 +Change the disabled-session test to runtime settings:
446 +```ts
447 +it("disabled runtime setting restores working row and default editor", async () => {
448 + const h = createHarness({ neko: { enabled: false }, editorPaddingX: 2 });
450 + await h.emit("session_start");
452 + expect(h.last("setWorkingVisible")?.args).toEqual([true]);
453 + expect(h.last("setEditorComponent")?.args).toEqual([undefined]);
454 +});
455 +```
457 +- [x] **Step 3: Run tests to verify they fail**
459 +Run:
461 +```bash
462 +cd pi-ext && npm run test -- extensions/leaks/__tests__/pi-direct.test.ts extensions/neko/__tests__/lifecycle.test.ts
463 +```
465 +Expected: Leaks fails because it ignores runtime settings; Neko may fail or require harness adjustment because it reads files directly.
467 +- [x] **Step 4: Implement Leaks runtime settings**
469 +In `extensions/leaks/src/pi.ts`:
471 +- Remove `existsSync`, `readFileSync`, and `path` imports if no longer used.
472 +- Add:
474 +```ts
475 +type SettingsAPI = ExtensionAPI & {
476 + settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
479 +function readSettings(pi: ExtensionAPI) {
480 + return loadLeaksSettings((pi as SettingsAPI).settingsManager?.getSettings?.())
481 + .settings;
483 +```
485 +- Change both call sites:
487 +```ts
488 +engine.reload(ctx.cwd, readSettings(pi), process.env);
489 +```
491 +- [x] **Step 5: Implement Neko merged settings reads**
493 +In `extensions/neko/index.ts`:
495 +- Add a local settings API type:
497 +```ts
498 +type SettingsAPI = ExtensionAPI & {
499 + settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
501 +```
503 +- Replace direct read helpers with runtime readers:
505 +```ts
506 +function mergedSettings(pi: ExtensionAPI): Record<string, unknown> {
507 + return (pi as SettingsAPI).settingsManager?.getSettings?.() ?? {};
510 +function resolveEditorPaddingX(pi: ExtensionAPI): number {
511 + const value = mergedSettings(pi).editorPaddingX;
512 + return typeof value === "number" && value > 0 ? value : 0;
515 +function isNekoEnabled(pi: ExtensionAPI): boolean {
516 + const raw = mergedSettings(pi).neko;
517 + return !(
518 + raw
519 + && typeof raw === "object"
520 + && !Array.isArray(raw)
521 + && (raw as Record<string, unknown>).enabled === false
522 + );
524 +```
526 +- Update call sites:
528 +```ts
529 +if (!isNekoEnabled(pi)) {
530 +```
532 +```ts
533 +const paddingX = resolveEditorPaddingX(pi);
534 +```
536 +- Keep `updateNekoSettings()` writing global `settings.json`; it is a command convenience that writes Pi's global settings file, not a custom config file.
538 +- [x] **Step 6: Run Leaks and Neko tests**
540 +Run:
542 +```bash
543 +cd pi-ext && npm run test -- extensions/leaks/__tests__/pi-direct.test.ts extensions/neko/__tests__/lifecycle.test.ts
544 +```
546 +Expected: PASS.
548 +---
550 +### Task 5: Tune moves config knobs to `settings.tune`
552 +**Files:**
554 +- Modify: `extensions/tune/index.ts`
555 +- Modify: `extensions/tune/shortcuts.ts`
556 +- Modify: `extensions/tune/__tests__/unit.test.ts`
557 +- Modify: `extensions/tune/__tests__/remaining.test.ts`
559 +- [x] **Step 1: Define target Tune settings shape**
561 +Use this shape in Pi settings:
563 +```json
565 + "tune": {
566 + "maxIterations": 12,
567 + "autoResumeLimit": 20,
568 + "shortcuts": {
569 + "toggleDashboard": "ctrl+shift+t",
570 + "fullscreenDashboard": "ctrl+shift+f"
574 +```
576 +Rules:
578 +- Missing `maxIterations` or `autoResumeLimit` means unlimited (`null`).
579 +- Non-finite, zero, negative, and non-number limits mean unlimited (`null`).
580 +- Limit numbers are floored.
581 +- Shortcut values may be non-empty strings or `null`; `null` disables that shortcut.
582 +- Missing shortcuts use existing defaults.
584 +- [x] **Step 2: Write failing Tune settings tests**
586 +In `extensions/tune/__tests__/unit.test.ts`, replace the current `.pi/tune/config.json`-based `readAutoResumeLimit` tests with pure settings tests:
588 +```ts
589 +describe("tune settings", () => {
590 + it("reads positive numeric limits from settings.tune", () => {
591 + expect(
592 + __test.readTuneSettings({
593 + settingsManager: {
594 + getSettings: () => ({
595 + tune: { maxIterations: 9.8, autoResumeLimit: 12.9 },
596 + }),
597 + },
598 + } as never),
599 + ).toMatchObject({ maxIterations: 9, autoResumeLimit: 12 });
600 + });
602 + it("treats invalid limits as unlimited", () => {
603 + for (
604 + const tune of [
605 + {},
606 + { maxIterations: 0, autoResumeLimit: 0 },
607 + { maxIterations: -1, autoResumeLimit: -1 },
608 + { maxIterations: "20", autoResumeLimit: "20" },
610 + ) {
611 + expect(
612 + __test.readTuneSettings({
613 + settingsManager: { getSettings: () => ({ tune }) },
614 + } as never),
615 + ).toMatchObject({ maxIterations: null, autoResumeLimit: null });
617 + });
618 +});
619 +```
621 +In `extensions/tune/__tests__/remaining.test.ts`, replace the shortcuts test with:
623 +```ts
624 +describe("shortcuts", () => {
625 + it("returns defaults when settings are missing", () => {
626 + const s = resolveTuneShortcuts();
627 + expect(s.toggleDashboard).toBe("ctrl+shift+t");
628 + expect(s.fullscreenDashboard).toBe("ctrl+shift+f");
629 + });
631 + it("reads shortcut overrides and null disables from settings.tune.shortcuts", () => {
632 + const s = resolveTuneShortcuts({
633 + tune: {
634 + shortcuts: {
635 + toggleDashboard: null,
636 + fullscreenDashboard: "ctrl+alt+f",
637 + },
638 + },
639 + });
640 + expect(s.toggleDashboard).toBeNull();
641 + expect(s.fullscreenDashboard).toBe("ctrl+alt+f");
642 + });
643 +});
644 +```
646 +- [x] **Step 3: Run tests to verify they fail**
648 +Run:
650 +```bash
651 +cd pi-ext && npm run test -- extensions/tune/__tests__/unit.test.ts extensions/tune/__tests__/remaining.test.ts
652 +```
654 +Expected: FAIL because `readTuneSettings` does not exist and `resolveTuneShortcuts` still expects a file path.
656 +- [x] **Step 4: Replace shortcut file config parser**
658 +Rewrite `extensions/tune/shortcuts.ts` to remove all fs/path/getAgentDir usage:
660 +```ts
661 +/** Keyboard shortcut configuration for tune dashboard from settings.tune.shortcuts. */
663 +export const DEFAULT_TOGGLE_DASHBOARD_SHORTCUT = "ctrl+shift+t";
664 +export const DEFAULT_FULLSCREEN_DASHBOARD_SHORTCUT = "ctrl+shift+f";
666 +export interface TuneShortcuts {
667 + toggleDashboard: string | null;
668 + fullscreenDashboard: string | null;
671 +function isRecord(value: unknown): value is Record<string, unknown> {
672 + return typeof value === "object" && value !== null && !Array.isArray(value);
675 +function shortcutFromConfig(
676 + configured: unknown,
677 + fallback: string,
678 +): string | null {
679 + if (configured === null) return null;
680 + return typeof configured === "string" && configured !== ""
681 + ? configured
682 + : fallback;
685 +export function resolveTuneShortcuts(settings?: unknown): TuneShortcuts {
686 + const tune = isRecord(settings) && isRecord(settings.tune)
687 + ? settings.tune
688 + : {};
689 + const shortcuts = isRecord(tune.shortcuts) ? tune.shortcuts : {};
690 + return {
691 + toggleDashboard: shortcutFromConfig(
692 + shortcuts.toggleDashboard,
693 + DEFAULT_TOGGLE_DASHBOARD_SHORTCUT,
694 + ),
695 + fullscreenDashboard: shortcutFromConfig(
696 + shortcuts.fullscreenDashboard,
697 + DEFAULT_FULLSCREEN_DASHBOARD_SHORTCUT,
698 + ),
699 + };
701 +```
703 +- [x] **Step 5: Add Tune runtime settings helper**
705 +In `extensions/tune/index.ts`, import `TuneShortcuts` with `resolveTuneShortcuts`:
707 +```ts
708 +import { resolveTuneShortcuts, type TuneShortcuts } from "./shortcuts.ts";
709 +```
711 +Then add near the settings helpers:
713 +```ts
714 +type SettingsAPI = ExtensionAPI & {
715 + settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
718 +interface TuneSettings {
719 + maxIterations: number | null;
720 + autoResumeLimit: number | null;
721 + shortcuts: TuneShortcuts;
724 +function positiveIntOrNull(value: unknown): number | null {
725 + return typeof value === "number" && Number.isFinite(value) && value > 0
726 + ? Math.floor(value)
727 + : null;
730 +function readTuneSettings(pi: ExtensionAPI): TuneSettings {
731 + const settings = (pi as SettingsAPI).settingsManager?.getSettings?.() ?? {};
732 + const tune = settings.tune && typeof settings.tune === "object"
733 + && !Array.isArray(settings.tune)
734 + ? (settings.tune as Record<string, unknown>)
735 + : {};
736 + return {
737 + maxIterations: positiveIntOrNull(tune.maxIterations),
738 + autoResumeLimit: positiveIntOrNull(tune.autoResumeLimit),
739 + shortcuts: resolveTuneShortcuts(settings),
740 + };
742 +```
744 +- [x] **Step 6: Remove `.pi/tune/config.json` reads**
746 +In `extensions/tune/index.ts`:
748 +- Delete `tuneConfigPath`.
749 +- Delete `readMaxExperiments(cwd)` and `readAutoResumeLimit(cwd)`.
750 +- Replace extension-level shortcut constant with dynamic settings:
752 +```ts
753 +const tuneSettings = (): TuneSettings => readTuneSettings(pi);
754 +```
756 +- In `dashboardHintVariants`, read shortcuts inside the function:
758 +```ts
759 +const shortcuts = tuneSettings().shortcuts;
760 +```
762 +- Replace auto-resume limit lookup:
764 +```ts
765 +const limit = tuneSettings().autoResumeLimit;
766 +```
768 +- Replace max-iteration lookups:
770 +```ts
771 +state.maxExperiments = tuneSettings().maxIterations;
772 +```
774 +- Replace user-visible text:
776 +```ts
777 +? `\nMax iterations: ${state.maxExperiments} (from settings.tune.maxIterations)`
778 +: "";
779 +```
781 +- Keep `.pi/tune/session.jsonl`, `.pi/tune/lock.json`, hooks, benchmark, ideas, checks, and dashboard export paths unchanged.
783 +- Export helper for tests:
785 +```ts
786 +readTuneSettings,
787 +```
789 +inside `__test`.
791 +- [x] **Step 7: Run Tune tests**
793 +Run:
795 +```bash
796 +cd pi-ext && npm run test -- extensions/tune/__tests__/unit.test.ts extensions/tune/__tests__/remaining.test.ts
797 +```
799 +Expected: PASS.
801 +---
803 +### Task 6: Docs and final verification
805 +**Files:**
807 +- Modify touched extension READMEs only if they mention removed config files.
808 +- Modify `CHANGELOG.md` if repo convention requires release notes for behavior changes.
810 +- [x] **Step 1: Search for stale config docs**
812 +Run:
814 +```bash
815 +cd pi-ext && /usr/bin/rg -n 'cwd/settings\.json|workspace.*settings\.json|\.pi/tune/config\.json|extensions/tune\.json|tune\.json|settings\.tune|maxIterations|autoResumeLimit' extensions docs README.md CHANGELOG.md
816 +```
818 +Expected: old custom config docs appear only in changelog history or tests deliberately describing removed behavior.
820 +- [x] **Step 2: Update active docs**
822 +For any active README/help text found in Step 1:
824 +- Replace `.pi/tune/config.json` with `settings.tune.maxIterations` and `settings.tune.autoResumeLimit`.
825 +- Replace `~/.pi/agent/extensions/tune.json` with `settings.tune.shortcuts`.
826 +- Remove workspace-root `settings.json` examples.
827 +- Keep `.pi/workflows` docs unchanged.
829 +- [x] **Step 3: Run targeted tests**
831 +Run:
833 +```bash
834 +cd pi-ext && npm run test -- \
835 + extensions/angel/__tests__/settings.test.ts \
836 + extensions/angel/__tests__/harness.test.ts \
837 + extensions/lazy/__tests__/unit.test.ts \
838 + extensions/ultra/__tests__/settings.test.ts \
839 + extensions/ultra/__tests__/harness.test.ts \
840 + extensions/leaks/__tests__/pi-direct.test.ts \
841 + extensions/neko/__tests__/lifecycle.test.ts \
842 + extensions/tune/__tests__/unit.test.ts \
843 + extensions/tune/__tests__/remaining.test.ts
844 +```
846 +Expected: PASS.
848 +- [x] **Step 4: Run static guard**
850 +Run:
852 +```bash
853 +cd pi-ext && mise run check
854 +```
856 +Expected: PASS. If unrelated existing static failures appear, record exact failures and do not claim full static health.
858 +- [x] **Step 5: Run formatter on touched files**
860 +Run:
862 +```bash
863 +cd pi-ext && mise run fmt
864 +```
866 +Expected: formats touched files. Re-check `git diff` for unrelated formatting; revert unrelated formatting before continuing.
868 +- [x] **Step 6: Final audit grep**
870 +Run:
872 +```bash
873 +cd pi-ext && /usr/bin/rg -n --glob '!**/__tests__/**' --glob '!**/__fixtures__/**' --glob '!**/README.md' --glob '!**/CHANGELOG.md' --glob '!**/package.json' 'join\([^\n]*(process\.cwd\(\)|\bcwd\b)[^\n]*,\s*"settings\.json"|\.pi/tune/config\.json|tuneConfigPath|extensions/tune\.json|"tune\.json"' extensions scripts
874 +```
876 +Expected: no matches, except intentional static-check test patterns in `scripts/test_extensions_static_check.mjs` if included by the glob.
878 +- [x] **Step 7: Dirty-work safety check**
880 +Run:
882 +```bash
883 +git status --short && git -C pi-ext status --short
884 +```
886 +Expected: only planned files plus pre-existing unrelated dirty files. Do not stage unrelated files.
888 +- [x] **Step 8: Commit only if requested**
890 +If the human asks for a commit, stage only files touched by this plan:
892 +```bash
893 +cd pi-ext && git add \
894 + scripts/extensions.mjs \
895 + scripts/test_extensions_static_check.mjs \
896 + extensions/angel/index.ts \
897 + extensions/angel/__tests__/settings.test.ts \
898 + extensions/lazy/src/config.ts \
899 + extensions/lazy/__tests__/unit.test.ts \
900 + extensions/ultra/settings.ts \
901 + extensions/ultra/index.ts \
902 + extensions/ultra/__tests__/settings.test.ts \
903 + extensions/leaks/src/pi.ts \
904 + extensions/leaks/__tests__/pi-direct.test.ts \
905 + extensions/neko/index.ts \
906 + extensions/neko/__tests__/lifecycle.test.ts \
907 + extensions/tune/index.ts \
908 + extensions/tune/shortcuts.ts \
909 + extensions/tune/__tests__/unit.test.ts \
910 + extensions/tune/__tests__/remaining.test.ts \
911 + CHANGELOG.md
912 +```
914 +Then inspect staged diff:
916 +```bash
917 +cd pi-ext && git diff --cached --stat && git diff --cached --check
918 +```
920 +Commit message:
922 +```bash
923 +cd pi-ext && git commit -m "refactor: use pi settings for extension config"
924 +```

extensions/angel/README.md

Modified
61 61 ### Settings
63 -`angel` settings are read from Pi agent settings, workspace `.pi/settings.json`,
64 -workspace `settings.json`, and runtime settings.
65 -Later sources override earlier sources.
63 +`angel` settings are read from Pi settings: global
64 +`~/.pi/agent/settings.json` and project `.pi/settings.json`.
67 66 Example:

extensions/angel/__tests__/settings.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "vitest";
2 +import { __test } from "../index.ts";
4 +describe("angel settings", () => {
5 + it("loads only the merged Pi settings angel block", () => {
6 + expect(
7 + __test.loadSettings({
8 + settingsManager: {
9 + getSettings: () => ({
10 + angel: { enabled: false, maxCallsPerTask: 4 },
11 + }),
12 + },
13 + } as never),
14 + ).toMatchObject({ enabled: false, maxCallsPerTask: 4 });
15 + });
17 + it("defaults when runtime settings are missing", () => {
18 + expect(__test.loadSettings({} as never)).toEqual({});
19 + });
20 +});

extensions/angel/index.ts

Modified
11 11 * Commands: /angel on|off
14 -import { existsSync, readFileSync } from "node:fs";
15 14 import * as fs from "node:fs/promises";
16 15 import * as path from "node:path";
17 16 import { complete, type Model } from "@earendil-works/pi-ai";
22 21 } from "@earendil-works/pi-coding-agent";
23 22 import {
24 23 convertToLlm,
25 - getAgentDir,
26 24 serializeConversation,
27 25 } from "@earendil-works/pi-coding-agent";
28 26 import type { AutocompleteItem } from "@earendil-works/pi-tui";
176 174 return v !== null && typeof v === "object" && !Array.isArray(v);
179 -function readSettings(file: string): Settings {
180 - try {
181 - if (!existsSync(file)) return {};
182 - const raw = JSON.parse(readFileSync(file, "utf-8"));
183 - if (!isPlainObject(raw)) return {};
184 - const angel = (raw as Record<string, unknown>).angel;
185 - return isPlainObject(angel) ? (angel as Settings) : {};
186 - } catch {
187 - return {};
188 - }
191 177 function loadSettings(pi: ExtensionAPI): Settings {
192 - const fromFiles = Object.assign(
193 - {},
194 - ...[
195 - path.join(getAgentDir(), "settings.json"),
196 - path.join(process.cwd(), ".pi", "settings.json"),
197 - path.join(process.cwd(), "settings.json"),
198 - ].map(readSettings),
199 - );
201 178 const allSettings = (pi as SettingsAPI).settingsManager?.getSettings();
202 - const runtime = isPlainObject(allSettings?.angel)
179 + return isPlainObject(allSettings?.angel)
203 180 ? (allSettings.angel as Settings)
206 - return { ...fromFiles, ...runtime };
209 184 // ── model resolution ───────────────────────────────────────────────────
797 +export const __test = { loadSettings };

extensions/lazy/__tests__/unit.test.ts

Modified
4 4 import { mkdirSync, writeFileSync } from "node:fs";
5 5 import { mkdtemp, rm } from "node:fs/promises";
6 6 import { tmpdir } from "node:os";
7 7 import path from "node:path";
8 8 import { afterEach, describe, expect, it } from "vitest";
9 9 import {
10 - loadLazySettings,
10 + loadLazySettingsForCwd,
11 11 mergeLazySettings,
12 12 pickLazy,
13 13 settingsSnippet,
86 - it("loads files before runtime", async () => {
86 + it("loads runtime Pi settings and ignores workspace-root settings.json", async () => {
87 87 const dir = await tempDir();
88 - const file = path.join(dir, "settings.json");
89 - writeFileSync(file, JSON.stringify({ lazy: { defaultMode: "lite" } }));
88 + writeFileSync(
89 + path.join(dir, "settings.json"),
90 + JSON.stringify({ lazy: { defaultMode: "lite" } }),
91 + );
90 93 expect(
91 - loadLazySettings({
92 - files: [file],
93 - runtime: { lazy: { defaultMode: "ultra" } },
94 + loadLazySettingsForCwd(dir, {
95 + settingsManager: {
96 + getSettings: () => ({ lazy: { defaultMode: "ultra" } }),
97 + },
94 98 }).defaultMode,
95 99 ).toBe("ultra");
101 + expect(
102 + loadLazySettingsForCwd(dir, {
103 + settingsManager: { getSettings: () => ({}) },
104 + }).defaultMode,
105 + ).toBe("full");
98 108 it("prints settings snippet", () => {

extensions/lazy/src/config.ts

Modified
1 -import { existsSync, readFileSync } from "node:fs";
2 -import path from "node:path";
3 -import { getAgentDir } from "@earendil-works/pi-coding-agent";
4 1 import { type LazyMode, normalizeMode } from "./modes.ts";
6 3 export interface LazySettings {
13 10 status: true,
16 -export interface SettingsSource {
17 - files: string[];
18 - runtime?: unknown;
19 -}
21 13 type SettingsAPI = {
22 14 settingsManager?: { getSettings(): unknown };
35 27 return out;
38 -export function readLazySettings(file: string): Partial<LazySettings> {
39 - try {
40 - if (!existsSync(file)) return {};
41 - return pickLazy(JSON.parse(readFileSync(file, "utf8")));
42 - } catch {
43 - return {};
44 - }
45 -}
47 30 export function mergeLazySettings(
48 31 ...partials: Partial<LazySettings>[]
49 32 ): LazySettings {
60 -export function loadLazySettings(source: SettingsSource): LazySettings {
61 - return mergeLazySettings(
62 - ...source.files.map(readLazySettings),
63 - pickLazy(source.runtime),
64 - );
43 +export function loadLazySettings(runtime?: unknown): LazySettings {
44 + return mergeLazySettings(pickLazy(runtime));
67 47 export function loadLazySettingsForCwd(
68 - cwd: string,
48 + _cwd: string,
69 49 pi: SettingsAPI,
70 50 ): LazySettings {
71 - return loadLazySettings({
72 - files: [
73 - path.join(getAgentDir(), "settings.json"),
74 - path.join(cwd, ".pi", "settings.json"),
75 - path.join(cwd, "settings.json"),
76 - ],
77 - runtime: pi.settingsManager?.getSettings(),
78 - });
51 + return loadLazySettings(pi.settingsManager?.getSettings());
81 54 export function settingsSnippet(mode: LazyMode): string {

extensions/leaks/__tests__/pi-direct.test.ts

Modified
17 17 handlers,
18 18 commands,
19 19 pi: {
20 + settingsManager: {
21 + getSettings: () => ({
22 + leaks: { regex: [{ pattern: "TOKEN_[0-9]+", label: "TOKEN" }] },
23 + }),
24 + },
20 25 on(name: string, handler: Handler) {
21 26 handlers.set(name, handler);
88 93 { ...view.ctx, cwd: temp() },
96 + const custom = await runtime.handlers.get("before_provider_request")?.(
97 + { payload: { text: "TOKEN_123" } },
98 + view.ctx,
99 + );
100 + expect(JSON.stringify(custom)).not.toContain("TOKEN_123");
91 102 const context = await runtime.handlers.get("context")?.(
92 103 { messages: [{ content: secret }] },
93 104 view.ctx,

extensions/leaks/src/pi.ts

Modified
1 -import { existsSync, readFileSync } from "node:fs";
2 1 import path from "node:path";
3 2 import type {
4 3 ExtensionAPI,
8 7 import { isPlainObject } from "./safety.ts";
9 8 import { loadLeaksSettings } from "./settings.ts";
10 +type SettingsAPI = ExtensionAPI & {
11 + settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
12 +};
11 14 export default function leaks(pi: ExtensionAPI) {
12 15 const engine = new LeaksEngine();
14 17 pi.on("session_start", async (_event, ctx) => {
15 - engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env);
18 + engine.reload(ctx.cwd, readSettings(pi), process.env);
16 19 if (ctx.hasUI) ctx.ui.setStatus("leaks", "leaks on | last 0");
61 64 return;
63 66 if (command === "reload") {
64 - engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env);
67 + engine.reload(ctx.cwd, readSettings(pi), process.env);
65 68 ctx.ui.notify("leaks reloaded", "info");
66 69 return;
238 -function readSettings(cwd: string) {
239 - const file = path.join(cwd, ".pi", "settings.json");
240 - if (!existsSync(file)) return { regex: [] };
241 - try {
242 - return loadLeaksSettings(JSON.parse(readFileSync(file, "utf8"))).settings;
243 - } catch {
244 - return { regex: [] };
245 - }
241 +function readSettings(pi: ExtensionAPI) {
242 + return loadLeaksSettings((pi as SettingsAPI).settingsManager?.getSettings?.())
243 + .settings;
248 246 function formatNotice(result: {

extensions/neko/__tests__/lifecycle.test.ts

Modified
70 70 return text.replace(/\x1b\[[0-9;]*m/g, "");
73 -function createHarness() {
73 +function createHarness(
74 + runtimeSettings: Record<string, unknown> = {
75 + neko: { enabled: true },
76 + editorPaddingX: 1,
77 + },
78 +) {
74 79 const handlers = new Map<string, Handler[]>();
75 80 const commands = new Map<string, any>();
76 81 const uiCalls: Array<{ method: string; args: any[] }> = [];
90 95 list.push(handler);
91 96 handlers.set(event, list);
98 + settingsManager: {
99 + getSettings: () => runtimeSettings,
100 + },
93 101 registerCommand(name: string, options: any) {
94 102 commands.set(name, options);
164 172 ).toHaveLength(0);
167 - it("disabled session restores working row and default editor", async () => {
168 - writeSettings({ neko: { enabled: false } });
169 - const h = createHarness();
175 + it("disabled runtime setting restores working row and default editor", async () => {
176 + const h = createHarness({ neko: { enabled: false }, editorPaddingX: 2 });
171 178 await h.emit("session_start");

extensions/neko/index.ts

Modified
384 -function readSettingFromPath(filePath: string): number {
385 - if (!existsSync(filePath)) return 0;
386 - try {
387 - return JSON.parse(readFileSync(filePath, "utf-8"))?.editorPaddingX ?? 0;
388 - } catch {
389 - return 0;
390 - }
393 -function resolveEditorPaddingX(cwd: string): number {
394 - // Project settings override global
395 - const project = readSettingFromPath(join(cwd, ".pi", "settings.json"));
396 - if (project > 0) return project;
397 - return readSettingFromPath(join(getAgentDir(), "settings.json"));
384 +type SettingsAPI = ExtensionAPI & {
385 + settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
400 388 interface NekoSettings {
401 389 enabled?: boolean;
404 -function readNekoSettings(): NekoSettings {
405 - const filePath = join(getAgentDir(), "settings.json");
406 - if (!existsSync(filePath)) return {};
407 - try {
408 - const neko = JSON.parse(readFileSync(filePath, "utf-8"))?.neko;
409 - return neko && typeof neko === "object" && !Array.isArray(neko) ? neko : {};
410 - } catch {
411 - return {};
412 - }
392 +function mergedSettings(pi: ExtensionAPI): Record<string, unknown> {
393 + return (pi as SettingsAPI).settingsManager?.getSettings?.() ?? {};
396 +function resolveEditorPaddingX(pi: ExtensionAPI): number {
397 + const value = mergedSettings(pi).editorPaddingX;
398 + return typeof value === "number" && value > 0 ? value : 0;
401 +function isNekoEnabled(pi: ExtensionAPI, override?: boolean): boolean {
402 + if (override !== undefined) return override;
403 + const raw = mergedSettings(pi).neko;
404 + return !(
405 + raw &&
406 + typeof raw === "object" &&
407 + !Array.isArray(raw) &&
408 + (raw as Record<string, unknown>).enabled === false
409 + );
415 412 function updateNekoSettings(values: Partial<NekoSettings>): void {
438 -function isNekoEnabled(): boolean {
439 - return readNekoSettings().enabled !== false;
442 435 export default function nekoExtension(pi: ExtensionAPI) {
443 436 const activeEditors = new Set<NekoEditor>();
444 437 let agentRunning = false;
445 438 let toolsRunning = 0;
446 439 let compacting = false;
440 + let enabledOverride: boolean | undefined;
447 441 let compactingTimer: ReturnType<typeof setTimeout> | null = null;
448 442 let errorUntil = 0;
449 443 let errorTimer: ReturnType<typeof setTimeout> | null = null;
472 466 disposeEditors();
474 - if (!isNekoEnabled()) {
468 + if (!isNekoEnabled(pi, enabledOverride)) {
475 469 ctx.ui.setWorkingVisible?.(true);
476 470 ctx.ui.setEditorComponent?.(undefined);
477 471 return;
480 474 ctx.ui.setWorkingVisible?.(false);
482 - const paddingX = resolveEditorPaddingX(ctx.cwd);
476 + const paddingX = resolveEditorPaddingX(pi);
483 477 ctx.ui.setEditorComponent?.((tui, theme, keybindings) => {
484 478 const editor = new NekoEditor(
485 479 paddingX,
496 490 const setEnabled = (ctx: ExtensionContext, enabled: boolean) => {
491 + enabledOverride = enabled;
497 492 updateNekoSettings({ enabled });
498 493 applyEditor(ctx);
499 494 if (ctx.hasUI) ctx.ui.notify(`Neko ${enabled ? "ON" : "OFF"}`, "info");
543 538 handler: async (args, ctx) => {
544 539 const arg = args.trim().toLowerCase();
545 - const enabled = isNekoEnabled();
540 + const enabled = isNekoEnabled(pi, enabledOverride);
547 542 switch (arg) {
548 543 case "":

extensions/tune/README.md

Modified
23 23 `METRIC name=value` lines, and run checks when configured
24 24 - `log_experiment` — record result and keep or discard VCS changes
26 -Settings:
28 -Config file: `<agent-dir>/extensions/tune.json`.
26 +Settings live under `tune` in Pi settings (`~/.pi/agent/settings.json` or
27 +project `.pi/settings.json`).
30 29 Keys:
32 31 - `shortcuts.toggleDashboard` — default `ctrl+shift+t`; `null` disables
33 32 - `shortcuts.fullscreenDashboard` — default `ctrl+shift+f`; `null` disables
35 -Run config file: `.pi/tune/config.json`.
37 -Keys:
39 33 - `maxIterations` — positive number caps experiments per segment; default `null`
40 34 - `autoResumeLimit` — positive number caps auto-resume turns; default `null`
63 57 All state lives in `.pi/tune/`.
65 -| File | Purpose |
66 -| ------------------ | --------------------------------------------------- |
67 -| `session.jsonl` | Append-only experiment log |
68 -| `session.md` | Living document: objective, what's been tried |
69 -| `ideas.md` | Backlog of untried optimizations |
70 -| `benchmark.mjs` | Benchmark script |
71 -| `checks.mjs` | Optional correctness gate |
72 -| `config.json` | Optional `maxIterations` / `autoResumeLimit` config |
73 -| `hooks/before.mjs` | Optional pre-iteration hook |
74 -| `hooks/after.mjs` | Optional post-iteration hook |
59 +| File | Purpose |
60 +| ------------------ | --------------------------------------------- |
61 +| `session.jsonl` | Append-only experiment log |
62 +| `session.md` | Living document: objective, what's been tried |
63 +| `ideas.md` | Backlog of untried optimizations |
64 +| `benchmark.mjs` | Benchmark script |
65 +| `checks.mjs` | Optional correctness gate |
66 +| `hooks/before.mjs` | Optional pre-iteration hook |
67 +| `hooks/after.mjs` | Optional post-iteration hook |
76 69 ## Behavior
112 105 Compaction skips the default LLM summary and rebuilds a deterministic summary
113 106 from persisted tune state.
115 -`.pi/tune/config.json` may set `maxIterations` to cap experiments per segment and
116 -`autoResumeLimit` to cap automatic resume turns.
117 -`autoResumeLimit` defaults to `null`, meaning unlimited.
108 +`settings.tune.maxIterations` caps experiments per segment.
109 +`settings.tune.autoResumeLimit` caps automatic resume turns.
110 +Both default to `null`, meaning unlimited.

extensions/tune/__tests__/remaining.test.ts

Modified
108 108 // ── 3. SHORTCUTS ──────────────────────────────────────────────────────
110 110 describe("shortcuts", () => {
111 - it("returns defaults when no config file", () => {
112 - const s = resolveTuneShortcuts("/nonexistent/path");
111 + it("returns defaults when settings are missing", () => {
112 + const s = resolveTuneShortcuts();
113 113 expect(s.toggleDashboard).toBe("ctrl+shift+t");
114 114 expect(s.fullscreenDashboard).toBe("ctrl+shift+f");
117 + it("reads shortcut overrides and null disables from settings.tune.shortcuts", () => {
118 + const s = resolveTuneShortcuts({
119 + tune: {
120 + shortcuts: {
121 + toggleDashboard: null,
122 + fullscreenDashboard: "ctrl+alt+f",
123 + },
124 + },
125 + });
126 + expect(s.toggleDashboard).toBeNull();
127 + expect(s.fullscreenDashboard).toBe("ctrl+alt+f");
128 + });
118 131 // ── 4. REPO LOCK ───────────────────────────────────────────────────────

extensions/tune/__tests__/unit.test.ts

Modified
1 1 import * as fs from "node:fs";
2 -import * as os from "node:os";
3 2 import * as path from "node:path";
4 3 import { DEFAULT_MAX_LINES } from "@earendil-works/pi-coding-agent";
5 4 import { describe, expect, it } from "vitest";
82 81 // ── Tune config ───────────────────────────────────────────────────────────
84 -describe("readAutoResumeLimit", () => {
85 - function withTuneConfig(contents?: string): string {
86 - const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "pi-ext-tune-"));
87 - if (contents !== undefined) {
88 - const dir = path.join(cwd, ".pi", "tune");
89 - fs.mkdirSync(dir, { recursive: true });
90 - fs.writeFileSync(path.join(dir, "config.json"), contents);
91 - }
92 - return cwd;
93 - }
95 - it("defaults to unlimited", () => {
96 - for (const contents of [undefined, "{}", '{"autoResumeLimit":null}']) {
97 - const cwd = withTuneConfig(contents);
98 - try {
99 - expect(__test.readAutoResumeLimit(cwd)).toBeNull();
100 - } finally {
101 - fs.rmSync(cwd, { recursive: true, force: true });
102 - }
103 - }
104 - });
106 - it("uses positive numeric limits", () => {
107 - const cwd = withTuneConfig('{"autoResumeLimit":12.9}');
108 - try {
109 - expect(__test.readAutoResumeLimit(cwd)).toBe(12);
110 - } finally {
111 - fs.rmSync(cwd, { recursive: true, force: true });
112 - }
83 +describe("tune settings", () => {
84 + it("reads positive numeric limits from settings.tune", () => {
85 + expect(
86 + __test.readTuneSettings({
87 + settingsManager: {
88 + getSettings: () => ({
89 + tune: { maxIterations: 9.8, autoResumeLimit: 12.9 },
90 + }),
91 + },
92 + } as never),
93 + ).toMatchObject({ maxIterations: 9, autoResumeLimit: 12 });
115 96 it("treats invalid limits as unlimited", () => {
116 - for (const contents of [
117 - '{"autoResumeLimit":0}',
118 - '{"autoResumeLimit":-1}',
119 - '{"autoResumeLimit":"20"}',
97 + for (const tune of [
98 + {},
99 + { maxIterations: 0, autoResumeLimit: 0 },
100 + { maxIterations: -1, autoResumeLimit: -1 },
101 + { maxIterations: "20", autoResumeLimit: "20" },
121 - const cwd = withTuneConfig(contents);
122 - try {
123 - expect(__test.readAutoResumeLimit(cwd)).toBeNull();
124 - } finally {
125 - fs.rmSync(cwd, { recursive: true, force: true });
126 - }
103 + expect(
104 + __test.readTuneSettings({
105 + settingsManager: { getSettings: () => ({ tune }) },
106 + } as never),
107 + ).toMatchObject({ maxIterations: null, autoResumeLimit: null });

extensions/tune/index.ts

Modified
54 54 parseJsonlEntry,
55 55 reconstructJsonlState,
56 56 } from "./jsonl.ts";
57 -import { resolveTuneShortcuts } from "./shortcuts.ts";
57 +import { resolveTuneShortcuts, type TuneShortcuts } from "./shortcuts.ts";
59 59 // ── Constants ─────────────────────────────────────────────────────────────
376 376 const tuneChecksPath = (dir: string) => path.join(stateDir(dir), "checks.mjs");
377 377 const tuneScriptPath = (dir: string) =>
378 378 path.join(stateDir(dir), "benchmark.mjs");
379 -const tuneConfigPath = (dir: string) => path.join(stateDir(dir), "config.json");
380 379 const tuneLockPath = (dir: string) => path.join(stateDir(dir), "lock.json");
382 381 interface TuneLock {
479 478 return base;
482 -function readMaxExperiments(cwd: string): number | null {
483 - try {
484 - const configPath = tuneConfigPath(cwd);
485 - if (!fs.existsSync(configPath)) return null;
486 - const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
487 - return typeof config.maxIterations === "number" && config.maxIterations > 0
488 - ? Math.floor(config.maxIterations)
489 - : null;
490 - } catch {
491 - return null;
481 +type SettingsAPI = ExtensionAPI & {
482 + settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
485 +interface TuneSettings {
486 + maxIterations: number | null;
487 + autoResumeLimit: number | null;
488 + shortcuts: TuneShortcuts;
495 -function readAutoResumeLimit(cwd: string): number | null {
496 - try {
497 - const configPath = tuneConfigPath(cwd);
498 - if (!fs.existsSync(configPath)) return null;
499 - const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
500 - return typeof config.autoResumeLimit === "number" &&
501 - Number.isFinite(config.autoResumeLimit) &&
502 - config.autoResumeLimit > 0
503 - ? Math.floor(config.autoResumeLimit)
504 - : null;
505 - } catch {
506 - return null;
491 +function positiveIntOrNull(value: unknown): number | null {
492 + return typeof value === "number" && Number.isFinite(value) && value > 0
493 + ? Math.floor(value)
494 + : null;
497 +function readTuneSettings(pi: ExtensionAPI): TuneSettings {
498 + const settings = (pi as SettingsAPI).settingsManager?.getSettings?.() ?? {};
499 + const tune =
500 + settings.tune &&
501 + typeof settings.tune === "object" &&
502 + !Array.isArray(settings.tune)
503 + ? (settings.tune as Record<string, unknown>)
504 + : {};
505 + return {
506 + maxIterations: positiveIntOrNull(tune.maxIterations),
507 + autoResumeLimit: positiveIntOrNull(tune.autoResumeLimit),
508 + shortcuts: resolveTuneShortcuts(settings),
509 + };
510 512 // ── State factories ───────────────────────────────────────────────────────
1160 1162 detectVcsKind,
1161 1163 keepVcsChanges,
1162 1164 discardVcsChanges,
1163 - readAutoResumeLimit,
1165 + readTuneSettings,
1164 1166 findBestMetric,
1165 1167 LOG_ASI_GUIDELINE,
1171 1173 const BENCHMARK_GUARDRAIL =
1172 1174 "Be careful not to overfit to the benchmarks and do not cheat on the benchmarks.";
1173 1175 const SETTLED_WINDOW_MS = 800;
1174 - const shortcuts = resolveTuneShortcuts();
1176 + const tuneSettings = (): TuneSettings => readTuneSettings(pi);
1177 + const shortcuts = tuneSettings().shortcuts;
1176 1179 const dashboardHintVariants = (
1177 1180 toggleAction: "expand" | "collapse",
1178 1181 ): string[] => {
1182 + const shortcuts = tuneSettings().shortcuts;
1179 1183 const toggle = shortcuts.toggleDashboard
1180 1184 ? `${shortcuts.toggleDashboard} ${toggleAction}`
1181 1185 : null;
1273 1277 runtime.tuneMode;
1275 1279 const reachedAutoResumeLimit = (
1276 - ctx: ExtensionContext,
1280 + _ctx: ExtensionContext,
1277 1281 runtime: TuneRuntime,
1278 1282 ): number | null => {
1279 - const limit = readAutoResumeLimit(ctx.cwd);
1283 + const limit = tuneSettings().autoResumeLimit;
1280 1284 return limit !== null && runtime.autoResumeTurns >= limit ? limit : null;
1483 - state.maxExperiments = readMaxExperiments(ctx.cwd);
1487 + state.maxExperiments = tuneSettings().maxIterations;
1484 1488 runtime.tuneMode =
1485 1489 fs.existsSync(jsonlPath) && ownsTuneLock(ctx.cwd, getSessionKey(ctx));
1486 1490 updateWidget(ctx);
1871 1875 state.bestMetric = null;
1872 1876 state.secondaryMetrics = [];
1873 1877 state.confidence = null;
1874 - state.maxExperiments = readMaxExperiments(ctx.cwd);
1878 + state.maxExperiments = tuneSettings().maxIterations;
1876 1880 // Ensure state directory exists
1877 1881 const dir = stateDir(ctx.cwd);
1925 1929 const limitNote =
1926 1930 state.maxExperiments !== null
1927 - ? `\nMax iterations: ${state.maxExperiments} (from config.json)`
1931 + ? `\nMax iterations: ${state.maxExperiments} (from settings.tune.maxIterations)`
1929 1933 return {
1930 1934 content: [

extensions/tune/shortcuts.ts

Modified
1 -/**
2 - * Keyboard shortcut configuration for tune dashboard.
3 - *
4 - * Config file: <agent-dir>/extensions/tune.json
5 - * Keys: shortcuts.toggleDashboard, shortcuts.fullscreenDashboard
6 - */
8 -import { existsSync, readFileSync } from "node:fs";
9 -import { join } from "node:path";
10 -import { getAgentDir } from "@earendil-works/pi-coding-agent";
12 -// ── Constants ─────────────────────────────────────────────────────────────
1 +/** Keyboard shortcut configuration for tune dashboard from settings.tune.shortcuts. */
14 3 export const DEFAULT_TOGGLE_DASHBOARD_SHORTCUT = "ctrl+shift+t";
15 4 export const DEFAULT_FULLSCREEN_DASHBOARD_SHORTCUT = "ctrl+shift+f";
17 -const CONFIG_FILE_NAME = "tune.json";
19 -// ── Types ─────────────────────────────────────────────────────────────────
21 6 export interface TuneShortcuts {
22 7 toggleDashboard: string | null;
23 8 fullscreenDashboard: string | null;
26 -// ── Helpers ───────────────────────────────────────────────────────────────
28 11 function isRecord(value: unknown): value is Record<string, unknown> {
29 12 return typeof value === "object" && value !== null && !Array.isArray(value);
32 -function isValidShortcutConfigValue(
33 - value: unknown,
34 -): value is string | null | undefined {
35 - return (
36 - value === undefined ||
37 - value === null ||
38 - (typeof value === "string" && value !== "")
39 - );
42 -function hasValidShortcutValues(shortcuts: Record<string, unknown>): boolean {
43 - return (
44 - isValidShortcutConfigValue(shortcuts.toggleDashboard) &&
45 - isValidShortcutConfigValue(shortcuts.fullscreenDashboard)
46 - );
49 15 function shortcutFromConfig(
50 16 configured: unknown,
51 17 fallback: string,
52 18 ): string | null {
53 19 if (configured === null) return null;
54 - return typeof configured === "string" ? configured : fallback;
20 + return typeof configured === "string" && configured !== ""
21 + ? configured
22 + : fallback;
57 -function defaultTuneShortcuts(): TuneShortcuts {
58 - return {
59 - toggleDashboard: DEFAULT_TOGGLE_DASHBOARD_SHORTCUT,
60 - fullscreenDashboard: DEFAULT_FULLSCREEN_DASHBOARD_SHORTCUT,
61 - };
64 -function warnUsingDefaults(
65 - reason: "Could not read" | "Invalid",
66 - configPath: string,
67 -): void {
68 - console.warn(
69 - `${reason} tune config at ${configPath}; using default shortcuts.`,
70 - );
73 -// ── Public API ────────────────────────────────────────────────────────────
75 -export function tuneShortcutsConfigPath(
76 - agentDir: string = getAgentDir(),
77 -): string {
78 - return join(agentDir, "extensions", CONFIG_FILE_NAME);
81 -export function resolveTuneShortcuts(
82 - configPath: string = tuneShortcutsConfigPath(),
83 -): TuneShortcuts {
84 - if (!existsSync(configPath)) return defaultTuneShortcuts();
86 - let parsed: unknown;
87 - try {
88 - parsed = JSON.parse(readFileSync(configPath, "utf-8"));
89 - } catch {
90 - warnUsingDefaults("Could not read", configPath);
91 - return defaultTuneShortcuts();
92 - }
94 - const shortcuts = isRecord(parsed) ? parsed.shortcuts : undefined;
95 - if (shortcuts === undefined) return defaultTuneShortcuts();
97 - if (!isRecord(shortcuts) || !hasValidShortcutValues(shortcuts)) {
98 - warnUsingDefaults("Invalid", configPath);
99 - return defaultTuneShortcuts();
100 - }
25 +export function resolveTuneShortcuts(settings?: unknown): TuneShortcuts {
26 + const tune =
27 + isRecord(settings) && isRecord(settings.tune) ? settings.tune : {};
28 + const shortcuts = isRecord(tune.shortcuts) ? tune.shortcuts : {};
102 29 return {
103 30 toggleDashboard: shortcutFromConfig(
104 31 shortcuts.toggleDashboard,

extensions/ultra/__tests__/settings.test.ts

Modified
1 -import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 -import { tmpdir } from "node:os";
3 -import { join } from "node:path";
4 -import { afterEach, describe, expect, it } from "vitest";
1 +import { describe, expect, it } from "vitest";
5 2 import {
6 3 loadUltraSettings,
7 4 mergeUltraSettings,
8 5 pickUltra,
9 - readUltraSettings,
10 6 ULTRA_DEFAULTS,
11 7 } from "../settings.ts";
13 -let dir: string | undefined;
14 -afterEach(() => {
15 - if (dir) rmSync(dir, { recursive: true, force: true });
16 - dir = undefined;
17 -});
19 -function tmp(): string {
20 - dir = mkdtempSync(join(tmpdir(), "ultra-settings-"));
21 - return dir;
24 -function write(file: string, json: unknown): string {
25 - writeFileSync(file, JSON.stringify(json));
26 - return file;
29 9 describe("ULTRA_DEFAULTS", () => {
30 10 it("matches the documented defaults", () => {
31 11 expect(ULTRA_DEFAULTS).toEqual({
133 -describe("readUltraSettings", () => {
134 - it("reads the `ultra` block from a JSON file", () => {
135 - const root = tmp();
136 - const f = write(join(root, "settings.json"), {
137 - ultra: { concurrency: 12 },
138 - angel: {},
139 - });
140 - expect(readUltraSettings(f)).toEqual({ concurrency: 12 });
141 - });
143 - it("returns {} for a missing file", () => {
144 - const root = tmp();
145 - expect(readUltraSettings(join(root, "nope.json"))).toEqual({});
146 - });
148 - it("returns {} for malformed JSON", () => {
149 - const root = tmp();
150 - const f = join(root, "bad.json");
151 - writeFileSync(f, "{ not json");
152 - expect(readUltraSettings(f)).toEqual({});
153 - });
154 -});
156 113 describe("loadUltraSettings", () => {
157 - it("applies precedence: defaults < earlier file < later file < runtime", () => {
158 - const root = tmp();
159 - const agent = write(join(root, "agent.json"), {
160 - ultra: { concurrency: 6, maxRetries: 9 },
161 - });
162 - const project = write(join(root, "project.json"), {
163 - ultra: { concurrency: 7 },
164 - });
165 - const workspace = write(join(root, "workspace.json"), {
166 - ultra: { concurrency: 8 },
167 - });
114 + it("uses runtime Pi settings over defaults", () => {
169 115 const merged = loadUltraSettings({
170 - files: [agent, project, workspace],
171 - runtime: { ultra: { concurrency: 10 } },
116 + runtime: { ultra: { concurrency: 10, maxRetries: 9 } },
174 119 expect(merged).toEqual({
175 120 enabled: true,
176 - concurrency: 10, // runtime wins
177 - maxRetries: 9, // only the agent file set it
178 - defaultTimeoutMs: 180000, // default
179 - subagentExtensions: "all", // default
121 + concurrency: 10,
122 + maxRetries: 9,
123 + defaultTimeoutMs: 180000,
124 + subagentExtensions: "all",
183 128 it("falls back to defaults when no source provides values", () => {
184 - expect(loadUltraSettings({ files: [] })).toEqual(ULTRA_DEFAULTS);
129 + expect(loadUltraSettings({})).toEqual(ULTRA_DEFAULTS);

extensions/ultra/index.ts

Modified
9 9 // overlay, the `onUpdate` tool surface — is exactly the part only the Task-10
10 10 // live gate can prove; the harness test asserts registration only.
12 -import path from "node:path";
13 12 import { complete } from "@earendil-works/pi-ai";
14 13 import {
15 14 createAgentSession,
57 56 // can change mid-session) always wins. The angel precedence pattern.
58 57 const settings = (): UltraSettings =>
59 58 loadUltraSettings({
60 - files: [
61 - path.join(getAgentDir(), "settings.json"),
62 - path.join(process.cwd(), ".pi", "settings.json"),
63 - path.join(process.cwd(), "settings.json"),
64 - ],
65 59 runtime: (
66 60 pi as { settingsManager?: { getSettings(): unknown } }
67 61 ).settingsManager?.getSettings(),

extensions/ultra/settings.ts

Modified
1 1 // ultra — settings (Task 9, offline-testable half).
3 -// Reads the `ultra.*` block from agent settings, workspace `.pi/settings.json`,
4 -// and workspace `settings.json`, later overriding earlier, with the runtime
5 -// `settingsManager` on top — the `angel` precedence pattern (angel/index.ts).
6 -// Pure logic + file reads only; `index.ts` supplies the real paths + runtime
7 -// settings object, so this module is unit-tested with temp files + a fake
8 -// runtime block.
10 -import { existsSync, readFileSync } from "node:fs";
3 +// Reads the `ultra.*` block from Pi settings via runtime `settingsManager`.
12 5 /** Resolved `ultra` configuration (design §Settings). */
13 6 export interface UltraSettings {
59 52 return out;
62 -/** Read the `ultra` block from one settings file; missing/malformed → `{}`. */
63 -export function readUltraSettings(file: string): Partial<UltraSettings> {
64 - try {
65 - if (!existsSync(file)) return {};
66 - return pickUltra(JSON.parse(readFileSync(file, "utf-8")));
67 - } catch {
68 - return {};
69 - }
72 55 /** Fold partial settings over the defaults; later partials win. Wrong-typed
73 56 * fields are ignored (keep the prior value). */
74 57 export function mergeUltraSettings(
97 -/** Settings sources, lowest precedence first; `runtime` is the raw
98 - * `settingsManager.getSettings()` object (highest precedence). */
80 +/** Settings source; `runtime` is the raw `settingsManager.getSettings()` object. */
99 81 export interface SettingsSources {
100 - files: string[];
101 82 runtime?: unknown;
104 -/**
105 - * Resolve effective settings: defaults < each file (in order) < runtime. The
106 - * SDK-coupled part (locating the files + the runtime settings object) lives in
107 - * `index.ts`; this stays pure for testing.
108 - */
85 +/** Resolve effective settings: defaults < runtime. */
109 86 export function loadUltraSettings(sources: SettingsSources): UltraSettings {
110 - return mergeUltraSettings(
111 - ...sources.files.map(readUltraSettings),
112 - pickUltra(sources.runtime),
113 - );
87 + return mergeUltraSettings(pickUltra(sources.runtime));

scripts/extensions.mjs

Modified
37 37 /(api[_-]?key|secret|token|password)\s*[:=]\s*['"][^'"]{12,}/i;
38 38 const SECRET_SCAN_IGNORE_KEY = "secretScanIgnore";
39 39 const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)$/;
40 +const FORBIDDEN_EXTENSION_CONFIG_PATTERNS = [
41 + {
42 + re: /(?:path\.)?join\(\s*(?:process\.cwd\(\)|\bcwd\b)\s*,\s*["']settings\.json["']\s*\)/,
43 + message:
44 + "workspace-root settings.json is not a Pi settings file; use merged Pi settings",
45 + },
46 + {
47 + re: /(?:\.pi["'][^\n]{0,80}tune[^\n]{0,80}config\.json|tuneConfigPath)/,
48 + message:
49 + "custom tune config file is forbidden; use settings.tune in Pi settings",
50 + },
51 + {
52 + re: /["']tune\.json["']/,
53 + message:
54 + "agent extension config file is forbidden; use settings.tune in Pi settings",
55 + },
56 +];
41 58 const CHANGELOG_STYLE = `Voice:
42 59 - terse, technical, human
347 364 const ignores = secretScanIgnorePaths(root);
348 365 for (const file of tsFiles(ext)) {
349 366 const text = readFileSync(file, "utf8");
367 + for (const pattern of FORBIDDEN_EXTENSION_CONFIG_PATTERNS) {
368 + if (pattern.re.test(text))
369 + err(errors, ext, `${pattern.message} in ${rel(file, ext)}`);
350 371 IMPORT_RE.lastIndex = 0;
351 372 for (const m of text.matchAll(IMPORT_RE)) {
352 373 const spec = m[1] || m[2];

scripts/test_extensions_static_check.mjs

Modified
84 +withTemp((root) => {
85 + writeExtension(
86 + root,
87 + "bad-config",
88 + { devDependencies: { [HARNESS]: "^0.6.1" } },
89 + [
90 + 'import path from "node:path";',
91 + 'const a = path.join(process.cwd(), "settings.json");',
92 + 'const b = path.join(process.cwd(), ".pi", "tune", "config.json");',
93 + 'const c = "tune.json";',
94 + "void [a, b, c];",
95 + ].join("\n"),
96 + );
97 + const errors = staticCheck(join(root, "bad-config"), { root });
98 + assert(errors.some((e) => e.includes("workspace-root settings.json")));
99 + assert(errors.some((e) => e.includes("custom tune config file")));
100 + assert(errors.some((e) => e.includes("agent extension config file")));
101 +});
84 103 withTemp((root) => {
85 104 mkdirSync(join(root, "scripts"));
86 105 writeFileSync(