@nice-code/commander 0.94.0 → 0.96.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"file":"main-B7EwREFQ.cjs","names":["sep","loadCommanderConfigFile","validateCommanderConfig","RuntimeCoordinate","orderByDependency","createPortInspector","ActionRuntime","createRealmServerEngine","commanderStatusRealm","serveChannel","commanderChannel","createMemoryStorageAdapter_json","wsAcceptorCarrier","httpAcceptorCarrier","commanderControlDomain","withDependencies","createRealmAcceptor","createDefaultServeLogger","parseLogsClientMessage","overrideFingerprint","effectiveEnv","withDependencies","envVarViews","commanderStatePaths","readInstanceRecord","recordDaemonAlive","commanderRuntimeError","resolveCommanderDataDir","loadCommanderConfigFile","validateCommanderConfig","ensureStateDir","readEnvOverrides","applyEnvMutation","countOverrides","WebSocketServer","COMMANDER_TICKET_PROTOCOL_PREFIX","ws","writeInstanceRecord","commanderPackageVersion","commanderStatusRealm","removeInstanceRecord"],"sources":["../src/daemon/rotatingLog.ts","../src/daemon/aggregateSink.ts","../../nice-local-http-shared/src/index.ts","../src/daemon/auth.ts","../src/daemon/configWatch.ts","../src/daemon/controlPlane.ts","../src/daemon/history.ts","../src/daemon/logsEndpoint.ts","../src/daemon/staticFiles.ts","../src/daemon/supervisor.ts","../src/daemon/main.ts"],"sourcesContent":["// Rotated line log, owned INSIDE the process (an inherited forever-open redirected fd cannot\n// rotate correctly on Windows — the plan's daemon-log note). Size-based segment roll with a\n// bounded total, so crash forensics never become the leak. Synchronous appends: volume is low\n// (daemon events, one aggregate line per process line) and a sync write can't interleave.\n\nimport {\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n renameSync,\n statSync,\n writeSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport interface IRotatingLogOptions {\n /** Roll the current segment when it exceeds this many bytes. Default 1_000_000. */\n segmentBytes?: number;\n /** Total segments retained including the current one. Default 5. */\n keepSegments?: number;\n}\n\nexport class RotatingLog {\n private readonly _path: string;\n private readonly _segmentBytes: number;\n private readonly _keepSegments: number;\n private _fd: number | null = null;\n private _bytes = 0;\n\n constructor(dir: string, basename: string, options: IRotatingLogOptions = {}) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n this._path = join(dir, `${basename}.log`);\n this._segmentBytes = options.segmentBytes ?? 1_000_000;\n this._keepSegments = options.keepSegments ?? 5;\n }\n\n get path(): string {\n return this._path;\n }\n\n /** Existing segments, NEWEST first (`x.log`, `x.log.1`, …) — the order a reader wants. */\n segments(): string[] {\n const paths: string[] = [];\n for (let index = 0; index < this._keepSegments; index += 1) {\n const path = index === 0 ? this._path : `${this._path}.${index}`;\n if (existsSync(path)) paths.push(path);\n }\n return paths;\n }\n\n write(line: string): void {\n try {\n if (this._fd == null) this._open();\n const data = line.endsWith(\"\\n\") ? line : `${line}\\n`;\n if (this._bytes + data.length > this._segmentBytes && this._bytes > 0) this._roll();\n writeSync(this._fd as number, data);\n this._bytes += data.length;\n } catch {\n // A log that cannot write must never take the daemon down with it.\n }\n }\n\n close(): void {\n if (this._fd == null) return;\n try {\n closeSync(this._fd);\n } catch {\n // already closed\n }\n this._fd = null;\n this._bytes = 0;\n }\n\n private _open(): void {\n this._fd = openSync(this._path, \"a\", 0o600);\n this._bytes = statSync(this._path).size;\n }\n\n private _roll(): void {\n this.close();\n for (let index = this._keepSegments - 1; index >= 1; index -= 1) {\n const from = index === 1 ? this._path : `${this._path}.${index - 1}`;\n const to = `${this._path}.${index}`;\n if (existsSync(from)) renameSync(from, to);\n }\n this._open();\n }\n}\n","// The supervisor's aggregate log sink: every line from every process, stamped with\n// `(generation, ingestSeq)` — the deterministic merged-timeline ordering key (R5 consumes it).\n// ingestSeq persists as a high-water mark so a new daemon generation continues the sequence\n// instead of restarting it; a crash can only skip forward, never duplicate.\n\nimport { readFileSync, writeFileSync } from \"node:fs\";\nimport type { INiceProcessLine } from \"@nice-code/process\";\nimport { RotatingLog } from \"./rotatingLog\";\n\nexport interface IAggregateEntry {\n g: number;\n s: number;\n id: string;\n seq: number;\n ts: number;\n stream: INiceProcessLine[\"stream\"];\n op: INiceProcessLine[\"op\"];\n text: string;\n}\n\nconst FLUSH_EVERY = 100;\n\nexport class AggregateSink {\n readonly generation: number;\n private readonly _log: RotatingLog;\n private readonly _persistPath: string;\n private _seq: number;\n private _sinceFlush = 0;\n\n constructor(logsDir: string, persistPath: string, generation: number) {\n this.generation = generation;\n this._log = new RotatingLog(logsDir, \"aggregate\", {\n segmentBytes: 10_000_000,\n keepSegments: 5,\n });\n this._persistPath = persistPath;\n let highWater = 0;\n try {\n highWater = Number.parseInt(readFileSync(persistPath, \"utf8\"), 10) || 0;\n } catch {\n // First boot (or an unreadable mark) starts at 0 — generation disambiguates either way.\n }\n this._seq = highWater;\n }\n\n get nextSeq(): number {\n return this._seq + 1;\n }\n\n /** Stamps, persists, and returns the ordering key — consumers of the merged timeline need it. */\n record(id: string, line: INiceProcessLine): { g: number; s: number } {\n this._seq += 1;\n const entry: IAggregateEntry = {\n g: this.generation,\n s: this._seq,\n id,\n seq: line.seq,\n ts: line.ts,\n stream: line.stream,\n op: line.op,\n text: line.text,\n };\n this._log.write(JSON.stringify(entry));\n this._sinceFlush += 1;\n if (this._sinceFlush >= FLUSH_EVERY) this.flush();\n return { g: entry.g, s: entry.s };\n }\n\n /** Newest-first segment paths, for the bounded history reader. */\n segments(): string[] {\n return this._log.segments();\n }\n\n flush(): void {\n this._sinceFlush = 0;\n try {\n writeFileSync(this._persistPath, String(this._seq), { mode: 0o600 });\n } catch {\n // A lost high-water mark only means the next generation skips ahead — never duplicates.\n }\n }\n\n close(): void {\n this.flush();\n this._log.close();\n }\n}\n","import { timingSafeEqual } from \"node:crypto\";\nimport { readFile, realpath, stat } from \"node:fs/promises\";\nimport type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from \"node:http\";\nimport { extname, isAbsolute, join, normalize, relative, resolve, sep } from \"node:path\";\n\nconst MIME_TYPES: Readonly<Record<string, string>> = Object.freeze({\n \".css\": \"text/css; charset=utf-8\",\n \".gif\": \"image/gif\",\n \".html\": \"text/html; charset=utf-8\",\n \".ico\": \"image/x-icon\",\n \".jpeg\": \"image/jpeg\",\n \".jpg\": \"image/jpeg\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".map\": \"application/json; charset=utf-8\",\n \".png\": \"image/png\",\n \".svg\": \"image/svg+xml\",\n \".webmanifest\": \"application/manifest+json; charset=utf-8\",\n \".webp\": \"image/webp\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n});\n\nexport class LocalHttpRequestError extends Error {\n readonly status: number;\n readonly code: string;\n\n constructor(status: number, code: string, message: string) {\n super(message);\n this.name = \"LocalHttpRequestError\";\n this.status = status;\n this.code = code;\n }\n}\n\nexport interface ILocalHttpRequestLike {\n method?: string;\n headers: IncomingHttpHeaders;\n}\n\nexport function headerValue(\n request: ILocalHttpRequestLike,\n name: keyof IncomingHttpHeaders,\n): string | undefined {\n const value = request.headers[name];\n return Array.isArray(value) ? undefined : value;\n}\n\n/** Accepts only names whose DNS semantics are unambiguously loopback. */\nexport function hostIsLoopbackForm(host: string | undefined): boolean {\n if (host == null || host === \"\") return false;\n const closingBracket = host.indexOf(\"]\");\n const name = host.startsWith(\"[\")\n ? closingBracket > 0\n ? host.slice(1, closingBracket).toLowerCase()\n : \"\"\n : (host.split(\":\", 1)[0]?.toLowerCase() ?? \"\");\n if (name === \"::1\" || name === \"localhost\" || name.endsWith(\".localhost\")) return true;\n if (!name.startsWith(\"127.\")) return false;\n const octets = name.split(\".\");\n return (\n octets.length === 4 && octets.every((octet) => /^\\d{1,3}$/.test(octet) && Number(octet) <= 255)\n );\n}\n\nexport function addressIsLoopback(address: string | undefined): boolean {\n if (address == null) return false;\n return address === \"::1\" || address.startsWith(\"127.\") || address.startsWith(\"::ffff:127.\");\n}\n\n/** DNS-rebinding and browser cross-site request floor. This does not grant authority. */\nexport function crossSiteRequestAllowed(request: ILocalHttpRequestLike): boolean {\n const fetchSite = headerValue(request, \"sec-fetch-site\");\n if (fetchSite != null && fetchSite !== \"same-origin\" && fetchSite !== \"none\") return false;\n const origin = headerValue(request, \"origin\");\n if (origin == null) return true;\n return origin === `http://${headerValue(request, \"host\") ?? \"\"}`;\n}\n\n/** Strict browser-only form used by capability bootstrap and other mutation entry points. */\nexport function sameOriginBrowserRequestAllowed(\n request: ILocalHttpRequestLike,\n options: { method: string; destinations: readonly string[] },\n): boolean {\n if (request.method !== options.method) return false;\n const host = headerValue(request, \"host\");\n const origin = headerValue(request, \"origin\");\n const fetchSite = headerValue(request, \"sec-fetch-site\");\n const mode = headerValue(request, \"sec-fetch-mode\");\n const destination = headerValue(request, \"sec-fetch-dest\") ?? \"\";\n return (\n hostIsLoopbackForm(host) &&\n origin === `http://${host ?? \"\"}` &&\n fetchSite === \"same-origin\" &&\n (mode === \"cors\" || mode === \"same-origin\") &&\n options.destinations.includes(destination)\n );\n}\n\nexport function constantTimeTokenEqual(expected: string, presented: string | undefined): boolean {\n if (presented == null) return false;\n const left = Buffer.from(expected);\n const right = Buffer.from(presented);\n return left.length === right.length && timingSafeEqual(left, right);\n}\n\nexport function mimeTypeForPath(path: string): string {\n return MIME_TYPES[extname(path).toLowerCase()] ?? \"application/octet-stream\";\n}\n\nexport function pathIsContained(root: string, path: string): boolean {\n const fromRoot = relative(resolve(root), resolve(path));\n return (\n fromRoot === \"\" ||\n (!fromRoot.startsWith(`..${sep}`) && fromRoot !== \"..\" && !isAbsolute(fromRoot))\n );\n}\n\nexport async function resolveContainedFile(\n root: string,\n requestPath: string,\n): Promise<string | null> {\n let decoded: string;\n try {\n decoded = decodeURIComponent(requestPath);\n } catch {\n return null;\n }\n if (decoded.includes(\"\\0\")) return null;\n const canonicalRoot = await realpath(resolve(root));\n const lexical = normalize(join(canonicalRoot, decoded.replace(/^[/\\\\]+/, \"\")));\n if (!pathIsContained(canonicalRoot, lexical)) return null;\n try {\n const canonicalFile = await realpath(lexical);\n if (!pathIsContained(canonicalRoot, canonicalFile)) return null;\n return (await stat(canonicalFile)).isFile() ? canonicalFile : null;\n } catch {\n return null;\n }\n}\n\nexport async function readJsonBody(\n request: IncomingMessage,\n maximumBytes = 32_768,\n): Promise<unknown> {\n const contentType = headerValue(request, \"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n if (contentType !== \"application/json\") {\n throw new LocalHttpRequestError(415, \"content_type_unsupported\", \"expected application/json\");\n }\n const chunks: Buffer[] = [];\n let length = 0;\n for await (const chunk of request) {\n const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n length += bytes.length;\n if (length > maximumBytes) {\n throw new LocalHttpRequestError(413, \"body_too_large\", \"request body is too large\");\n }\n chunks.push(bytes);\n }\n try {\n return JSON.parse(Buffer.concat(chunks).toString(\"utf8\"));\n } catch {\n throw new LocalHttpRequestError(400, \"json_malformed\", \"request body is not valid JSON\");\n }\n}\n\nexport function applySecurityHeaders(\n response: ServerResponse,\n contentSecurityPolicy: string,\n): void {\n response.setHeader(\"x-content-type-options\", \"nosniff\");\n response.setHeader(\"referrer-policy\", \"no-referrer\");\n response.setHeader(\"x-frame-options\", \"DENY\");\n response.setHeader(\"content-security-policy\", contentSecurityPolicy);\n}\n\nexport async function serveStaticFile(options: {\n root: string;\n requestPath: string;\n response: ServerResponse;\n contentSecurityPolicy: string;\n immutable?: boolean;\n transform?: (bytes: Buffer, file: string) => Buffer | string;\n}): Promise<boolean> {\n const file = await resolveContainedFile(options.root, options.requestPath);\n if (file == null) return false;\n const original = await readFile(file);\n const body = options.transform?.(original, file) ?? original;\n options.response.statusCode = 200;\n options.response.setHeader(\"content-type\", mimeTypeForPath(file));\n options.response.setHeader(\n \"cache-control\",\n options.immutable === true ? \"public, max-age=31536000, immutable\" : \"no-store\",\n );\n applySecurityHeaders(options.response, options.contentSecurityPolicy);\n options.response.end(body);\n return true;\n}\n","// Daemon HTTP/ws auth (security posture §): the instance-record root token is the CLI's\n// authority; the browser flow is cookie/URL-free — a guarded, no-store bootstrap mints a\n// short-lived capability, which exchanges for one-use ws tickets. All values are random,\n// in-memory only, swept lazily (no timers), and never logged. The guards below are the\n// DNS-rebinding / hostile-web-origin floor; they authorize nothing by themselves.\n\nimport { randomBytes, timingSafeEqual } from \"node:crypto\";\n\nexport { crossSiteRequestAllowed, hostIsLoopbackForm } from \"nice-local-http-shared\";\n\nconst CAPABILITY_TTL_MS = 5 * 60_000;\nconst TICKET_TTL_MS = 30_000;\n\nfunction bearerToken(authorization: string | undefined): string | null {\n if (authorization == null || !authorization.startsWith(\"Bearer \")) return null;\n const token = authorization.slice(\"Bearer \".length).trim();\n return token === \"\" ? null : token;\n}\n\nexport class CommanderAuth {\n private readonly _rootToken: string;\n /** token → expiresAt (ms). */\n private readonly _capabilities = new Map<string, number>();\n private readonly _tickets = new Map<string, number>();\n\n constructor(rootToken: string) {\n this._rootToken = rootToken;\n }\n\n /** The CLI's authority, straight from the instance record. */\n isRoot(authorization: string | undefined): boolean {\n const presented = bearerToken(authorization);\n if (presented == null) return false;\n const a = Buffer.from(presented);\n const b = Buffer.from(this._rootToken);\n return a.length === b.length && timingSafeEqual(a, b);\n }\n\n /** What the browser bootstrap hands out: short-lived, JS-memory-only by design. */\n mintCapability(now = Date.now()): string {\n this._sweep(now);\n const capability = randomBytes(24).toString(\"base64url\");\n this._capabilities.set(capability, now + CAPABILITY_TTL_MS);\n return capability;\n }\n\n hasCapability(authorization: string | undefined, now = Date.now()): boolean {\n const token = bearerToken(authorization);\n if (token == null) return false;\n this._sweep(now);\n return (this._capabilities.get(token) ?? 0) > now;\n }\n\n canMintTicket(authorization: string | undefined, now = Date.now()): boolean {\n return this.isRoot(authorization) || this.hasCapability(authorization, now);\n }\n\n mintTicket(now = Date.now()): string {\n this._sweep(now);\n const ticket = randomBytes(24).toString(\"base64url\");\n this._tickets.set(ticket, now + TICKET_TTL_MS);\n return ticket;\n }\n\n /** One-use: a consumed or expired ticket never authorizes again. */\n consumeTicket(ticket: string, now = Date.now()): boolean {\n this._sweep(now);\n const expires = this._tickets.get(ticket);\n if (expires == null) return false;\n this._tickets.delete(ticket);\n return expires > now;\n }\n\n private _sweep(now: number): void {\n for (const [token, expires] of this._capabilities) {\n if (expires <= now) this._capabilities.delete(token);\n }\n for (const [ticket, expires] of this._tickets) {\n if (expires <= now) this._tickets.delete(ticket);\n }\n }\n}\n","// Config watch (G10/D2): fs.watch + debounce with a slow stat-reconcile fallback (watchers are\n// flaky on Windows and /mnt/c). Every attempt loads through a FRESH loader context. A parse or\n// validation failure keeps the last-good model and surfaces the errors — a bad save can never\n// kill your dev environment. A semantic no-op edit (same revision hash) never marks anything.\n\nimport { type FSWatcher, watch } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport { loadCommanderConfigFile } from \"../config/loader\";\nimport type { IResolvedCommanderConfig } from \"../config/types\";\nimport { validateCommanderConfig } from \"../config/validate\";\n\nconst DEBOUNCE_MS = 150;\nconst RECONCILE_MS = 5_000;\n\nexport interface IConfigWatchOptions {\n configPath: string;\n watchFiles: readonly string[];\n onConfig: (next: IResolvedCommanderConfig) => void;\n onError: (errors: string[]) => void;\n}\n\nexport interface IConfigWatch {\n close(): void;\n /** Force a reload attempt now (the `reloadConfig` control action uses this). */\n reloadNow(): Promise<void>;\n}\n\nexport function watchCommanderConfig(options: IConfigWatchOptions): IConfigWatch {\n let closed = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let inFlight: Promise<void> | null = null;\n let queued = false;\n const mtimes = new Map<string, number>();\n const watchers: FSWatcher[] = [];\n\n const rememberMtimes = async () => {\n for (const file of [options.configPath, ...options.watchFiles]) {\n try {\n mtimes.set(file, (await stat(file)).mtimeMs);\n } catch {\n mtimes.delete(file); // a deleted helper triggers a reload attempt below\n }\n }\n };\n\n // A caller that JOINS an in-flight pass must wait for it, not return immediately: the\n // `reloadConfig` ack reports what is live once the attempt settles, and an early return would\n // have it describing the state from before the reload it just asked for.\n const runAttempts = async () => {\n do {\n queued = false;\n // Stamp mtimes BEFORE reading, so an edit landing mid-load is still seen as newer than\n // what we recorded. Stamping after left the post-edit mtime paired with pre-edit\n // content, and the reconcile pass — the fallback that exists precisely because fs.watch\n // is unreliable on Windows and /mnt/c — would then never notice that edit at all.\n await rememberMtimes();\n try {\n const file = await loadCommanderConfigFile(options.configPath);\n const { resolved, errors } = validateCommanderConfig(file.raw, {\n configPath: file.configPath,\n configDir: file.configDir,\n });\n if (resolved != null) options.onConfig(resolved);\n else options.onError(errors);\n } catch (error) {\n options.onError([(error as Error).message]);\n }\n } while (queued && !closed);\n };\n\n const attempt = async (): Promise<void> => {\n if (closed) return;\n if (inFlight != null) {\n queued = true; // the running pass loops again before it exits, covering this request\n await inFlight;\n return;\n }\n inFlight = runAttempts().finally(() => {\n inFlight = null;\n });\n await inFlight;\n };\n\n const trigger = () => {\n if (closed) return;\n if (timer != null) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n void attempt();\n }, DEBOUNCE_MS);\n timer.unref();\n };\n\n for (const file of [options.configPath, ...options.watchFiles]) {\n try {\n const watcher = watch(file, { persistent: false }, trigger);\n watcher.on(\"error\", () => {}); // a vanished file is covered by the reconcile pass\n watchers.push(watcher);\n } catch {\n // Files that do not exist (yet) are covered by the reconcile pass.\n }\n }\n void rememberMtimes();\n\n // Slow stat-reconcile: the reliable fallback when fs.watch silently drops events.\n const reconcile = setInterval(() => {\n void (async () => {\n for (const file of [options.configPath, ...options.watchFiles]) {\n let mtime: number | null = null;\n try {\n mtime = (await stat(file)).mtimeMs;\n } catch {\n // missing\n }\n const seen = mtimes.get(file) ?? null;\n if (mtime !== seen) {\n mtimes.set(file, mtime ?? 0);\n trigger();\n return;\n }\n }\n })();\n }, RECONCILE_MS);\n reconcile.unref();\n\n return {\n close() {\n closed = true;\n if (timer != null) clearTimeout(timer);\n clearInterval(reconcile);\n for (const watcher of watchers) watcher.close();\n },\n reloadNow: attempt,\n };\n}\n","// The daemon's wire plane (D1): control actions + the status realm multiplexed on one ws,\n// plus the action channel's plain-HTTP surface for simple clients. Shape proven by the R0 D1\n// spike: capability-gated upgrade happens in main.ts BEFORE a socket reaches here; the realm\n// floor still requires an authenticated wire identity (defense in depth, not conflation). A\n// socket whose buffered egress blows the cap is terminated — a forgotten observer must never\n// grow daemon memory; its next attach resyncs from the engine.\n\nimport {\n ActionRuntime,\n createDefaultServeLogger,\n ESecurityLevel,\n httpAcceptorCarrier,\n RuntimeCoordinate,\n serveChannel,\n wsAcceptorCarrier,\n} from \"@nice-code/action\";\nimport type { INiceProcessExitInfo } from \"@nice-code/process\";\nimport { createRealmAcceptor, createRealmServerEngine } from \"@nice-code/realm\";\nimport { createMemoryStorageAdapter_json } from \"@nice-code/util\";\nimport type { WebSocket } from \"ws\";\nimport { orderByDependency, withDependencies } from \"../config/resolve\";\nimport type { IResolvedCommanderConfig } from \"../config/types\";\nimport { createPortInspector } from \"../ports/listeners\";\nimport { commanderChannel, commanderControlDomain, type ISetEnvInput } from \"../protocol/control\";\nimport {\n commanderStatusRealm,\n type IStatusProcessNode,\n type TCommanderStatusState,\n} from \"../protocol/statusRealm\";\nimport type { CommanderSupervisor, ISupervisedStatus } from \"./supervisor\";\n\nconst DAEMON_COORD = RuntimeCoordinate.env(\"commander_daemon\");\nconst SLOW_CONSUMER_DROP_BYTES = 256 * 1024;\n\nexport interface IControlPlaneOptions {\n supervisor: CommanderSupervisor;\n /** Daemon incarnation — stamped into the realm root so observers can spot a restart. */\n generation: number;\n /** Forces a config reload attempt (the watcher's fresh-load path, not a cache poke). */\n reloadConfig: () => Promise<void>;\n /** Persist an env-override mutation and hand it to the supervisor; refusals come back. */\n setEnvOverrides: (input: ISetEnvInput) => Promise<string[]>;\n /** Runs the daemon shutdown ladder after the ack has been flushed. */\n requestShutdown: () => void;\n log: (line: string) => void;\n}\n\nexport interface IControlPlane {\n /** The action channel's HTTP exchange surface (main.ts routes authed POST/OPTIONS here). */\n fetch(request: Request): Promise<Response>;\n /** Adopt a ticket-gated ws as the wire lane. */\n handleConnection(ws: WebSocket): void;\n /** Config reload applied: refresh groups/revision, clear configError, resync every process. */\n syncConfig(next: IResolvedCommanderConfig): void;\n /** A reload attempt failed: last-good stays live, the errors become observable state. */\n syncConfigError(errors: string[]): void;\n close(): void;\n}\n\nfunction projectExit(exit: INiceProcessExitInfo): IStatusProcessNode[\"lastExit\"] {\n return {\n ...(exit.code != null ? { code: exit.code } : {}),\n ...(exit.signal != null ? { signal: exit.signal } : {}),\n expected: exit.expected,\n };\n}\n\nfunction projectProcess(status: ISupervisedStatus): IStatusProcessNode {\n return {\n kind: status.kind,\n state: status.state,\n ...(status.pid != null ? { pid: status.pid } : {}),\n ...(status.startedAt != null ? { startedAt: status.startedAt } : {}),\n ...(status.sawOutputAt != null ? { sawOutputAt: status.sawOutputAt } : {}),\n ...(status.lastTask != null\n ? {\n lastTask: {\n outcome: status.lastTask.outcome,\n ...(status.lastTask.reason != null ? { reason: status.lastTask.reason } : {}),\n timedOut: status.lastTask.timedOut,\n endedAt: status.lastTask.endedAt,\n ...(status.lastTask.durationMs != null\n ? { durationMs: status.lastTask.durationMs }\n : {}),\n },\n }\n : {}),\n recentRuns: status.recentRuns.map((run) => ({\n startedAt: run.startedAt,\n ...(run.endedAt != null ? { endedAt: run.endedAt } : {}),\n ...(run.outcome != null ? { outcome: run.outcome } : {}),\n })),\n restarts: status.restarts,\n ...(status.lastExit != null ? { lastExit: projectExit(status.lastExit) } : {}),\n stale: status.stale,\n removed: status.removed,\n envDrift: status.envDrift,\n ...(status.blockedBy != null ? { blockedBy: status.blockedBy } : {}),\n degradedBy: status.degradedBy,\n ...(status.unreadyReason != null ? { unreadyReason: status.unreadyReason } : {}),\n ...(status.capability != null\n ? {\n capability: {\n treeMechanism: status.capability.treeMechanism,\n degraded: status.capability.degraded,\n notes: status.capability.notes,\n },\n }\n : {}),\n tags: status.tags,\n detail: {\n command: status.detail.command,\n cwd: status.detail.cwd,\n dependsOn: status.detail.dependsOn,\n ...(status.detail.ready != null ? { ready: status.detail.ready } : {}),\n ...(status.detail.timeoutMs != null ? { timeoutMs: status.detail.timeoutMs } : {}),\n endpoints: status.detail.endpoints.map((endpoint) => ({\n name: endpoint.name,\n protocol: endpoint.protocol,\n host: endpoint.host,\n port: endpoint.port,\n ownership: endpoint.ownership,\n ...(endpoint.url != null ? { url: endpoint.url } : {}),\n })),\n // Already filtered by `envVarViews` — a secret and an inherited value never carry `value`.\n envVars: status.detail.envVars.map((declared) => ({\n name: declared.name,\n ...(declared.description != null ? { description: declared.description } : {}),\n secret: declared.secret,\n required: declared.required,\n ...(declared.values != null ? { values: declared.values } : {}),\n source: declared.source,\n ...(declared.value != null ? { value: declared.value } : {}),\n })),\n },\n };\n}\n\n/**\n * Members are projected in DAG order (the same `orderByDependency` `up` spawns with), so the\n * UI's \"members in dependency order\" and the CLI's execution order are one rule, not two.\n */\nfunction projectGroups(config: IResolvedCommanderConfig): TCommanderStatusState[\"groups\"] {\n return Object.fromEntries(\n Object.entries(config.groups).map(([name, group]) => [\n name,\n { members: orderByDependency(config.processes, new Set(group.ids)) },\n ]),\n );\n}\n\nexport function createControlPlane(options: IControlPlaneOptions): IControlPlane {\n const { supervisor, log } = options;\n const ports = createPortInspector({\n config: () => supervisor.config,\n states: async () => new Map(supervisor.status().map((s) => [s.id, s.state])),\n });\n const runtime = new ActionRuntime(DAEMON_COORD);\n const write = (...parts: unknown[]) => log(parts.map(String).join(\" \"));\n const serveSink = { log: write, error: write };\n /** Errors from the most recent reload attempt — empty means the new revision is live. */\n let lastReloadErrors: string[] = [];\n\n const initialState = (): TCommanderStatusState => ({\n generation: options.generation,\n configName: supervisor.config.name,\n configRevisionHash: supervisor.config.configRevisionHash,\n configError: [],\n processes: Object.fromEntries(\n supervisor.status().map((status) => [status.id, projectProcess(status)]),\n ),\n groups: projectGroups(supervisor.config),\n });\n\n const engine = createRealmServerEngine(commanderStatusRealm, {\n initialState: initialState(),\n });\n\n // Every supervisor state event re-projects exactly that process; the realm emits the patch.\n supervisor.subscribe((id) => {\n const status = supervisor.status().find((candidate) => candidate.id === id);\n if (status == null) return;\n engine.update((draft: TCommanderStatusState) => {\n draft.processes[id] = projectProcess(status);\n });\n });\n\n const liveSockets = new Set<WebSocket>();\n // Broken out of the serveChannel initializer: the realm resolver closures run on inbound\n // hello — after `server` exists (same indirection as the D1 spike).\n const acceptorAccess: {\n clientFor?: (ws: WebSocket) => RuntimeCoordinate | undefined;\n levelFor?: (ws: WebSocket) => ESecurityLevel;\n } = {};\n\n const server = serveChannel(runtime, commanderChannel, {\n storage: createMemoryStorageAdapter_json(),\n carriers: [\n wsAcceptorCarrier<WebSocket>({\n send: (ws, frame) => {\n // Slow-consumer seam: every egress byte to this socket funnels through here.\n if (ws.bufferedAmount > SLOW_CONSUMER_DROP_BYTES) {\n log(\"wire: dropping a slow consumer\");\n liveSockets.delete(ws);\n server.drop(ws);\n ws.terminate();\n return;\n }\n ws.send(frame);\n },\n }),\n httpAcceptorCarrier(),\n ],\n handlers: [\n commanderControlDomain.wrapAsLocalHandler({\n ports: (input) => ports.run(input),\n start: async ({ ids, wait, staggerMs }) => {\n const config = supervisor.config;\n const ordered = orderByDependency(\n config.processes,\n withDependencies(config.processes, ids),\n );\n return supervisor.start(ordered, { wait: wait ?? true, staggerMs: staggerMs ?? 0 });\n },\n stop: async ({ ids }) => supervisor.stop(ids),\n restart: async ({ ids, wait, staggerMs }) => {\n const config = supervisor.config;\n const ordered = orderByDependency(\n config.processes,\n withDependencies(config.processes, ids),\n );\n return supervisor.restart(ordered, { wait: wait ?? true, staggerMs: staggerMs ?? 0 });\n },\n setEnv: async (input) => ({\n ok: true as const,\n warnings: await options.setEnvOverrides(input),\n }),\n reloadConfig: async () => {\n await options.reloadConfig();\n // Report what is LIVE now, not merely that the attempt finished. A reload whose file\n // fails validation deliberately keeps last-good — indistinguishable from success\n // until the ack says which revision actually won.\n return {\n ok: true as const,\n applied: lastReloadErrors.length === 0,\n configRevisionHash: supervisor.config.configRevisionHash,\n errors: [...lastReloadErrors],\n };\n },\n shutdown: async () => {\n // Ack first, ladder second — the client must see the response before its socket dies.\n setTimeout(() => options.requestShutdown(), 25).unref();\n return { ok: true as const };\n },\n }),\n ],\n protocols: [\n createRealmAcceptor<WebSocket>({\n realms: {\n commander_status: {\n engine,\n // The realm floor is authenticated; `levelFor` lets the acceptor fail closed.\n minSecurity: ESecurityLevel.authenticated,\n resolveAvatar: (ws) => {\n const client = acceptorAccess.clientFor?.(ws);\n if (client?.perId == null) return undefined;\n return {\n type: \"viewer\" as const,\n persistentId: client.perId,\n instanceId: client.insId ?? \"default\",\n };\n },\n },\n },\n levelFor: (ws) => acceptorAccess.levelFor?.(ws) ?? ESecurityLevel.none,\n }),\n ],\n // ⚠ Onto the daemon's ROTATED log, never the default `console`. The daemon's stdout/stderr are\n // the boot-error handoff fd — held open for its whole life and never rotated — so a default\n // logger quietly turned every control action into unbounded growth of a file documented as a\n // \"small fixed handoff\".\n logger: createDefaultServeLogger({ sink: serveSink }),\n });\n\n acceptorAccess.clientFor = (ws) => server.acceptors[0]?.wireAcceptor.clientForConnection(ws);\n acceptorAccess.levelFor = (ws) =>\n server.acceptors[0]?.wireAcceptor.levelFor(ws) ?? ESecurityLevel.none;\n\n return {\n fetch: (request) => server.fetch(request),\n handleConnection: (ws) => {\n liveSockets.add(ws);\n ws.on(\"message\", (data, isBinary) => {\n // ws' RawData is Buffer | ArrayBuffer | Buffer[] — normalize to one Uint8Array or string.\n const frame = isBinary\n ? Array.isArray(data)\n ? Buffer.concat(data)\n : data instanceof ArrayBuffer\n ? Buffer.from(data)\n : data\n : data.toString(\"utf8\");\n server.receive(ws, frame);\n });\n const forget = () => {\n liveSockets.delete(ws);\n server.drop(ws);\n };\n ws.on(\"close\", forget);\n ws.on(\"error\", forget);\n },\n syncConfig: (next) => {\n lastReloadErrors = [];\n engine.update((draft: TCommanderStatusState) => {\n draft.configName = next.name;\n draft.configRevisionHash = next.configRevisionHash;\n draft.configError = [];\n draft.groups = projectGroups(next);\n for (const status of supervisor.status()) {\n draft.processes[status.id] = projectProcess(status);\n }\n });\n },\n syncConfigError: (errors) => {\n lastReloadErrors = [...errors];\n engine.update((draft: TCommanderStatusState) => {\n draft.configError = errors;\n });\n },\n close: () => {\n for (const ws of [...liveSockets]) ws.terminate();\n liveSockets.clear();\n },\n };\n}\n","// Bounded reads over the aggregate log — the merged timeline's backfill and the server-side\n// search behind it (R5).\n//\n// Everything here is bounded and yields. A naive `grep` over rotated segments is an unbounded\n// synchronous read on the daemon's event loop, and the common case is a viewer retyping a query\n// three times a second: without a budget and a cancel, the daemon spends its life re-scanning\n// history for answers nobody is waiting for any more.\n//\n// Reads run NEWEST → OLDEST and stop as soon as the caller has enough, so the usual \"what just\n// happened\" question costs one partial segment rather than the whole retention window.\n\nimport { createReadStream } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline\";\nimport type { INiceProcessLine } from \"@nice-code/process\";\nimport type { ILogsEntry } from \"../protocol/logs\";\nimport type { IAggregateEntry } from \"./aggregateSink\";\n\n/** Entries one read may return. A viewer renders a screenful; this is already generous. */\nexport const MAX_HISTORY_ENTRIES = 2_000;\n/** Lines one read may look at before giving up and saying so (`complete: false`). */\nexport const MAX_HISTORY_SCAN = 200_000;\n/** Bytes of one segment tail to consider. Segments are 10 MB; this is the recent end of one. */\nconst SEGMENT_TAIL_BYTES = 4_000_000;\n\nexport interface IHistoryQuery {\n /** Restrict to these ids; absent = every process. */\n procs?: readonly string[];\n /** Case-insensitive substring; absent = no text filter (plain backfill). */\n query?: string;\n /** Only entries with `s` at or below this — the merged view's \"older than what I hold\". */\n beforeS?: number;\n /** Only entries with `s` strictly above this — a resume cursor. */\n afterS?: number;\n limit: number;\n /** Returns true to abandon the scan (the client cancelled, or the socket went away). */\n cancelled?: () => boolean;\n}\n\nexport interface IHistoryResult {\n /** OLDEST first, so a caller can append them straight onto a timeline. */\n entries: ILogsEntry[];\n /** False = the budget or a cancel ended the scan before the history did. */\n complete: boolean;\n scanned: number;\n}\n\n/**\n * Read matching entries from the newest end of the aggregate log backwards.\n *\n * The on-disk shape is flat (`{g,s,id,seq,ts,stream,op,text}`) while the wire shape nests the\n * library's line — changing the file to match would invalidate every segment already written, so\n * the mapping lives here instead.\n */\nexport async function readHistory(\n segments: readonly string[],\n query: IHistoryQuery,\n): Promise<IHistoryResult> {\n const limit = Math.min(query.limit, MAX_HISTORY_ENTRIES);\n const needle = query.query == null || query.query === \"\" ? null : query.query.toLowerCase();\n const wanted = query.procs == null ? null : new Set(query.procs);\n const found: ILogsEntry[] = [];\n let scanned = 0;\n /**\n * ⚠ A segment larger than the byte window is only read from its tail, so the scan did NOT see\n * the whole history even if the line budget was never touched. Reporting `complete` off the\n * budget alone would answer \"no matches\" for a line that is sitting in the part we skipped —\n * the exact thing the caller's \"stopped after N lines\" wording exists to prevent.\n */\n let windowed = false;\n /**\n * ⚠ A read that failed is not a read that found nothing. This function is the merged view's\n * ENTIRE backfill, so throwing out of it took the caller's `await` with it — and the pane sat\n * blank, indistinguishable from a process that had never printed. A segment can roll away\n * between `segments()` listing it and this opening it; that is normal, not fatal.\n */\n let torn = false;\n\n for (const segment of segments) {\n if (found.length >= limit || scanned >= MAX_HISTORY_SCAN) break;\n if (query.cancelled?.() === true) return { entries: found, complete: false, scanned };\n if ((await fileSize(segment)) > SEGMENT_TAIL_BYTES) windowed = true;\n\n // A segment is read forwards (the only way to split lines) and matched into a buffer we keep\n // only the newest `limit` of — so memory is bounded by the answer, not by the segment.\n const newest: ILogsEntry[] = [];\n try {\n for await (const line of segmentLines(segment)) {\n scanned += 1;\n if (scanned % 5_000 === 0) {\n if (query.cancelled?.() === true) {\n return {\n entries: [...newest.slice(-limit), ...found].slice(-limit),\n complete: false,\n scanned,\n };\n }\n await new Promise((resolve) => setImmediate(resolve));\n }\n if (scanned >= MAX_HISTORY_SCAN) break;\n const entry = toEntry(line);\n if (entry == null) continue;\n if (wanted != null && !wanted.has(entry.id)) continue;\n if (query.beforeS != null && entry.s > query.beforeS) continue;\n if (query.afterS != null && entry.s <= query.afterS) continue;\n if (needle != null && !entry.line.text.toLowerCase().includes(needle)) continue;\n newest.push(entry);\n if (newest.length > limit) newest.shift();\n }\n } catch {\n // Whatever this segment still held is unreadable now; keep what it did yield and carry on\n // into the older ones. `complete: false` is how the caller learns not to say \"no matches\".\n torn = true;\n }\n // Segments are newest-first, so this segment's matches are all older than what we have.\n found.unshift(...newest);\n if (found.length > limit) found.splice(0, found.length - limit);\n }\n\n return {\n entries: found,\n complete: scanned < MAX_HISTORY_SCAN && !windowed && !torn,\n scanned,\n };\n}\n\n/** 0 when the segment rotated away between listing it and reading it. */\nasync function fileSize(path: string): Promise<number> {\n try {\n return (await stat(path)).size;\n } catch {\n return 0;\n }\n}\n\n/**\n * Lines of one segment, reading at most its last {@link SEGMENT_TAIL_BYTES}. Starting mid-file\n * can land inside a line; that first partial is dropped rather than parsed into a wrong entry.\n */\nasync function* segmentLines(path: string): AsyncGenerator<string> {\n const size = await fileSize(path);\n if (size === 0) return;\n const start = Math.max(0, size - SEGMENT_TAIL_BYTES);\n const stream = createReadStream(path, { start, encoding: \"utf8\" });\n const reader = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });\n let first = true;\n try {\n for await (const line of reader) {\n if (first) {\n first = false;\n if (start > 0) continue;\n }\n if (line !== \"\") yield line;\n }\n } finally {\n reader.close();\n stream.destroy();\n }\n}\n\nfunction toEntry(text: string): ILogsEntry | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null; // a torn tail line, or a segment rolled mid-write\n }\n if (parsed == null || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const raw = parsed as Partial<IAggregateEntry>;\n if (\n typeof raw.g !== \"number\" ||\n typeof raw.s !== \"number\" ||\n typeof raw.id !== \"string\" ||\n typeof raw.text !== \"string\" ||\n typeof raw.seq !== \"number\" ||\n typeof raw.ts !== \"number\"\n ) {\n return null;\n }\n // The file does not store `id`/`at`/`truncated` per line — history is for reading, not for\n // replaying replace-ops, so the reconstruction is honest about what it does not know.\n const line: INiceProcessLine = {\n id: raw.seq,\n seq: raw.seq,\n ts: raw.ts,\n at: 0,\n stream: raw.stream === \"err\" ? \"err\" : \"out\",\n op: \"append\",\n text: raw.text,\n truncated: false,\n };\n return { g: raw.g, s: raw.s, id: raw.id, line };\n}\n","// The `/logs` ws lane (D5): per-process subscriptions → bounded ring backfill + live tail,\n// batched on a ~30 ms coalesce. Every client queue is byte-capped — a client that falls\n// behind gets an explicit `gap` marker and a `reset` resnap from the ring, never silent loss\n// and never unbounded daemon memory.\n//\n// It also carries the MERGED timeline and the search behind it (R5). Both are ordered by the\n// daemon's `(g, s)` — assigned at receipt — because neither wall clocks (which jump) nor\n// per-process `seq` (incomparable between processes) can order two processes against each other.\n// Merged history comes off the aggregate file rather than a second in-memory copy of every line.\n\nimport type { INiceProcessLine } from \"@nice-code/process\";\nimport type { WebSocket } from \"ws\";\nimport {\n type ILogsBatch,\n type ILogsEntry,\n type ILogsGap,\n type ILogsMergedBatch,\n parseLogsClientMessage,\n type TLogsServerMessage,\n} from \"../protocol/logs\";\nimport { type IHistoryResult, MAX_HISTORY_ENTRIES, readHistory } from \"./history\";\nimport type { CommanderSupervisor } from \"./supervisor\";\n\nconst FLUSH_MS = 30;\n/** Per-subscription egress cap (pending queue + what the socket still owes). */\nconst CLIENT_CAP_BYTES = 256 * 1024;\n/** Rough per-line wire estimate; the cap is a memory bound, not an accounting exercise. */\nconst LINE_OVERHEAD_BYTES = 96;\n/**\n * Concurrent subscriptions one socket may hold. Every subscription costs a supervisor listener,\n * a pending queue, and a full ring backfill on arrival — so without a ceiling a single ticketed\n * client could multiply the daemon's per-client memory by however many `sub` frames it cares to\n * send. The byte cap above bounds each subscription; this bounds their number.\n */\nconst MAX_SUBSCRIPTIONS = 64;\n/**\n * Merged-lane egress cap. Separate from the per-process one because this lane carries EVERY\n * process: a viewer watching a 20-process environment can fall behind on volume no single\n * process could produce.\n */\nconst MERGED_CAP_BYTES = 512 * 1024;\n/** Concurrent searches one socket may have in flight — each holds a file read. */\nconst MAX_SEARCHES = 4;\n\ninterface ILogsEndpointOptions {\n supervisor: CommanderSupervisor;\n /** Newest-first aggregate segment paths — the merged backfill and search read these. */\n segments: () => string[];\n log: (line: string) => void;\n}\n\nexport interface ILogsEndpoint {\n /** Adopt a ticket-gated ws as the logs lane. */\n handleConnection(ws: WebSocket): void;\n close(): void;\n}\n\ninterface ISubscription {\n off: () => void;\n pending: INiceProcessLine[];\n pendingBytes: number;\n dropped: number;\n}\n\ninterface IMergedSubscription {\n off: () => void;\n pending: ILogsEntry[];\n pendingBytes: number;\n dropped: number;\n /** False until the backfill has been sent — live entries queue behind it, never in front. */\n live: boolean;\n}\n\n/**\n * What a subscribe gets back. A resume cursor is an OPTIMISATION, never a promise: it is honored\n * only where the ring can prove it still holds everything after it, so a reconnecting client can\n * never be handed a log that looks continuous but isn't.\n *\n * - contiguous → an append batch (`reset` absent). Answering a cursor with `reset: true` would\n * tell the client to discard everything before it, which is the opposite of resuming.\n * - the ring rotated past the cursor → the exact `gap`, then a resnap.\n * - the ring is entirely older than the cursor → the process was rebuilt (a config reload gives it\n * a fresh ring and a fresh sequence), so the two histories are not comparable: resnap.\n */\nfunction backfillFrames(\n proc: string,\n ring: readonly INiceProcessLine[],\n fromSeq: number | undefined,\n): TLogsServerMessage[] {\n const resnap: ILogsBatch = { k: \"batch\", proc, reset: true, lines: [...ring] };\n if (fromSeq == null || ring.length === 0) return [resnap];\n const oldest = ring[0]?.seq ?? 0;\n const newest = ring[ring.length - 1]?.seq ?? 0;\n if (newest < fromSeq) return [resnap];\n if (oldest <= fromSeq + 1) {\n return [{ k: \"batch\", proc, lines: ring.filter((line) => line.seq > fromSeq) }];\n }\n return [{ k: \"gap\", proc, dropped: oldest - fromSeq - 1 }, resnap];\n}\n\nfunction sendFrame(ws: WebSocket, message: TLogsServerMessage): void {\n if (ws.readyState !== ws.OPEN) return;\n ws.send(JSON.stringify(message));\n}\n\nexport function createLogsEndpoint(options: ILogsEndpointOptions): ILogsEndpoint {\n const { supervisor, segments, log } = options;\n const sockets = new Set<WebSocket>();\n\n const handleConnection = (ws: WebSocket) => {\n sockets.add(ws);\n const subs = new Map<string, ISubscription>();\n let merged: IMergedSubscription | null = null;\n /** Ids of searches the client has abandoned (or that outlived the socket). */\n const cancelledSearches = new Set<string>();\n let searchesInFlight = 0;\n let disposed = false;\n\n const flush = setInterval(() => {\n if (ws.readyState !== ws.OPEN) return;\n const backedUp = ws.bufferedAmount > CLIENT_CAP_BYTES;\n for (const [proc, sub] of subs) {\n if (backedUp) {\n // A backed-up socket gets nothing new — count the miss; exactly one gap + resnap\n // goes out once it drains, never a resnap every window into a dead-slow client.\n sub.dropped += sub.pending.length;\n sub.pending = [];\n sub.pendingBytes = 0;\n continue;\n }\n if (sub.dropped > 0) {\n const dropped = sub.dropped + sub.pending.length;\n sub.pending = [];\n sub.pendingBytes = 0;\n sub.dropped = 0;\n const gap: ILogsGap = { k: \"gap\", proc, dropped };\n sendFrame(ws, gap);\n const resnap: ILogsBatch = {\n k: \"batch\",\n proc,\n reset: true,\n lines: [...supervisor.ringFor(proc)],\n };\n sendFrame(ws, resnap);\n continue;\n }\n if (sub.pending.length === 0) continue;\n const batch: ILogsBatch = { k: \"batch\", proc, lines: sub.pending };\n sendFrame(ws, batch);\n sub.pending = [];\n sub.pendingBytes = 0;\n }\n\n if (merged == null || !merged.live) return;\n if (ws.bufferedAmount > MERGED_CAP_BYTES) {\n merged.dropped += merged.pending.length;\n merged.pending = [];\n merged.pendingBytes = 0;\n return;\n }\n if (merged.dropped > 0) {\n const dropped = merged.dropped + merged.pending.length;\n merged.pending = [];\n merged.pendingBytes = 0;\n merged.dropped = 0;\n sendFrame(ws, { k: \"merged-gap\", dropped });\n // No resnap here: unlike a per-process ring, the merged history lives on disk, and\n // re-reading it under load is what put the client behind. The gap is the honest answer —\n // the viewer can search the history for what it missed.\n return;\n }\n if (merged.pending.length === 0) return;\n sendFrame(ws, { k: \"merged\", entries: merged.pending });\n merged.pending = [];\n merged.pendingBytes = 0;\n }, FLUSH_MS);\n\n /**\n * Merged backfill without a second copy of every line in memory: attach the live tap FIRST\n * and buffer, then read the file for everything OLDER than the first buffered entry. The\n * two halves meet exactly at `s`, so nothing is lost in the gap between them and nothing is\n * delivered twice — which a read-then-attach would get wrong in both directions.\n */\n const subscribeMerged = async (procs: string[] | undefined, fromS: number | undefined) => {\n merged?.off();\n const sub: IMergedSubscription = {\n off: () => {},\n pending: [],\n pendingBytes: 0,\n dropped: 0,\n live: false,\n };\n const wanted = procs == null ? null : new Set(procs);\n sub.off = supervisor.onMergedLine((entry) => {\n if (wanted != null && !wanted.has(entry.id)) return;\n sub.pending.push(entry);\n sub.pendingBytes += entry.line.text.length + LINE_OVERHEAD_BYTES;\n if (sub.pendingBytes > MERGED_CAP_BYTES) {\n sub.dropped += sub.pending.length;\n sub.pending = [];\n sub.pendingBytes = 0;\n }\n });\n merged = sub;\n\n let history: IHistoryResult = { entries: [], complete: true, scanned: 0 };\n try {\n history = await readHistory(segments(), {\n ...(procs == null ? {} : { procs }),\n ...(fromS == null ? {} : { afterS: fromS }),\n limit: MAX_HISTORY_ENTRIES,\n cancelled: () => disposed || merged !== sub,\n });\n } catch (error) {\n // ⚠ A backfill that cannot be read must still OPEN the lane. Falling out here left\n // `sub.live` false forever, so the live tail never flushed either and the viewer got a\n // blank pane that no reconnect could fix. An empty backfill loses history; a dead\n // subscription loses the present.\n log(\n `logs: merged backfill failed, serving the live tail only: ${(error as Error).message}`,\n );\n }\n if (disposed || merged !== sub) return;\n\n // ⚠ The two halves meet at the FIRST buffered live entry, and that boundary can only be\n // read once the file read has finished — everything that arrived during it is in the file\n // too, so taking the boundary beforehand (when nothing has arrived yet) hands the same\n // lines out twice and, once the page cap cuts the file half short, emits them out of order.\n const boundary = sub.pending[0]?.s;\n const backfill =\n boundary == null ? history.entries : history.entries.filter((entry) => entry.s < boundary);\n const batch: ILogsMergedBatch =\n fromS == null\n ? { k: \"merged\", reset: true, entries: backfill }\n : { k: \"merged\", entries: backfill };\n sendFrame(ws, batch);\n sub.live = true;\n };\n\n const runSearch = async (\n id: string,\n query: string,\n procs: string[] | undefined,\n limit = 200,\n ) => {\n if (searchesInFlight >= MAX_SEARCHES) {\n log(`logs: refusing search \"${id}\" — client is at ${MAX_SEARCHES} concurrent searches`);\n sendFrame(ws, { k: \"search-result\", id, entries: [], complete: false, scanned: 0 });\n return;\n }\n searchesInFlight += 1;\n try {\n const result = await readHistory(segments(), {\n ...(procs == null ? {} : { procs }),\n query,\n limit,\n cancelled: () => disposed || cancelledSearches.has(id),\n });\n if (disposed || cancelledSearches.delete(id)) return;\n sendFrame(ws, {\n k: \"search-result\",\n id,\n entries: result.entries,\n complete: result.complete,\n scanned: result.scanned,\n });\n } catch (error) {\n // Every search MUST be answered — the pane says \"searching…\" until one arrives, and an\n // incomplete empty answer is the honest one for a read that failed.\n log(`logs: search \"${id}\" failed: ${(error as Error).message}`);\n if (!disposed && !cancelledSearches.delete(id)) {\n sendFrame(ws, { k: \"search-result\", id, entries: [], complete: false, scanned: 0 });\n }\n } finally {\n searchesInFlight -= 1;\n }\n };\n\n ws.on(\"message\", (data) => {\n const message = parseLogsClientMessage(data.toString());\n if (message == null) return;\n if (message.k === \"unsub-merged\") {\n merged?.off();\n merged = null;\n return;\n }\n if (message.k === \"sub-merged\") {\n // An unhandled rejection is a daemon exit under node's default, and this lane's work is\n // all `void`-called from a ws event — every path out of it has to be caught here.\n void subscribeMerged(message.procs, message.fromS).catch((error: Error) => {\n log(`logs: merged subscribe failed: ${error.message}`);\n });\n return;\n }\n if (message.k === \"search-cancel\") {\n cancelledSearches.add(message.id);\n return;\n }\n if (message.k === \"search\") {\n cancelledSearches.delete(message.id);\n void runSearch(message.id, message.query, message.procs, message.limit).catch(\n (error: Error) => log(`logs: search dispatch failed: ${error.message}`),\n );\n return;\n }\n if (message.k === \"unsub\") {\n subs.get(message.proc)?.off();\n subs.delete(message.proc);\n return;\n }\n // Re-subscribing to a proc already held is a reset, not a new slot — count only new ids.\n if (!subs.has(message.proc) && subs.size >= MAX_SUBSCRIPTIONS) {\n log(`logs: refusing subscription to \"${message.proc}\" — client is at ${MAX_SUBSCRIPTIONS}`);\n return;\n }\n subs.get(message.proc)?.off();\n const sub: ISubscription = { off: () => {}, pending: [], pendingBytes: 0, dropped: 0 };\n sub.off = supervisor.onLine(message.proc, (line) => {\n sub.pending.push(line);\n sub.pendingBytes += line.text.length + LINE_OVERHEAD_BYTES;\n if (sub.pendingBytes > CLIENT_CAP_BYTES) {\n // Overflowing inside the window: count + drop now; the flush sends gap + resnap.\n sub.dropped += sub.pending.length;\n sub.pending = [];\n sub.pendingBytes = 0;\n }\n });\n subs.set(message.proc, sub);\n for (const frame of backfillFrames(\n message.proc,\n supervisor.ringFor(message.proc),\n message.fromSeq,\n )) {\n sendFrame(ws, frame);\n }\n });\n\n const cleanup = () => {\n disposed = true;\n clearInterval(flush);\n for (const sub of subs.values()) sub.off();\n subs.clear();\n merged?.off();\n merged = null;\n cancelledSearches.clear();\n sockets.delete(ws);\n };\n ws.on(\"close\", cleanup);\n ws.on(\"error\", cleanup);\n };\n\n return {\n handleConnection: (ws) => {\n try {\n handleConnection(ws);\n } catch (error) {\n // A bad lane must never take the daemon down with it.\n log(`logs: connection dropped after setup error: ${(error as Error).message}`);\n ws.terminate();\n }\n },\n close: () => {\n for (const ws of [...sockets]) ws.terminate();\n sockets.clear();\n },\n };\n}\n","// Serving the built web UI (`build/client`, produced by `vite build`). Read-only GETs, loopback\n// only, behind the same Host/cross-site guards as everything else on this server.\n//\n// The CSP is the important part: `default-src 'none'` with an explicit allowance for the ws\n// lanes. The log pane renders fully attacker-influenced text (any dependency can print anything),\n// so even though it escapes by construction, a policy that forbids inline script and every\n// external origin is the second lock on that door.\n\nimport { existsSync } from \"node:fs\";\nimport type { ServerResponse } from \"node:http\";\nimport { join, normalize } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n applySecurityHeaders as applyLocalHttpSecurityHeaders,\n serveStaticFile,\n} from \"nice-local-http-shared\";\n\n/**\n * Where the built client lives, which depends on how the daemon was loaded:\n *\n * - **published / built** — this module is bundled into `build/`, so `./client` is right there.\n * - **from source** (the e2e shim, and `bun run` in this repo) — this file is `src/daemon/`, and\n * the bundle is still at `<package>/build/client`.\n *\n * Resolved once, on first use rather than at import, so a daemon started before `build:client`\n * ran still finds the assets once they exist.\n */\nlet clientDir: string | null = null;\n\nexport function resolveClientDir(): string {\n if (clientDir != null) return clientDir;\n const here = fileURLToPath(new URL(\".\", import.meta.url));\n for (const candidate of [join(here, \"client\"), join(here, \"..\", \"..\", \"build\", \"client\")]) {\n if (existsSync(join(candidate, \"index.html\"))) {\n clientDir = normalize(candidate);\n return clientDir;\n }\n }\n // Nothing built yet: keep the bundled location so the 404 message names a real path.\n clientDir = normalize(join(here, \"client\"));\n return clientDir;\n}\n\nconst CSP = [\n \"default-src 'none'\",\n \"script-src 'self'\",\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data:\",\n \"font-src 'self'\",\n \"manifest-src 'self'\",\n \"connect-src 'self' ws: wss:\",\n \"frame-ancestors 'none'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n].join(\"; \");\n\nexport function applySecurityHeaders(response: ServerResponse): void {\n applyLocalHttpSecurityHeaders(response, CSP);\n}\n\n/**\n * Serve one file from the client bundle. `immutable` is for hashed `/assets/*` only — the\n * entry document must never be cached, or a daemon upgrade keeps serving the old app shell.\n */\nexport async function serveClientFile(\n pathname: string,\n response: ServerResponse,\n immutable: boolean,\n): Promise<boolean> {\n return serveStaticFile({\n root: resolveClientDir(),\n requestPath: pathname,\n response,\n contentSecurityPolicy: CSP,\n immutable,\n });\n}\n","// The process supervisor: owns one NiceProcess per config definition and implements the\n// commander lifecycle on top — DAG-ordered starts that WAIT on dependencies (service deps to\n// ready, task deps to succeeded, bounded so a hung dep returns `blocked` instead of hanging\n// the action), idempotent overlap-safe control, task timeouts, degraded-on-regression\n// marking, stale/removed config-reload marking, and the shutdown ladder (edge 39).\n\nimport { connect } from \"node:net\";\nimport {\n createNiceProcess,\n type INiceProcess,\n type INiceProcessCapability,\n type INiceProcessExitInfo,\n type INiceProcessLedger,\n type INiceProcessLine,\n signalProcessGroup,\n type TNiceProcessKind,\n type TNiceProcessState,\n type TNiceProcessUnreadyReason,\n taskkillTree,\n} from \"@nice-code/process\";\nimport {\n effectiveEnv,\n envVarViews,\n type IEnvVarView,\n overrideFingerprint,\n type TEnvOverrides,\n} from \"../config/envVars\";\nimport { withDependencies } from \"../config/resolve\";\nimport type { IResolvedCommanderConfig, IResolvedCommanderProcess } from \"../config/types\";\nimport type { IActionReport, IProcessActionResult } from \"../protocol/control\";\nimport type { ILogsEntry } from \"../protocol/logs\";\nimport type { AggregateSink } from \"./aggregateSink\";\n\nexport type { IActionReport, IProcessActionResult, TActionOutcome } from \"../protocol/control\";\n\nconst ACTIVE_STATES: ReadonlySet<TNiceProcessState> = new Set([\n \"starting\",\n \"running\",\n \"ready\",\n \"unready\",\n \"backoff\",\n \"stopping\",\n]);\n\n/**\n * How a task's most recent run ended, kept AFTER the run so `status` can answer \"what happened\"\n * without the start reply that carried it. A timeout is the load-bearing case: the kill lands as\n * an expected stop, so the process state alone paints a neutral \"stopped\" over a failed check.\n */\nexport interface ILastTaskRun {\n outcome: \"succeeded\" | \"failed\" | \"stopped\";\n reason: string | null;\n /** The run was killed by its own `timeoutMs` — the one failure the exit info cannot show. */\n timedOut: boolean;\n endedAt: number;\n durationMs: number | null;\n definitionHash: string;\n}\n\nexport type TRunOutcome = \"succeeded\" | \"failed\" | \"stopped\" | \"crashed\" | \"timedOut\";\n\n/**\n * One run of a process, kept in a small bounded ring so a viewer can draw a recent-history\n * timeline. `endedAt`/`outcome` are null while the run is live. `timedOut` folds into the\n * outcome vocabulary (not a flag) because on a bar \"hung and killed\" and \"ran and failed\" want\n * different colours and different next actions.\n */\nexport interface ISupervisedRun {\n startedAt: number;\n endedAt: number | null;\n outcome: TRunOutcome | null;\n}\n\n/** Per-process run ring bound — enough to fill the UI's 30-minute window, never a log. */\nconst RECENT_RUNS_CAP = 12;\n\nexport interface ISupervisedStatus {\n id: string;\n kind: TNiceProcessKind;\n state: TNiceProcessState | \"blocked\" | \"not-started\";\n pid: number | null;\n startedAt: number | null;\n /**\n * First output of the current (or most recent) run — null while it has printed nothing. A\n * run that is `running` with this still null past a few seconds is the signature of a child\n * wedged before its first line (a hung spawn, not a quiet worker).\n */\n sawOutputAt: number | null;\n /** Task kind only: how the most recent completed run ended. */\n lastTask: ILastTaskRun | null;\n /** Newest-last ring of recent runs (both kinds); the live run has null endedAt/outcome. */\n recentRuns: ISupervisedRun[];\n restarts: number;\n lastExit: INiceProcessExitInfo | null;\n stale: boolean;\n removed: boolean;\n /** Running with different env overrides than a start would use now — restart to apply. */\n envDrift: boolean;\n blockedBy: string | null;\n degradedBy: string[];\n unreadyReason: TNiceProcessUnreadyReason | null;\n capability: INiceProcessCapability | null;\n tags: Record<string, string>;\n /**\n * The resolved definition, for the UI's detail panel. Low-churn (it only moves on a config\n * reload or an override change), so it belongs on the realm rather than behind another request.\n *\n * ⚠ Still never the resolved `env` — a realm is a state plane, not a secret store, and every\n * viewer sees every field. `envVars` is the narrow, deliberate exception: only names the config\n * DECLARED as knobs, with secrets and inherited values already stripped by `envVarViews`.\n */\n detail: IProcessDetail;\n}\n\nexport interface IProcessDetail {\n /** Exactly what will be executed, already resolved — shell string or joined argv. */\n command: string;\n cwd: string;\n dependsOn: string[];\n /** A one-line description of the readiness contract, or absent for \"ready when spawned\". */\n ready?: string;\n endpoints: IEndpointBadge[];\n /** Declared knobs with their effective value and where it came from; `[]` when none. */\n envVars: IEnvVarView[];\n /** Tasks only: the run's hard cap — the UI draws elapsed/timeout from it. */\n timeoutMs?: number;\n}\n\nexport interface IEndpointBadge {\n name: string;\n protocol: string;\n host: string;\n port: number;\n ownership: string;\n /** The configured URL, or the one derived from protocol/host/port for http(s). */\n url?: string;\n}\n\ninterface ISupervised {\n definition: IResolvedCommanderProcess;\n proc: INiceProcess | null;\n /** The overrides baked into `proc` when it was built — null while there is no process. */\n envFingerprint: string | null;\n startedAt: number | null;\n stale: boolean;\n removed: boolean;\n blockedBy: string | null;\n degradedBy: Set<string>;\n taskTimer: ReturnType<typeof setTimeout> | null;\n /** The active task run, coalescing concurrent requests across actions (M5). */\n taskRun: Promise<IProcessActionResult> | null;\n chain: Promise<unknown>;\n /** First line of the current run, reset on every `starting` transition. */\n sawOutputAt: number | null;\n lastTask: ILastTaskRun | null;\n recentRuns: ISupervisedRun[];\n}\n\nexport interface ISupervisorOptions {\n config: IResolvedCommanderConfig;\n ledger: INiceProcessLedger;\n sink: AggregateSink;\n /** Bound on waiting for a dependency to ready/succeed before reporting `blocked`. */\n depWaitMs?: number;\n /** Per-process file-sink anchor (logsDir/<id>/run-*). */\n logsDir: string;\n /** Sticky env overrides read from the store at boot; layered over each definition's `env`. */\n envOverrides?: TEnvOverrides;\n}\n\ntype TListener = (id: string) => void;\n\nconst wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nconst ENDPOINT_PROBE_MS = 250;\n/** A just-stopped listener can linger for an instant; a restart must not trip over its own port. */\nconst ENDPOINT_RECHECK_MS = 150;\n\n/** Is anything listening? A bare connect — deliberately NOT an attempt to attribute an owner. */\nfunction tcpBound(host: string, port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = connect({ host, port });\n const settle = (bound: boolean) => {\n socket.destroy();\n resolve(bound);\n };\n socket.setTimeout(ENDPOINT_PROBE_MS, () => settle(false));\n socket.once(\"connect\", () => settle(true));\n socket.once(\"error\", () => settle(false));\n });\n}\n\nexport class CommanderSupervisor {\n private _config: IResolvedCommanderConfig;\n private readonly _holders = new Map<string, ISupervised>();\n private readonly _ledger: INiceProcessLedger;\n private readonly _sink: AggregateSink;\n private readonly _depWaitMs: number;\n private readonly _logsDir: string;\n private readonly _listeners = new Set<TListener>();\n private readonly _lineListeners = new Map<string, Set<(line: INiceProcessLine) => void>>();\n private readonly _mergedListeners = new Set<(entry: ILogsEntry) => void>();\n private _envOverrides: TEnvOverrides;\n private _stopping = false;\n\n constructor(options: ISupervisorOptions) {\n this._config = options.config;\n this._ledger = options.ledger;\n this._sink = options.sink;\n this._depWaitMs = options.depWaitMs ?? 60_000;\n this._logsDir = options.logsDir;\n this._envOverrides = options.envOverrides ?? {};\n for (const definition of options.config.processes) {\n this._holders.set(definition.id, this._newHolder(definition));\n }\n }\n\n get config(): IResolvedCommanderConfig {\n return this._config;\n }\n\n subscribe(listener: TListener): () => void {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n }\n\n /**\n * Live line tap for the `/logs` lane. Keyed by id (not process instance) so a subscription\n * placed before the first spawn — or across a config-reload process rebuild — just works.\n */\n onLine(id: string, listener: (line: INiceProcessLine) => void): () => void {\n let set = this._lineListeners.get(id);\n if (set == null) {\n set = new Set();\n this._lineListeners.set(id, set);\n }\n set.add(listener);\n return () => {\n set.delete(listener);\n if (set.size === 0) this._lineListeners.delete(id);\n };\n }\n\n /**\n * The merged tap: every process's lines on one stream, stamped with the daemon's `(g, s)`.\n * Distinct from `onLine` because the merged timeline's whole point is a single ordering across\n * processes — reassembling it from N per-process taps would put the ordering back in the\n * client, which is exactly where it cannot be decided.\n */\n onMergedLine(listener: (entry: ILogsEntry) => void): () => void {\n this._mergedListeners.add(listener);\n return () => this._mergedListeners.delete(listener);\n }\n\n /** The bounded ring snapshot for `/logs` backfill; empty while the process was never spawned. */\n ringFor(id: string): readonly INiceProcessLine[] {\n return this._holders.get(id)?.proc?.ring() ?? [];\n }\n\n private _notify(id: string): void {\n for (const listener of this._listeners) listener(id);\n }\n\n private _runStarted(holder: ISupervised): void {\n holder.recentRuns.push({ startedAt: Date.now(), endedAt: null, outcome: null });\n if (holder.recentRuns.length > RECENT_RUNS_CAP) holder.recentRuns.shift();\n }\n\n /** Close the live tail record — idempotent; the first close wins. */\n private _runEnded(holder: ISupervised, outcome: TRunOutcome): void {\n const tail = holder.recentRuns[holder.recentRuns.length - 1];\n if (tail == null || tail.endedAt != null) return;\n tail.endedAt = Date.now();\n tail.outcome = outcome;\n }\n\n private _newHolder(definition: IResolvedCommanderProcess): ISupervised {\n return {\n definition,\n proc: null,\n envFingerprint: null,\n startedAt: null,\n stale: false,\n removed: false,\n blockedBy: null,\n degradedBy: new Set(),\n taskTimer: null,\n taskRun: null,\n chain: Promise.resolve(),\n sawOutputAt: null,\n lastTask: null,\n recentRuns: [],\n };\n }\n\n /** Serialize every control action per process id. */\n private _enqueue<T>(holder: ISupervised, action: () => Promise<T>): Promise<T> {\n const run = holder.chain.then(action, action);\n holder.chain = run.catch(() => {});\n return run;\n }\n\n private _ensureProc(holder: ISupervised): INiceProcess {\n const definition = holder.definition;\n const fingerprint = overrideFingerprint(definition, this._envOverrides);\n // A NiceProcess is built once and reused across restarts, so its env is fixed at construction:\n // without this, an override set while the process was up would survive a `restart` unapplied.\n // Only ever when idle — dropping the handle to a LIVE process would orphan its tree.\n if (\n holder.proc != null &&\n holder.envFingerprint !== fingerprint &&\n !ACTIVE_STATES.has(holder.proc.state)\n ) {\n holder.proc = null;\n }\n if (holder.proc != null) return holder.proc;\n holder.envFingerprint = fingerprint;\n const proc = createNiceProcess({\n id: definition.id,\n run: definition.run,\n ...(definition.shell != null ? { shell: definition.shell } : {}),\n cwd: definition.cwd,\n env: effectiveEnv(definition, this._envOverrides),\n stdin: definition.stdin,\n kind: definition.kind,\n ...(definition.ready != null ? { ready: definition.ready } : {}),\n ...(definition.restart != null ? { restart: definition.restart } : {}),\n stop: definition.stop,\n log: { ...definition.log, file: { dir: this._logsDir } },\n ledger: this._ledger,\n });\n proc.on(\"line\", (line) => {\n // One status notify per run, on the FIRST line only — `sawOutputAt` is how a viewer tells\n // a quiet worker from a child wedged before its first print, and it must not turn the\n // low-churn status realm into a per-line stream.\n if (holder.sawOutputAt == null) {\n holder.sawOutputAt = Date.now();\n this._notify(definition.id);\n }\n const stamp = this._sink.record(definition.id, line);\n const tapped = this._lineListeners.get(definition.id);\n if (tapped != null) for (const listener of tapped) listener(line);\n if (this._mergedListeners.size > 0) {\n const entry: ILogsEntry = { ...stamp, id: definition.id, line };\n for (const listener of this._mergedListeners) listener(entry);\n }\n });\n proc.on(\"state\", (next) => {\n // Covers every path into a fresh run, service auto-restarts included.\n if (next === \"starting\") {\n holder.sawOutputAt = null;\n this._runStarted(holder);\n }\n // Services close their run record here, on the terminal transition (which fires before\n // any backoff → restart cycle). Tasks do NOT: their record is closed where the run\n // settles (_awaitTaskExit), so a timeout kill reads \"timedOut\", not the bare \"stopped\"\n // the state alone would say.\n if (\n definition.kind === \"service\" &&\n (next === \"stopped\" || next === \"succeeded\" || next === \"failed\" || next === \"crashed\")\n ) {\n this._runEnded(\n holder,\n next === \"stopped\" ? \"stopped\" : next === \"succeeded\" ? \"succeeded\" : \"crashed\",\n );\n }\n this._recomputeDegraded();\n this._notify(definition.id);\n });\n holder.proc = proc;\n return proc;\n }\n\n /** A dependent is degraded while it is active and any dependency is not ready/succeeded. */\n private _recomputeDegraded(): void {\n for (const holder of this._holders.values()) {\n holder.degradedBy.clear();\n if (holder.proc == null || !ACTIVE_STATES.has(holder.proc.state)) continue;\n for (const depId of holder.definition.dependsOn) {\n const dep = this._holders.get(depId);\n if (dep?.proc == null) {\n holder.degradedBy.add(depId);\n continue;\n }\n const satisfied =\n dep.definition.kind === \"task\"\n ? dep.proc.state === \"succeeded\"\n : dep.proc.state === \"ready\";\n if (!satisfied) holder.degradedBy.add(depId);\n }\n }\n }\n\n /**\n * Edge 13 — a declared EXCLUSIVE endpoint that is already bound belongs to somebody else, and\n * spawning on top of it produces exactly the confusion the endpoint model exists to prevent:\n * the child either fails to bind with a message nobody reads, or (with a fallback binder)\n * quietly drifts to another port while readiness latches on the squatter (edge 48).\n *\n * ⚠ Reported, never cleared. Attributing a listening socket to a pid is not portable, so an\n * occupied port is surfaced and the start refused — killing an unidentified holder is the one\n * thing this must not do. Our own orphans are already gone by here (the boot scavenger reaps\n * them before anything starts) and a live foreign lease was refused earlier (C1).\n */\n private async _exclusiveEndpointConflict(holder: ISupervised): Promise<string | null> {\n for (const endpoint of holder.definition.endpoints) {\n if (endpoint.ownership !== \"exclusive\") continue;\n if (!(await tcpBound(endpoint.host, endpoint.port))) continue;\n // Confirm before failing: a restart's own listener may still be going away.\n await wait(ENDPOINT_RECHECK_MS);\n if (!(await tcpBound(endpoint.host, endpoint.port))) continue;\n return (\n `exclusive endpoint \"${endpoint.name}\" (${endpoint.host}:${endpoint.port}) is already ` +\n `in use — use inspect ports in the UI, or run \\`nice-commander ports ${holder.definition.id}\\` to identify and stop its owner`\n );\n }\n return null;\n }\n\n /** Wait until `proc.state` satisfies `want`, a terminal state intervenes, or the bound lapses. */\n private _waitForState(\n proc: INiceProcess,\n want: (state: TNiceProcessState) => boolean,\n timeoutMs: number,\n ): Promise<boolean> {\n if (want(proc.state)) return Promise.resolve(true);\n return new Promise((resolve) => {\n const off = proc.on(\"state\", (next) => {\n if (want(next) || !ACTIVE_STATES.has(next)) {\n off();\n clearTimeout(timer);\n resolve(want(next));\n }\n });\n const timer = setTimeout(() => {\n off();\n resolve(want(proc.state));\n }, timeoutMs);\n timer.unref();\n });\n }\n\n /**\n * Start a DAG-ordered id set. Dependencies are awaited (services to ready, tasks to\n * succeeded — task deps run once per transaction); a bounded wait reports `blocked` with\n * the dependency reason instead of hanging the action.\n */\n async start(\n orderedIds: readonly string[],\n options: { wait?: boolean; staggerMs?: number } = {},\n ): Promise<IActionReport> {\n const waitForReady = options.wait !== false;\n const staggerMs = options.staggerMs ?? 0;\n const results: IProcessActionResult[] = [];\n const taskRuns = new Map<string, Promise<IProcessActionResult>>();\n let spawned = 0;\n\n // Foreign execution leases (C1), read once per transaction: an id a live foreground `run`\n // holds is never double-started here — the mirror of the refusal `run` performs against us.\n let leased: ReadonlyMap<string, string>;\n try {\n leased = new Map(\n (await this._ledger.liveLeases()).map((record) => [\n record.id,\n record.owner?.kind ?? \"another\",\n ]),\n );\n } catch {\n leased = new Map(); // a ledger read failure must not wedge control\n }\n\n for (const id of orderedIds) {\n const holder = this._holders.get(id);\n if (holder == null) {\n results.push({ id, outcome: \"failed\", reason: \"unknown id\" });\n continue;\n }\n if (holder.removed) {\n results.push({ id, outcome: \"failed\", reason: \"removed from config\" });\n continue;\n }\n const leaseKind = leased.get(id);\n if (leaseKind != null) {\n results.push({\n id,\n outcome: \"failed\",\n reason: `held by a live \\`${leaseKind}\\` process — stop it there first`,\n });\n continue;\n }\n // Dependencies first — the ordered list already has them ahead of us.\n let blocked: string | null = null;\n for (const depId of holder.definition.dependsOn) {\n const dep = this._holders.get(depId);\n if (dep == null || dep.removed) {\n blocked = `dependency \"${depId}\" is unavailable`;\n break;\n }\n if (dep.definition.kind === \"task\") {\n const taskResult = await (taskRuns.get(depId) ?? this._runTaskOnce(dep, taskRuns));\n // A task run as a dependency only (not itself selected) still belongs in the report.\n if (!orderedIds.includes(depId)) results.push({ ...taskResult, id: depId });\n if (taskResult.outcome !== \"succeeded\") {\n blocked = `task dependency \"${depId}\" did not succeed (${taskResult.outcome})`;\n break;\n }\n } else if (dep.proc != null && ACTIVE_STATES.has(dep.proc.state)) {\n const ready = await this._waitForState(\n dep.proc,\n (state) => state === \"ready\",\n this._depWaitMs,\n );\n if (!ready) {\n blocked = `dependency \"${depId}\" did not become ready (${dep.proc.state})`;\n break;\n }\n } else if (dep.proc == null || dep.proc.state !== \"ready\") {\n blocked = `dependency \"${depId}\" is not running`;\n break;\n }\n }\n if (blocked != null) {\n holder.blockedBy = blocked;\n this._notify(id);\n results.push({ id, outcome: \"blocked\", reason: blocked });\n continue;\n }\n holder.blockedBy = null;\n\n // Tasks enqueue themselves inside _runTaskOnce (wrapping them here would self-deadlock\n // the holder's chain); services take the enqueue directly.\n //\n // ⚠ `wait: false` is honored for TASKS too (REVIEW-AND-FIX F2): the run is kicked off and\n // reported `spawned` — completion travels on the status realm, which every viewer already\n // renders. Before this, a task group's `start` reply blocked for the full run duration,\n // and the web UI's 10 s request deadline turned every real group run into a spurious\n // \"timeout\" while the tasks ran on fine. The promise still lands in `taskRuns`, so a\n // same-call dependent still awaits the actual outcome, never the ack.\n let result: IProcessActionResult;\n if (holder.definition.kind === \"task\") {\n const run = this._runTaskOnce(holder, taskRuns);\n if (waitForReady) {\n result = await run;\n } else {\n // State transitions and the task report flow through _notify regardless; this guard\n // only keeps an unawaited failure from becoming an unhandled rejection.\n run.catch(() => {});\n result = { id, outcome: \"spawned\" };\n }\n } else {\n result = await this._enqueue(holder, async (): Promise<IProcessActionResult> => {\n const proc = this._ensureProc(holder);\n if (ACTIVE_STATES.has(proc.state)) return { id, outcome: \"already-running\" };\n if (this._stopping) {\n return { id, outcome: \"failed\", reason: \"supervisor is stopping\" };\n }\n const conflict = await this._exclusiveEndpointConflict(holder);\n if (conflict != null) return { id, outcome: \"failed\", reason: conflict };\n if (spawned > 0 && staggerMs > 0) await wait(staggerMs);\n spawned += 1;\n try {\n await proc.start();\n holder.startedAt = Date.now();\n holder.stale = false;\n this._recomputeDegraded();\n this._notify(id);\n } catch (error) {\n // A spawn that fails after \"starting\" fired leaves an open run record — close it.\n this._runEnded(holder, \"failed\");\n return { id, outcome: \"failed\", reason: (error as Error).message };\n }\n if (!waitForReady) return { id, outcome: \"spawned\" };\n const ready = await this._waitForState(\n proc,\n (state) => state === \"ready\",\n this._depWaitMs,\n );\n if (ready) return { id, outcome: \"ready\" };\n return {\n id,\n outcome: \"failed\",\n reason: `did not become ready (state: ${proc.state})`,\n };\n });\n }\n results.push(result);\n }\n return { results, warnings: [] };\n }\n\n /**\n * A task within ONE start transaction: task dependencies run once per transaction, so a\n * repeat request inside the same action joins that run rather than starting a second one.\n */\n private _runTaskOnce(\n holder: ISupervised,\n taskRuns: Map<string, Promise<IProcessActionResult>>,\n ): Promise<IProcessActionResult> {\n const existing = taskRuns.get(holder.definition.id);\n if (existing != null) return existing;\n const run = this._taskRun(holder);\n taskRuns.set(holder.definition.id, run);\n return run;\n }\n\n /**\n * The active run of a task, coalesced ACROSS actions on the holder (M5) — two concurrent\n * `up`s sharing a task dependency join one run instead of executing it twice back to back.\n *\n * ⚠ Only the START TRANSITION takes the holder's chain; the wait for exit deliberately sits\n * OUTSIDE it. Holding the chain for a task's full duration made `stop`/`shutdown` queue behind\n * the task's own exit — an unbounded deadlock for a task with no `timeoutMs`, and the reason a\n * wedged check could hang daemon shutdown forever (C3, edges 14/36/39).\n */\n private _taskRun(holder: ISupervised): Promise<IProcessActionResult> {\n if (holder.taskRun != null) return holder.taskRun;\n const id = holder.definition.id;\n const run = (async (): Promise<IProcessActionResult> => {\n const failure = await this._enqueue(\n holder,\n async (): Promise<IProcessActionResult | null> => {\n const proc = this._ensureProc(holder);\n if (ACTIVE_STATES.has(proc.state)) return null; // already running — just await its exit\n if (this._stopping) return { id, outcome: \"failed\", reason: \"supervisor is stopping\" };\n const conflict = await this._exclusiveEndpointConflict(holder);\n if (conflict != null) return { id, outcome: \"failed\", reason: conflict };\n try {\n await proc.start();\n holder.startedAt = Date.now();\n holder.stale = false;\n this._notify(id);\n } catch (error) {\n // A spawn that fails after \"starting\" fired leaves an open run record — close it.\n this._runEnded(holder, \"failed\");\n return { id, outcome: \"failed\", reason: (error as Error).message };\n }\n return null;\n },\n );\n if (failure != null) return failure;\n return this._awaitTaskExit(holder);\n })().finally(() => {\n if (holder.taskRun === run) holder.taskRun = null;\n });\n holder.taskRun = run;\n return run;\n }\n\n /** Await a started task's exit (outside the chain, so a stop can always get through). */\n private async _awaitTaskExit(holder: ISupervised): Promise<IProcessActionResult> {\n const id = holder.definition.id;\n const proc = holder.proc;\n if (proc == null) return { id, outcome: \"failed\", reason: \"no active run\" };\n const timeoutMs = holder.definition.timeoutMs;\n let timedOut = false;\n const exit = await new Promise<INiceProcessExitInfo>((resolve) => {\n const off = proc.on(\"exit\", (info) => {\n off();\n if (holder.taskTimer != null) {\n clearTimeout(holder.taskTimer);\n holder.taskTimer = null;\n }\n resolve(info);\n });\n // An already-terminal process emits no new exit — report its recorded one.\n if (!ACTIVE_STATES.has(proc.state) && proc.lastExit != null) {\n off();\n resolve(proc.lastExit);\n return;\n }\n if (timeoutMs != null) {\n holder.taskTimer = setTimeout(() => {\n timedOut = true;\n holder.taskTimer = null;\n // The exit event resolves the promise above; a stop failure here must not become an\n // unhandled rejection that takes the daemon down (C2).\n void proc.stop().catch(() => {});\n }, timeoutMs);\n holder.taskTimer.unref();\n }\n });\n let outcome: ILastTaskRun[\"outcome\"];\n let reason: string | null = null;\n if (timedOut) {\n outcome = \"failed\";\n reason = `timeout after ${timeoutMs} ms`;\n } else if (exit.expected) {\n // A stop WE asked for is not a task failure. Without this, `down <task>` mid-run — or a\n // shutdown with tasks in flight — answered every coalesced `up` waiter with\n // \"failed: exit SIGTERM\" and painted the task panel red for a deliberate act. The timeout\n // rung above stays a failure: that stop is expected too, but the task genuinely did not\n // pass.\n outcome = \"stopped\";\n } else if (exit.code === 0) {\n outcome = \"succeeded\";\n } else {\n outcome = \"failed\";\n reason = `exit ${exit.code ?? exit.signal ?? \"unknown\"}`;\n }\n // Kept past the run — and notified — so `status` can answer \"what happened\" after the start\n // reply is gone. Before this, a timeout-killed task showed a bare \"stopped\" with the reason\n // living only in a reply nobody could re-read.\n const endedAt = Date.now();\n holder.lastTask = {\n outcome,\n reason,\n timedOut,\n endedAt,\n durationMs: holder.startedAt != null ? endedAt - holder.startedAt : null,\n definitionHash: holder.definition.definitionHash,\n };\n // The task's run record closes HERE, not on the terminal state transition: this is the only\n // place the timeout verdict exists. The tail is this run's record — no new run can have\n // started while this coalesced run was unsettled (M5).\n const tail = holder.recentRuns[holder.recentRuns.length - 1];\n if (tail != null) {\n tail.endedAt = endedAt;\n tail.outcome = timedOut ? \"timedOut\" : outcome;\n }\n this._notify(id);\n return reason != null ? { id, outcome, reason } : { id, outcome };\n }\n\n /** Stop a set (reverse-DAG order — dependents first), warning about live reverse dependents. */\n async stop(ids: readonly string[]): Promise<IActionReport> {\n const stopping = new Set(ids);\n // Removed-from-config processes keep their last definition in the holder — stop ordering\n // and reverse-dependency checks must see THEM too, not only the current config.\n const knownDefinitions = [...this._holders.values()].map((holder) => holder.definition);\n const warnings: string[] = [];\n for (const id of ids) {\n const live = [...this._holders.values()].filter((holder) => {\n if (stopping.has(holder.definition.id)) return false;\n if (holder.proc == null || !ACTIVE_STATES.has(holder.proc.state)) return false;\n return withDependencies(knownDefinitions, [holder.definition.id]).has(id);\n });\n if (live.length > 0) {\n warnings.push(\n `stopping \"${id}\" leaves live reverse dependents: ${live.map((h) => h.definition.id).join(\", \")}`,\n );\n }\n }\n const order = orderForStop(knownDefinitions, ids);\n const results: IProcessActionResult[] = [];\n for (const id of order) {\n const holder = this._holders.get(id);\n if (holder == null) {\n results.push({ id, outcome: \"failed\", reason: \"unknown id\" });\n continue;\n }\n results.push(\n await this._enqueue(holder, async (): Promise<IProcessActionResult> => {\n if (holder.proc == null || !ACTIVE_STATES.has(holder.proc.state)) {\n holder.blockedBy = null;\n return { id, outcome: \"already-stopped\" };\n }\n if (holder.taskTimer != null) {\n clearTimeout(holder.taskTimer);\n holder.taskTimer = null;\n }\n try {\n await holder.proc.stop();\n } catch (error) {\n return { id, outcome: \"failed\", reason: (error as Error).message };\n }\n this._recomputeDegraded();\n this._notify(id);\n return { id, outcome: \"stopped\" };\n }),\n );\n }\n return { results, warnings };\n }\n\n async restart(\n orderedIds: readonly string[],\n options: { wait?: boolean; staggerMs?: number } = {},\n ): Promise<IActionReport> {\n const stopped = await this.stop(orderedIds);\n const started = await this.start(orderedIds, options);\n return {\n results: started.results.map((result) => {\n const stopResult = stopped.results.find((candidate) => candidate.id === result.id);\n if (stopResult?.outcome !== \"failed\") return result;\n // A stop failure is reported even when the restart went on to succeed. Merging it only\n // into a failed start meant \"stop failed, start said already-running\" surfaced as a\n // clean success — hiding a tree the ladder could not verify gone.\n return result.outcome === \"failed\"\n ? { ...result, reason: `${stopResult.reason}; ${result.reason}` }\n : { ...result, reason: `restarted, but the stop reported: ${stopResult.reason}` };\n }),\n warnings: [...stopped.warnings, ...started.warnings],\n };\n }\n\n /**\n * Config reload (last-good already validated): changed definitions of RUNNING processes mark\n * `stale` (never auto-restart); deleted definitions stay addressable as `removed`; idle\n * processes just pick up the new definition on their next start.\n */\n applyConfig(next: IResolvedCommanderConfig): void {\n this._config = next;\n const seen = new Set<string>();\n for (const definition of next.processes) {\n seen.add(definition.id);\n const holder = this._holders.get(definition.id);\n if (holder == null) {\n this._holders.set(definition.id, this._newHolder(definition));\n continue;\n }\n // A definition that came back is startable again. Without this reset, one\n // comment-out/comment-in editing round left the id permanently \"removed from config\"\n // until the daemon restarted (M1).\n holder.removed = false;\n const active = holder.proc != null && ACTIVE_STATES.has(holder.proc.state);\n if (active && holder.definition.definitionHash !== definition.definitionHash) {\n holder.stale = true; // the running instance predates this definition — restart to apply\n }\n if (!active) {\n holder.proc = null; // next start builds on the new definition\n holder.envFingerprint = null;\n holder.stale = false;\n }\n holder.definition = definition;\n this._notify(definition.id);\n }\n for (const holder of this._holders.values()) {\n if (!seen.has(holder.definition.id)) {\n holder.removed = true;\n this._notify(holder.definition.id);\n }\n }\n }\n\n get envOverrides(): TEnvOverrides {\n return this._envOverrides;\n }\n\n /**\n * A new override store is live. Deliberately mirrors `applyConfig` rather than restarting\n * anything: a running process is marked drifted (see `status`), an idle one just picks the new\n * values up on its next start. Changing a value must never be able to kill a dev environment.\n */\n applyEnvOverrides(next: TEnvOverrides): void {\n this._envOverrides = next;\n for (const holder of this._holders.values()) this._notify(holder.definition.id);\n }\n\n status(): ISupervisedStatus[] {\n return [...this._holders.values()].map((holder) => {\n const proc = holder.proc;\n const rawState: ISupervisedStatus[\"state\"] =\n proc != null ? proc.state : holder.blockedBy != null ? \"blocked\" : \"not-started\";\n // A timeout kill lands as OUR stop, so nice-process honestly paints \"stopped\" — but the\n // run failed its check. Reporting the neutral state here made a timed-out task illegible\n // from `status`/the grid (the eye-mobile-app incident: \"stopped\", empty notes, and the\n // reason gone with the start reply). The remap is safe against later runs: any restart\n // moves the state off \"stopped\", and its own exit rewrites `lastTask`.\n const state: ISupervisedStatus[\"state\"] =\n rawState === \"stopped\" && holder.lastTask?.timedOut === true ? \"failed\" : rawState;\n const active = proc != null && ACTIVE_STATES.has(proc.state);\n const envVars = envVarViews(holder.definition, this._envOverrides, process.env);\n return {\n id: holder.definition.id,\n kind: holder.definition.kind,\n state,\n pid: proc?.pid ?? null,\n startedAt: holder.startedAt,\n sawOutputAt: holder.sawOutputAt,\n lastTask: holder.lastTask,\n // Copied: the ring mutates its tail record in place on close, and a status consumer\n // must never hold a live supervisor reference.\n recentRuns: holder.recentRuns.map((run) => ({ ...run })),\n restarts: proc?.restarts ?? 0,\n lastExit: proc?.lastExit ?? null,\n stale: holder.stale,\n removed: holder.removed,\n // Derived, not stored: \"what it is running with\" versus \"what a start would use now\" is\n // exactly the comparison, and a stored flag would be one more thing to keep in sync.\n envDrift:\n active &&\n holder.envFingerprint !== overrideFingerprint(holder.definition, this._envOverrides),\n blockedBy: holder.blockedBy,\n degradedBy: [...holder.degradedBy],\n unreadyReason: proc?.unreadyReason ?? null,\n capability: proc?.capability ?? null,\n tags: holder.definition.tags,\n detail: describe(holder.definition, envVars),\n };\n });\n }\n\n /** The shutdown ladder (edge 39): stop everything concurrently, bounded per ladder. */\n async shutdown(): Promise<{ errors: string[] }> {\n this._stopping = true;\n const errors: string[] = [];\n const stops = [...this._holders.values()].map((holder) =>\n this._enqueue(holder, async () => {\n if (holder.taskTimer != null) {\n clearTimeout(holder.taskTimer);\n holder.taskTimer = null;\n }\n if (holder.proc == null || !ACTIVE_STATES.has(holder.proc.state)) return;\n try {\n await holder.proc.stop();\n } catch (error) {\n errors.push(`${holder.definition.id}: ${(error as Error).message}`);\n }\n }),\n );\n await Promise.all(stops);\n this._sink.close();\n return { errors };\n }\n\n /**\n * Second-signal escalation (C3): skip the graceful rungs and end every owned tree NOW. An\n * impatient operator's second Ctrl+C must still mean \"kill the children\", never \"abandon\n * them\" — so this force-kills the trees and then lets each ladder verify and settle.\n */\n async forceStopAll(): Promise<void> {\n this._stopping = true;\n await Promise.allSettled(\n [...this._holders.values()].map(async (holder) => {\n const proc = holder.proc;\n if (proc?.pid == null) return;\n const pid = proc.pid;\n if (process.platform === \"win32\") {\n await taskkillTree(pid).catch(() => {});\n } else {\n try {\n signalProcessGroup(pid, \"SIGKILL\");\n } catch {\n // Already gone, or not ours to signal — the stop below reports what remains.\n }\n }\n await proc.stop().catch(() => {});\n }),\n );\n }\n}\n\n/** Reverse-DAG order over the given ids (dependents stop first); definition order breaks ties. */\n/**\n * The parts of a resolved definition a viewer needs to answer \"what is this, exactly?\" without\n * opening the config — and nothing more. ⚠ The resolved `env` is deliberately absent: it routinely\n * holds tokens, and every attached viewer would see it. `envVars` carries only what the config\n * declared as a knob, already stripped of secrets and of inherited values by `envVarViews`.\n */\nfunction describe(definition: IResolvedCommanderProcess, envVars: IEnvVarView[]): IProcessDetail {\n const run = definition.run;\n return {\n command: typeof run === \"string\" ? run : run.join(\" \"),\n cwd: definition.cwd,\n dependsOn: [...definition.dependsOn],\n envVars,\n ...(definition.timeoutMs == null ? {} : { timeoutMs: definition.timeoutMs }),\n ...(definition.ready == null ? {} : { ready: describeReady(definition.ready) }),\n endpoints: definition.endpoints.map((endpoint) => ({\n name: endpoint.name,\n protocol: endpoint.protocol,\n host: endpoint.host,\n port: endpoint.port,\n ownership: endpoint.ownership,\n ...(endpointUrl(endpoint) == null ? {} : { url: endpointUrl(endpoint) as string }),\n })),\n };\n}\n\nfunction describeReady(ready: NonNullable<IResolvedCommanderProcess[\"ready\"]>): string {\n switch (ready.kind) {\n case \"logMatch\":\n return `log matches ${String(ready.match)}`;\n case \"port\":\n return `port ${ready.port} accepts`;\n case \"httpOk\":\n return `GET ${ready.host ?? \"127.0.0.1\"}:${ready.port}${ready.path ?? \"/\"} is ok`;\n case \"delay\":\n return `${ready.ms} ms after spawn`;\n case \"exit0\":\n return \"process exits successfully\";\n }\n}\n\n/** Only http endpoints get a followable link; a tcp port is not something a browser can open. */\nfunction endpointUrl(endpoint: IResolvedCommanderProcess[\"endpoints\"][number]): string | undefined {\n if (endpoint.url != null) return endpoint.url;\n if (endpoint.protocol !== \"http\") return undefined;\n return `http://${endpoint.host}:${endpoint.port}`;\n}\n\nfunction orderForStop(\n definitions: readonly IResolvedCommanderProcess[],\n ids: readonly string[],\n): string[] {\n const set = new Set(ids);\n const seen = new Set<string>();\n const ordered: string[] = [];\n const visit = (id: string) => {\n if (!set.has(id) || seen.has(id)) return;\n seen.add(id);\n // Dependents (within the set) first.\n for (const proc of definitions) {\n if (set.has(proc.id) && proc.dependsOn.includes(id)) visit(proc.id);\n }\n ordered.push(id);\n };\n for (const proc of definitions) visit(proc.id);\n for (const id of ids) visit(id); // ids with no known definition still get stopped\n return ordered;\n}\n","// The daemon boot sequence (the hidden `nice-commander daemon` command). Early failures print\n// to stderr — the parent redirects that into the small boot-log handoff; once the rotated\n// daemon log opens, it owns the record of what happened. Boot order matters: scavenge orphans\n// BEFORE writing our instance record (our subdir is included while no live record exists).\n\nimport { randomUUID } from \"node:crypto\";\nimport { readdirSync } from \"node:fs\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { openProcessLedger, readProcessStartStamp } from \"@nice-code/process\";\nimport { type WebSocket, WebSocketServer } from \"ws\";\nimport { loadCommanderConfigFile } from \"../config/loader\";\nimport { validateCommanderConfig } from \"../config/validate\";\nimport {\n COMMANDER_BOOTSTRAP_PATH,\n COMMANDER_HEALTH_PATH,\n COMMANDER_LOGS_PATH,\n COMMANDER_TICKET_PATH,\n COMMANDER_TICKET_PROTOCOL_PREFIX,\n COMMANDER_WS_PATH,\n} from \"../protocol/auth\";\nimport type { ISetEnvInput } from \"../protocol/control\";\nimport { commanderStatusRealm } from \"../protocol/statusRealm\";\nimport { AggregateSink } from \"./aggregateSink\";\nimport { CommanderAuth, crossSiteRequestAllowed, hostIsLoopbackForm } from \"./auth\";\nimport { type IConfigWatch, watchCommanderConfig } from \"./configWatch\";\nimport { createControlPlane } from \"./controlPlane\";\nimport {\n commanderStatePaths,\n ensureStateDir,\n type ICommanderStatePaths,\n resolveCommanderDataDir,\n} from \"./dataDir\";\nimport { applyEnvMutation, countOverrides, readEnvOverrides } from \"./envOverrides\";\nimport {\n COMMANDER_PROTOCOL_VERSION,\n readInstanceRecord,\n recordDaemonAlive,\n removeInstanceRecord,\n writeInstanceRecord,\n} from \"./instanceRecord\";\nimport { createLogsEndpoint } from \"./logsEndpoint\";\nimport { commanderPackageVersion } from \"./packageVersion\";\nimport { RotatingLog } from \"./rotatingLog\";\nimport { commanderRuntimeError } from \"./runtime\";\nimport { serveClientFile } from \"./staticFiles\";\nimport { CommanderSupervisor } from \"./supervisor\";\n\nconst PORT_SCAN_LIMIT = 100;\nconst SCAVENGER_DIR_LIMIT = 32;\n/** Control inputs are small id lists — a bigger body is never legitimate. */\nconst MAX_BODY_BYTES = 32 * 1024;\n\nfunction argValue(argv: readonly string[], flag: string): string | null {\n const at = argv.indexOf(flag);\n return at >= 0 && at + 1 < argv.length ? (argv[at + 1] as string) : null;\n}\n\n\n/** Bounded global scavenger: dead-daemon ledgers in ANY config subdir get their orphans reaped. */\nasync function scavengeDeadDaemons(\n dataDir: string,\n ownConfigKey: string,\n log: (line: string) => void,\n): Promise<void> {\n let subdirs: string[];\n try {\n subdirs = readdirSync(dataDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .slice(0, SCAVENGER_DIR_LIMIT);\n } catch {\n return; // no data dir yet — nothing to scavenge\n }\n // ⚠ The booting config's OWN subdir is scavenged regardless of the cap (REVIEW-AND-FIX F3d).\n // The limit takes the first N readdir entries UNSORTED, so a data dir with more than\n // SCAVENGER_DIR_LIMIT configs could skip the one ledger that matters most here — the previous\n // generation of exactly this config, whose orphans this boot is about to collide with.\n if (!subdirs.includes(ownConfigKey)) subdirs.push(ownConfigKey);\n for (const configKey of subdirs) {\n try {\n const paths = commanderStatePaths(dataDir, configKey);\n const record = await readInstanceRecord(paths.instanceRecordPath);\n if (record != null && (await recordDaemonAlive(record))) continue; // a live daemon owns it\n // A stale record stays too: it's the generation tombstone the next daemon bumps off.\n const ledger = openProcessLedger({ dir: paths.stateDir, namespace: configKey });\n const result = await ledger.reapOrphans();\n if (result.reaped.length > 0 || result.quarantined.length > 0) {\n log(\n `scavenger[${configKey}]: reaped ${result.reaped.length} orphan record(s), quarantined ${result.quarantined.length}`,\n );\n }\n } catch (error) {\n log(`scavenger[${configKey}] failed: ${(error as Error).message}`);\n }\n }\n}\n\nexport interface IRunningDaemon {\n port: number;\n configKey: string;\n paths: ICommanderStatePaths;\n shutdown(): Promise<void>;\n}\n\nexport async function startCommanderDaemon(argv: readonly string[]): Promise<IRunningDaemon> {\n const runtimeError = commanderRuntimeError();\n if (runtimeError != null) throw new Error(runtimeError);\n const configArg = argValue(argv, \"--config\");\n if (configArg == null) throw new Error(\"daemon requires --config <path>\");\n const dataDir = argValue(argv, \"--data-dir\") ?? resolveCommanderDataDir();\n\n const file = await loadCommanderConfigFile(configArg);\n const { resolved, errors } = validateCommanderConfig(file.raw, {\n configPath: file.configPath,\n configDir: file.configDir,\n });\n if (resolved == null) {\n throw new Error(`config validation failed:\\n${errors.map((e) => ` - ${e}`).join(\"\\n\")}`);\n }\n\n const paths = commanderStatePaths(dataDir, resolved.configKey);\n await ensureStateDir(paths);\n const daemonLog = new RotatingLog(paths.daemonLogDir, \"daemon\");\n const log = (line: string) => daemonLog.write(`${new Date().toISOString()} ${line}`);\n log(`boot pid=${process.pid} runtime=${process.version} config=${file.configPath}`);\n\n await scavengeDeadDaemons(dataDir, resolved.configKey, log);\n\n const previous = await readInstanceRecord(paths.instanceRecordPath);\n const generation = (previous?.generation ?? 0) + 1;\n const ledger = openProcessLedger({\n dir: paths.stateDir,\n namespace: paths.ledgerNamespace,\n ownerKind: \"daemon\", // the execution lease a foreground `run` refuses to cross (C1)\n });\n const sink = new AggregateSink(paths.logsDir, paths.ingestSeqPath, generation);\n const envOverrides = await readEnvOverrides(paths.envOverridesPath);\n const supervisor = new CommanderSupervisor({\n config: resolved,\n ledger,\n sink,\n logsDir: paths.logsDir,\n envOverrides,\n });\n\n const token = randomUUID();\n const auth = new CommanderAuth(token);\n const startedAt = Date.now();\n let watcher: IConfigWatch | null = null;\n let shutdown: () => Promise<void> = async () => {}; // replaced once every resource exists\n\n // Env-override writes take one chain: the store is a single small file, and two overlapping\n // read-modify-writes would silently drop one of the two edits.\n let envWrites: Promise<unknown> = Promise.resolve();\n const setEnvOverrides = (input: ISetEnvInput): Promise<string[]> => {\n const run = envWrites.then(async () => {\n const applied = await applyEnvMutation(paths.envOverridesPath, supervisor.config, input);\n supervisor.applyEnvOverrides(applied.overrides);\n log(`env: ${countOverrides(applied.overrides)} override(s) live`);\n return applied.warnings;\n });\n envWrites = run.catch(() => {});\n return run;\n };\n\n const plane = createControlPlane({\n supervisor,\n generation,\n reloadConfig: () => watcher?.reloadNow() ?? Promise.resolve(),\n setEnvOverrides,\n requestShutdown: () => void shutdown(),\n log,\n });\n const logsPlane = createLogsEndpoint({ supervisor, segments: () => sink.segments(), log });\n\n const json = (response: ServerResponse, status: number, body: unknown): void => {\n response.writeHead(status, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"x-content-type-options\": \"nosniff\",\n });\n response.end(JSON.stringify(body));\n };\n\n const readBodyBounded = async (request: IncomingMessage): Promise<Buffer> => {\n const chunks: Buffer[] = [];\n let length = 0;\n for await (const chunk of request) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n length += buffer.length;\n if (length > MAX_BODY_BYTES) throw new Error(\"request body too large\");\n chunks.push(buffer);\n }\n return Buffer.concat(chunks);\n };\n\n const route = async (request: IncomingMessage, response: ServerResponse): Promise<void> => {\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\");\n // /health is the CLI's reuse probe — the instance-record root token, nothing else.\n if (url.pathname === COMMANDER_HEALTH_PATH) {\n if (!auth.isRoot(request.headers.authorization)) {\n json(response, 401, { error: \"unauthorized\" });\n return;\n }\n json(response, 200, {\n ok: true,\n configKey: resolved.configKey,\n generation,\n uptimeMs: Date.now() - startedAt,\n });\n return;\n }\n // Everything past here sits behind the cross-site + Host guards.\n if (!hostIsLoopbackForm(request.headers.host) || !crossSiteRequestAllowed(request)) {\n json(response, 403, { error: \"forbidden\" });\n return;\n }\n // Cookie/URL-free bootstrap: guarded + no-store, never the root token itself.\n if (url.pathname === COMMANDER_BOOTSTRAP_PATH && request.method === \"GET\") {\n json(response, 200, { capability: auth.mintCapability() });\n return;\n }\n if (url.pathname === COMMANDER_TICKET_PATH && request.method === \"POST\") {\n if (!auth.canMintTicket(request.headers.authorization)) {\n json(response, 401, { error: \"unauthorized\" });\n return;\n }\n json(response, 200, { ticket: auth.mintTicket() });\n return;\n }\n // The built web UI. GET-only, unauthenticated by design: these are static assets, and the\n // page they boot has no privileges until it exchanges the guarded `/bootstrap` capability\n // for a one-use ticket. Serving them behind a token would mean putting one in a URL.\n if (request.method === \"GET\") {\n // No catch-all SPA fallback: the UI is one page, so serving index.html for every unmatched\n // path would only make typos and probes look like the app. `/assets/*` are hashed bundles;\n // a root-level file with no further `/` is a static asset (favicon, web manifest).\n const asset = url.pathname.startsWith(\"/assets/\");\n const rootStatic = url.pathname.length > 1 && !url.pathname.includes(\"/\", 1);\n if (asset || url.pathname === \"/\" || rootStatic) {\n const servePath = asset ? url.pathname : url.pathname === \"/\" ? \"index.html\" : url.pathname.slice(1);\n if (await serveClientFile(servePath, response, asset)) return;\n json(response, 404, {\n error: asset\n ? \"not found\"\n : \"web UI not built — run `bun run build` in @nice-code/commander\",\n });\n return;\n }\n json(response, 404, { error: \"not found\" });\n return;\n }\n // The action channel's HTTP surface: root token (CLI) or a browser capability (POST).\n if (request.method === \"POST\" || request.method === \"OPTIONS\") {\n if (\n request.method === \"POST\" &&\n !auth.isRoot(request.headers.authorization) &&\n !auth.hasCapability(request.headers.authorization)\n ) {\n json(response, 401, { error: \"unauthorized\" });\n return;\n }\n const headers = new Headers();\n for (let i = 0; i < request.rawHeaders.length; i += 2) {\n headers.append(request.rawHeaders[i] ?? \"\", request.rawHeaders[i + 1] ?? \"\");\n }\n const body = request.method === \"POST\" ? await readBodyBounded(request) : undefined;\n const wireResponse = await plane.fetch(\n new Request(url, {\n method: request.method,\n headers,\n body: body == null ? undefined : new Uint8Array(body),\n }),\n );\n response.writeHead(wireResponse.status, Object.fromEntries(wireResponse.headers.entries()));\n response.end(Buffer.from(await wireResponse.arrayBuffer()));\n return;\n }\n json(response, 404, { error: \"not found\" });\n };\n\n const server: Server = createServer((request, response) => {\n void route(request, response).catch((error) => {\n log(`http ${request.method} ${request.url}: ${(error as Error).message}`);\n const tooLarge = (error as Error).message.includes(\"too large\");\n if (!response.headersSent) json(response, tooLarge ? 413 : 500, { error: \"internal\" });\n else response.end();\n });\n });\n\n const wss = new WebSocketServer({\n noServer: true,\n // The client offers `commander-auth.<ticket>`; selecting it completes the negotiation.\n handleProtocols: (protocols) => {\n for (const protocol of protocols) {\n if (protocol.startsWith(COMMANDER_TICKET_PROTOCOL_PREFIX)) return protocol;\n }\n return false;\n },\n });\n\n server.on(\"upgrade\", (request, socket, head) => {\n const reject = (status: string) => {\n socket.write(`HTTP/1.1 ${status}\\r\\n\\r\\n`);\n socket.destroy();\n };\n const lane = new URL(request.url ?? \"/\", \"http://127.0.0.1\").pathname;\n if (\n (lane !== COMMANDER_WS_PATH && lane !== COMMANDER_LOGS_PATH) ||\n !hostIsLoopbackForm(request.headers.host) ||\n !crossSiteRequestAllowed(request)\n ) {\n reject(\"403 Forbidden\");\n return;\n }\n const offered = String(request.headers[\"sec-websocket-protocol\"] ?? \"\")\n .split(\",\")\n .map((value) => value.trim());\n const authProtocol = offered.find((value) =>\n value.startsWith(COMMANDER_TICKET_PROTOCOL_PREFIX),\n );\n const ticket = authProtocol?.slice(COMMANDER_TICKET_PROTOCOL_PREFIX.length);\n // One-use ticket: a missing, replayed, or expired ticket never reaches the wire handshake.\n if (ticket == null || !auth.consumeTicket(ticket)) {\n reject(\"401 Unauthorized\");\n return;\n }\n wss.handleUpgrade(request, socket, head, (ws: WebSocket) => {\n if (lane === COMMANDER_WS_PATH) plane.handleConnection(ws);\n else logsPlane.handleConnection(ws);\n });\n });\n\n const port = await new Promise<number>((resolvePort, rejectPort) => {\n let candidate = resolved.daemon.port;\n const tryBind = () => {\n server.once(\"error\", (error: NodeJS.ErrnoException) => {\n if (error.code === \"EADDRINUSE\" && candidate < resolved.daemon.port + PORT_SCAN_LIMIT) {\n candidate += 1;\n tryBind();\n } else {\n rejectPort(error);\n }\n });\n server.listen(candidate, \"127.0.0.1\", () => resolvePort(candidate));\n };\n tryBind();\n });\n log(`listening on 127.0.0.1:${port} generation=${generation}`);\n\n // ⚠ Last gate before we claim this config (M4). The CLI's up-lock serializes `ensureDaemon`,\n // but it cannot cover a daemon that outlived its spawner's handshake timeout, nor a direct\n // `nice-commander daemon` invocation — either way the record write would clobber a LIVE\n // daemon's entry, leaving it supervising invisibly with only its pid to find it by.\n const incumbent = await readInstanceRecord(paths.instanceRecordPath);\n if (incumbent != null && (await recordDaemonAlive(incumbent))) {\n throw new Error(\n `another nice-commander daemon (pid ${incumbent.pid}, port ${incumbent.port}) already ` +\n `serves this config — stop it first (\\`nice-commander shutdown\\`).`,\n );\n }\n\n await writeInstanceRecord(paths.instanceRecordPath, {\n service: \"nice-commander\",\n instanceId: randomUUID(),\n generation,\n pid: process.pid,\n startStamp: await readProcessStartStamp(process.pid),\n port,\n token,\n configKey: resolved.configKey,\n configRevisionHash: resolved.configRevisionHash,\n configPath: resolved.configPath,\n protocolVersion: COMMANDER_PROTOCOL_VERSION,\n packageVersion: await commanderPackageVersion(),\n realmSchemaHash: commanderStatusRealm.schemaHash,\n });\n\n watcher = watchCommanderConfig({\n configPath: resolved.configPath,\n watchFiles: resolved.watchFiles,\n onConfig: (next) => {\n supervisor.applyConfig(next);\n plane.syncConfig(next);\n log(`config reloaded revision=${next.configRevisionHash}`);\n // Patch only the revision hash — the record's identity fields (pid/startStamp/token)\n // stay exactly as the CLI verified them.\n void readInstanceRecord(paths.instanceRecordPath)\n .then((current) => {\n if (current == null) return;\n return writeInstanceRecord(paths.instanceRecordPath, {\n ...current,\n configRevisionHash: next.configRevisionHash,\n });\n })\n .catch(() => {});\n },\n onError: (reloadErrors) => {\n // Last-good stays live; the errors become observable state on the status realm.\n plane.syncConfigError(reloadErrors);\n log(`config reload failed (last-good kept): ${reloadErrors.join(\"; \")}`);\n },\n });\n\n // A repeat call JOINS the ladder already in flight. It must never resolve early: the old\n // `if (shuttingDown) return` handed its caller an instant resolve, and the signal handler's\n // `process.exit(0)` then abandoned every child mid-ladder — edge 39's exact violation (C3).\n let shutdownInFlight: Promise<void> | null = null;\n shutdown = () => {\n shutdownInFlight ??= (async () => {\n log(\"shutdown requested\");\n watcher?.close();\n watcher = null;\n const { errors: stopErrors } = await supervisor.shutdown();\n for (const line of stopErrors) log(`stop error: ${line}`);\n await removeInstanceRecord(paths.instanceRecordPath);\n plane.close();\n logsPlane.close();\n wss.close();\n await new Promise<void>((resolveClose) => server.close(() => resolveClose()));\n sink.close();\n daemonLog.close();\n })();\n return shutdownInFlight;\n };\n\n let signalCount = 0;\n const onSignal = (signal: string): void => {\n signalCount += 1;\n if (signalCount === 1) {\n log(`${signal}: walking the shutdown ladder`);\n void shutdown().then(\n () => process.exit(0),\n (error: Error) => {\n log(`shutdown failed: ${error.message}`);\n process.exit(1);\n },\n );\n return;\n }\n if (signalCount === 2) {\n // Impatient operator: escalate to the force rungs — still verified, never a bare exit\n // that leaves the trees behind (the `run` two-Ctrl+C contract, applied to the daemon).\n log(`${signal} again: escalating to force`);\n void supervisor.forceStopAll().finally(() => {\n void removeInstanceRecord(paths.instanceRecordPath).finally(() => process.exit(1));\n });\n return;\n }\n log(`${signal} (${signalCount}): exiting now`);\n process.exit(1);\n };\n process.on(\"SIGINT\", () => onSignal(\"SIGINT\"));\n process.on(\"SIGTERM\", () => onSignal(\"SIGTERM\"));\n\n return { port, configKey: resolved.configKey, paths, shutdown };\n}\n\n/** The `nice-commander daemon` entry: boot, stay alive, exit nonzero on a boot failure. */\nexport async function runCommanderDaemon(argv: readonly string[]): Promise<number> {\n try {\n await startCommanderDaemon(argv);\n return await new Promise<number>(() => {}); // alive until a signal runs the shutdown ladder\n } catch (error) {\n process.stderr.write(`nice-commander daemon: ${(error as Error).message}\\n`);\n return 2;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA,MAA6B;CAC7B,SAAiB;CAEjB,YAAY,KAAa,UAAkB,UAA+B,CAAC,GAAG;EAC5E,CAAA,GAAA,QAAA,UAAA,CAAU,KAAK;GAAE,WAAW;GAAM,MAAM;EAAM,CAAC;EAC/C,KAAK,SAAA,GAAA,UAAA,KAAA,CAAa,KAAK,GAAG,SAAS,KAAK;EACxC,KAAK,gBAAgB,QAAQ,gBAAgB;EAC7C,KAAK,gBAAgB,QAAQ,gBAAgB;CAC/C;CAEA,IAAI,OAAe;EACjB,OAAO,KAAK;CACd;;CAGA,WAAqB;EACnB,MAAM,QAAkB,CAAC;EACzB,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,eAAe,SAAS,GAAG;GAC1D,MAAM,OAAO,UAAU,IAAI,KAAK,QAAQ,GAAG,KAAK,MAAM,GAAG;GACzD,KAAA,GAAA,QAAA,WAAA,CAAe,IAAI,GAAG,MAAM,KAAK,IAAI;EACvC;EACA,OAAO;CACT;CAEA,MAAM,MAAoB;EACxB,IAAI;GACF,IAAI,KAAK,OAAO,MAAM,KAAK,MAAM;GACjC,MAAM,OAAO,KAAK,SAAS,IAAI,IAAI,OAAO,GAAG,KAAK;GAClD,IAAI,KAAK,SAAS,KAAK,SAAS,KAAK,iBAAiB,KAAK,SAAS,GAAG,KAA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