Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(push): managed worktrees stop recommending and re-recording a refused sources push (#6083)
garrytan40a3868b60ee
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 0dacfa5743..2f902eb1e9 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -30,8 +30,8 @@- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts at message boundaries once a part would pass `PART_TARGET_BYTES` (45,000 bytes, 0.9 × the content-sanity warn line `DEFAULT_BYTES_WARN`; `renderSessionParts(…, { partTargetBytes })` overrides it for measurement). `scripts/measure-transcript-split-cost.ts` imports one deterministic synthetic 1 MB session through the real redact → render → `importFromContent` path into in-memory PGLite with a token-counting stub embedder at the former 300,000-byte target and the current one: 4 → 27 pages (×6.75), 380 → 424 chunks (×1.116), 199,614 → 217,057 embed input tokens (×1.087); the extra tokens are the part headers and the two overlap messages repeated at each boundary. Each `RenderedPart` carries the `frontmatter` it owns and its `body`; on re-ingest `runTranscriptsIngest` carries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431, `test/transcripts-retitle.test.ts`).- `src/core/context/sensitivity-scan.ts` — composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with the `Bearer ` keyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface as `pii:bearer`. Every family honors the same `.gbrain-scan-allow` fingerprint escape hatch. `formatSensitivityDrop(drop, workspaceRoot)` renders the one content-free stderr line `gbrain compile-context` prints per dropped entry: reason `sensitivity_scan`, the pattern family, the fingerprint and the absolute `.gbrain-scan-allow` path, never the value (`test/sensitivity-scan.test.ts`).- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v2`, which includes the `connector` asset kind; a cache with any other schema reads as absent and is recomputed; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.-- `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`.-- `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`.+- `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/gbrain-home.ts` — the single GBRAIN_HOME resolution choke point (delegates to config's parent-dir semantics; 0700 on create) — durability, push, hooks, and bootstrap all route through it so home semantics cannot drift.- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.- `src/core/bootstrap/template-repo.ts` + `scripts/generate-template-repo.ts` — deterministic public-template generation (render `--minimal` + placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.diff --git a/docs/operations/backup-check.md b/docs/operations/backup-check.mdindex 052a66dfea..bcafd5ffc3 100644--- a/docs/operations/backup-check.md+++ b/docs/operations/backup-check.md@@ -189,6 +189,7 @@ source id. Full per-asset detail (which repo, which fix) is local-only:`git remote add origin [email protected]:you/your-brain-repo.git && git push -u origin main`,then `gbrain sources harden <source-id>` for auto-push durability.- Unpushed workspace work: for a managed canonical worktree, inspect the managed writer with `gbrain sources writer status --probe --json` (legacy bulk push is refused there); otherwise `gbrain sources push --path <workspace>`.+ On a managed worktree the persistence coordinator commits and pushes as Git effects; the probe lists `effects`, `blocking_effects` and `recent_failures`, and a parked push is retried with `gbrain sources writer retry-effects <source> --request-id <id>`. gbrain's own ownership stamp (`.gbrain-owner.json`) never counts as uncommitted work, the session hooks never start `sources push` there, and a root with no `origin` remote reads `no_remote` (add one: `git remote add origin <url>`) even after a recorded push refusal. A recorded push failure stops warning once the tree matches its origin branch with nothing uncommitted.- db_only pages: `gbrain export --source <id> --dir BACKUP_DIR/<id>` foreach source the row names, with `BACKUP_DIR` replaced by a directoryoutside the gitignored dirs (another disk, another repo, anywhere durable). One directory per source:diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex a76e336d9d..cbc712241f 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -34,7 +34,7 @@ src/commands/sources.ts 2042 ratchet +5 #5988: sources status/retry-held help rosrc/core/link-extraction.ts 2204 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_atsrc/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetsrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh-src/commands/hook.ts 1919 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts)+src/commands/hook.ts 1924 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + importsrc/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)src/core/config.ts 1896 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYSsrc/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook envdiff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.tsindex 981d31983f..0983e2fef1 100644--- a/src/commands/doctor/bootstrap-checks.ts+++ b/src/commands/doctor/bootstrap-checks.ts@@ -16,6 +16,7 @@ import { resolveGbrainHome } from '../../core/gbrain-home.ts';import { isManagedFilesystemPath } from '../../core/persistence/filesystem-guard.ts';import { withoutPhysicalRootMetadata } from '../../core/persistence/root-metadata.ts';import { agentFix } from './check-fix.ts';+import type { PushStatusEntry } from '../../core/workspace-push.ts';import { VERSION as GBRAIN_BINARY_VERSION } from '../../version.ts';import type { Check } from '../doctor.ts';@@ -70,6 +71,35 @@ function pushHealthCheck(root: string | null | undefined, status: 'warn' | 'fail};}+/** #6083: a tree with nothing uncommitted (ownership metadata aside) on a named branch, 0 commits ahead of a configured origin. */+function treeMatchesOrigin(root: string): boolean {+ const g = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 }).toString().trim();+ try {+ g('remote', 'get-url', 'origin');+ const branch = g('branch', '--show-current');+ return branch !== '' && withoutPhysicalRootMetadata(g('status', '--porcelain')) === ''+ && g('rev-list', '--count', `origin/${branch}..HEAD`) === '0';+ } catch { return false; }+}++/**+ * #6083: the recorded push failure finding. A failure whose tree now matches+ * its origin is superseded (nothing is unpushed, and on a managed worktree+ * nothing ever clears a refusal record); the first live failure decides.+ */+function recordedPushFailureCheck(failing: PushStatusEntry[], ws: string | null): Check {+ const live = failing.filter((s) => !s.repoRoot || !treeMatchesOrigin(s.repoRoot));+ if (live.length === 0) {+ return { name: 'bootstrap_push_health', status: 'ok',+ message: `last recorded push failed for ${failing.map((s) => s.repoRoot).join(', ')} (${failing[0]!.ts ?? 'unknown'}), but the tree matches its origin branch with nothing uncommitted; nothing to push` };+ }+ const s = live[0]!;+ const target = s.repoRoot ?? ws ?? undefined;+ const rest = live.length > 1 ? ` [+${live.length - 1} more workspace(s)]` : '';+ return pushHealthCheck(target, 'warn', `last workspace push FAILED${target ? ` for ${target}` : ''} (${s.ts ?? 'unknown'}): ${s.reason ?? 'unknown'}${rest}`,+ ` — run \`gbrain sources push${target ? ` --path ${target}` : ''}\``);+}+export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise<Check[]> {const checks: Check[] = [];let home: string;@@ -278,11 +308,7 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promiseconst { PUSH_STALE_MS } = await import('../hook.ts'); // hook.ts owns the threshold (single source)const failing = pushStatuses.filter((s) => s.ok === false);if (failing.length > 0) {- const s = failing[0]!;- const target = s.repoRoot ?? ws ?? undefined;- const rest = failing.length > 1 ? ` [+${failing.length - 1} more workspace(s)]` : '';- checks.push(pushHealthCheck(target, 'warn', `last workspace push FAILED${target ? ` for ${target}` : ''} (${s.ts ?? 'unknown'}): ${s.reason ?? 'unknown'}${rest}`,- ` — run \`gbrain sources push${target ? ` --path ${target}` : ''}\``));+ checks.push(recordedPushFailureCheck(failing, ws));} else {const stamps = pushStatuses.map((s) => Date.parse(s.ts ?? '')).filter((t) => Number.isFinite(t));const stalest = stamps.length > 0 ? Math.min(...stamps) : NaN;diff --git a/src/commands/doctor/checks/backup-coverage.ts b/src/commands/doctor/checks/backup-coverage.tsindex 7950ef6a5e..99884defda 100644--- a/src/commands/doctor/checks/backup-coverage.ts+++ b/src/commands/doctor/checks/backup-coverage.ts@@ -81,7 +81,9 @@ function backupAssetFix(s: BackupStatus): Action | undefined {argv: filled, consent: egress ? ['credentials', 'egress'] : [], actor: 'agent', requires_exclusive: false,why: egress? 'Creates a private GitHub repository for the brain and pushes to it (needs the user\'s GitHub credentials; content leaves this machine).'- : `Writes a Markdown copy of '${a.id}' (pages and facts) to a directory outside the brain so it survives losing the database.`,+ : argv[2] === 'writer'+ ? `'${a.id}' is a managed canonical worktree: the persistence coordinator commits and pushes it as Git effects, and \`gbrain sources push\` refuses there by design. The read-only probe lists effects, blocking_effects and recent_failures; a parked push is retried with \`gbrain sources writer retry-effects <source> --request-id <id>\`.`+ : `Writes a Markdown copy of '${a.id}' (pages and facts) to a directory outside the brain so it survives losing the database.`,...(filled.some((x) => x.includes('<BACKUP_DIR>')) ? { inputs: [{ name: 'BACKUP_DIR', how: 'Ask the user where backups should live (a directory outside the brain, ideally synced or on another disk).' }] } : {}),verify: doctorVerify('backup_coverage'), docs: 'docs/operations/backup-check.md',};diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex e5b1bb1c64..2581936046 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -113,6 +113,7 @@ import {import { realpathOrResolve } from '../core/path-confine.ts';import { isClaudeCliSelfTranscriptPath } from '../core/ai/providers/claude-cli-scratch.ts';import { withoutPhysicalRootMetadata } from '../core/persistence/root-metadata.ts';+import { isManagedFilesystemPath } from '../core/persistence/filesystem-guard.ts';// ── Tunables ────────────────────────────────────────────────────────────────@@ -818,6 +819,7 @@ async function dirtyTreePush(const root = await resolveBootstrapWorkspaceRoot(ws);if (!root) return null;if (!(await treeNeedsPush(root))) return null; // clean + up to date → nothing to recover+ if (isManagedFilesystemPath(root)) return { reason: 'push_managed_coordinator' };// There IS unpushed work. Defer until the repo phase verified privacy +// recorded repo_url — never recover-push to an unverified origin// (create-repo-first race). Only fires when work actually exists (P2-1).@@ -944,6 +946,7 @@ async function stopPushIfDue(ws: string, io: HookIo): Promise<string> {// verified the origin and recorded repo_url (create-repo-first race).if (!(await repoPhaseComplete(root))) return 'push_deferred_repo_pending';if (!(await treeNeedsPush(root))) return 'push_clean';+ if (isManagedFilesystemPath(root)) return 'push_managed_coordinator';try {// Written BEFORE the spawn so repeated fail-fast children stay debounced// on the healthy path; the [D20] failing-status bypass handles retries.@@ -1858,7 +1861,9 @@ async function hookSessionEnd(io: HookIo): Promise<number> {try {if (ws) {const root = await resolveBootstrapWorkspaceRoot(ws);- if (root && (await repoPhaseComplete(root))) {+ if (root && isManagedFilesystemPath(root)) {+ if (outcome === 'ok' && !reason) reason = 'push_managed_coordinator';+ } else if (root && (await repoPhaseComplete(root))) {try {(io.spawnPush ?? spawnDetachedPush)(root);if (outcome === 'ok' && !reason) reason = 'push_spawned';diff --git a/src/core/backup/repository.ts b/src/core/backup/repository.tsindex 2b71c7978f..5bd95cad90 100644--- a/src/core/backup/repository.ts+++ b/src/core/backup/repository.ts@@ -4,6 +4,8 @@ import { existsSync, realpathSync, statSync } from 'node:fs';import { buildGitEnv } from '../git-remote.ts';import { pushStatusPathForRoot, readPushStatusForRoot } from '../workspace-push.ts';import { readManifest } from '../bootstrap/format.ts';+import { managedFilesystemRootFor } from '../persistence/filesystem-guard.ts';+import { withoutPhysicalRootMetadata } from '../persistence/root-metadata.ts';import { BACKUP_VERIFICATION_MAX_AGE_MS, type BackupAssetVerdict } from './status-file.ts';export const BACKUP_REMOTE_PROBE_CAP = 8;@@ -61,29 +63,36 @@ export async function assessBackupRepository(const asset: BackupAssetVerdict = { kind, id, state: 'unknown', fix_argv: null, verification: { state: 'not_checked' } };try {const failedPush = readPushStatusForRoot(root)?.ok === false;- if (failedPush && kind === 'bootstrap_workspace') asset.fix_argv = ['gbrain', 'sources', 'push', '--path', root];+ // #6083: a managed canonical worktree is committed and pushed by its persistence owner; `sources push` refuses there.+ const managed = managedFilesystemRootFor(root);+ const managedFix = managed ? ['gbrain', 'sources', 'writer', 'status', ...(managed.sourceId ? [managed.sourceId] : []), '--probe', '--json'] : null;+ if (failedPush && kind === 'bootstrap_workspace') asset.fix_argv = managedFix ?? ['gbrain', 'sources', 'push', '--path', root];let origin: string;try {origin = git(root, ['remote', 'get-url', 'origin']);asset.configured_remote = true;} catch (error) {- if (failedPush) return { ...asset, state: 'failing', detail: 'last_push_failed' };- if ((error as { status?: number }).status !== 2) throw error;+ if ((error as { status?: number }).status !== 2) {+ if (failedPush) return { ...asset, state: 'failing', detail: 'last_push_failed' };+ throw error;+ }asset.configured_remote = false;asset.state = 'no_remote';- asset.detail = 'fix: git remote add origin <url> && git push -u origin <branch>, then gbrain sources harden <id>';+ asset.fix_argv = null;+ asset.detail = `${failedPush ? 'the last recorded push failed because there is no origin remote; ' : ''}fix: git remote add origin <url> && git push -u origin <branch>, then gbrain sources harden <id>`;try { if (readManifest(root).state === 'initialized') asset.fix_argv = ['gbrain', 'bootstrap', 'repo']; } catch {}return asset;}const branch = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);const head = git(root, ['rev-parse', '--verify', 'HEAD']);- const dirty = git(root, ['status', '--porcelain']).length > 0;+ const dirty = withoutPhysicalRootMetadata(git(root, ['status', '--porcelain'])).length > 0;let ahead: number | undefined;try { ahead = Number(git(root, ['rev-list', '--count', `refs/remotes/origin/${branch}..HEAD`])); } catch {}asset.state = ahead && ahead > 0 ? 'unpushed' : dirty ? 'dirty' : 'ok';if (ahead && ahead > 0) { asset.ahead = ahead; asset.detail = `${ahead} commit(s) ahead of origin/${branch} (local tracking ref only)`; }else if (dirty) asset.detail = 'uncommitted changes';if (failedPush) { asset.state = 'failing'; asset.detail = 'last_push_failed'; }+ if (managedFix && (dirty || (ahead ?? 0) > 0 || failedPush)) asset.fix_argv = managedFix;const fingerprint = repositoryFingerprint(root, origin, branch, head);asset.verification = { state: 'not_checked', repository_fingerprint: fingerprint };if (!budget) {@@ -132,7 +141,7 @@ export async function assessBackupRepository(}const stillClean = git(root, ['rev-parse', '--verify', 'HEAD']) === head&& git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']) === branch- && git(root, ['status', '--porcelain']).length === 0+ && withoutPhysicalRootMetadata(git(root, ['status', '--porcelain'])).length === 0&& git(root, ['remote', 'get-url', 'origin']) === origin&& repositoryFingerprint(root, origin, branch, head) === fingerprint;asset.verification = { state: remoteHead === head && stillClean && !dirty ? 'verified' : 'mismatch', checked_at: now.toISOString(), local_commit: head, remote_commit: remoteHead, repository_fingerprint: fingerprint };diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 91edf1d383..978f37ffd3 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -258,6 +258,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },{ since: '0.0.0-wave11', text: 'An explicit `memory.auto_writeback off` now stops every ambient capture lane: the compaction harvest (PreCompact segments and OpenClaw compactions) and SessionEnd transcripts stop extracting too, and session text banked under off is never extracted later, even after writeback is turned back on. Unset keeps both lanes running. An unreadable, drifted or unrecognized setting now holds them instead of extracting. Restart `gbrain serve`, cron or autopilot sweeps and OpenClaw gateways started on an older version; `gbrain bootstrap harness --remove` stops the hooks from banking session text at all.' },+ { since: '0.0.0-wave11', text: 'On a managed canonical worktree the session hooks no longer start `gbrain sources push` (it refuses there; heartbeat reason `push_managed_coordinator`), backup check no longer counts gbrain\'s `.gbrain-owner.json` as uncommitted work and points managed roots at `gbrain sources writer status --probe --json`, a root with no origin remote reads `no_remote` even after a recorded push refusal, and doctor `bootstrap_push_health` reports ok once a recorded push failure\'s tree matches its origin branch.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.tsindex d715d51c0a..647ebce48c 100644--- a/src/core/workspace-push.ts+++ b/src/core/workspace-push.ts@@ -426,6 +426,8 @@ export interface PushStatusEntry {reason?: string;ahead?: number;repoRoot?: string;+ /** #6083: machine code of a refusal (`writer_coordinator_required` on a managed worktree). */+ code?: string;/** Absolute path of the status file (per-root announce-state keying). */file: string;}@@ -635,7 +637,7 @@ export function summarizePushStatuses(entries: PushStatusEntry[]): {}function writePushStatus(- status: { ts: string; ok: boolean; reason?: string; ahead?: number; repoRoot: string },+ status: { ts: string; ok: boolean; reason?: string; ahead?: number; repoRoot: string; code?: string },): void {try {const p = pushStatusPathForRoot(status.repoRoot);@@ -677,7 +679,7 @@ export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspaceP// No lock winner can be in flight here: the same guard refuses every legacy// push of this root.if (root && e instanceof OperationError) {- writePushStatus({ ts: new Date().toISOString(), ok: false, reason: `${e.code}: ${e.message}`, repoRoot: root });+ writePushStatus({ ts: new Date().toISOString(), ok: false, code: e.code, reason: `${e.code}: ${e.message}`, repoRoot: root });}throw e;}diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.tsindex acd5fa2822..2a708c2941 100644--- a/test/hook-command.serial.test.ts+++ b/test/hook-command.serial.test.ts@@ -1273,13 +1273,27 @@ describe('stop-hook per-turn push [D3]', () => {expect((await lastHeartbeat())?.reason).toBe('push_clean');});- test('#5371: a real change beside the ownership stamp still spawns the push', async () => {+ test('#5371: a real change beside the ownership stamp is still unpushed work (#6083: its persistence owner pushes it, so no detached push)', async () => {const repo = bootRepo('stop-stamp-dirty', { clean: true });writeFileSync(join(repo, '.gbrain-owner.json'), '{}');writeFileSync(join(repo, 'note.md'), 'unpushed\n');const spawned: string[] = [];await runHook(['stop'], stopIo(repo, spawned));- expect(spawned).toHaveLength(1);+ expect(spawned).toEqual([]);+ expect((await lastHeartbeat())?.reason).toBe('push_managed_coordinator');+ });++ test('#6083: no hook spawns the refused sources push on a managed canonical worktree', async () => {+ const repo = bootRepo('managed-all-hooks');+ writeFileSync(join(repo, '.gbrain-owner.json'), '{}');+ const spawned: string[] = [];+ await runHook(['session-start'], { write: () => {}, spawnPush: (root: string) => { spawned.push(root); }, stdin: '', cwd: repo });+ expect((await lastHeartbeat())?.reason).toBe('push_managed_coordinator');+ await runHook(['stop'], stopIo(repo, spawned));+ expect((await lastHeartbeat())?.reason).toBe('push_managed_coordinator');+ expect(spawned).toEqual([]);+ await runHook(['session-end'], { write: () => {}, spawnPush: (root: string) => { spawned.push(root); }, stdin: JSON.stringify({ session_id: 'sess-managed-end', cwd: repo }) });+ expect(spawned).toEqual([]);});test('corrupt per-root state file is treated as due (fail-open)', async () => {diff --git a/test/managed-push-remedy.serial.test.ts b/test/managed-push-remedy.serial.test.tsnew file mode 100644index 0000000000..d724f2e509--- /dev/null+++ b/test/managed-push-remedy.serial.test.ts@@ -0,0 +1,135 @@+/**+ * #6083 / W2.9: on a managed canonical worktree, `gbrain sources push` refuses+ * by design (the persistence coordinator commits and pushes it as Git+ * effects), so nothing may keep recommending it or re-recording its refusal.+ *+ * 1. Protects: backup coverage never counts gbrain's own `.gbrain-owner.json`+ * as dirt, classifies a root with no origin as `no_remote` even after a+ * recorded refusal, and gives a managed root the read-only writer-status+ * fix; doctor `bootstrap_push_health` lets a tree that matches its real+ * origin supersede a recorded push failure; the managed guard's refusal+ * record carries a machine `code`.+ * 2. Fails when: any of those surfaces names the refused `sources push` for a+ * managed root, the stamp reads as unpushed work, or a stale refusal warns+ * forever on a tree with nothing to push.+ * 3. The hook call sites (no detached push on a managed root) are pinned in+ * hook-command.serial.test.ts.+ *+ * SERIAL: mutates GBRAIN_HOME. Run with GIT_CONFIG_NOSYSTEM=1 on machines whose+ * system git config rewrites github.com URLs.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { assessBackupRepository } from '../src/core/backup/repository.ts';+import { pushStatusPathForRoot, workspacePush } from '../src/core/workspace-push.ts';+import { bootstrapDoctorChecks } from '../src/commands/doctor/bootstrap-checks.ts';+import { makeGitFixture } from './helpers/git-fixture.ts';+import { withEnv } from './helpers/with-env.ts';++let tmp: string;+let oldHome: string | undefined;+const now = new Date('2026-10-06T12:00:00Z');+const WRITER_STATUS = ['gbrain', 'sources', 'writer', 'status'];++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-managed-push-'));+ oldHome = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = tmp;+});+afterEach(() => {+ if (oldHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = oldHome;+ rmSync(tmp, { recursive: true, force: true });+});++function git(root: string, ...args: string[]): string {+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+async function repository(opts: { origin?: boolean } = {}): Promise<string> {+ const root = join(tmp, 'ws');+ mkdirSync(root);+ await makeGitFixture(root);+ git(root, 'branch', '-M', 'main');+ writeFileSync(join(root, 'note.md'), '# Fixture memory\n');+ git(root, 'add', '.');+ git(root, 'commit', '-m', 'fixture');+ if (opts.origin !== false) {+ const remote = join(tmp, 'ws.git');+ git(tmp, 'init', '--bare', '-b', 'main', remote);+ git(root, 'remote', 'add', 'origin', remote);+ git(root, 'push', '-u', 'origin', 'main');+ }+ return root;+}+const manage = (root: string) => writeFileSync(join(root, '.gbrain-owner.json'), '{}\n');+function recordRefusal(root: string): void {+ const p = pushStatusPathForRoot(root);+ mkdirSync(join(tmp, '.gbrain', 'bootstrap'), { recursive: true });+ writeFileSync(p, JSON.stringify({ ts: now.toISOString(), ok: false, repoRoot: root,+ reason: 'writer_coordinator_required: This path belongs to the managed canonical worktree.' }) + '\n');+}++describe('backup coverage on a managed worktree (#6083)', () => {+ test('the ownership stamp is not dirt: a stamp-only tree matching origin verifies', async () => {+ const root = await repository();+ manage(root);+ const a = await assessBackupRepository(root, 'bootstrap_workspace', root, now, { remaining: 4 });+ expect(a.state).toBe('ok');+ expect(a.verification?.state).toBe('verified');+ });++ test('no origin remote is no_remote even after a recorded refusal', async () => {+ const root = await repository({ origin: false });+ manage(root);+ recordRefusal(root);+ const a = await assessBackupRepository(root, 'bootstrap_workspace', root, now, { remaining: 4 });+ expect(a.state).toBe('no_remote');+ expect(a.detail).toContain('git remote add origin');+ expect(a.fix_argv ?? []).not.toContain('push');+ });++ test('a dirty managed root with a recorded refusal gets the writer-status fix, never sources push', async () => {+ const root = await repository();+ manage(root);+ writeFileSync(join(root, 'unpublished.md'), 'edit\n');+ recordRefusal(root);+ const a = await assessBackupRepository(root, 'bootstrap_workspace', root, now);+ expect(a.fix_argv?.slice(0, 4)).toEqual(WRITER_STATUS);+ expect(a.fix_argv).toContain('--probe');+ });+});++describe('doctor bootstrap_push_health (#6083)', () => {+ test('a recorded failure on a tree that matches its origin is superseded: ok, nothing to push', async () => {+ const root = await repository();+ recordRefusal(root);+ const checks = await withEnv({ GBRAIN_HOME: tmp }, () => bootstrapDoctorChecks(null));+ const c = checks.find((x) => x.name === 'bootstrap_push_health');+ expect(c?.status).toBe('ok');+ expect(c?.message).toContain('nothing to push');+ });++ test('a recorded failure with unpushed work still warns', async () => {+ const root = await repository();+ writeFileSync(join(root, 'more.md'), 'unpushed\n');+ git(root, 'add', '.');+ git(root, 'commit', '-m', 'local');+ recordRefusal(root);+ const checks = await withEnv({ GBRAIN_HOME: tmp }, () => bootstrapDoctorChecks(null));+ expect(checks.find((x) => x.name === 'bootstrap_push_health')?.status).toBe('warn');+ });+});++describe('the managed guard refusal record (#6083)', () => {+ test('carries code writer_coordinator_required', async () => {+ const root = await repository();+ manage(root);+ await expect(workspacePush({ dir: root })).rejects.toMatchObject({ code: 'writer_coordinator_required' });+ const record = JSON.parse(readFileSync(pushStatusPathForRoot(root), 'utf8'));+ expect(record.ok).toBe(false);+ expect(record.code).toBe('writer_coordinator_required');+ });+});