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 065a6d1..2c35632 100644 --- a/settings.ts +++ b/settings.ts @@ -2,11 +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. Two locations - * are searched, mirroring pi's own settings.json layout: + * arbitrary extension config, so we keep our own JSON file under pi's global + * and project config roots: * - * ~/.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`. 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) @@ -23,16 +27,24 @@ * 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 { 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(); -export const PI_PYTHON_DIR = join(homedir(), ".pi", "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. */ +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"); + return join(cwd, CONFIG_DIR_NAME, "pi-python", "settings.json"); } export interface PiPythonSettings { @@ -103,7 +115,9 @@ export interface SettingsSources { export interface ResolvedSettings { values: PiPythonSettings; sources: SettingsSources; - /** Where each settings file was looked up — for /python-status. */ + /** + * Where each settings file was looked up — for /python-status. + */ paths: { global: string; project: string | null }; /** Errors encountered while loading; surfaced in /python-status, never thrown. */ warnings: string[]; @@ -112,8 +126,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 under pi's agent config directory (best-effort, warning on failure). */ export function loadSettings(opts?: { cwd?: string; @@ -137,8 +152,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 +221,40 @@ 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, + }, warnings, }; } +/** + * 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. + */ +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(globalFile), { recursive: true }); + renameSync(legacyFile, globalFile); + warnings.push(`migrated settings: ${legacyFile} -> ${globalFile}`); + } catch (err) { + warnings.push( + `could not move ${legacyFile} to ${globalFile} ` + + `(${err instanceof Error ? err.message : String(err)}); still reading the legacy location`, + ); + } + return true; +} + function applyFile( path: string, source: "global" | "project", 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"] }