{"version":3,"file":"main-CcxTP9yh.cjs","names":["sep","loadCommanderConfigFile","validateCommanderConfig","CommanderConfigLoadError","savedFilterId","hashCanonical","orderByDependency","withDependencies","runTaskPool","RuntimeCoordinate","orderByDependency","createPortInspector","createRealmServerEngine","commanderStatusRealm","serveChannel","commanderChannel","createMemoryStorageAdapter_json","wsAcceptorCarrier","httpAcceptorCarrier","commanderControlDomain","withDependencies","stopSetWithDependencies","createRealmAcceptor","createDefaultServeLogger","parseLogsClientMessage","withDuration","overrideFingerprint","runWithArgs","effectiveEnv","missingRequired","requiredRefusal","ancestors","identifyEndpointOwner","signalStray","resolveFlags","durationKey","withDependencies","envVarViews","estimateMs","commanderStatePaths","readInstanceRecord","recordDaemonAlive","commanderRuntimeError","resolveCommanderDataDir","loadCommanderConfigFile","validateCommanderConfig","ensureStateDir","findDaemonProcesses","readEnvOverrides","readLastStarts","writeLastStarts","readTaskDurations","writeTaskDurations","applyEnvMutation","countOverrides","readSavedFilters","mutateSavedFilters","writeSavedFilters","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/suiteRuns.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//\n// What is watched follows the config: the file, its declared `watchFiles`, and every local module\n// the latest load pulled in — so an edit to an imported helper reloads without being declared.\n\nimport { type FSWatcher, watch } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport { CommanderConfigLoadError, 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/**\n * `fs.watch` holds a descriptor per file on some platforms, and a config can import its way into\n * a whole source tree. Files past this many are still caught by the stat-reconcile pass.\n */\nconst MAX_FS_WATCHERS = 128;\n\nexport interface IConfigWatchOptions {\n  configPath: string;\n  /** What to watch beside the config until the first reload: declared files + the boot load's. */\n  watchFiles: readonly string[];\n  /** When the caller's own load of the config began — a file changed since then is reloaded. */\n  loadedAt: number;\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 = new Map<string, FSWatcher>();\n  let files = new Set([options.configPath, ...options.watchFiles]);\n\n  const rememberMtimes = async () => {\n    for (const file of files) {\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  /**\n   * Stamp the files no pass has stamped yet. One edited after the load that read it began stays\n   * unstamped, so the reconcile pass reloads it — that load may have read it before the edit.\n   */\n  const rememberDiscovered = async (loadStartedAt: number) => {\n    for (const file of files) {\n      if (mtimes.has(file)) continue;\n      try {\n        const { mtimeMs } = await stat(file);\n        if (mtimeMs < loadStartedAt) mtimes.set(file, mtimeMs);\n      } catch {\n        // missing — the reconcile pass reads that as \"unchanged\" until it appears\n      }\n    }\n  };\n\n  /** Move the watchers onto `next`. Only the difference is touched: a kept file keeps its watcher. */\n  const watchFiles = (next: Set<string>) => {\n    files = next;\n    for (const [file, watcher] of watchers) {\n      if (files.has(file)) continue;\n      watcher.close();\n      watchers.delete(file);\n      mtimes.delete(file);\n    }\n    for (const file of files) {\n      if (watchers.has(file) || watchers.size >= MAX_FS_WATCHERS) continue;\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.set(file, watcher);\n      } catch {\n        // Files that do not exist (yet) are covered by the reconcile pass.\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      const loadStartedAt = Date.now();\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 (closed) return;\n        if (resolved != null) {\n          watchFiles(new Set([options.configPath, ...resolved.watchFiles, ...file.loadedFiles]));\n          await rememberDiscovered(loadStartedAt);\n          options.onConfig(resolved);\n        } else {\n          // Last-good stays live, and so does its file set — plus what this attempt reached.\n          watchFiles(new Set([...files, ...file.loadedFiles]));\n          await rememberDiscovered(loadStartedAt);\n          options.onError(errors);\n        }\n      } catch (error) {\n        if (closed) return;\n        // A helper that failed to parse has to stay watched, or fixing it would reload nothing.\n        if (error instanceof CommanderConfigLoadError) {\n          watchFiles(new Set([...files, ...error.loadedFiles]));\n          await rememberDiscovered(loadStartedAt);\n        }\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  watchFiles(files);\n  void rememberDiscovered(options.loadedAt);\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 files) {\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.values()) watcher.close();\n    },\n    reloadNow: attempt,\n  };\n}\n","// A suite run inside the daemon: services up first (ordered, staggered), then the tasks through\n// the same dependency-gated pool the foreground `run` uses. The action that starts one answers on\n// acceptance; everything after travels on the status realm.\n\nimport { hashCanonical } from \"../config/hash\";\nimport { orderByDependency, withDependencies } from \"../config/resolve\";\nimport type { IActionReport, IRunSuiteInput, IRunSuiteReport } from \"../protocol/control\";\nimport { MAX_RECENTS, savedFilterId } from \"../protocol/savedFilters\";\nimport type { IStatusRun_Suite, TRunMemberVerdict } from \"../protocol/statusRealm\";\nimport { runTaskPool } from \"../run/scheduler\";\nimport type { CommanderSupervisor } from \"./supervisor\";\n\n/** Tasks a tag-group run starts at once — a suite declares its own. */\nconst TAG_GROUP_PARALLEL = 4;\n\nexport interface ISuiteRunnerOptions {\n  supervisor: Pick<CommanderSupervisor, \"config\" | \"start\" | \"stop\">;\n  /** Write a run into the realm, or drop it (`null`). */\n  publish: (runKey: string, run: IStatusRun_Suite | null) => void;\n  log: (line: string) => void;\n}\n\nexport interface ISuiteRunner {\n  run(input: IRunSuiteInput): IRunSuiteReport;\n  /** Settles when no run is in flight — tests and the shutdown ladder. */\n  idle(): Promise<void>;\n}\n\nexport function createSuiteRunner(options: ISuiteRunnerOptions): ISuiteRunner {\n  const { supervisor, publish, log } = options;\n  const runs = new Map<string, IStatusRun_Suite>();\n  const live = new Map<string, Promise<void>>();\n\n  const verdictOf = (report: IActionReport, id: string): TRunMemberVerdict => {\n    const outcome = report.results.find((result) => result.id === id)?.outcome;\n    if (outcome === \"blocked\") return \"blocked\";\n    return outcome === \"failed\" || outcome == null ? \"fail\" : \"pass\";\n  };\n\n  const evictTagGroupRuns = (): void => {\n    const ended = [...runs.entries()]\n      .filter(([, run]) => run.suite == null && run.endedAt != null)\n      .sort(([, a], [, b]) => (b.endedAt ?? 0) - (a.endedAt ?? 0));\n    for (const [key] of ended.slice(MAX_RECENTS)) {\n      runs.delete(key);\n      publish(key, null);\n    }\n  };\n\n  return {\n    idle: async () => {\n      await Promise.all(live.values());\n    },\n    run: (input) => {\n      const config = supervisor.config;\n      const suite = input.suite == null ? undefined : config.suites[input.suite];\n      if (input.suite != null && suite == null) {\n        return { accepted: false, reason: `unknown suite \"${input.suite}\"` };\n      }\n      const known = new Set(config.processes.map((proc) => proc.id));\n      const direct = (suite?.ids ?? input.ids ?? []).filter((id) => known.has(id));\n      if (direct.length === 0) return { accepted: false, reason: \"nothing to run\" };\n\n      const filterId = input.filter == null ? undefined : savedFilterId(input.filter);\n      const runKey = suite?.name ?? `tg-${hashCanonical(filterId ?? [...direct].sort(), 12)}`;\n      if (live.has(runKey)) return { accepted: false, runKey, reason: \"already running\" };\n\n      const ordered = orderByDependency(\n        config.processes,\n        withDependencies(config.processes, direct),\n      );\n      const byId = new Map(config.processes.map((proc) => [proc.id, proc]));\n      const definitions = ordered.flatMap((id) => byId.get(id) ?? []);\n      const services = definitions.filter((proc) => proc.kind === \"service\");\n      const tasks = definitions.filter((proc) => proc.kind === \"task\");\n\n      const previous = runs.get(runKey);\n      const run: IStatusRun_Suite = {\n        ...(suite != null ? { suite: suite.name } : {}),\n        ...(filterId != null ? { filterId } : {}),\n        startedAt: Date.now(),\n        ...(previous?.endedAt != null\n          ? { previousDurationMs: previous.endedAt - previous.startedAt }\n          : {}),\n        members: Object.fromEntries(ordered.map((id) => [id, \"pending\" as const])),\n      };\n      // ⚠ Always a COPY: the realm engine freezes what it is handed, and this object keeps\n      // changing for the life of the run.\n      const announce = (): void => publish(runKey, { ...run, members: { ...run.members } });\n      const mark = (id: string, verdict: TRunMemberVerdict): void => {\n        run.members[id] = verdict;\n        announce();\n      };\n      runs.set(runKey, run);\n      announce();\n\n      const execute = async (): Promise<void> => {\n        // Services first. Their task dependencies run inside this one transaction, so the pool\n        // below must not run them a second time.\n        const satisfied = new Set<string>();\n        if (services.length > 0) {\n          for (const proc of services) mark(proc.id, \"running\");\n          const report = await supervisor.start(\n            services.map((proc) => proc.id),\n            { wait: true, staggerMs: suite?.staggerMs ?? 0 },\n          );\n          for (const proc of services) mark(proc.id, verdictOf(report, proc.id));\n          for (const result of report.results) {\n            if (byId.get(result.id)?.kind !== \"task\") continue;\n            mark(result.id, result.outcome === \"succeeded\" ? \"pass\" : \"fail\");\n            if (result.outcome === \"succeeded\") satisfied.add(result.id);\n          }\n        }\n\n        const pool = await runTaskPool({\n          tasks: tasks.filter((task) => run.members[task.id] === \"pending\"),\n          parallel: input.parallel ?? suite?.parallel ?? TAG_GROUP_PARALLEL,\n          failFast: input.failFast ?? suite?.failFast ?? false,\n          run: async (task) => {\n            mark(task.id, \"running\");\n            const report = await supervisor.start([task.id], { wait: true, satisfied });\n            const verdict = verdictOf(report, task.id);\n            if (verdict === \"pass\") satisfied.add(task.id);\n            mark(task.id, verdict);\n            return verdict === \"pass\";\n          },\n          onBlocked: (task) => mark(task.id, \"blocked\"),\n          onFailFast: () => {\n            const running = tasks\n              .filter((task) => run.members[task.id] === \"running\")\n              .map((task) => task.id);\n            if (running.length > 0) void supervisor.stop(running);\n          },\n        });\n        for (const task of pool.leftover) mark(task.id, \"skipped\");\n\n        run.endedAt = Date.now();\n        run.outcome = Object.values(run.members).every((verdict) => verdict === \"pass\")\n          ? \"passed\"\n          : \"failed\";\n        announce();\n        log(`run ${runKey}: ${run.outcome} in ${run.endedAt - run.startedAt} ms`);\n        evictTagGroupRuns();\n      };\n\n      const settled = execute()\n        .catch((error: unknown) => {\n          run.endedAt = Date.now();\n          run.outcome = \"failed\";\n          announce();\n          log(`run ${runKey}: aborted — ${(error as Error).message}`);\n        })\n        .finally(() => live.delete(runKey));\n      live.set(runKey, settled);\n      return { accepted: true, runKey };\n    },\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  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, stopSetWithDependencies, withDependencies } from \"../config/resolve\";\nimport type { IResolvedCommanderConfig } from \"../config/types\";\nimport { createPortInspector } from \"../ports/listeners\";\nimport { commanderChannel, commanderControlDomain, type ISetEnvInput } from \"../protocol/control\";\nimport type { ISavedFilter } from \"../protocol/savedFilters\";\nimport {\n  commanderStatusRealm,\n  type IStatusProcessNode,\n  type TCommanderStatusState,\n} from \"../protocol/statusRealm\";\nimport type { TSavedFilterChange } from \"./savedFilters\";\nimport { createSuiteRunner } from \"./suiteRuns\";\nimport type { CommanderSupervisor, ISupervisedStatus } from \"./supervisor\";\n\nconst DAEMON_COORD = RuntimeCoordinate.env(\"commander_daemon\");\nconst SLOW_CONSUMER_DROP_BYTES = 256 * 1024;\nconst LIVE_STATES: ReadonlySet<string> = new Set([\n  \"starting\",\n  \"running\",\n  \"ready\",\n  \"unready\",\n  \"backoff\",\n  \"stopping\",\n]);\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  /** What the saved-filter store held at boot. */\n  savedFilters: readonly ISavedFilter[];\n  /** Persist a saved-filter change; resolves to the list now in force. */\n  changeSavedFilters: (change: TSavedFilterChange) => Promise<ISavedFilter[]>;\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.lastStartedAt != null ? { lastStartedAt: status.lastStartedAt } : {}),\n    flags: status.flags,\n    ...(status.estimatedMs != null ? { estimatedMs: status.estimatedMs } : {}),\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    ...(status.startError != null ? { startError: status.startError } : {}),\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    optIn: status.optIn,\n    detail: {\n      command: status.detail.command,\n      cwd: status.detail.cwd,\n      dependsOn: status.detail.dependsOn,\n      ...(status.detail.url != null ? { url: status.detail.url } : {}),\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      flags: status.detail.flags.map((flag) => ({\n        name: flag.name,\n        args: flag.args,\n        ...(flag.description != null ? { description: flag.description } : {}),\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 projectSuites(config: IResolvedCommanderConfig): TCommanderStatusState[\"suites\"] {\n  return Object.fromEntries(\n    Object.values(config.suites).map((suite) => [\n      suite.name,\n      {\n        ...(suite.description != null ? { description: suite.description } : {}),\n        members: orderByDependency(config.processes, new Set(suite.ids)),\n        parallel: suite.parallel,\n        failFast: suite.failFast,\n      },\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 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    suites: projectSuites(supervisor.config),\n    runs: {},\n    savedFilters: [...options.savedFilters],\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 suiteRunner = createSuiteRunner({\n    supervisor,\n    log,\n    publish: (runKey, run) => {\n      engine.update((draft: TCommanderStatusState) => {\n        if (run == null) delete draft.runs[runKey];\n        else draft.runs[runKey] = run;\n      });\n    },\n  });\n  const changeSavedFilters = async (change: TSavedFilterChange): Promise<void> => {\n    const next = await options.changeSavedFilters(change);\n    engine.update((draft: TCommanderStatusState) => {\n      draft.savedFilters = next;\n    });\n  };\n\n  const liveSockets = new Set<WebSocket>();\n  const server = serveChannel(commanderChannel, {\n    identity: DAEMON_COORD,\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, replaceSame, flags }) => {\n          const config = supervisor.config;\n          const ordered = orderByDependency(\n            config.processes,\n            withDependencies(config.processes, ids),\n          );\n          return supervisor.start(ordered, {\n            wait: wait ?? true,\n            staggerMs: staggerMs ?? 0,\n            replaceSame: replaceSame === true,\n            ...(flags != null ? { flags } : {}),\n          });\n        },\n        stop: async ({ ids, withDependencies: alsoDependencies }) => {\n          if (alsoDependencies !== true) return supervisor.stop(ids);\n          // From the supervisor's rows, not the config: a process removed from the config while\n          // it runs is no longer declared, and still needs what it depends on.\n          const statuses = supervisor.status();\n          const nodes = statuses.map((status) => ({\n            id: status.id,\n            dependsOn: status.detail.dependsOn,\n          }));\n          const live = new Set(\n            statuses.filter((status) => LIVE_STATES.has(status.state)).map((status) => status.id),\n          );\n          const { stop, kept } = stopSetWithDependencies(nodes, ids, (id) => live.has(id));\n          const neededBy = (id: string): string[] =>\n            nodes\n              .filter((node) => node.id !== id && live.has(node.id) && !stop.includes(node.id))\n              .filter((node) => withDependencies(nodes, [node.id]).has(id))\n              .map((node) => node.id);\n          const report = await supervisor.stop(stop);\n          return {\n            ...report,\n            warnings: [\n              ...report.warnings,\n              ...kept.map(\n                (id) => `\"${id}\" left running — still needed by ${neededBy(id).join(\", \")}`,\n              ),\n            ],\n          };\n        },\n        restart: async ({ ids, wait, staggerMs, replaceSame, flags }) => {\n          const config = supervisor.config;\n          const ordered = orderByDependency(\n            config.processes,\n            withDependencies(config.processes, ids),\n          );\n          return supervisor.restart(ordered, {\n            wait: wait ?? true,\n            staggerMs: staggerMs ?? 0,\n            stopIds: ids,\n            replaceSame: replaceSame === true,\n            ...(flags != null ? { flags } : {}),\n          });\n        },\n        runSuite: async (input) => {\n          const report = suiteRunner.run(input);\n          if (report.accepted && input.filter != null) {\n            await changeSavedFilters({ kind: \"ran\", query: input.filter, at: Date.now() });\n          }\n          return report;\n        },\n        saveFilter: async ({ filter, name }) => {\n          await changeSavedFilters({ kind: \"pin\", query: filter, name });\n          return { ok: true as const };\n        },\n        removeFilter: async ({ id }) => {\n          await changeSavedFilters({ kind: \"remove\", id });\n          return { ok: true as const };\n        },\n        setEnv: async (input) => ({\n          ok: true as const,\n          warnings: await options.setEnvOverrides(input),\n        }),\n        noteRuns: async ({ runs }) => {\n          for (const run of runs) supervisor.noteForegroundRun(run);\n          return { ok: true as const };\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            // Identity and negotiated security arrive from wire's trusted protocol context.\n            minSecurity: ESecurityLevel.authenticated,\n            resolveAvatar: (_ws, { client }) => {\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      }),\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  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.suites = projectSuites(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 { cp, rm } from \"node:fs/promises\";\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\n/**\n * Copy the client bundle into the daemon's state dir and serve that copy for the daemon's life.\n *\n * ⚠ An in-place upgrade rewrites `build/client` under a daemon still running the OLD code. Served\n * live, the page it hands out is the NEW client, which refuses to attach the old daemon's status\n * realm (`schema_mismatch`) — a page stuck on an error with no controls. Pinned, a daemon always\n * serves the client it was built with. Returns false (and stays on the lazy live lookup) when\n * nothing is built yet.\n */\nexport async function pinClientBundle(stateDir: string): Promise<boolean> {\n  clientDir = null;\n  const live = resolveClientDir();\n  if (!existsSync(join(live, \"index.html\"))) {\n    clientDir = null;\n    return false;\n  }\n  const pinned = join(stateDir, \"client\");\n  await rm(pinned, { recursive: true, force: true });\n  await cp(live, pinned, { recursive: true });\n  clientDir = normalize(pinned);\n  return true;\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  missingRequired,\n  overrideFingerprint,\n  requiredRefusal,\n  type TEnvOverrides,\n} from \"../config/envVars\";\nimport { type IFlagSelection, resolveFlags, runWithArgs } from \"../config/flags\";\nimport { withDependencies } from \"../config/resolve\";\nimport type { IResolvedCommanderConfig, IResolvedCommanderProcess } from \"../config/types\";\nimport { type IStray, signalStray } from \"../ports/definitionMatch\";\nimport { ancestors, identifyEndpointOwner } from \"../ports/listeners\";\nimport type { IActionReport, IProcessActionResult } from \"../protocol/control\";\nimport type { ILogsEntry } from \"../protocol/logs\";\nimport type { AggregateSink } from \"./aggregateSink\";\nimport type { TLastStarts } from \"./lastStarts\";\nimport { durationKey, estimateMs, type TTaskDurations, withDuration } from \"./taskDurations\";\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   * The last start request that spawned — from this daemon, else from the last-start store. Never\n   * moved by a crash-loop respawn, so a flapping service does not read as \"recently worked on\".\n   */\n  lastStartedAt: number | null;\n  /** The flags the current (or most recent) run was started with, in declaration order. */\n  flags: string[];\n  /**\n   * Tasks only: the mean of the latest successful runs with those same flags — what a running\n   * task's progress fills toward. Null until one such run has succeeded.\n   */\n  estimatedMs: 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  /** Running on a definition the config has since changed — restart to apply. */\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  /**\n   * Why the most recent start attempt did not spawn (an occupied endpoint, a spawn error, a\n   * foreign lease) — kept until a later start succeeds or the process is stopped, so `status`\n   * can answer \"why is it not running\" after the `up` that said so has scrolled away.\n   */\n  startError: string | null;\n  degradedBy: string[];\n  unreadyReason: TNiceProcessUnreadyReason | null;\n  capability: INiceProcessCapability | null;\n  tags: Record<string, string[]>;\n  optIn: boolean;\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  /** The definition's primary link, when it declares one apart from its endpoints. */\n  url?: 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  /** Declared flags, with what each appends; `[]` when none. */\n  flags: IFlagView[];\n  /** Tasks only: the run's hard cap — the UI draws elapsed/timeout from it. */\n  timeoutMs?: number;\n}\n\nexport interface IFlagView {\n  name: string;\n  /** The arguments it appends, joined for display. */\n  args: string;\n  description?: string;\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  /** The flags baked into `proc`'s argv when it was built — null while there is no process. */\n  procFlags: readonly string[] | null;\n  /** The `definitionHash` `proc` was built from — null while there is no process. */\n  procDefinitionHash: string | null;\n  startedAt: number | null;\n  /** This daemon's latest start, a foreground run's, or the store's from before this boot. */\n  lastStartedAt: number | null;\n  /** The flags of the current (or most recent) run. */\n  flags: readonly string[];\n  removed: boolean;\n  blockedBy: string | null;\n  /** The dependency `blockedBy` names — what `_recomputeBlocked` watches to clear the note. */\n  blockedOn: string | null;\n  startError: 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  /** The flags `taskRun` runs with — known from its request, before its spawn sets `flags`. */\n  taskRunFlags: readonly string[];\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  /** Last starts read from the store at boot — `lastStartedAt` until this daemon starts the id. */\n  lastStarts?: TLastStarts;\n  /** Every start that spawned, for the store to persist. */\n  onStart?: (id: string, at: number) => void;\n  /** Task run times read from the store at boot — the samples each estimate averages. */\n  taskDurations?: TTaskDurations;\n  /** The durations after a successful run added a sample, for the store to persist. */\n  onTaskDurations?: (durations: TTaskDurations) => void;\n}\n\n/** A start's flags: a selection, or null for \"no preference\" — plain if it spawns, else join. */\ntype TFlagRequest = IFlagSelection | null;\n\nconst NO_FLAGS: IFlagSelection = { flags: [], args: [] };\n\nconst sameFlags = (a: readonly string[], b: readonly string[]): boolean =>\n  a.length === b.length && a.every((flag, index) => flag === b[index]);\n\nconst flagsLabel = (flags: readonly string[]): string =>\n  flags.length === 0 ? \"no flags\" : `flags ${flags.join(\", \")}`;\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 readonly _lastStarts: TLastStarts;\n  private readonly _onStart: ((id: string, at: number) => void) | undefined;\n  private _taskDurations: TTaskDurations;\n  private readonly _onTaskDurations: ((durations: TTaskDurations) => void) | undefined;\n  private _stopping = false;\n  /** The daemon and its ancestors — never a stray, never signalled. Read once. */\n  private _protectedPids: Promise<ReadonlySet<number>> | null = null;\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    this._lastStarts = options.lastStarts ?? {};\n    this._onStart = options.onStart;\n    this._taskDurations = options.taskDurations ?? {};\n    this._onTaskDurations = options.onTaskDurations;\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  private _markStarted(holder: ISupervised): void {\n    const at = Date.now();\n    holder.startedAt = at;\n    holder.lastStartedAt = at;\n    holder.flags = holder.procFlags ?? [];\n    this._onStart?.(holder.definition.id, at);\n  }\n\n  private _recordDuration(key: string, ms: number): void {\n    this._taskDurations = withDuration(this._taskDurations, key, ms);\n    this._onTaskDurations?.(this._taskDurations);\n  }\n\n  /** Why a start that named flags did not get them: the process already runs another set. */\n  private _flagConflict(running: readonly string[], request: TFlagRequest): string | null {\n    if (request == null || sameFlags(request.flags, running)) return null;\n    return (\n      `already running with ${flagsLabel(running)} — restart it to run with ` +\n      flagsLabel(request.flags)\n    );\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      procFlags: null,\n      procDefinitionHash: null,\n      startedAt: null,\n      lastStartedAt: this._lastStarts[definition.id] ?? null,\n      flags: [],\n      removed: false,\n      blockedBy: null,\n      blockedOn: null,\n      startError: null,\n      degradedBy: new Set(),\n      taskTimer: null,\n      taskRun: null,\n      taskRunFlags: [],\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, flags: IFlagSelection = NO_FLAGS): INiceProcess {\n    const definition = holder.definition;\n    const fingerprint = overrideFingerprint(definition, this._envOverrides);\n    // A NiceProcess is built once and reused across restarts, so everything it was given is\n    // fixed at construction: without this, a definition or an override changed while the process\n    // was up would survive a `restart` unapplied, and a start with other flags would rerun the\n    // old ones. Only ever when idle — dropping the handle to a LIVE process would orphan its tree.\n    if (\n      holder.proc != null &&\n      (holder.procDefinitionHash !== definition.definitionHash ||\n        holder.envFingerprint !== fingerprint ||\n        !sameFlags(holder.procFlags ?? [], flags.flags)) &&\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    holder.procFlags = flags.flags;\n    holder.procDefinitionHash = definition.definitionHash;\n    const proc = createNiceProcess({\n      id: definition.id,\n      run: runWithArgs(definition.run, flags.args),\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._recomputeBlocked();\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   * A blocked note names ONE dependency; once that dependency is ready (or, for a task, has\n   * succeeded) the note is stale and is dropped. Before this, `status` could show a dependent\n   * \"blocked: dependency X is not running\" two rows under an X that was plainly ready — the\n   * reason was from an earlier generation and nothing ever re-evaluated it.\n   */\n  private _recomputeBlocked(): void {\n    for (const holder of this._holders.values()) {\n      if (holder.blockedBy == null || holder.blockedOn == null) continue;\n      const dep = this._holders.get(holder.blockedOn);\n      if (dep == null || dep.removed || dep.proc == null) continue;\n      const satisfied =\n        dep.definition.kind === \"task\"\n          ? dep.proc.state === \"succeeded\"\n          : dep.proc.state === \"ready\";\n      if (!satisfied) continue;\n      holder.blockedBy = null;\n      holder.blockedOn = null;\n      this._notify(holder.definition.id);\n    }\n  }\n\n  /**\n   * `required` is a start-time contract: nothing spawns until each such variable has a value —\n   * an override, a declared default, or this daemon's own environment, which the child inherits.\n   */\n  private _requiredRefusal(holder: ISupervised): string | null {\n    const missing = missingRequired(holder.definition, this._envOverrides, process.env);\n    return missing.length === 0 ? null : requiredRefusal(holder.definition.id, missing, \"daemon\");\n  }\n\n  private _protected(): Promise<ReadonlySet<number>> {\n    this._protectedPids ??= ancestors().then((pids) => new Set(pids));\n    return this._protectedPids;\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   * The owner is identified where the platform allows (argv + cwd, up the listener's ancestry).\n   * A STRAY — this very definition's command, started outside the daemon — is the one owner a\n   * start may replace, and only when asked (`replaceSame`); it is stopped as the tree that was\n   * matched. Anything else is reported with what it is and refused: killing an unidentified or\n   * foreign holder is the one thing this must not do. Our own orphans are already gone by here\n   * (the boot scavenger reaps them before anything starts) and a live foreign lease was refused\n   * earlier (C1).\n   */\n  private async _exclusiveEndpointConflict(\n    holder: ISupervised,\n    replaceSame: boolean,\n  ): Promise<string | null> {\n    const id = holder.definition.id;\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      const where = `exclusive endpoint \"${endpoint.name}\" (${endpoint.host}:${endpoint.port})`;\n      const owner = await identifyEndpointOwner(\n        holder.definition,\n        endpoint,\n        await this._protected(),\n      ).catch(() => null);\n      if (owner?.stray != null) {\n        const root = owner.stray.root.pid;\n        if (!replaceSame) {\n          return (\n            `${where} is held by a stray copy of this definition (pid ${root}, the same command ` +\n            `in the same cwd, started outside the daemon) — \\`up ${id} --replace-same\\` replaces ` +\n            `it, \\`ports ${id} --kill-owner\\` stops it, or set replaceSame: true on the definition`\n          );\n        }\n        if (await this._replaceStray(endpoint, owner.stray, holder.definition.stop.graceMs)) {\n          continue;\n        }\n        return (\n          `${where} is held by a stray copy of this definition (pid ${root}) that did not release ` +\n          `the port after SIGTERM and SIGKILL — \\`nice-commander ports ${id}\\` shows what remains`\n        );\n      }\n      if (owner != null) {\n        return (\n          `${where} is already in use by pid ${owner.pid} (${owner.command}` +\n          `${owner.cwd != null ? `, cwd ${owner.cwd}` : \"\"}) — not this definition's command, so ` +\n          `it is never stopped automatically; \\`nice-commander ports ${id}\\` inspects and stops it`\n        );\n      }\n      return (\n        `${where} is already in use — use inspect ports in the UI, or run ` +\n        `\\`nice-commander ports ${id}\\` to identify and stop its owner`\n      );\n    }\n    return null;\n  }\n\n  /** Take a stray's port: the same ladder a stop uses — SIGTERM, grace, SIGKILL — then verify. */\n  private async _replaceStray(\n    endpoint: { host: string; port: number },\n    stray: IStray,\n    graceMs = 4_000,\n  ): Promise<boolean> {\n    const released = async (bound: number): Promise<boolean> => {\n      const deadline = Date.now() + bound;\n      while (Date.now() < deadline) {\n        if (!(await tcpBound(endpoint.host, endpoint.port))) return true;\n        await wait(100);\n      }\n      return !(await tcpBound(endpoint.host, endpoint.port));\n    };\n    if ((await signalStray(stray, \"SIGTERM\")) === 0) return released(500);\n    if (await released(graceMs)) return true;\n    await signalStray(stray, \"SIGKILL\");\n    return released(2_000);\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: {\n      wait?: boolean;\n      staggerMs?: number;\n      /** Task dependencies a suite run already ran to success — never re-run inside it. */\n      satisfied?: ReadonlySet<string>;\n      /** Replace a stray on an exclusive endpoint for this action — see `replaceSame`. */\n      replaceSame?: boolean;\n      /** Declared flag names per id; an id without an entry starts plain (or joins a live run). */\n      flags?: Readonly<Record<string, readonly string[]>>;\n    } = {},\n  ): Promise<IActionReport> {\n    const waitForReady = options.wait !== false;\n    const staggerMs = options.staggerMs ?? 0;\n    const replaceSame = options.replaceSame === true;\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        holder.startError = `held by a live \\`${leaseKind}\\` process — stop it there first`;\n        this._notify(id);\n        results.push({ id, outcome: \"failed\", reason: holder.startError });\n        continue;\n      }\n      const requested = options.flags?.[id];\n      const flags = requested == null ? null : resolveFlags(holder.definition, requested);\n      if (flags != null && \"error\" in flags) {\n        results.push({ id, outcome: \"failed\", reason: flags.error });\n        continue;\n      }\n      // Dependencies first — the ordered list already has them ahead of us.\n      let blocked: string | null = null;\n      let blockedOn: string | null = null;\n      for (const depId of holder.definition.dependsOn) {\n        blockedOn = depId;\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          if (options.satisfied?.has(depId) === true) continue;\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        holder.blockedOn = blockedOn;\n        this._notify(id);\n        results.push({ id, outcome: \"blocked\", reason: blocked });\n        continue;\n      }\n      holder.blockedBy = null;\n      holder.blockedOn = 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, replaceSame, flags);\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, flags ?? NO_FLAGS);\n          if (ACTIVE_STATES.has(proc.state)) {\n            const conflict = this._flagConflict(holder.flags, flags);\n            return conflict == null\n              ? { id, outcome: \"already-running\" }\n              : { id, outcome: \"already-running\", reason: conflict };\n          }\n          if (this._stopping) {\n            return { id, outcome: \"failed\", reason: \"supervisor is stopping\" };\n          }\n          const unmet = this._requiredRefusal(holder);\n          if (unmet != null) {\n            holder.startError = unmet;\n            this._notify(id);\n            return { id, outcome: \"failed\", reason: unmet };\n          }\n          const conflict = await this._exclusiveEndpointConflict(\n            holder,\n            replaceSame || holder.definition.replaceSame,\n          );\n          if (conflict != null) {\n            holder.startError = conflict;\n            this._notify(id);\n            return { id, outcome: \"failed\", reason: conflict };\n          }\n          if (spawned > 0 && staggerMs > 0) await wait(staggerMs);\n          spawned += 1;\n          try {\n            await proc.start();\n            this._markStarted(holder);\n            holder.startError = null;\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            holder.startError = (error as Error).message;\n            this._notify(id);\n            return { id, outcome: \"failed\", reason: holder.startError };\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    replaceSame = false,\n    flags: TFlagRequest = null,\n  ): Promise<IProcessActionResult> {\n    const existing = taskRuns.get(holder.definition.id);\n    if (existing != null) return existing;\n    const run = this._taskRun(holder, replaceSame, flags);\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(\n    holder: ISupervised,\n    replaceSame = false,\n    flags: TFlagRequest = null,\n  ): Promise<IProcessActionResult> {\n    const id = holder.definition.id;\n    if (holder.taskRun != null) {\n      // Joining a run of OTHER flags would answer this request with that run's verdict.\n      const conflict = this._flagConflict(holder.taskRunFlags, flags);\n      return conflict == null\n        ? holder.taskRun\n        : Promise.resolve({ id, outcome: \"already-running\", reason: conflict });\n    }\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, flags ?? NO_FLAGS);\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 unmet = this._requiredRefusal(holder);\n          if (unmet != null) {\n            holder.startError = unmet;\n            this._notify(id);\n            return { id, outcome: \"failed\", reason: unmet };\n          }\n          const conflict = await this._exclusiveEndpointConflict(\n            holder,\n            replaceSame || holder.definition.replaceSame,\n          );\n          if (conflict != null) {\n            holder.startError = conflict;\n            this._notify(id);\n            return { id, outcome: \"failed\", reason: conflict };\n          }\n          try {\n            await proc.start();\n            this._markStarted(holder);\n            holder.startError = null;\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            holder.startError = (error as Error).message;\n            this._notify(id);\n            return { id, outcome: \"failed\", reason: holder.startError };\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    holder.taskRunFlags = flags?.flags ?? [];\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    const durationMs = holder.startedAt != null ? endedAt - holder.startedAt : null;\n    holder.lastTask = {\n      outcome,\n      reason,\n      timedOut,\n      endedAt,\n      durationMs,\n      definitionHash: holder.definition.definitionHash,\n    };\n    // Only a success is a sample: a failure often ends early, and a stop says nothing at all.\n    if (outcome === \"succeeded\" && durationMs != null) {\n      this._recordDuration(durationKey(id, holder.flags), durationMs);\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            // A stop is the operator acknowledging the row: its blocked/refused notes go too.\n            const noted = holder.blockedBy != null || holder.startError != null;\n            holder.blockedBy = null;\n            holder.blockedOn = null;\n            holder.startError = null;\n            if (noted) this._notify(id);\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  /**\n   * ⚠ Stops only `stopIds` — the ids the caller NAMED — then starts the whole ordered closure.\n   * Stopping the closure bounced every shared dependency under its other live dependents: a\n   * restart of three frontends took the backend down with it.\n   */\n  async restart(\n    orderedIds: readonly string[],\n    options: {\n      wait?: boolean;\n      staggerMs?: number;\n      stopIds?: readonly string[];\n      replaceSame?: boolean;\n      flags?: Readonly<Record<string, readonly string[]>>;\n    } = {},\n  ): Promise<IActionReport> {\n    const stopIds = options.stopIds ?? orderedIds;\n    // A restart is \"that again\": an id the request names no flags for keeps its last run's, less\n    // any a config reload has since removed.\n    const flags: Record<string, readonly string[]> = {};\n    for (const id of stopIds) {\n      const holder = this._holders.get(id);\n      if (holder == null) continue;\n      const declared = new Set(holder.definition.flags.map((flag) => flag.name));\n      flags[id] = options.flags?.[id] ?? holder.flags.filter((flag) => declared.has(flag));\n    }\n    const stopped = await this.stop(stopIds);\n    const started = await this.start(orderedIds, {\n      ...options,\n      flags: { ...options.flags, ...flags },\n    });\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). Nothing restarts: a RUNNING process whose\n   * definition changed reads `stale` until something restarts it, a deleted definition stays\n   * addressable as `removed`, and an idle process is rebuilt on its next start (`_ensureProc`).\n   *\n   * ⚠ No handle is dropped here, running or idle. A start that is between building its handle\n   * and spawning it would lose the process it is about to own — and a reload that changed nothing\n   * would still wipe every finished run's state and log ring.\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      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    this._recomputeBlocked();\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  /**\n   * A foreground `run` of `id`: outside this daemon, so never in its status — but still \"recently\n   * started\", and a success is still a sample for the estimate.\n   */\n  noteForegroundRun(run: {\n    id: string;\n    startedAt: number;\n    flags: readonly string[];\n    durationMs?: number;\n  }): void {\n    const holder = this._holders.get(run.id);\n    if (holder == null) return;\n    if ((holder.lastStartedAt ?? 0) < run.startedAt) {\n      holder.lastStartedAt = run.startedAt;\n      this._onStart?.(run.id, run.startedAt);\n    }\n    if (run.durationMs != null && holder.definition.kind === \"task\") {\n      this._recordDuration(durationKey(run.id, run.flags), run.durationMs);\n    }\n    this._notify(run.id);\n  }\n\n  status(): ISupervisedStatus[] {\n    return [...this._holders.values()].map((holder) => {\n      const proc = holder.proc;\n      const active = proc != null && ACTIVE_STATES.has(proc.state);\n      // A live note wins over an idle process: a refused or blocked start builds the NiceProcess\n      // without ever spawning it, and \"idle\" would say nothing about why nothing is running.\n      const rawState: ISupervisedStatus[\"state\"] = active\n        ? proc.state\n        : holder.blockedBy != null\n          ? \"blocked\"\n          : proc != null && proc.state !== \"idle\"\n            ? proc.state\n            : \"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 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        lastStartedAt: holder.lastStartedAt,\n        flags: [...holder.flags],\n        estimatedMs:\n          holder.definition.kind === \"task\"\n            ? estimateMs(this._taskDurations[durationKey(holder.definition.id, holder.flags)])\n            : null,\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        removed: holder.removed,\n        // `stale` and `envDrift` are derived, not stored: \"what it is running with\" versus \"what\n        // a start would use now\" is exactly the comparison, and a stored flag is one more thing a\n        // start or a reload can set wrongly.\n        stale: active && holder.procDefinitionHash !== holder.definition.definitionHash,\n        envDrift:\n          active &&\n          holder.envFingerprint !== overrideFingerprint(holder.definition, this._envOverrides),\n        blockedBy: holder.blockedBy,\n        startError: active ? null : holder.startError,\n        degradedBy: [...holder.degradedBy],\n        unreadyReason: proc?.unreadyReason ?? null,\n        capability: proc?.capability ?? null,\n        tags: holder.definition.tags,\n        optIn: holder.definition.optIn,\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    ...(definition.url == null ? {} : { url: definition.url }),\n    envVars,\n    flags: definition.flags.map((flag) => ({\n      name: flag.name,\n      args: flag.args.join(\" \"),\n      ...(flag.description == null ? {} : { description: flag.description }),\n    })),\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_SHUTDOWN_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 { findDaemonProcesses } from \"./daemonProcesses\";\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 { readLastStarts, type TLastStarts, writeLastStarts } from \"./lastStarts\";\nimport { createLogsEndpoint } from \"./logsEndpoint\";\nimport { commanderPackageVersion } from \"./packageVersion\";\nimport { RotatingLog } from \"./rotatingLog\";\nimport { commanderRuntimeError } from \"./runtime\";\nimport {\n  mutateSavedFilters,\n  readSavedFilters,\n  type TSavedFilterChange,\n  writeSavedFilters,\n} from \"./savedFilters\";\nimport { pinClientBundle, serveClientFile } from \"./staticFiles\";\nimport { CommanderSupervisor } from \"./supervisor\";\nimport { readTaskDurations, type TTaskDurations, writeTaskDurations } from \"./taskDurations\";\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 * A store save that coalesces: a suite run starts many processes in one burst, and only the newest\n * value needs to land — a save queued behind a write in flight takes whatever is newest by then.\n */\nfunction latestWins<T>(write: (value: T) => Promise<void>): (value: T) => void {\n  let latest: T;\n  let queued = false;\n  let writes: Promise<void> = Promise.resolve();\n  return (value) => {\n    latest = value;\n    if (queued) return;\n    queued = true;\n    writes = writes.then(() => {\n      queued = false;\n      return write(latest);\n    });\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 configLoadedAt = Date.now();\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  // ⚠ One daemon per config, checked by argv before anything is touched. A live peer whose\n  // record is skewed or already lost is invisible to the record gate below — and booting past\n  // it (onto the next free port) is exactly how a daemon gets orphaned.\n  const peers = await findDaemonProcesses(configArg, argValue(argv, \"--data-dir\") ?? dataDir);\n  if (peers.length > 0) {\n    throw new Error(\n      `another nice-commander daemon (pid ${peers.map((peer) => peer.pid).join(\", \")}) already ` +\n        \"serves this config — stop it first (`nice-commander shutdown`).\",\n    );\n  }\n\n  await scavengeDeadDaemons(dataDir, resolved.configKey, log);\n  const servesOwnClient = await pinClientBundle(paths.stateDir).catch((error: Error) => {\n    log(`client bundle not pinned (serving it live): ${error.message}`);\n    return false;\n  });\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\n  let lastStarts = await readLastStarts(paths.lastStartsPath);\n  const saveLastStarts = latestWins((value: TLastStarts) =>\n    writeLastStarts(paths.lastStartsPath, value).catch((error: Error) =>\n      log(`last starts not saved: ${error.message}`),\n    ),\n  );\n  const taskDurations = await readTaskDurations(paths.taskDurationsPath);\n  const saveTaskDurations = latestWins((value: TTaskDurations) =>\n    writeTaskDurations(paths.taskDurationsPath, value).catch((error: Error) =>\n      log(`task durations not saved: ${error.message}`),\n    ),\n  );\n\n  const supervisor = new CommanderSupervisor({\n    config: resolved,\n    ledger,\n    sink,\n    logsDir: paths.logsDir,\n    envOverrides,\n    lastStarts,\n    onStart: (id, at) => {\n      lastStarts = { ...lastStarts, [id]: at };\n      saveLastStarts(lastStarts);\n    },\n    taskDurations,\n    onTaskDurations: saveTaskDurations,\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  // Same single-writer chain as the env store, for the same reason.\n  let savedFilters = await readSavedFilters(paths.savedFiltersPath);\n  let filterWrites: Promise<unknown> = Promise.resolve();\n  const changeSavedFilters = (change: TSavedFilterChange) => {\n    const run = filterWrites.then(async () => {\n      savedFilters = mutateSavedFilters(savedFilters, change);\n      await writeSavedFilters(paths.savedFiltersPath, savedFilters);\n      return savedFilters;\n    });\n    filterWrites = run.catch(() => {});\n    return run;\n  };\n\n  const plane = createControlPlane({\n    supervisor,\n    generation,\n    reloadConfig: () => watcher?.reloadNow() ?? Promise.resolve(),\n    setEnvOverrides,\n    savedFilters,\n    changeSavedFilters,\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_SHUTDOWN_PATH && request.method === \"POST\") {\n      if (\n        !auth.isRoot(request.headers.authorization) &&\n        !auth.hasCapability(request.headers.authorization)\n      ) {\n        json(response, 401, { error: \"unauthorized\" });\n        return;\n      }\n      log(\"shutdown requested over http\");\n      json(response, 202, { accepted: true });\n      // Ack first, ladder second — the same order the wire's shutdown action keeps.\n      setTimeout(() => void shutdown(), 25).unref();\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\n          ? url.pathname\n          : url.pathname === \"/\"\n            ? \"index.html\"\n            : 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    servesOwnClient,\n  });\n\n  watcher = watchCommanderConfig({\n    configPath: resolved.configPath,\n    watchFiles: [...resolved.watchFiles, ...file.loadedFiles],\n    loadedAt: configLoadedAt,\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  // Only ever OUR entry: deleting a peer's record is how that peer ends up running where no\n  // lookup can find it. A record that reads as someone else's (or not at all) is left alone.\n  const removeOwnRecord = async (): Promise<void> => {\n    const current = await readInstanceRecord(paths.instanceRecordPath);\n    if (current?.pid === process.pid) await removeInstanceRecord(paths.instanceRecordPath);\n  };\n\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 removeOwnRecord();\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 removeOwnRecord().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,cA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