From a28f892b71e90155e111f682272cef0d639b4f99 Mon Sep 17 00:00:00 2001 From: Oluf Lorenzen Date: Sun, 20 Sep 2026 00:47:17 +0200 Subject: [PATCH 1/2] feat!: move global settings to $PI_CODING_AGENT_DIR/extensions Store the global pi-python settings.json next to pi's other user extensions instead of ~/.pi/pi-python/settings.json: $PI_CODING_AGENT_DIR/extensions/pi-python/settings.json Resolve the agent dir via pi's own getAgentDir(), which honours PI_CODING_AGENT_DIR and defaults to ~/.pi/agent. Migrate the pre-extensions location once, on load: if the legacy file exists and the new one does not, create the parent directories and move it. The move is best-effort - failure surfaces as a /python-status warning and the legacy file is still read. The project file (/.pi/pi-python/settings.json) is unchanged. --- settings.ts | 80 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 68 insertions(+), 12 deletions(-) diff --git a/settings.ts b/settings.ts index 065a6d1..a37cfa8 100644 --- a/settings.ts +++ b/settings.ts @@ -2,11 +2,16 @@ * pi-python settings. * * pi's built-in `Settings` schema is strongly typed and has no slot for - * arbitrary extension config, so we keep our own JSON file. Two locations - * are searched, mirroring pi's own settings.json layout: + * arbitrary extension config, so we keep our own JSON file. The global file + * lives next to pi's other user extensions, the project file mirrors pi's + * project layout: * - * ~/.pi/pi-python/settings.json (global) - * /.pi/pi-python/settings.json (project, overrides global) + * ${PI_CODING_AGENT_DIR}/extensions/pi-python/settings.json (global) + * /.pi/pi-python/settings.json (project, overrides global) + * + * `PI_CODING_AGENT_DIR` defaults to `~/.pi/agent` when unset. The pre- + * `extensions/` location (`~/.pi/pi-python/settings.json`) is migrated once, + * on load, when it exists and the new file does not. * * Both files are optional. Missing fields fall back to the lower-precedence * source. Malformed JSON is ignored (a warning surfaces in /python-status) @@ -23,13 +28,21 @@ * kernel spawn without restarting pi. */ -import { existsSync, readFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs"; import { homedir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; +import { getAgentDir } from "@earendil-works/pi-coding-agent"; + +/** Agent config dir — respects PI_CODING_AGENT_DIR, defaults to ~/.pi/agent. */ +export const AGENT_DIR = getAgentDir(); -export const PI_PYTHON_DIR = join(homedir(), ".pi", "pi-python"); +/** Global settings live alongside the installed pi-python extension. */ +export const PI_PYTHON_DIR = join(AGENT_DIR, "extensions", "pi-python"); export const GLOBAL_SETTINGS_FILE = join(PI_PYTHON_DIR, "settings.json"); +/** Pre-`extensions/` location, moved to GLOBAL_SETTINGS_FILE on first load. */ +export const LEGACY_GLOBAL_SETTINGS_FILE = join(homedir(), ".pi", "pi-python", "settings.json"); + /** Where the project settings file lives, given a working directory. */ export function projectSettingsFileFor(cwd: string): string { return join(cwd, ".pi", "pi-python", "settings.json"); @@ -103,8 +116,12 @@ export interface SettingsSources { export interface ResolvedSettings { values: PiPythonSettings; sources: SettingsSources; - /** Where each settings file was looked up — for /python-status. */ - paths: { global: string; project: string | null }; + /** + * Where each settings file was looked up — for /python-status. `legacy` + * is only present once the old location has been migrated (or failed to + * migrate) so status can explain the transition. + */ + paths: { global: string; project: string | null; legacy?: string | null }; /** Errors encountered while loading; surfaced in /python-status, never thrown. */ warnings: string[]; } @@ -112,8 +129,9 @@ export interface ResolvedSettings { /** * Resolve effective settings from JSON files + environment variables. * - * Pure: no caching, safe to call repeatedly. Cost is two stats + up to two - * parses. + * No caching, safe to call repeatedly. Cost is two stats + up to two parses. + * Side effect: the first call after an upgrade may move the legacy global + * file into the extensions directory (best-effort, warning on failure). */ export function loadSettings(opts?: { cwd?: string; @@ -137,8 +155,18 @@ export function loadSettings(opts?: { const warnings: string[] = []; const projectFile = cwd ? projectSettingsFileFor(cwd) : null; + // One-shot move of the pre-`extensions/` global file, so existing users + // keep their config without an ongoing legacy read path. + const legacyPresent = migrateLegacyGlobalSettings(warnings); + // Apply files in precedence order: global first (so project can override). applyFile(GLOBAL_SETTINGS_FILE, "global", values, sources, warnings); + // Only if the migration above could not run (rename failed): the legacy + // file is still the effective global config. + const legacyUsed = legacyPresent && !existsSync(GLOBAL_SETTINGS_FILE); + if (legacyUsed) { + applyFile(LEGACY_GLOBAL_SETTINGS_FILE, "global", values, sources, warnings); + } if (projectFile) applyFile(projectFile, "project", values, sources, warnings); // Env var beats files. @@ -196,11 +224,39 @@ export function loadSettings(opts?: { return { values, sources, - paths: { global: GLOBAL_SETTINGS_FILE, project: projectFile }, + paths: { + // Point /python-status at whichever file is actually effective. + global: legacyUsed ? LEGACY_GLOBAL_SETTINGS_FILE : GLOBAL_SETTINGS_FILE, + project: projectFile, + legacy: legacyPresent ? LEGACY_GLOBAL_SETTINGS_FILE : null, + }, warnings, }; } +/** + * Move ~/.pi/pi-python/settings.json into the extensions directory when the + * old file exists and the new one does not. Best-effort: any failure is a + * warning, never fatal. Returns whether the legacy file was present. + */ +function migrateLegacyGlobalSettings(warnings: string[]): boolean { + if (!existsSync(LEGACY_GLOBAL_SETTINGS_FILE)) return false; + if (existsSync(GLOBAL_SETTINGS_FILE)) return true; + try { + mkdirSync(dirname(GLOBAL_SETTINGS_FILE), { recursive: true }); + renameSync(LEGACY_GLOBAL_SETTINGS_FILE, GLOBAL_SETTINGS_FILE); + warnings.push( + `migrated settings: ${LEGACY_GLOBAL_SETTINGS_FILE} -> ${GLOBAL_SETTINGS_FILE}`, + ); + } catch (err) { + warnings.push( + `could not move ${LEGACY_GLOBAL_SETTINGS_FILE} to ${GLOBAL_SETTINGS_FILE} ` + + `(${err instanceof Error ? err.message : String(err)}); still reading the legacy location`, + ); + } + return true; +} + function applyFile( path: string, source: "global" | "project", From 6ec9020addd75c1033d18f3b1010949ea8f6cdb5 Mon Sep 17 00:00:00 2001 From: Simon Brakhane Date: Sun, 20 Sep 2026 08:09:06 +0200 Subject: [PATCH 2/2] fix: keep global settings outside extension source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The proposed path under $PI_CODING_AGENT_DIR/extensions/pi-python can be the extension itself: local installations commonly put a symlink there. Migrating settings into that directory would write user configuration into the source checkout, dirtying it and risking deletion on package updates. Keep the useful part of the change — honoring pi's agent directory — but store configuration at $PI_CODING_AGENT_DIR/pi-python/settings.json. Use CONFIG_DIR_NAME for the project path as pi's extension API requires, and retain best-effort migration from the historical ~/.pi location. Add cross-runtime tests for path resolution, migration, precedence, and the case where both old and new files exist. --- README.md | 10 ++++- package.json | 4 +- settings.ts | 56 +++++++++++++-------------- test-settings.ts | 98 ++++++++++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 2 +- 5 files changed, 136 insertions(+), 34 deletions(-) create mode 100644 test-settings.ts diff --git a/README.md b/README.md index 81a78aa..d1d486b 100644 --- a/README.md +++ b/README.md @@ -150,10 +150,16 @@ later cell times out. Optional settings are read from: ```text -~/.pi/pi-python/settings.json # global -/.pi/pi-python/settings.json # project, overrides global +${PI_CODING_AGENT_DIR}/pi-python/settings.json # global +/${CONFIG_DIR_NAME}/pi-python/settings.json # project, overrides global ``` +`PI_CODING_AGENT_DIR` defaults to `~/.pi/agent`; `CONFIG_DIR_NAME` defaults to +`.pi`. On upgrade, an existing `~/.pi/pi-python/settings.json` is moved to the +new global location when that location does not already exist. Migration failure +is non-fatal: the old file remains effective and `/python-status` reports a +warning. + Environment variables override project settings, which override global settings, which override built-in defaults. diff --git a/package.json b/package.json index 47dc763..a01033d 100644 --- a/package.json +++ b/package.json @@ -43,8 +43,8 @@ }, "scripts": { "check": "tsc --noEmit", - "test": "node --no-warnings test-interrupt.ts", - "test:bun": "bun test-interrupt.ts" + "test": "node --no-warnings test-settings.ts && node --no-warnings test-interrupt.ts", + "test:bun": "bun test-settings.ts && bun test-interrupt.ts" }, "peerDependencies": { "@earendil-works/pi-coding-agent": "*", diff --git a/settings.ts b/settings.ts index a37cfa8..2c35632 100644 --- a/settings.ts +++ b/settings.ts @@ -2,16 +2,15 @@ * pi-python settings. * * pi's built-in `Settings` schema is strongly typed and has no slot for - * arbitrary extension config, so we keep our own JSON file. The global file - * lives next to pi's other user extensions, the project file mirrors pi's - * project layout: + * arbitrary extension config, so we keep our own JSON file under pi's global + * and project config roots: * - * ${PI_CODING_AGENT_DIR}/extensions/pi-python/settings.json (global) - * /.pi/pi-python/settings.json (project, overrides global) + * ${PI_CODING_AGENT_DIR}/pi-python/settings.json (global) + * /${CONFIG_DIR_NAME}/pi-python/settings.json (project, overrides global) * - * `PI_CODING_AGENT_DIR` defaults to `~/.pi/agent` when unset. The pre- - * `extensions/` location (`~/.pi/pi-python/settings.json`) is migrated once, - * on load, when it exists and the new file does not. + * `PI_CODING_AGENT_DIR` defaults to `~/.pi/agent`; `CONFIG_DIR_NAME` defaults + * to `.pi`. The old global location (`~/.pi/pi-python/settings.json`) is + * migrated once, on load, when it exists and the new file does not. * * Both files are optional. Missing fields fall back to the lower-precedence * source. Malformed JSON is ignored (a warning surfaces in /python-status) @@ -31,13 +30,13 @@ import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; -import { getAgentDir } from "@earendil-works/pi-coding-agent"; +import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent"; /** Agent config dir — respects PI_CODING_AGENT_DIR, defaults to ~/.pi/agent. */ export const AGENT_DIR = getAgentDir(); -/** Global settings live alongside the installed pi-python extension. */ -export const PI_PYTHON_DIR = join(AGENT_DIR, "extensions", "pi-python"); +/** Global settings live under pi's config root, never inside extension code. */ +export const PI_PYTHON_DIR = join(AGENT_DIR, "pi-python"); export const GLOBAL_SETTINGS_FILE = join(PI_PYTHON_DIR, "settings.json"); /** Pre-`extensions/` location, moved to GLOBAL_SETTINGS_FILE on first load. */ @@ -45,7 +44,7 @@ export const LEGACY_GLOBAL_SETTINGS_FILE = join(homedir(), ".pi", "pi-python", " /** Where the project settings file lives, given a working directory. */ export function projectSettingsFileFor(cwd: string): string { - return join(cwd, ".pi", "pi-python", "settings.json"); + return join(cwd, CONFIG_DIR_NAME, "pi-python", "settings.json"); } export interface PiPythonSettings { @@ -117,11 +116,9 @@ export interface ResolvedSettings { values: PiPythonSettings; sources: SettingsSources; /** - * Where each settings file was looked up — for /python-status. `legacy` - * is only present once the old location has been migrated (or failed to - * migrate) so status can explain the transition. + * Where each settings file was looked up — for /python-status. */ - paths: { global: string; project: string | null; legacy?: string | null }; + paths: { global: string; project: string | null }; /** Errors encountered while loading; surfaced in /python-status, never thrown. */ warnings: string[]; } @@ -131,7 +128,7 @@ export interface ResolvedSettings { * * No caching, safe to call repeatedly. Cost is two stats + up to two parses. * Side effect: the first call after an upgrade may move the legacy global - * file into the extensions directory (best-effort, warning on failure). + * file under pi's agent config directory (best-effort, warning on failure). */ export function loadSettings(opts?: { cwd?: string; @@ -228,29 +225,30 @@ export function loadSettings(opts?: { // Point /python-status at whichever file is actually effective. global: legacyUsed ? LEGACY_GLOBAL_SETTINGS_FILE : GLOBAL_SETTINGS_FILE, project: projectFile, - legacy: legacyPresent ? LEGACY_GLOBAL_SETTINGS_FILE : null, }, warnings, }; } /** - * Move ~/.pi/pi-python/settings.json into the extensions directory when the - * old file exists and the new one does not. Best-effort: any failure is a + * Move ~/.pi/pi-python/settings.json under pi's agent config directory when + * the old file exists and the new one does not. Best-effort: any failure is a * warning, never fatal. Returns whether the legacy file was present. */ -function migrateLegacyGlobalSettings(warnings: string[]): boolean { - if (!existsSync(LEGACY_GLOBAL_SETTINGS_FILE)) return false; - if (existsSync(GLOBAL_SETTINGS_FILE)) return true; +export function migrateLegacyGlobalSettings( + warnings: string[], + legacyFile = LEGACY_GLOBAL_SETTINGS_FILE, + globalFile = GLOBAL_SETTINGS_FILE, +): boolean { + if (!existsSync(legacyFile)) return false; + if (existsSync(globalFile)) return true; try { - mkdirSync(dirname(GLOBAL_SETTINGS_FILE), { recursive: true }); - renameSync(LEGACY_GLOBAL_SETTINGS_FILE, GLOBAL_SETTINGS_FILE); - warnings.push( - `migrated settings: ${LEGACY_GLOBAL_SETTINGS_FILE} -> ${GLOBAL_SETTINGS_FILE}`, - ); + mkdirSync(dirname(globalFile), { recursive: true }); + renameSync(legacyFile, globalFile); + warnings.push(`migrated settings: ${legacyFile} -> ${globalFile}`); } catch (err) { warnings.push( - `could not move ${LEGACY_GLOBAL_SETTINGS_FILE} to ${GLOBAL_SETTINGS_FILE} ` + + `could not move ${legacyFile} to ${globalFile} ` + `(${err instanceof Error ? err.message : String(err)}); still reading the legacy location`, ); } diff --git a/test-settings.ts b/test-settings.ts new file mode 100644 index 0000000..f0cd1e3 --- /dev/null +++ b/test-settings.ts @@ -0,0 +1,98 @@ +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { mkdtempSync } from "node:fs"; + +let passed = 0; +let failed = 0; + +function check(condition: boolean, label: string): void { + if (condition) { + passed++; + console.log(` ✓ ${label}`); + } else { + failed++; + console.log(` ✗ ${label}`); + } +} + +const root = mkdtempSync(join(tmpdir(), "pi-python-settings-")); +const home = join(root, "home"); +const agentDir = join(root, "agent"); +const cwd = join(root, "project"); +mkdirSync(home, { recursive: true }); +mkdirSync(cwd, { recursive: true }); + +const previous = { + HOME: process.env.HOME, + USERPROFILE: process.env.USERPROFILE, + PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR, +}; +process.env.HOME = home; +process.env.USERPROFILE = home; +process.env.PI_CODING_AGENT_DIR = agentDir; + +try { + // Import only after setting the environment: settings.ts resolves its global + // paths once at module load, exactly as it does when pi starts. + const settings = await import(`./settings.ts?test=${Date.now()}`); + const legacy = join(home, ".pi", "pi-python", "settings.json"); + const global = join(agentDir, "pi-python", "settings.json"); + const extensionTree = join(agentDir, "extensions", "pi-python", "settings.json"); + + console.log("\n[1] paths follow pi's config roots"); + check(settings.GLOBAL_SETTINGS_FILE === global, "global path uses PI_CODING_AGENT_DIR"); + check( + settings.projectSettingsFileFor(cwd) === join(cwd, ".pi", "pi-python", "settings.json"), + "project path uses CONFIG_DIR_NAME", + ); + check(settings.GLOBAL_SETTINGS_FILE !== extensionTree, "settings never live inside extension code"); + + console.log("\n[2] legacy global settings migrate once"); + mkdirSync(join(home, ".pi", "pi-python"), { recursive: true }); + writeFileSync(legacy, JSON.stringify({ maxTimeoutSeconds: 17 })); + const migrationWarnings: string[] = []; + settings.migrateLegacyGlobalSettings(migrationWarnings, legacy, global); + const migrated = settings.loadSettings({ cwd, env: {} }); + check(!existsSync(legacy), "legacy file was moved"); + check(existsSync(global), "new global file exists"); + check(migrated.values.maxTimeoutSeconds === 17, "migrated value is active"); + check(migrated.sources.maxTimeoutSeconds === "global", "migrated value reports global source"); + check( + migrationWarnings.some((warning: string) => warning.includes("migrated settings")), + "migration is reported", + ); + + console.log("\n[3] project and environment precedence stay intact"); + const project = settings.projectSettingsFileFor(cwd); + mkdirSync(join(cwd, ".pi", "pi-python"), { recursive: true }); + writeFileSync(project, JSON.stringify({ maxTimeoutSeconds: 23 })); + const projectResult = settings.loadSettings({ cwd, env: {} }); + check(projectResult.values.maxTimeoutSeconds === 23, "project overrides global"); + check(projectResult.sources.maxTimeoutSeconds === "project", "project source is reported"); + const envResult = settings.loadSettings({ + cwd, + env: { PI_PYTHON_MAX_TIMEOUT_SECONDS: "31" }, + }); + check(envResult.values.maxTimeoutSeconds === 31, "environment overrides project"); + check(envResult.sources.maxTimeoutSeconds === "env", "environment source is reported"); + + console.log("\n[4] an existing new file is never overwritten"); + writeFileSync(global, JSON.stringify({ maxTimeoutSeconds: 41 })); + mkdirSync(join(home, ".pi", "pi-python"), { recursive: true }); + writeFileSync(legacy, JSON.stringify({ maxTimeoutSeconds: 99 })); + settings.migrateLegacyGlobalSettings([], legacy, global); + const existing = settings.loadSettings({ cwd: undefined, env: {} }); + check(existing.values.maxTimeoutSeconds === 41, "new global file wins"); + check(existsSync(legacy), "legacy file remains when destination already exists"); + check(JSON.parse(readFileSync(global, "utf8")).maxTimeoutSeconds === 41, "destination was not modified"); +} finally { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(root, { recursive: true, force: true }); +} + +console.log(`\n══ ${passed} passed · ${failed} failed ══`); +if (failed > 0) process.exit(1); diff --git a/tsconfig.json b/tsconfig.json index 268dc51..5ffe9f6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,5 +11,5 @@ "noEmit": true, "types": ["node"] }, - "include": ["index.ts", "kernel.ts", "settings.ts", "test-interrupt.ts"] + "include": ["index.ts", "kernel.ts", "settings.ts", "test-interrupt.ts", "test-settings.ts"] }