/** * The generated nvim init the daemon hands to every headless instance. * * Why this exists: a spawned `nvim --headless -u ` only reaches the * daemon if the user's own config happens to load pi2.nvim and `pi.host`. With * lazy.nvim, a dev worktree behind `PI_DEV_DIR`, or a systemd unit with a frozen * `PATH`, it often does not — and the failure mode is a process that stays alive * and silent. A tiny generated init that (1) prepends the resolved plugin, (2) * keeps nvim from writing swap/shada state into the workspace and (3) `cquit 1`s * when the plugin cannot be loaded, turns that silence into a real exit code and * a log line the supervisor can read back. * * The init deliberately loads nothing else: `pi2 open` must work regardless of * the user's config, and the plugin's own `host.start()` owns the wait loop. */ import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; export const HOST_INIT_FILENAME = "host-init.lua"; /** * Written once per `(dir, pluginDir)` in the daemon's lifetime. * * Spawns are frequent (one per workspace, plus every crash/retry) while the init * only changes when the plugin directory changes, so a module-level memo keeps * the spawn path free of filesystem writes without needing a cache file. */ const written = new Map(); /** Lua double-quoted string literal: backslash, quote and control chars only. */ export function luaString(value: string): string { const escaped = value .replace(/\\/g, "\\\\") .replace(/"/g, '\\"') .replace(/\n/g, "\\n") .replace(/\r/g, "\\r") .replace(/\t/g, "\\t"); return `"${escaped}"`; } /** Pure renderer (exported so tests and diagnostics can assert the content). */ export function renderHostInit(pluginDir: string): string { return [ "-- Generated by pi2d (pi2 daemon). Do not edit: rewritten on spawn.", `-- plugin: ${pluginDir}`, "--", "-- Minimal init for a daemon-managed instance: the user config is NOT", "-- loaded, so a broken/slow/lazy config can never hide the plugin again.", "", `vim.opt.runtimepath:prepend(${luaString(pluginDir)})`, "vim.opt.swapfile = false", 'vim.opt.shadafile = "NONE"', 'vim.g.mapleader = " "', "", 'local ok, host = pcall(require, "pi.host")', "if not ok then", ' vim.api.nvim_err_writeln("pi2: " .. tostring(host))', ' vim.cmd("cquit 1")', "else", " host.start()", "end", "", ].join("\n"); } /** * Writes `/host-init.lua` for `pluginDir` and returns its absolute path. * * Atomic rename keeps a half-written init from ever reaching a concurrently * spawning nvim; comparing before writing keeps the file's mtime (and therefore * anything watching it) stable across daemon restarts. */ export async function writeHostInit(options: { dir: string; pluginDir: string }): Promise { const dir = resolve(options.dir); const pluginDir = resolve(options.pluginDir); const key = `${dir}\u0000${pluginDir}`; const cached = written.get(key); if (cached !== undefined) return cached; const content = renderHostInit(pluginDir); const path = join(dir, HOST_INIT_FILENAME); await mkdir(dir, { recursive: true, mode: 0o700 }); let existing: string | undefined; try { existing = await readFile(path, "utf8"); } catch { existing = undefined; } if (existing !== content) { const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`; try { await writeFile(tmp, content, { mode: 0o600 }); await rename(tmp, path); } catch (error) { await unlink(tmp).catch(() => undefined); throw error; } } written.set(key, path); return path; } /** Test seam: forget every memoized path. */ export function resetHostInitCache(): void { written.clear(); }