8000 Guard shared Minimap runtime reuse and replacement by rore · Pull Request #26 · 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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,14 @@ Each skill exposes the same four scripts under `scripts/`. Agents use these only
| Script | What it does |
|---|---|
| `start-server.mjs` | Start, or detect + reuse a running instance. |
| `status.mjs` | Print port/pid/version. Exit 0 running, 1 stale, 3 not running. |
| `status.mjs` | Print live runtime version/API/source and process status. Exit 0 running, 1 stale, 3 not running. |
| `stop-server.mjs` | Graceful shutdown via `POST /api/shutdown`. Cleans stale registry. |
| `restart-server.mjs` | Compose stop + start. |
| `restart-server.mjs [--replace-runtime]` | Restart the same runtime; explicitly opt in to replacing a different or unknown shared runtime. |

A single running server is shared across both skills and across any number of repos.

Start reuses compatible server APIs even across package releases; unknown/incompatible APIs are left untouched. Status shows the live runtime version, API compatibility, and canonical source path. Restart requires the same version and source path by default; coordinate before `--replace-runtime`, which interrupts shared clients and can downgrade the server. Update every relevant installed skill copy using the same copy-in method (or a checkout link); old launcher copies cannot be retroactively protected, and updating files does not itself restart the server.

## Tests

```bash
Expand Down
6 changes: 6 additions & 0 deletions package/minimap/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,12 @@ Do not assume in v1:

## Package Contents

### Shared server lifecycle

Both self-contained skills share a per-home server. Live health reports runtime package version, API compatibility integer (currently 1), canonical server source path, and PID. Start may reuse different releases only when the API is compatible and effective participant settings match; unknown/incompatible health is refused without replacing the server.

Restart preflights registered/requested targets before any shutdown. By default the live version and canonical source path must match the caller's bundled runtime, and live PID/port must match the home registry. An unregistered requested-port target requires explicit replacement even when its runtime matches. In-place development edits remain routine; different copies/checkouts require `--replace-runtime`, even at the same version. The flag explicitly allows unknown, incompatible, or older replacement and interrupts all shared clients. Restarts retain per-home serialization, bindability/IPC checks, and PID-scoped failed-child cleanup; they never sweep unrelated adjacent ports. Status prints live runtime identity, not stale registry version. Installed folders must be updated using the copy-in method or checkout links; old launchers cannot be retroactively guarded, and file updates do not replace a running server.

A copy-in minimap package should include:

- app/server files (shared by both workspaces)
Expand Down
6 changes: 3 additions & 3 deletions package/minimap/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@ Each skill exposes the same four scripts under `scripts/`. Agents use these only
| Script | What it does |
|---|---|
| `start-server.mjs` | Start, or detect + reuse a running instance. |
| `status.mjs` | Print port/pid/version. Exit 0 running, 1 stale, 3 not running. |
| `status.mjs` | Print live runtime version/API/source and process status. Exit 0 running, 1 stale, 3 not running. |
| `stop-server.mjs` | Graceful shutdown via `POST /api/shutdown`. Cleans stale registry. |
| `restart-server.mjs` | Compose stop + start. |
| `restart-server.mjs [--replace-runtime]` | Restart the same runtime; explicitly opt in to replacing a different or unknown shared runtime. |

The launcher detects an already-running instance via `$MINIMAP_HOME/server.json` and reuses it — one server serves both skills and any number of repos.
The launcher probes `$MINIMAP_HOME/server.json` and live health. Compatible APIs can reuse different releases; unknown/incompatible runtimes remain untouched. Status prints live version/API/source. Routine restart requires the same version and canonical runtime source path; coordinate shared-client impact before `--replace-runtime`, which can replace or downgrade a different/unknown server. No adjacent-port sweep is performed. Update relevant installed skill copies via the existing copy-in method or checkout links; old launchers cannot be retroactively guarded. File updates alone do not replace a running server.

Optional roadmap Participants lookup is configured separately from agent MCP availability. Validated loopback `MINIMAP_PALLIUM_ENDPOINT` and optional `MINIMAP_PALLIUM_DASHBOARD_ENDPOINT` values supplied to a successful start or restart command are remembered locally; an explicit empty dashboard value disables links while retaining lookup, and an explicit empty lookup value clears both. Reuse verifies the exact effective settings, and `status.mjs` reports lookup and link state without exposing either origin.

Expand Down
8 changes: 4 additions & 4 deletions package/minimap/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
updateFileSessionSuggestionStatus,
updateFileSessionCommentStatus,
} from "./src/sessions.js";
import { readServerRegistry, writeServerRegistry, deleteServerRegistry } from "./src/server-registry.js";
import { readServerRegistry, writeServerRegistry, deleteServerRegistry, readRuntimeIdentity } from "./src/server-registry.js";
import { matchRoute } from "./src/router.js";
import {
isTrustedLocalRequest,
Expand Down Expand Up @@ -60,8 +60,8 @@ const palliumConfig = parsePalliumConfig(
process.env.MINIMAP_PALLIUM_DASHBOARD_ENDPOINT,
);

const packageJsonPath = path.join(__dirname, "package.json");
const serverVersion = JSON.parse(await fs.readFile(packageJsonPath, "utf8")).version || "0.0.0";
const runtimeIdentity = await readRuntimeIdentity(__filename);
const serverVersion = runtimeIdentity.version;

// Set when /api/shutdown has been observed once; prevents a second concurrent
// caller from scheduling a duplicate shutdown() (which would race process.exit
Expand Down Expand Up @@ -220,7 +220,7 @@ async function buildSpecSessionsByItemId(repoRoot, workspace) {
// ---------------------------------------------------------------------------

async function handleHealth(request, response) {
sendJson(response, 200, { ok: true, participants: {
sendJson(response, 200, { ok: true, runtime: runtimeIdentity, pid: process.pid, participants: {
mode: palliumConfig.endpoint ? "enabled" : "disabled",
links: palliumConfig.dashboardEndpoint ? "enabled" : "disabled",
configId: palliumConfigId(palliumConfig),
Expand Down
2 changes: 2 additions & 0 deletions package/minimap/skills/minimap-roadmap/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ The launcher prints one line: `Minimap running at http://localhost:<port>` (just

