#!/usr/bin/env node /** * Rebuilds the bundle-owned config directory inside the Pi agent directory. * * Every piece of bundle-owned, rebuildable state lives under * `/my-pi/` (policy files, Tool Search config, the system prompt * cover, permission logs). `config/bundle-manifest.json` is the authoritative * source→target list: this helper builds the full tree in a sibling temp * directory, deletes any existing `my-pi/` wholesale — no backup — and renames * the fresh tree into place, so a rebuild can never half-apply. * * Nothing outside `my-pi/` is read or removed; leftovers at the old locations * are ignored rather than migrated. */ import { realpathSync } from "node:fs"; import { chmod, copyFile, lstat, mkdir, readFile, rename, rm, unlink } from "node:fs/promises"; import { dirname, isAbsolute, join, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; const scriptPath = fileURLToPath(import.meta.url); const bundleRoot = dirname(dirname(scriptPath)); export const BUNDLE_ROOT = bundleRoot; export const MANIFEST_PATH = join(bundleRoot, "config", "bundle-manifest.json"); /** Thrown for an unusable agentDir argument; maps to CLI exit code 2. */ export class RebuildUsageError extends Error {} function isObject(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } /** * Load and validate the manifest. * * Every source must be a readable repo-relative file and every target a * relative path that stays inside the bundle directory — a `..` or absolute * target would escape `my-pi/` during the rebuild, so it is rejected before * anything is touched. * * @param {string} manifestPath * @returns {Promise<{ directory: string, files: Array<{ source: string, target: string }> }>} */ export async function loadManifest(manifestPath) { let manifest; try { manifest = JSON.parse(await readFile(manifestPath, "utf8")); } catch (error) { throw new Error( `cannot read bundle manifest at ${manifestPath}: ${ error instanceof Error ? error.message : String(error) }`, ); } if (!isObject(manifest) || manifest.directory !== "my-pi" || !Array.isArray(manifest.files)) { throw new Error(`bundle manifest at ${manifestPath} is malformed`); } const files = manifest.files.map((entry, index) => { if (!isObject(entry) || typeof entry.source !== "string" || typeof entry.target !== "string") { throw new Error(`bundle manifest entry ${index} lacks source/target strings`); } const directoryBase = resolve(manifest.directory); const resolved = resolve(directoryBase, entry.target); if ( isAbsolute(entry.target) || resolved === directoryBase || !resolved.startsWith(directoryBase + sep) ) { throw new Error( `bundle manifest target ${entry.target} escapes the ${manifest.directory}/ directory`, ); } const sourcePath = join(bundleRoot, entry.source); return { source: entry.source, sourcePath, target: entry.target }; }); // Fail before deleting anything: a missing source must not wipe the live tree. for (const file of files) { try { await readFile(file.sourcePath); } catch (error) { throw new Error( `cannot read manifest source ${file.source}: ${ error instanceof Error ? error.message : String(error) }`, ); } } return { directory: manifest.directory, files }; } /** * Rebuild `/my-pi` from the bundle manifest. * * The tree is staged in `/.my-pi.rebuild--` (dirs 0700, * files 0600), then the existing `my-pi` is removed — a symlink is unlinked, * never followed — and the stage is renamed into place. Any failure removes * the stage and throws. * * @param {string} agentDir - Absolute Pi agent directory. * @param {{ manifestPath?: string }} [options] * @returns {Promise<{ targetDir: string }>} */ export async function rebuildBundleConfig(agentDir, { manifestPath = MANIFEST_PATH } = {}) { if (typeof agentDir !== "string" || agentDir.length === 0 || !isAbsolute(agentDir)) { throw new RebuildUsageError("rebuild-bundle-config requires an absolute agentDir argument"); } const manifest = await loadManifest(manifestPath); const targetDir = join(agentDir, manifest.directory); const stageDir = join( agentDir, `.${manifest.directory}.rebuild-${process.pid}-${Math.random().toString(16).slice(2)}`, ); try { await mkdir(agentDir, { recursive: true, mode: 0o700 }); await mkdir(stageDir, { mode: 0o700 }); for (const file of manifest.files) { const destination = join(stageDir, file.target); await mkdir(dirname(destination), { recursive: true, mode: 0o700 }); // copyFile keeps the source mode on some platforms; pin owner-only. await copyFile(file.sourcePath, destination); await chmod(destination, 0o600); } // Never follow a symlink: unlink the link itself, never its target. try { const stats = await lstat(targetDir); if (stats.isSymbolicLink()) { await unlink(targetDir); } else { await rm(targetDir, { recursive: true, force: true }); } } catch (error) { if (error?.code !== "ENOENT") throw error; } await rename(stageDir, targetDir); return { targetDir }; } catch (error) { await rm(stageDir, { recursive: true, force: true }).catch(() => {}); throw error; } } function isMainModule() { if (!process.argv[1]) return false; try { return fileURLToPath(import.meta.url) === realpathSync(process.argv[1]); } catch { return false; } } async function main() { const agentDir = process.argv[2] ?? ""; if (agentDir.length === 0 || !isAbsolute(agentDir)) { console.error("usage: rebuild-bundle-config.mjs "); process.exitCode = 2; return; } const { targetDir } = await rebuildBundleConfig(agentDir); process.stdout.write(`rebuilt:${targetDir}\n`); } if (isMainModule()) { main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = error instanceof RebuildUsageError ? 2 : 1; }); }