8000 Retain bounded privacy-safe server lifecycle diagnostics by rore · Pull Request #29 · rore/minimap · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion package/minimap/server.js
8000
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
} from "./src/sessions.js";
import { readServerRegistry, writeServerRegistry, deleteServerRegistry, readRuntimeIdentity } from "./src/server-registry.js";
import { matchRoute } from "./src/router.js";
import { createLifecycleLog, lifecycleError } from "./src/server-lifecycle-log.js";
import {
isTrustedLocalRequest,
lookupPalliumParticipantCounts,
Expand All @@ -50,9 +51,17 @@ export { matchRoute };

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const launchMode = process.send ? "ipc-detached-restart"
: path.basename(process.argv[1] || "") === "start-server.mjs" ? "foreground-start" : "direct";
let lifecycleLog = createLifecycleLog({ sourcePath: __filename, launchMode });
process.on("uncaughtExceptionMonitor", (error, origin) => {
try { lifecycleLog("fatal", { origin, error: lifecycleError(error, __dirname) }); } catch {}
});
process.once("exit", (code) => lifecycleLog("exit", { code }));
const staticRoot = path.join(__dirname, "ui");
const cwdFallback = process.cwd();
const requestedPort = Number(process.env.PORT || 4312);
lifecycleLog("startup", { port: Number.isInteger(requestedPort) ? requestedPort : null });
const maxPortAttempts = 20;
const LOCAL_SERVER_HOST = "127.0.0.1";
const palliumConfig = parsePalliumConfig(
Expand All @@ -62,6 +71,7 @@ const palliumConfig = parsePalliumConfig(

const runtimeIdentity = await readRuntimeIdentity(__filename);
const serverVersion = runtimeIdentity.version;
lifecycleLog = createLifecycleLog({ ...runtimeIdentity, launchMode });

// Set when /api/shutdown has been observed once; prevents a second concurrent
// caller from scheduling a duplicate shutdown() (which would race process.exit
Expand All @@ -81,7 +91,12 @@ if (process.send) {
}

async function clearOwnRegistry() {
if ((await readServerRegistry())?.pid === process.pid) await deleteServerRegistry();
try {
if ((await readServerRegistry())?.pid === process.pid) await deleteServerRegistry();
} catch (error) {
lifecycleLog("registry-cleanup-failed", { error: lifecycleError(error, __dirname) });
throw error;
}
}

const contentTypes = new Map([
Expand Down Expand Up @@ -681,9 +696,11 @@ async function startServer() {
participantMode: palliumConfig.endpoint ? "enabled" : "disabled",
participantConfigId: palliumConfigId(palliumConfig),
});
lifecycleLog("started", { port: boundPort });
process.send?.({ type: "minimap-ready", pid: process.pid, port: boundPort });
process.stdout.write(`Minimap running at http://localhost:${boundPort}${fallbackNote}\n`);
} catch (error) {
lifecycleLog("startup-failed", { error: lifecycleError(error, __dirname) });
if (error && error.code === "EADDRINUSE" && noFallback) {
// The launcher will re-probe.
throw error;
Expand All @@ -695,6 +712,7 @@ async function startServer() {
}

async function shutdown(signal) {
lifecycleLog("shutdown", { reason: signal });
try {
await clearOwnRegistry();
} catch (error) {
Expand Down
10 changes: 9 additions & 1 deletion package/minimap/skills/minimap-roadmap/references/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,20 @@ The server binds to IPv4 loopback (`127.0.0.1`) only. Every API request must com
| Command | Exit codes | What it does |
| --- | --- | --- |
| `node <skill>/scripts/start-server.mjs` | 0 = running (started or reused); 1 = incompatible/unknown API, settings mismatch, or occupied port | Probe the registry and live `/health`; reuse only a compatible API with matching participan 8000 t settings. |
| `node <skill>/scripts/status.mjs` | 0 = running; 1 = stale registry; 3 = not running | Print live pid, runtime version, API compatibility and source, plus registry port/startedAt. Legacy identity prints unknown. |
| `node <skill>/scripts/status.mjs` | 0 = running; 1 = stale registry; 3 = not running | Print live identity, registry port/startedAt, and local lifecycle log path/recent evidence, including when stale or stopped. Legacy identity prints unknown. |
| `node <skill>/scripts/stop-server.mjs` | 0 = stopped (or was already not running, or stale cleaned); 1 = shutdown failed | `POST /api/shutdown`, wait for the port to free. |
| `node <skill>/scripts/restart-server.mjs [--replace-runtime]` | 0 = restarted; 1 = refusal, stop, start, or verification failure | Preflight registered/requested targets before any stop; default permits only the same runtime. Serialize per home, then stop/spawn and verify the child-reported port/identity/configuration. Failed cleanup targets only its own child PID. |

Exit codes follow `systemctl` conventions for `status` (0/1/3 = running/stale/not-running).

## Local lifecycle diagnostics

The common server entry records startup identity (PID/parent PID, runtime source/version, port and known launch mode), graceful shutdown reasons, observed exit codes, and sanitized startup/cleanup/fatal errors under the resolved `$MINIMAP_HOME`. Foreground starts and detached restarts use the same logger. `server-lifecycle.jsonl` rotates at 128 KiB to one backup, `server-lifecycle.jsonl.1`, with a 4 KiB event limit. `status.mjs` shows the path and the last eight retained events without changing its exit codes.

These local records contain no request bodies, roadmap/spec content, environment dump, raw stderr or arbitrary error messages. Error evidence retains only recognized native class/code and up to five runtime-relative JavaScript source locations. Message detail is deliberately lost to avoid storing private content or credentials. The fatal monitor is observational: errors still terminate normally and normal stderr is unchanged. Logging I/O failure cannot block startup or shutdown.

Historical events are not proof of the current failure's cause. A verified live PID does not receive a missing-exit warning. Forced termination (including Windows hard kills/job teardown) and failures before the logger loads may leave no final event; missing exit evidence means **unknown**, not a diagnosed crash. Concurrent launch races can lose rotation evidence or briefly exceed the rotation threshold. This is bounded best-effort diagnostics, not telemetry, a watchdog, or a guarantee of recovery.

## Discovery

`start-server.mjs` reads `$MINIMAP_HOME/server.json` and probes `/health`. A compatible running API is reused even when package versions or runtime sources differ. Unknown/legacy or incompatible API identity is refused without shutdown or saved preference changes. The same checks apply to a race winner on the requested port. Both skills share one registry/server across repositories.
Expand Down
20 changes: 19 additions & 1 deletion package/minimap/skills/minimap-roadmap/runtime/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
} from "./src/sessions.js";
import { readServerRegistry, writeServerRegistry, deleteServerRegistry, readRuntimeIdentity } from "./src/server-registry.js";
import { matchRoute } from "./src/router.js";
import { createLifecycleLog, lifecycleError } from "./src/server-lifecycle-log.js";
import {
isTrustedLocalRequest,
lookupPalliumParticipantCounts,
Expand All @@ -50,9 +51,17 @@ export { matchRoute };

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const launchMode = process.send ? "ipc-detached-restart"
: path.basename(process.argv[1] || "") === "start-server.mjs" ? "foreground-start" : "direct";
let lifecycleLog = createLifecycleLog({ sourcePath: __filename, launchMode });
process.on("uncaughtExceptionMonitor", (error, origin) => {
try { lifecycleLog("fatal", { origin, error: lifecycleError(error, __dirname) }); } catch {}
});
process.once("exit", (code) => lifecycleLog("exit", { code }));
const staticRoot = path.join(__dirname, "ui");
const cwdFallback = process.cwd();
const requestedPort = Number(process.env.PORT || 4312);
lifecycleLog("startup", { port: Number.isInteger(requestedPort) ? requestedPort : null });
const maxPortAttempts = 20;
const LOCAL_SERVER_HOST = "127.0.0.1";
const palliumConfig = parsePalliumConfig(
Expand All @@ -62,6 +71,7 @@ const palliumConfig = parsePalliumConfig(

const runtimeIdentity = await readRuntimeIdentity(__filename);
const serverVersion = runtimeIdentity.version;
lifecycleLog = createLifecycleLog({ ...runtimeIdentity, launchMode });

// Set when /api/shutdown has been observed once; prevents a second concurrent
// caller from scheduling a duplicate shutdown() (which would race process.exit
Expand All @@ -81,7 +91,12 @@ if (process.send) {
}

async function clearOwnRegistry() {
if ((await readServerRegistry())?.pid === process.pid) await deleteServerRegistry();
try {
if ((await readServerRegistry())?.pid === process.pid) await deleteServerRegistry();
} catch (error) {
lifecycleLog("registry-cleanup-failed", { error: lifecycleError(error, __dirname) });
throw error;
}
}

const contentTypes = new Map([
Expand Down Expand Up @@ -681,9 +696,11 @@ async function startServer() {
participantMode: palliumConfig.endpoint ? "enabled" : "disabled",
participantConfigId: palliumConfigId(palliumConfig),
});
lifecycleLog("started", { port: boundPort });
process.send?.({ type: "minimap-ready", pid: process.pid, port: boundPort });
process.stdout.write(`Minimap running at http://localhost:${boundPort}${fallbackNote}\n`);
} catch (error) {
lifecycleLog("startup-failed", { error: lifecycleError(error, __dirname) });
if (error && error.code === "EADDRINUSE" && noFallback) {
// The launcher will re-probe.
throw error;
Expand All @@ -695,6 +712,7 @@ async function startServer() {
}

async function shutdown(signal) {
lifecycleLog("shutdown", { reason: signal });
try {
await clearOwnRegistry();
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { resolveMinimapHome } from "./sessions.js";

export const LIFECYCLE_LOG_LIMIT = 128 * 1024;
export function lifecycleLogPath(home = resolveMinimapHome()) {
return path.join(home, "server-lifecycle.jsonl");
}

// Keep only known error identifiers and runtime-owned source locations, not
// messages, function names, arbitrary stack text, or paths to reviewed files.
export function lifecycleError(error, runtimeRoot) {
try {
const classes = ["Error", "TypeError", "RangeError", "ReferenceError", "SyntaxError", "URIError", "EvalError", "AggregateError"];
const codes = ["EACCES", "EPERM", "ENOENT", "EEXIST", "ENOTDIR", "EISDIR", "ENOSPC", "EROFS", "EMFILE", "ENFILE", "EADDRINUSE", "EADDRNOTAVAIL", "EINVAL", "ERR_UNHANDLED_REJECTION", "ERR_OUT_OF_RANGE", "ERR_INVALID_ARG_VALUE", "ERR_INVALID_ARG_TYPE", "ERR_IPC_CHANNEL_CLOSED"];
const name = error?.name, code = error?.code;
const locations = [];
for (const line of String(error?.stack || "").slice(0, 8192).split("\n").slice(1, 33)) {
const match = line.match(/^\s+at (?:.* \()?((?:file:\/\/\/|[A-Za-z]:[\\/]|\/)[^()\r\n]+):(\d+):(\d+)\)?$/);
if (!match) continue;
let source;
try { source = match[1].startsWith("file:") ? fileURLToPath(match[1]) : match[1]; } catch { continue; }
const relative = path.relative(runtimeRoot, source);
if (relative.startsWith("..") || path.isAbsolute(relative) || !/^[\w./\\-]+\.m?js$/.test(relative) || !fs.existsSync(source)) continue;
locations.push(`${relative.replace(/\\/g, "/")}:${match[2]}:${match[3]}`);
if (locations.length === 5) break;
}
return {
class: classes.includes(name) ? name : "Error",
...(codes.includes(code) ? { code } : {}),
locations,
};
} catch { return { class: "Error", locations: [] }; }
}

export function createLifecycleLog({ home = resolveMinimapHome(), sourcePath, version = "unknown", launchMode = "direct" }) {
const logPath = lifecycleLogPath(home);
return (event, details = {}) => {
try {
const record = { timestamp: new Date().toISOString(), pid: process.pid, parentPid: process.ppid, sourcePath, version, launchMode, event, ...details };
const line = `${JSON.stringify(record)}\n`;
if (Buffer.byteLength(line) > 4096) return;
fs.mkdirSync(home, { recursive: true });
// ponytail: one server normally writes per home; concurrent launch races
// can lose rotation evidence. Add locking only if that evidence matters.
const size = fs.existsSync(logPath) ? fs.statSync(logPath).size : 0;
if (size + Buffer.byteLength(line) > LIFECYCLE_LOG_LIMIT) {
fs.rmSync(`${logPath}.1`, { force: true });
fs.renameSync(logPath, `${logPath}.1`);
}
fs.appendFileSync(logPath, line, { encoding: "utf8", mode: 0o600 });
} catch { /* Diagnostics must never affect lifecycle or fatal semantics. */ }
};
}

export function printLifecycleHistory(home = resolveMinimapHome(), livePid = null) {
const logPath = lifecycleLogPath(home);
process.stdout.write(` lifecycle log: ${logPath}\n`);
const events = [];
for (const file of [`${logPath}.1`, logPath]) {
let fd;
try {
fd = fs.openSync(file, "r");
const size = fs.fstatSync(fd).size;
const buffer = Buffer.alloc(Math.min(size, LIFECYCLE_LOG_LIMIT));
fs.readSync(fd, buffer, 0, buffer.length, Math.max(0, size - buffer.length));
for (const line of buffer.toString("utf8").split("\n")) {
try { const event = JSON.parse(line); if (event && Number.isSafeInteger(event.pid)) events.push(event); } catch {}
}
} catch {} finally { if (fd !== undefined) try { fs.closeSync(fd); } catch {} }
}
const recent = events.slice(-8);
process.stdout.write(" Recent lifecycle evidence (historical PIDs; not proof of the current cause):\n");
if (!recent.length) process.stdout.write(" unavailable\n");
for (const event of recent) process.stdout.write(` ${JSON.stringify(event)}\n`);
const latestStart = events.findLast((event) => ["startup", "started"].includes(event.event));
const latestIsLive = Number.isSafeInteger(livePid) && (!latestStart || latestStart.pid === livePid);
if (!latestIsLive && (!latestStart || !events.some((event) => event.event === "exit" && event.pid === latestStart.pid && event.timestamp >= latestStart.timestamp))) {
process.stdout.write(" Final exit: unknown (no recorded exit; hard kill/job teardown cannot be logged).\n");
}
}
4 changes: 4 additions & 0 deletions package/minimap/skills/minimap-roadmap/scripts/status.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
// 3 — server is not running (no registry).
import { readServerRegistry } from "../runtime/src/server-registry.js";
import { probePort } from "./health-check.mjs";
import { printLifecycleHistory } from "../runtime/src/server-lifecycle-log.js";

const entry = await readServerRegistry();
if (!entry || typeof entry.port !== "number") {
process.stdout.write("Minimap is not running.\n");
printLifecycleHistory();
process.exit(3);
}

Expand All @@ -19,6 +21,7 @@ if (!probe) {
`Minimap registry is stale: ${entry.port} (pid ${entry.pid ?? "?"}) is not responding to /health.\n`
+ `Run stop-server.mjs to clean up the stale registry.\n`,
);
printLifecycleHistory();
process.exit(1);
}

Expand All @@ -35,4 +38,5 @@ process.stdout.write(
+ ` participant links: ${probe.participantLinks || "unknown"}\n`
+ ` url: http://localhost:${entry.port}/\n`,
);
printLifecycleHistory(undefined, probe.pid);
process.exit(0);
10 changes: 9 additions & 1 deletion package/minimap/skills/minimap-spec-review/references/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,20 @@ The server binds to IPv4 loopback (`127.0.0.1`) only. Every API request must com
| Command | Exit codes | What it does |
| --- | --- | --- |
| `node <skill>/scripts/start-server.mjs` | 0 = running (started or reused); 1 = incompatible/unknown API, settings mismatch, or occupied port | Probe the registry and live `/health`; reuse only a compatible API with matching participant settings. |
| `node <skill>/scripts/status.mjs` | 0 = running; 1 = stale registry; 3 = not running | Print live pid, runtime version, API compatibility and source, plus registry port/startedAt. Legacy identity prints unknown. |
| `node <skill>/scripts/status.mjs` | 0 = running; 1 = stale registry; 3 = not running | Print live identity, registry port/startedAt, and local lifecycle log path/recent evidence, including when stale or stopped. Legacy identity prints unknown. |
| `node <skill>/scripts/stop-server.mjs` | 0 = stopped (or was already not running, or stale cleaned); 1 = shutdown failed | `POST /api/shutdown`, wait for the port to free. |
| `node <skill>/scripts/restart-server.mjs [--replace-runtime]` | 0 = restarted; 1 = refusal, stop, start, or verification failure | Preflight registered/requested targets before any stop; default permits only the same runtime. Serialize per home, then stop/spawn and verify the child-reported port/identity/configuration. Failed cleanup targets only its own child PID. |

Exit codes follow `systemctl` conventions for `status` (0/1/3 = running/stale/not-running).

## Local lifecycle diagnostics

The common server entry records startup identity (PID/parent PID, runtime source/version, port and known launch mode), graceful shutdown reasons, observed exit codes, and sanitized startup/cleanup/fatal errors under the resolved `$MINIMAP_HOME`. Foreground starts and detached restarts use the same logger. `server-lifecycle.jsonl` rotates at 128 KiB to one backup, `server-lifecycle.jsonl.1`, with a 4 KiB event limit. `status.mjs` shows the path and the last eight retained events without changing its exit codes.

These local records contain no request bodies, roadmap/spec content, environment dump, raw stderr or arbitrary error messages. Error evidence retains only recognized native class/code and up to five runtime-relative JavaScript source locations. Message detail is deliberately lost to avoid storing private content or credentials. The fatal monitor is observational: errors still terminate normally and normal stderr is unchanged. Logging I/O failure cannot block startup or shutdown.

Historical events are not proof of the current failure's cause. A verified live PID does not receive a missing-exit warning. Forced termination (including Windows hard kills/job teardown) and failures before the logger loads may leave no final event; missing exit evidence means **unknown**, not a diagnosed crash. Concurrent launch races can lose rotation evidence or briefly exceed the rotation threshold. This is bounded best-effort diagnostics, not telemetry, a watchdog, or a guarantee of recovery.

## Discovery

`start-server.mjs` reads `$MINIMAP_HOME/server.json` and probes `/health`. A compatible running API is reused even when package versions or runtime sources differ. Unknown/legacy or incompatible API identity is refused without shutdown or saved preference changes. The same checks apply to a race winner on the requested port. Both skills share one registry/server across repositories.
Expand Down
Loading
Loading
0