For status / stop / restart, see [references/server.md](references/server.md).

Compatible APIs can reuse different releases. A refused start/restart is not permission to stop the shared server: inspect running/source identity and coordinate before explicitly replacing it with `restart-server.mjs --replace-runtime`.

### 2a. Showing the roadmap

Build the URL with the active repo's absolute path and reply with it:
Expand Down
18 changes: 14 additions & 4 deletions package/minimap/skills/minimap-roadmap/references/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,26 @@ 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 already up); 1 = port held by non-minimap process | Probe `$MINIMAP_HOME/server.json`, validate `/health`, reuse if alive; otherwise bind. |
| `node <skill>/scripts/status.mjs` | 0 = running; 1 = stale registry; 3 = not running | Print port, pid, version, startedAt. |
| `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/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` | 0 = restarted; 1 = stop, start, or verification failed | Serialize restarts per Minimap home, recover a crashed launcher lock, then stop and spawn. Verify the child-reported port via `/health`; on failure, shut down only that child by PID without deleting another server's registry. |
| `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).

## Discovery

`start-server.mjs` reads `$MINIMAP_HOME/server.json` and probes `/health`. If a minimap is already running, the launcher exits without spawning a second one. Both `minimap-roadmap` and `minimap-spec-review` use the same registry, so one running server transparently serves both modes.
`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.

## Shared runtime replacement

Health reports `runtime: { version, apiCompatibility, sourcePath }` and live `pid`. API compatibility is integer 1; it changes only for incompatible server API changes, independently of package release versions.

Routine restart requires both the running version and canonical real server source path to match this launcher's bundled runtime, and the live PID/port to match this home's registry. An unregistered requested-port server requires explicit replacement even with matching runtime identity: the same copy can serve another home. Version alone cannot distinguish development checkouts or installed copies. Editing code in place at the same path/version remains routine; this is location identity, not content attestation. Separate copies require explicit replacement even when their bytes match.

If restart refuses, inspect its running/requested version and source, coordinate with anyone using the shared board/spec server, then use `node <skill>/scripts/restart-server.mjs --replace-runtime` only when replacement is intended. This flag allows a different, incompatible, older, or unknown runtime to be replaced; it is not an automatic upgrade and interrupts all clients of that server. Explicit `stop-server.mjs` remains an intentional shared shutdown, not a version upgrade shortcut.

Restart checks every registered/requested target before any shutdown, does not sweep unrelated adjacent ports, and sends the live PID guard when available. Legacy servers cannot offer the new ownership guarantees. Update each relevant installed skill folder using the existing copy-in installation method (or its checkout link); old launcher copies cannot be retroactively protected. Updating files alone does not replace a running server.

## Multi-repo

