/** One line of `exit-history.jsonl` (FEAT-440 AC-1/AC-5). `durationMs` is * what lets a reader (doctor's crash-loop check) tell a real crash apart * from the instance-lock's healthy <100ms fast-exit — both can produce * `exitCode: 0`, but only genuine runs have a non-trivial duration; either * way `exitCode !== 0` is the actual crash signal the streak counts. */ export interface ExitHistoryEntry { ts: string; exitCode: number; durationMs: number; } export interface ShimPointer { nodeBin: string; entryJs: string; port: number; /** When set, the launcher exports ASTRA_LOG_DIR so the daemon rotates its * JSON logs there (service mode) instead of writing to a discarded stdout. */ logDir?: string; /** * Set true ONLY by `reinstall --dev` (FEAT-438 SLICE-418 AC-4): `entryJs` * points at the mutable checkout's `dist/` instead of an immutable release * dir. writePointer/writeShim round-trip this field like any other — the * doctor pointer check and `reinstall --rollback`'s target-selection logic * both read it back to tell a dev-pinned install apart from a release- * pinned one. Absent/false means release-pinned (the default, safe state). */ devPinned?: boolean; } export interface ShimPaths { binDir: string; cmdPath: string; launcherPath: string; pointerPath: string; /** * Hidden-launch VBS wrapper (win32 only, D1 slice 6 "windowless daemon"). * Present on every platform's `ShimPaths` for a single consistent shape, * but only ever written by `writeShim` when `cmdPath` is the `.cmd` form * (win32) — linux/darwin never had a console-flash problem (no conhost), * so this path is simply unused there. See `buildHiddenVbs`'s doc comment * for why the wrapper is a blocking `WScript.Shell.Run` rather than a * fire-and-forget one. */ vbsPath: string; } export interface ExitHistoryPaths { logsDir: string; historyPath: string; crashLogPath: string; } /** * Paths for the shim's own crash-loop observability artifacts (FEAT-440) — * distinct from the daemon's own rotated file logger (`ASTRA_LOG_DIR`'s * `daemon.log`, see log/logger.ts). Lives in the SAME `/logs` * directory (install-flow.ts / reinstall.ts already point `ASTRA_LOG_DIR` * there) but under different filenames so the two never collide: * - `exit-history.jsonl` — ring-buffered `{ts, exitCode, durationMs}` per * daemon exit, last 50 entries. * - `crash.log` — rolling last-~64KB of captured child stderr, verbatim, * so pre-file-logger boot errors survive the process exiting. * `LAUNCHER_SOURCE` below computes the identical path via * `join(__dirname, '..', 'logs')` (its `__dirname` is always `binDir`) — * this function is the TS-side mirror the doctor "Crash loop" check reads * from; the two must stay in lock-step on directory/filenames. */ export declare function exitHistoryPaths(dataDirOverride?: string): ExitHistoryPaths; /** * Captured stdout+stderr of the win32 hang-watchdog probe * (`astramem-local service watchdog-probe`, watchdog-probe.ts). Lives * alongside the shim's own exit-history/crash-log artifacts under the same * `/logs` directory (see exitHistoryPaths above) rather than a new * top-level location. * * Root cause this closes (watchdog-probe-output-capture, 2026-08-02): the * probe's scheduled task (schtasks.ts's `installWatchdogTimer`) runs hidden * via a `WScript.Shell.Run(cmd, 0, True)` VBS wrapper (`buildHiddenVbs` * below) with ZERO output capture — every diagnostic line the probe prints * (cli/service.ts's `[watchdog-probe] healthy/UNHEALTHY — action: detail`, * and stopLockHolder's own fail-closed reasons) was discarded outright. That * is exactly what made a live incident undiagnosable: the probe detected a * wedged daemon and its kill attempts failed for 45 minutes with no * on-disk trace of why. `schtasks.ts`'s `buildWatchdogProbeWrapperCmd` * redirects the probe's real invocation into this file via a generated * batch wrapper — the plain-shell equivalent of what `launch.cjs` already * does for the daemon itself via real fds (see LAUNCHER_SOURCE's stdio * comment above). * * systemd/launchd never had this gap: a systemd `Type=oneshot` unit's * stdout/stderr default to the journal, and launchd's watchdog agent plist * already sets `StandardOutPath`/`StandardErrorPath` (launchd.ts's * `buildWatchdogPlist`) — so this path is win32-only. */ export declare function watchdogProbeLogPath(dataDirOverride?: string): string; /** Size cap for watchdogProbeLogPath — mirrors the repo-standard rotation * size (`LOG_ROTATE_MAX_BYTES`, log/logger.ts; also what ingest.log * rotates at). The probe fires every `WATCHDOG_PROBE_INTERVAL_SEC` (3 min) * and prints one short line per run, so growth is slow — this is a * cheap truncate-if-over-size guard, not a real rotation scheme. Checked * and enforced by the generated wrapper itself (buildWatchdogProbeWrapperCmd) * since there is no live process to run a rotation sweep between scheduled * runs. */ export declare const WATCHDOG_PROBE_LOG_MAX_BYTES: number; /** Distinguishable non-zero exit code `buildWatchdogProbeWrapperCmd`'s * generated wrapper returns when its SCRATCH capture file was never * created — meaning the real probe command never actually ran (see that * function's doc comment for the %TEMP%-unwritable mechanism this guards * against). Deliberately not 1 (the everyday "something failed" code a * real probe run could also return) so schtasks' "Last Result" column can * tell "the probe ran and reported unhealthy" apart from "the probe never * ran at all." */ export declare const WATCHDOG_PROBE_SCRATCH_WRITE_FAILURE_EXIT = 98; /** * Batch-file body for the win32 watchdog probe's hidden-launch wrapper * (watchdog-probe-output-capture, 2026-08-02; log-write isolation fixed same * day after review — PR #471). `schtasks.ts`'s `installWatchdogTimer` writes * this to a stable `.cmd` file and points the hidden-launch VBS * (`buildHiddenVbs`) at THAT file instead of at the raw probe command line * directly — the daemon's own VBS already proves `WScript.Shell.Run` can * hidden-launch a `.cmd` file this way (see `buildWindowsCmd`/`writeShim` * above), so this reuses the same indirection rather than trying to embed * shell-redirection syntax straight into a VBS string literal. * * The FIRST version of this wrapper nested the real probe invocation * directly inside the log-append block: `( echo ... & ) >> logPath * 2>&1`. Review caught (and live-reproduced through real cmd.exe, twice) * that when the redirect target can't be opened — a file sitting where the * `logs` directory should be, or the log file held open exclusively by * another process (AV, backup, an operator tailing the log mid-incident) — * **cmd.exe skips the entire parenthesized block**, so the probe command * itself never runs. A logging hiccup could silently disable the watchdog * entirely: the exact silent-failure class this file exists to close. * * Fixed by decoupling the probe's execution from the log write, the same * way `LAUNCHER_SOURCE` above never lets its own log/history writes block * the daemon's spawn (there it's a JS try/catch around fs calls; here, * batch has no try/catch, so the equivalent is TWO INDEPENDENT STEPS): * 1. Run the real probe command with its stdout+stderr redirected to a * private SCRATCH file under `%TEMP%` — deliberately NOT under * `logDir`, so a `logDir` failure can never stop this step from * succeeding — and capture `%ERRORLEVEL%` immediately after, before * any other command can overwrite it. * 2. Best-effort copy that scratch file into the shared `logPath` * (mkdir the log dir if missing, truncate over `maxBytes`, `type ... * >> logPath`) — every one of these can fail (blocked dir, locked * file, full disk, read-only path) without affecting step 1, since * step 1 already ran and its exit code is already saved. * The wrapper's own `exit /b %PROBE_EXIT%` at the end always propagates the * PROBE's exit code (not the log-copy step's), regardless of what happened * to the shared log — schtasks' "Last Result" column is a diagnostic this * repo relies on, so that propagation is the actual invariant here, not * just "the log gets written when possible." * * Running the probe command as a plain (non-parenthesized) line also * sidesteps a second hazard the parenthesized form had: a probe command * whose quoted `execPath` contains literal parens (a real "Program Files * (x86)" install) no longer has to round-trip through `(...)` block * parsing at all. * * ROUND 3 (same day, second review pass on PR #471): the two-step split * above closed the "log write breaks the probe" class, but introduced a * narrower, WORSE-in-kind one — a false SUCCESS rather than a lost run. * When `%TEMP%`/`%TMP%` itself points at a directory that doesn't exist, * `cmd.exe` does not update `%ERRORLEVEL%` when a redirect target can't be * opened for an EXTERNAL program (verified against real cmd.exe) — so * `set "PROBE_EXIT=%ERRORLEVEL%"` right after the probe line would * silently capture a STALE 0 left over from an earlier successful internal * command, and the probe never actually launched. That is a watchdog * reporting healthy while it never checked anything — exactly the * "reports ok while actually broken" failure class this repo's ADR-015 * loud-failure invariant exists to kill, and worse than the round-2 bug * because it can't even be told apart from a genuine clean run by reading * schtasks' Last Result column. Two independent guards now close it: * - `mkdir "%TEMP%"` up front self-heals the common sub-case (parent * directory exists, `%TEMP%` itself just doesn't) — the probe then * runs and returns its own real exit code, same as any healthy run. * - `if not exist "%SCRATCH%" exit /b ` * is the real backstop, for cases the mkdir can't fix (e.g. a file * sitting where a path component of `%TEMP%` should be a directory — * the exact mirror of the round-2 `logDir` bug, just applied to * `%TEMP%` instead). If the scratch file was never created, the probe * never ran, full stop — the wrapper exits with a code that's * deliberately distinguishable from both 0 (healthy) and a real * probe-reported failure, so a genuinely lost run can never be * mistaken for either. * * @param commandLine The real ` service watchdog-probe` command, * already quoted the same way schtasks.ts's other wrapped commands are. * @param logPath Absolute path to the captured-output log file * (watchdogProbeLogPath()). */ export declare function buildWatchdogProbeWrapperCmd(commandLine: string, logPath: string, maxBytes?: number): string; /** * Stable bin dir: /bin (same root as the data dir; on * win32 this is byte-identical to the pre-FEAT-443 `%LOCALAPPDATA%\Astramem\bin` * since `defaultDataDir()` already resolves to `%LOCALAPPDATA%\Astramem`). * * @param dataDirOverride Test-only seam — overrides the base dir wholesale * (production callers never pass this; they let it resolve from the real * `defaultDataDir()`). * @param platformOverride Test-only seam — decides the shim script's format * (win32 → `.cmd` batch, else → POSIX `.sh`) independent of the host OS * running the test, mirroring `getServiceAdapter(overridePlatform)`'s * pattern. Production callers never pass this either. */ export declare function shimPaths(dataDirOverride?: string, platformOverride?: NodeJS.Platform): ShimPaths; /** * Atomically write current.json (tmp-file + rename — same pattern as * config/writer.ts's writeConfig / instance-lock.ts's lock steal). A reader * (the launcher on daemon start, or a `reinstall` repoint/rollback) must * never observe a torn/partial pointer file: rename() is atomic on the same * filesystem, so a concurrent read always sees either the complete old * pointer or the complete new one (FEAT-438 SLICE-417 AC-4). */ export declare function writePointer(pointer: ShimPointer, pointerPath: string): void; /** * Hidden-launch VBS wrapper (win32 only, D1 slice 6 "windowless daemon"). * * Root cause this closes: the scheduled task's Exec ultimately runs cmd.exe * (via the `.cmd` shim) under `InteractiveToken` — * that spawns a real conhost console window that stays open for the * daemon's entire lifetime (the PT5M keepalive re-runs it every 5 minutes, * so the window either persists or repeatedly flashes). Task Scheduler's * `` setting only hides the TASK from the UI, not the window its * Action creates — it does not suppress the console at all. * * `wscript.exe` (schtasks.ts's `hiddenLaunchExec`) is a windowless script * host; running a `WScript.Shell.Run` call inside it with `windowStyle = 0` * launches the wrapped command with no window whatsoever. The SECOND * argument, `bWaitOnReturn`, is set to `True` — this is load-bearing, not * incidental: * * - `launch.cjs` deliberately uses blocking `spawnSync` (not a detached * spawn) so the scheduler's own process lifetime matches the daemon's — * that is what lets the PT5M keepalive repetition, `schtasks /end`, and * `service status` all reflect reality (see LAUNCHER_SOURCE's header * comment above for the identical rationale on the daemon side). * - A fire-and-forget `Run(cmd, 0, False)` returns to wscript.exe * IMMEDIATELY — Task Scheduler would see the task "finish" in * milliseconds while the wrapped `.cmd`/`launch.cjs`/daemon process * tree kept running headless underneath, completely invisible to the * keepalive/hang-watchdog model (which polls task state and * `daemon.lock`, not "is some orphaned descendant still alive"). * - `True` (blocking) makes wscript.exe itself only return once the * wrapped command exits, so the "scheduler process lifetime == * daemon lifetime" invariant survives this indirection unchanged. * * @param commandLine The FULL command line to run, already quoted for * CreateProcess/cmd.exe the same way schtasks.ts's own `/tr` strings are * (e.g. `"C:\...\astramemd.cmd" serve --port 7777` or * `"C:\...\node.exe" "C:\...\index.js" backup --keep 7`) — this function * only handles the VBS-literal escaping, not path quoting. */ export declare function buildHiddenVbs(commandLine: string): string; /** * Write (or overwrite) the stable shim trio. Idempotent — we own the whole * file contents, so a plain overwrite is safe and self-healing. The pointer * (current.json) is written atomically via writePointer(); the cmd/launcher * are small, static, and rewritten in full on every call so a torn write * there just gets corrected on the next reinstall. * * The wrapper's format (batch vs. POSIX shell) is decided by `paths.cmdPath`'s * extension — set once by `shimPaths()` — rather than re-detecting the host * OS here, so a caller that deliberately built `paths` for a specific * platform (tests; a cross-compiled install) gets exactly that format. */ export declare function writeShim(pointer: ShimPointer, paths?: ShimPaths): ShimPaths;