Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

workspace-push: isSupersededPushStatus / livePushStatuses for managed roots (#5799 residual)

garrytand4784800c655
diff --git a/docs/architecture/key-files/workspace-push-and-backup.md b/docs/architecture/key-files/workspace-push-and-backup.md
index fca1acc2fd..48f7fb197d 100644
--- a/docs/architecture/key-files/workspace-push-and-backup.md
+++ b/docs/architecture/key-files/workspace-push-and-backup.md
@@ -8,4 +8,4 @@ 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. 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 uses aggregate cache only. 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*` refused regardless of .gitignore state) → 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_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — 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.
+- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → 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_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — 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())`.
diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.ts
index a804022b71..d3ff7bc7fb 100644
--- a/src/core/workspace-push.ts
+++ b/src/core/workspace-push.ts
@@ -1,4 +1,4 @@
-import { assertManagedFilesystemWrite } from './persistence/filesystem-guard.ts';
+import { assertManagedFilesystemWrite, isManagedFilesystemPath } from './persistence/filesystem-guard.ts';
import { OperationError } from './ops/contract.ts';
/**
* workspace-push.ts — the `gbrain sources push` core: scan-gated
@@ -627,6 +627,32 @@ export function formatBlockedSecrets(findings: readonly PushSecretFinding[]): st
return lines;
}
+/**
+ * #5799: a recorded push status that no longer describes a live legacy push.
+ * On a managed canonical worktree the legacy push is fenced
+ * (`writer_coordinator_required`) and the coordinator's git effect publishes
+ * page writes without ever writing push-status, so the refusal record (or a
+ * success from before the worktree was claimed) would feed the FAILING
+ * banner and the staleness note forever. True for a refusal record (its
+ * `code`, or the `reason` prefix an older record carries) and for any record
+ * whose root is a managed worktree now. A root whose marker cannot be read
+ * is not assumed managed.
+ */
+export function isSupersededPushStatus(entry: Pick<PushStatusEntry, 'code' | 'reason' | 'repoRoot'>): boolean {
+ if (entry.code === 'writer_coordinator_required' || entry.reason?.startsWith('writer_coordinator_required:')) return true;
+ if (entry.repoRoot === undefined) return false;
+ try {
+ return isManagedFilesystemPath(entry.repoRoot);
+ } catch {
+ return false;
+ }
+}
+
+/** The recorded statuses that still describe a live legacy push (#5799); the status surfaces read these. */
+export function livePushStatuses(entries: readonly PushStatusEntry[]): PushStatusEntry[] {
+ return entries.filter((e) => !isSupersededPushStatus(e));
+}
+
export function summarizePushStatuses(entries: PushStatusEntry[]): {
failing: PushStatusEntry[];
stalestTs: number | null;
diff --git a/test/workspace-push-superseded-status.test.ts b/test/workspace-push-superseded-status.test.ts
new file mode 100644
index 0000000000..f2ba621e54
--- /dev/null
+++ b/test/workspace-push-superseded-status.test.ts
@@ -0,0 +1,59 @@
+/**
+ * #5799: a push-status record that a managed worktree has superseded must not
+ * feed the hook's FAILING banner or staleness note. The predicate is pure
+ * apart from the managed-root marker lookup, exercised here with a real
+ * `.gbrain-managed` marker in a temp dir; no git, no engine, no env mutation.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { isSupersededPushStatus, livePushStatuses, type PushStatusEntry } from '../src/core/workspace-push.ts';
+
+let dir: string;
+let managedRoot: string;
+let plainRoot: string;
+beforeAll(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-push-superseded-'));
+ managedRoot = join(dir, 'managed');
+ plainRoot = join(dir, 'plain');
+ mkdirSync(managedRoot);
+ mkdirSync(plainRoot);
+ writeFileSync(join(managedRoot, '.gbrain-managed'), '');
+});
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+const entry = (over: Partial<PushStatusEntry>): PushStatusEntry => ({ ts: '2026-10-01T00:00:00.000Z', ok: false, file: '/dev/null', ...over });
+
+describe('isSupersededPushStatus (#5799)', () => {
+ test('a managed-worktree refusal is superseded by its code, and by the reason prefix an older record carries', () => {
+ expect(isSupersededPushStatus(entry({ code: 'writer_coordinator_required', reason: 'writer_coordinator_required: This path belongs to the managed canonical worktree /x.', repoRoot: plainRoot }))).toBe(true);
+ expect(isSupersededPushStatus(entry({ reason: 'writer_coordinator_required: This file belongs to a managed canonical worktree.', repoRoot: plainRoot }))).toBe(true);
+ });
+
+ test('any record whose root is a managed worktree now is superseded, success included', () => {
+ expect(isSupersededPushStatus(entry({ reason: 'push failed: remote rejected', repoRoot: managedRoot }))).toBe(true);
+ expect(isSupersededPushStatus(entry({ ok: true, repoRoot: managedRoot }))).toBe(true);
+ expect(isSupersededPushStatus(entry({ ok: true, repoRoot: join(managedRoot, 'brain') }))).toBe(true);
+ });
+
+ test('a live failure on an unmanaged root, or a record with no root, stays', () => {
+ expect(isSupersededPushStatus(entry({ reason: 'push failed: remote rejected', repoRoot: plainRoot }))).toBe(false);
+ expect(isSupersededPushStatus(entry({ reason: 'push failed: remote rejected', repoRoot: join(dir, 'gone') }))).toBe(false);
+ expect(isSupersededPushStatus(entry({ reason: 'push failed: remote rejected' }))).toBe(false);
+ expect(isSupersededPushStatus(entry({ code: 'secret_scan_blocked', reason: 'secret_scan_blocked: 1 finding', repoRoot: plainRoot }))).toBe(false);
+ });
+
+ test('livePushStatuses keeps order and drops only the superseded records', () => {
+ const live = entry({ reason: 'push failed: remote rejected', repoRoot: plainRoot });
+ const ok = entry({ ok: true, repoRoot: plainRoot });
+ const fenced = entry({ code: 'writer_coordinator_required', reason: 'writer_coordinator_required: fenced', repoRoot: plainRoot });
+ const managed = entry({ ok: true, repoRoot: managedRoot });
+ expect(livePushStatuses([fenced, live, managed, ok])).toEqual([live, ok]);
+ expect(livePushStatuses([])).toEqual([]);
+ });
+
+ // The hook.ts call site (banner + SessionStart note read livePushStatuses) is a stack hunk
+ // behind wave 13 PR3/PR4: ~/.capy/work/w14/pr4/stack-hunks/commands-hook.ts.patch.
+ test.todo('P4.16 hook banner: a stale writer_coordinator_required push-status record on a managed root raises no FAILING notice', () => {});
+});