Expand Down
8 changes: 4 additions & 4 deletions package/minimap/skills/minimap-roadmap/runtime/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
updateFileSessionSuggestionStatus,
updateFileSessionCommentStatus,
} from "./src/sessions.js";
import { readServerRegistry, writeServerRegistry, deleteServerRegistry } from "./src/server-registry.js";
import { readServerRegistry, writeServerRegistry, deleteServerRegistry, readRuntimeIdentity } from "./src/server-registry.js";
import { matchRoute } from "./src/router.js";
import {
isTrustedLocalRequest,
Expand Down Expand Up @@ -60,8 +60,8 @@ const palliumConfig = parsePalliumConfig(
process.env.MINIMAP_PALLIUM_DASHBOARD_ENDPOINT,
);

const packageJsonPath = path.join(__dirname, "package.json");
const serverVersion = JSON.parse(await fs.readFile(packageJsonPath, "utf8")).version || "0.0.0";
const runtimeIdentity = await readRuntimeIdentity(__filename);
const serverVersion = runtimeIdentity.version;

// Set when /api/shutdown has been observed once; prevents a second concurrent
// caller from scheduling a duplicate shutdown() (which would race process.exit
Expand Down Expand Up @@ -220,7 +220,7 @@ async function buildSpecSessionsByItemId(repoRoot, workspace) {
// ---------------------------------------------------------------------------

async function handleHealth(request, response) {
sendJson(response, 200, { ok: true, participants: {
sendJson(response, 200, { ok: true, runtime: runtimeIdentity, pid: process.pid, participants: {
mode: palliumConfig.endpoint ? "enabled" : "disabled",
links: palliumConfig.dashboardEndpoint ? "enabled" : "disabled",
configId: palliumConfigId(palliumConfig),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ import { resolveMinimapHome } from "./sessions.js";
const REGISTRY_FILE = "server.json";
const PREFERENCE_FILE = "pallium-preference.json";

// Bump only when the shared server API becomes incompatible with these clients.
export const SERVER_API_COMPATIBILITY = 1;

export async function readRuntimeIdentity(serverPath) {
const sourcePath = await fs.realpath(serverPath);
const pkg = JSON.parse(await fs.readFile(path.join(path.dirname(sourcePath), "package.json"), "utf8"));
return { version: pkg.version || "0.0.0", apiCompatibility: SERVER_API_COMPATIBILITY, sourcePath };
}

export function registryPath(minimapHome) {
return path.join(minimapHome, REGISTRY_FILE);
}
Expand Down
29 changes: 28 additions & 1 deletion package/minimap/skills/minimap-roadmap/scripts/health-check.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,28 @@
import { readServerRegistry } from "../runtime/src/server-registry.js";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { readServerRegistry, readRuntimeIdentity, SERVER_API_COMPATIBILITY } from "../runtime/src/server-registry.js";

export const localRuntime = await readRuntimeIdentity(fileURLToPath(new URL("../runtime/server.js", import.meta.url)));

export function isCompatibleRuntime(server) {
const runtime = server?.runtime;
return runtime?.apiCompatibility === SERVER_API_COMPATIBILITY
&& typeof runtime.version === "string" && runtime.version.length > 0
&& typeof runtime.sourcePath === "string" && path.isAbsolute(runtime.sourcePath);
}

export function isSameRuntime(server) {
const normalize = (value) => process.platform === "win32" ? path.normalize(value).toLowerCase() : path.normalize(value);
return isCompatibleRuntime(server) && server.runtime.version === localRuntime.version
&& normalize(server.runtime.sourcePath) === normalize(localRuntime.sourcePath);
}

export function replacementGuidance(server) {
const runtime = server?.runtime;
return `Running Minimap: version ${runtime?.version || "unknown"}, API ${runtime?.apiCompatibility ?? "unknown"}, source ${runtime?.sourcePath || "unknown"}.\n`
+ `Requested runtime: version ${localRuntime.version}, API ${localRuntime.apiCompatibility}, source ${localRuntime.sourcePath}.\n`
+ "This server is shared by roadmap/spec-review and other repositories. Replacement interrupts their sessions and may downgrade the runtime. Coordinate first, then run restart-server.mjs --replace-runtime to explicitly replace it.\n";
}

const HEALTH_TIMEOUT_MS = 1500;

Expand All @@ -18,6 +42,9 @@ export async function probePort(port, entry = null) {
if (!payload || payload.ok !== true) return null; 8
return {
...(entry || { port }),
// Never substitute stale registry identity for absent live health fields.
runtime: payload.runtime || null,
pid: Number.isSafeInteger(payload.pid) && payload.pid > 0 ? payload.pid : null,
participantMode: payload.participants?.mode || null,
participantLinks: payload.participants?.links || null,
participantConfigId: payload.participants?.configId || null,
Expand Down
Loading
Loading
0