Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): push records of deleted workspaces are not unreadable status

garrytanf88cabb35bd8
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.md
index f3f5b53524..4720ba5fb3 100644
--- a/docs/architecture/key-files/workspace-push-and-backup.md
+++ b/docs/architecture/key-files/workspace-push-and-backup.md
@@ -8,7 +8,7 @@ guide: [backup check](../../operations/backup-check.md).
Key files:
- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. An ordinary (non-forced) `getBackupStatus` re-probes before the one-hour sweep clock expires when the cached verdict still has pending repository evidence (a configured remote left `budget_exhausted`, relabelled `stale`, or `verified` older than the evidence window), at most once per `BACKUP_CONTINUATION_THROTTLE_MS` (60 s); real failures (`unavailable`, `mismatch`, `missing_ref`) are not retried per check (#6614, #6687; `test/backup-pending-continuation.serial.test.ts`). `budgetAllowsProbe` starts a probe only with its full two-second slot inside the deadline (a sub-slot leftover defers the root as `budget_exhausted` and the sweep keeps that root's first-pass `verified` evidence); an `unavailable` verification carries `cause: 'timeout' | 'exit'` (#6499). #6907: the slot is `resolveBackupRemoteTimeoutMs` (env `GBRAIN_BACKUP_REMOTE_TIMEOUT_MS` > DB `backup.remote_timeout_ms` > 2 s, clamped 500-30000 ms; the budget is `max(8 s, 4 slots)`), a timed-out probe is `isRemoteTimeout` (counted in `totals.remote_timeouts`, reason "remote check timed out"), and `worktreeDirty` streams `git status --porcelain` and stops at the first non-metadata line (`test/pathological/s-6907-backup-check-bounds.test.ts`). Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor and the advisor's remote collector use the aggregate cache only, read through `currentBackupEvidence`. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. API connector sources are not repositories: a `connector_database` source (managed, unbound) and an unmanaged connector whose directory is not a Git repo each become a `connector` info asset with the `gbrain sync --source <id> --full` fix (not `gbrain export`: the connector sync rebuilds pages from the provider and never reads a Markdown dump, so an export is an archive, not a restore path), while a bound connector keeps the repository verdict. The doctor `backup_coverage` message and the advisor collector list each asset that keeps the verdict in warn with its reason (`blockingAssetReasons` in status-file.ts: `no git remote`, `remote configured, nothing pushed`, `dirty`, a fixed `unknown` code, unverified remote) locally, and reason counts only on the remote surface; a warn with no blocking asset leads with the stale or degraded cause. `gbrain backup status` names a fix for dirty and unverified rows too. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/doctor-backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`. #6083: `assessBackupRepository` drops physical-root metadata (`withoutPhysicalRootMetadata`) from both porcelain probes, classifies a root with no origin remote as `no_remote` even after a recorded push failure, and gives a managed canonical worktree (`managedFilesystemRootFor`) the read-only `gbrain sources writer status [<source>] --probe --json` fix instead of the refused `sources push` (`backup-coverage.ts` explains that fix with the retry-effects step).
-- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*`, and since #5186 the ownership markers `.gbrain-owner.json` / `.gbrain-owner-*.json` / `.gbrain-owner.json.*.tmp` plus `.gbrain-bootstrap.lock/**`, refused regardless of .gitignore state; untracked matches are excluded from the commit and named in `excludedUntracked`) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_STREAM_SCAN_MAX_BYTES`, 512 MiB), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through. A blob up to `PUSH_MAX_SCAN_BYTES` (25 MiB) is read whole and scanned by `scanText` as before; a larger one is found by its index size (one `ls-files -s` plus one `cat-file --batch-check`, `stagedBlobSizes`), streamed by oid through `git cat-file blob` into `scanTextStream` (`secret-scan-stream.ts`) and fails closed when git errors, runs past 10 minutes or delivers a byte count other than the recorded size (`test/workspace-push-large-blob.serial.test.ts`: a clean 30 MiB file pushes, secrets across window seams block once each with their line, the ceiling still blocks) — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo). A `blocked_secrets` result carries `PushSecretFinding[]`: each finding adds `file`, `since`, the absolute `allowlistPath` of the root `.gbrain-scan-allow`, a shell-quoted `allowCommand` (`printf` append, runnable from any cwd), `retryCommand` (`gbrain sources push --path <abs>` plus the run's `--branch`/`--allow-unverified-remote`), `docs` (`SECRET_SCAN_REFUSAL_DOCS`, the `write-refusals.md#secret-scan-refusals-and-redaction` anchor; keep that heading) and, when the scanner's `legacyFingerprint` matches an allowlist entry, `staleAllowlistEntry { entry, replacement }`. `formatBlockedSecrets` renders the CLI text from the same objects, so human and `--json` output carry the same commands, and no field holds a value. `blockedSecretsReason` keeps `reason` a one-line summary (count, first location, pattern) within the 140 chars `sanitizePushReason` passes. `bootstrap/verify.ts` and `bootstrap/repo.ts` refusals reuse the docs anchor and print fingerprint, `since` and the absolute allowlist path. `pushStatusForWorkspace(entries, ws)` picks the record whose `repoRoot` resolves to `ws` (a single legacy record without `repoRoot` is attributed to it); `bootstrap status` `support.last_push` and doctor `bootstrap_push_health`'s dirty-tree FAIL use only that record (`test/doctor-not-verified-5432.test.ts`). Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`. #6083: the managed-guard refusal record carries `code: writer_coordinator_required` (`PushStatusEntry.code`); the hook push call sites (`dirtyTreePush`, `stopPushIfDue`, SessionEnd) skip a managed root with heartbeat reason `push_managed_coordinator`; doctor `bootstrap_push_health` (`src/commands/doctor/bootstrap-checks.ts` `recordedPushFailureCheck`) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted. #5799: `isSupersededPushStatus(entry)` / `livePushStatuses(entries)` drop a record the managed topology has superseded (code or reason prefix `writer_coordinator_required`, or a `repoRoot` that is a managed worktree now; an unreadable marker is not assumed managed), because the coordinator's git effect never writes push-status and the refusal would otherwise feed the hook's FAILING banner and staleness note forever (`test/workspace-push-superseded-status.test.ts`); the hook call sites read `livePushStatuses(readPushStatuses())`.
+- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*`, and since #5186 the ownership markers `.gbrain-owner.json` / `.gbrain-owner-*.json` / `.gbrain-owner.json.*.tmp` plus `.gbrain-bootstrap.lock/**`, refused regardless of .gitignore state; untracked matches are excluded from the commit and named in `excludedUntracked`) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS) keyed on the repo's realpath, so a symlinked spelling and git's physical toplevel share it (an absent path hashes its raw string). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_STREAM_SCAN_MAX_BYTES`, 512 MiB), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through. A blob up to `PUSH_MAX_SCAN_BYTES` (25 MiB) is read whole and scanned by `scanText` as before; a larger one is found by its index size (one `ls-files -s` plus one `cat-file --batch-check`, `stagedBlobSizes`), streamed by oid through `git cat-file blob` into `scanTextStream` (`secret-scan-stream.ts`) and fails closed when git errors, runs past 10 minutes or delivers a byte count other than the recorded size (`test/workspace-push-large-blob.serial.test.ts`: a clean 30 MiB file pushes, secrets across window seams block once each with their line, the ceiling still blocks) — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo). A `blocked_secrets` result carries `PushSecretFinding[]`: each finding adds `file`, `since`, the absolute `allowlistPath` of the root `.gbrain-scan-allow`, a shell-quoted `allowCommand` (`printf` append, runnable from any cwd), `retryCommand` (`gbrain sources push --path <abs>` plus the run's `--branch`/`--allow-unverified-remote`), `docs` (`SECRET_SCAN_REFUSAL_DOCS`, the `write-refusals.md#secret-scan-refusals-and-redaction` anchor; keep that heading) and, when the scanner's `legacyFingerprint` matches an allowlist entry, `staleAllowlistEntry { entry, replacement }`. `formatBlockedSecrets` renders the CLI text from the same objects, so human and `--json` output carry the same commands, and no field holds a value. `blockedSecretsReason` keeps `reason` a one-line summary (count, first location, pattern) within the 140 chars `sanitizePushReason` passes. `bootstrap/verify.ts` and `bootstrap/repo.ts` refusals reuse the docs anchor and print fingerprint, `since` and the absolute allowlist path. `pushStatusForWorkspace(entries, ws)` picks the record whose `repoRoot` resolves to `ws` (a single legacy record without `repoRoot` is attributed to it); `bootstrap status` `support.last_push` and doctor `bootstrap_push_health`'s dirty-tree FAIL use only that record (`test/doctor-not-verified-5432.test.ts`). Tests: `test/workspace-push-guidance.test.ts`, `test/sources-push-cli.serial.test.ts`. #6083: the managed-guard refusal record carries `code: writer_coordinator_required` (`PushStatusEntry.code`); the hook push call sites (`dirtyTreePush`, `stopPushIfDue`, SessionEnd) skip a managed root with heartbeat reason `push_managed_coordinator`; doctor `bootstrap_push_health` (`src/commands/doctor/bootstrap-checks.ts` `recordedPushFailureCheck`) reports ok when every recorded failure's tree now matches its configured origin with nothing uncommitted. #5799: `isSupersededPushStatus(entry)` / `livePushStatuses(entries)` drop a record the managed topology has superseded (code or reason prefix `writer_coordinator_required`, or a `repoRoot` that is a managed worktree now; an unreadable marker is not assumed managed), because the coordinator's git effect never writes push-status and the refusal would otherwise feed the hook's FAILING banner and staleness note forever (`test/workspace-push-superseded-status.test.ts`); the hook call sites read `livePushStatuses(readPushStatuses())`. `readPushStatuses` skips per-root records whose `repoRoot` stat answers ENOENT or ENOTDIR (a deleted workspace) and unreadable files (torn or non-object JSON, a missing-absolute or non-string `repoRoot`, any other stat error such as EACCES); the keyed `readPushStatusForRoot` parses with the same rule. `pushStatusRecordCounts` tells the two apart, so doctor's `bootstrap_push_health` reports files kept only for deleted workspaces as `ok` and anything unreadable as `push status unreadable`; no status file is changed or removed (#7377, `test/push-status-gone-roots-7377.test.ts`).
## Shared-checkout git writer
diff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.ts
index 3200517e4e..ca2b4583c7 100644
--- a/src/commands/doctor/bootstrap-checks.ts
+++ b/src/commands/doctor/bootstrap-checks.ts
@@ -149,7 +149,7 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise
const receipt = readReceipt(home);
// One reader for every push-status surface [D8]; per-root files [D13].
- const { readPushStatuses, pushStatusFilesExist, pushStatusForWorkspace } = await import('../../core/workspace-push.ts');
+ const { readPushStatuses, pushStatusFilesExist, pushStatusForWorkspace, pushStatusRecordCounts } = await import('../../core/workspace-push.ts');
const pushStatuses = readPushStatuses();
const statusFilesOnDisk = pushStatusFilesExist();
const heartbeatFile = join(home, 'integrations', 'hooks', 'heartbeat.jsonl');
@@ -408,7 +408,11 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise
} else if (statusFilesOnDisk) {
// Files exist but none parsed — the tolerant reader skips corrupt
// records; doctor must not let that read as "no news is good news".
- checks.push({ name: 'bootstrap_push_health', status: 'warn', message: 'push status unreadable' });
+ // #7377: records kept for workspaces that no longer exist are history.
+ const counts = pushStatusRecordCounts();
+ checks.push(counts.unreadable === 0 && counts.gone > 0
+ ? { name: 'bootstrap_push_health', status: 'ok', message: `push status is kept only for ${counts.gone} workspace(s) that no longer exist; no tracked workspace to check` }
+ : { name: 'bootstrap_push_health', status: 'warn', message: 'push status unreadable' });
}
} catch {
checks.push({ name: 'bootstrap_push_health', status: 'warn', message: 'push status unreadable' });
diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.ts
index 00349bb6d0..3808c27505 100644
--- a/src/core/workspace-push.ts
+++ b/src/core/workspace-push.ts
@@ -56,7 +56,7 @@ import { OperationError } from './ops/contract.ts';
import {
existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync,
} from 'fs';
-import { dirname, join, resolve } from 'path';
+import { dirname, isAbsolute, join, resolve } from 'path';
import { createHash, randomBytes } from 'crypto';
import { execFileSync, spawn } from './spawn.ts';
import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, detectDefaultBranch, divergenceSafePull, type PullStrategy } from './git-remote.ts';
@@ -565,20 +565,38 @@ export interface PushStatusEntry {
const PUSH_STATUS_FILE_RE = /^push-status-[0-9a-f]{12}\.json$/;
-/** Tolerant reader over every push-status file (banner, SessionStart note,
- * and doctor all consume THIS — one parse, one schema owner). Per-root files
- * win; the legacy global file is consulted only when none exist, so a stale
- * pre-upgrade record can't shadow live per-root state. */
-export function readPushStatuses(): PushStatusEntry[] {
+/** One push-status file as a record, or null when it is missing, torn or not
+ * a JSON object (#7377: a whole-file primitive, array or null is unreadable,
+ * never an empty record that reads as a success). Never throws. */
+function parsePushStatusFile(file: string): PushStatusEntry | null {
+ try {
+ const s: unknown = JSON.parse(readFileSync(file, 'utf8'));
+ return s !== null && typeof s === 'object' && !Array.isArray(s) ? { ...(s as Omit<PushStatusEntry, 'file'>), file } : null;
+ } catch {
+ return null;
+ }
+}
+
+/** #7377: a recorded repoRoot is gone only when stat answers ENOENT or
+ * ENOTDIR. A denied traversal (EACCES, EPERM), an I/O error or a value that
+ * is not an absolute path is unreadable, never proof the workspace is gone. */
+function pushStatusRootState(root: unknown): 'present' | 'gone' | 'unreadable' {
+ if (root === undefined) return 'present';
+ if (typeof root !== 'string' || !isAbsolute(root)) return 'unreadable';
+ try {
+ statSync(root);
+ return 'present';
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ return code === 'ENOENT' || code === 'ENOTDIR' ? 'gone' : 'unreadable';
+ }
+}
+
+/** Every authoritative push-status file, classified: a live record, the
+ * record of a workspace that no longer exists, or unreadable. Per-root files
+ * win; the legacy global file is consulted only when none exist. */
+function classifyPushStatusFiles(): Array<PushStatusEntry | 'gone' | 'unreadable'> {
const dir = join(ensureGbrainHome(), 'bootstrap');
- const parse = (file: string): PushStatusEntry | null => {
- try {
- const s = JSON.parse(readFileSync(file, 'utf8')) as Omit<PushStatusEntry, 'file'>;
- return { ...s, file };
- } catch {
- return null; // torn/corrupt/missing → skip, never throw
- }
- };
let names: string[] = [];
try {
names = readdirSync(dir).filter((n) => PUSH_STATUS_FILE_RE.test(n));
@@ -586,22 +604,41 @@ export function readPushStatuses(): PushStatusEntry[] {
return [];
}
// The legacy file is consulted only when NO per-root FILES exist on disk —
- // if per-root files exist but are all corrupt, an empty result is the honest
- // answer (doctor pairs it with pushStatusFilesExist for the loud warn); a
- // stale pre-upgrade record must never shadow live-but-unreadable state.
+ // a stale pre-upgrade record must never shadow live-but-unreadable state.
if (names.length === 0) {
- const legacy = parse(pushStatusPath());
- return legacy ? [legacy] : [];
+ const legacy = parsePushStatusFile(pushStatusPath());
+ return legacy ? [legacy] : existsSync(pushStatusPath()) ? ['unreadable'] : [];
}
- return names
- .map((n) => parse(join(dir, n)))
- .filter((e): e is PushStatusEntry => e !== null)
- // A record whose workspace no longer exists on disk is a ghost: it can
- // never be cleared by a re-push (the root is gone), so it must not feed
- // the failure banner / staleness note forever (deleted Conductor
- // workspaces are routine). Entries without repoRoot (legacy shape in a
- // per-root file) are kept — absence of evidence is not a ghost.
- .filter((e) => e.repoRoot === undefined || existsSync(e.repoRoot));
+ return names.map((n) => {
+ const entry = parsePushStatusFile(join(dir, n));
+ if (!entry) return 'unreadable';
+ // A record whose workspace no longer exists is a ghost: it can never be
+ // cleared by a re-push (the root is gone), so it must not feed the
+ // failure banner / staleness note forever (deleted Conductor workspaces
+ // are routine). Entries without repoRoot (legacy shape in a per-root
+ // file) are kept — absence of evidence is not a ghost.
+ const state = pushStatusRootState(entry.repoRoot);
+ return state === 'present' ? entry : state;
+ });
+}
+
+/** Tolerant reader over every push-status file (banner, SessionStart note,
+ * and doctor all consume THIS — one parse, one schema owner). Per-root files
+ * win; the legacy global file is consulted only when none exist, so a stale
+ * pre-upgrade record can't shadow live per-root state. Unreadable files and
+ * records of gone workspaces are skipped; doctor tells them apart with
+ * pushStatusRecordCounts. */
+export function readPushStatuses(): PushStatusEntry[] {
+ return classifyPushStatusFiles().filter((e): e is PushStatusEntry => typeof e !== 'string');
+}
+
+/** #7377: how many authoritative push-status files hold the record of a
+ * workspace that no longer exists, and how many hold nothing readable. Doctor
+ * reads an empty readPushStatuses() through this, so retained history of
+ * deleted workspaces is not reported as an unreadable status. */
+export function pushStatusRecordCounts(): { gone: number; unreadable: number } {
+ const states = classifyPushStatusFiles();
+ return { gone: states.filter((s) => s === 'gone').length, unreadable: states.filter((s) => s === 'unreadable').length };
}
/** True when any push-status file exists on disk (parseable or not). The
@@ -620,14 +657,7 @@ export function pushStatusFilesExist(): boolean {
/** The per-root status for one workspace, or null. Direct keyed read first —
* the scan is only a fallback for legacy records carrying a repoRoot field. */
export function readPushStatusForRoot(root: string): PushStatusEntry | null {
- const keyedPath = pushStatusPathForRoot(root);
- try {
- const s = JSON.parse(readFileSync(keyedPath, 'utf8')) as Omit<PushStatusEntry, 'file'>;
- return { ...s, file: keyedPath };
- } catch {
- /* fall through to the scan */
- }
- return readPushStatuses().find((e) => e.repoRoot === root) ?? null;
+ return parsePushStatusFile(pushStatusPathForRoot(root)) ?? readPushStatuses().find((e) => e.repoRoot === root) ?? null;
}
/**
diff --git a/test/push-status-gone-roots-7377.test.ts b/test/push-status-gone-roots-7377.test.ts
new file mode 100644
index 0000000000..861baa76d6
--- /dev/null
+++ b/test/push-status-gone-roots-7377.test.ts
@@ -0,0 +1,152 @@
+/**
+ * #7377: per-root push-status records whose workspace was deleted are kept
+ * on disk as history; doctor read the empty filtered result as a parse
+ * failure and warned "push status unreadable".
+ *
+ * - Only a stat ENOENT/ENOTDIR proves a root is gone; a denied traversal
+ * (EACCES) or an invalid repoRoot value stays unreadable, never green.
+ * - Whole-file primitive, array or null JSON is unreadable in the central
+ * reader and the keyed reader alike.
+ * - Per-root files keep precedence over the legacy file, and doctor never
+ * changes or removes a status file.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { bootstrapDoctorChecks, type Check } from '../src/commands/doctor.ts';
+import { pushStatusPathForRoot, readPushStatusForRoot, readPushStatuses } from '../src/core/workspace-push.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const T = 30_000;
+const tmpDirs: string[] = [];
+const locked: string[] = [];
+afterAll(() => {
+ for (const d of locked) chmodSync(d, 0o755);
+ for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });
+});
+
+function makeHome(): { parent: string; home: string; dir: string } {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-7377-'));
+ tmpDirs.push(parent);
+ const home = join(parent, '.gbrain');
+ const dir = join(home, 'bootstrap');
+ mkdirSync(dir, { recursive: true });
+ return { parent, home, dir };
+}
+
+const goneRoot = (parent: string, name: string) => join(parent, 'deleted-workspaces', name);
+const writeRoot = (dir: string, hash: string, body: unknown) => writeFileSync(join(dir, `push-status-${hash}.json`), typeof body === 'string' ? body : JSON.stringify(body));
+const snapshot = (dir: string) => Object.fromEntries(readdirSync(dir).sort().map((n) => [n, readFileSync(join(dir, n), 'utf8')]));
+const pushHealth = async (parent: string): Promise<Check | undefined> =>
+ withEnv({ GBRAIN_HOME: parent }, async () => (await bootstrapDoctorChecks(null)).find((c) => c.name === 'bootstrap_push_health'));
+const statuses = (parent: string) => withEnv({ GBRAIN_HOME: parent }, () => readPushStatuses());
+
+describe('#7377 push-status records of deleted workspaces', () => {
+ test('only gone roots → not reported unreadable, and every file is kept byte for byte', async () => {
+ const { parent, dir } = makeHome();
+ writeRoot(dir, 'aaaaaaaaaaaa', { ts: new Date().toISOString(), ok: true, repoRoot: goneRoot(parent, 'source-a') });
+ writeRoot(dir, 'bbbbbbbbbbbb', { ts: new Date().toISOString(), ok: false, reason: 'push rejected', repoRoot: goneRoot(parent, 'source-b') });
+ const before = snapshot(dir);
+ expect(await statuses(parent)).toEqual([]);
+ const c = await pushHealth(parent);
+ expect(c?.status).toBe('ok');
+ expect(c?.message).not.toContain('unreadable');
+ expect(c?.message).toContain('2');
+ expect(snapshot(dir)).toEqual(before);
+ }, T);
+
+ test('a root under a regular file (ENOTDIR) is gone too', async () => {
+ const { parent, dir } = makeHome();
+ const file = join(parent, 'plain-file');
+ writeFileSync(file, 'x');
+ writeRoot(dir, 'aaaaaaaaaaaa', { ts: new Date().toISOString(), ok: true, repoRoot: join(file, 'ws') });
+ expect((await pushHealth(parent))?.status).toBe('ok');
+ }, T);
+
+ test('per-root files keep precedence over the legacy file even when they all name gone roots', async () => {
+ const { parent, dir } = makeHome();
+ writeFileSync(join(dir, 'push-status.json'), JSON.stringify({ ts: new Date().toISOString(), ok: false, reason: 'legacy failure' }));
+ writeRoot(dir, 'aaaaaaaaaaaa', { ts: new Date().toISOString(), ok: true, repoRoot: goneRoot(parent, 'source-a') });
+ const before = snapshot(dir);
+ const c = await pushHealth(parent);
+ expect(c?.status).toBe('ok');
+ expect(c?.message).not.toContain('legacy failure');
+ expect(snapshot(dir)).toEqual(before);
+ }, T);
+
+ test('a gone root next to a live failing root → the failure is still reported', async () => {
+ const { parent, dir } = makeHome();
+ const live = join(parent, 'live-ws');
+ mkdirSync(live);
+ writeRoot(dir, 'aaaaaaaaaaaa', { ts: new Date().toISOString(), ok: true, repoRoot: goneRoot(parent, 'source-a') });
+ writeRoot(dir, 'bbbbbbbbbbbb', { ts: new Date().toISOString(), ok: false, reason: 'push rejected', repoRoot: live });
+ expect((await statuses(parent)).map((s) => s.repoRoot)).toEqual([live]);
+ expect((await pushHealth(parent))?.status).not.toBe('ok');
+ }, T);
+
+ test('a gone root next to a corrupt record → unreadable', async () => {
+ const { parent, dir } = makeHome();
+ writeRoot(dir, 'aaaaaaaaaaaa', { ts: new Date().toISOString(), ok: true, repoRoot: goneRoot(parent, 'source-a') });
+ writeRoot(dir, 'bbbbbbbbbbbb', 'torn{{{');
+ const c = await pushHealth(parent);
+ expect(c?.status).toBe('warn');
+ expect(c?.message).toBe('push status unreadable');
+ }, T);
+
+ test.skipIf(process.getuid?.() === 0)('a root behind a denied traversal (EACCES) stays unreadable', async () => {
+ const { parent, dir } = makeHome();
+ const guard = join(parent, 'guarded');
+ mkdirSync(join(guard, 'ws'), { recursive: true });
+ chmodSync(guard, 0o000);
+ locked.push(guard);
+ writeRoot(dir, 'aaaaaaaaaaaa', { ts: new Date().toISOString(), ok: true, repoRoot: join(guard, 'ws') });
+ const c = await pushHealth(parent);
+ chmodSync(guard, 0o755);
+ expect(c?.status).toBe('warn');
+ expect(c?.message).toBe('push status unreadable');
+ }, T);
+
+ for (const [label, repoRoot] of [['a number', 42], ['a relative path', 'relative/ws'], ['an empty string', ''], ['an object', { path: '/x' }]] as const) {
+ test(`an invalid repoRoot (${label}) never reads green`, async () => {
+ const { parent, dir } = makeHome();
+ writeRoot(dir, 'aaaaaaaaaaaa', { ts: new Date().toISOString(), ok: true, repoRoot });
+ const c = await pushHealth(parent);
+ expect(c?.status).toBe('warn');
+ expect(c?.message).toBe('push status unreadable');
+ }, T);
+ }
+});
+
+describe('#7377 whole-file non-object JSON is unreadable', () => {
+ for (const body of ['5', '"ok"', 'true', 'null', '[]', '[{"ok":true}]']) {
+ test(`per-root file ${body} → no entry, doctor warns unreadable`, async () => {
+ const { parent, dir } = makeHome();
+ writeRoot(dir, 'aaaaaaaaaaaa', body);
+ expect(await statuses(parent)).toEqual([]);
+ const c = await pushHealth(parent);
+ expect(c?.status).toBe('warn');
+ expect(c?.message).toBe('push status unreadable');
+ }, T);
+ }
+
+ test('legacy file holding a primitive → unreadable, never "last push ok"', async () => {
+ const { parent, dir } = makeHome();
+ writeFileSync(join(dir, 'push-status.json'), '7');
+ expect(await statuses(parent)).toEqual([]);
+ expect((await pushHealth(parent))?.message).toBe('push status unreadable');
+ }, T);
+
+ test('the keyed reader agrees with the central reader', async () => {
+ const { parent } = makeHome();
+ const root = join(parent, 'keyed-ws');
+ mkdirSync(root);
+ await withEnv({ GBRAIN_HOME: parent }, () => {
+ writeFileSync(pushStatusPathForRoot(root), '[]');
+ expect(readPushStatusForRoot(root)).toBeNull();
+ expect(readPushStatuses()).toEqual([]);
+ writeFileSync(pushStatusPathForRoot(root), JSON.stringify({ ts: '2026-01-01T00:00:00.000Z', ok: false, repoRoot: root }));
+ expect(readPushStatusForRoot(root)).toEqual(readPushStatuses()[0]!);
+ });
+ }, T);
+});