Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor,hook): managed worktrees get the writer-status remedy; the ownership stamp is not unpushed work (#5371)

time-attackfcc774fefe11
diff --git a/docs/operations/backup-check.md b/docs/operations/backup-check.md
index b6d7d1f4f9..052a66dfea 100644
--- a/docs/operations/backup-check.md
+++ b/docs/operations/backup-check.md
@@ -188,7 +188,7 @@ source id. Full per-asset detail (which repo, which fix) is local-only:
- A source repo with no remote:
`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: `gbrain sources push --path <workspace>`.
+- 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>`.
- db_only pages: `gbrain export --source <id> --dir BACKUP_DIR/<id>` for
each source the row names, with `BACKUP_DIR` replaced by a directory
outside 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.tsv
index 08c28eab80..7322fed90f 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 ro
src/core/link-extraction.ts 2158 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
src/core/embedding-migration.ts 1586 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)
src/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 1903 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
+src/commands/hook.ts 1904 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)
src/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 1872 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)
src/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 env
diff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.ts
index 306ca30b93..981d31983f 100644
--- a/src/commands/doctor/bootstrap-checks.ts
+++ b/src/commands/doctor/bootstrap-checks.ts
@@ -13,6 +13,9 @@ import { readHarnessReceiptState, readReceipt, type HarnessReceipt } from '../..
import { probeLivePgliteHolder, resolveBrainDataDir } from '../../core/bootstrap/uninstall.ts';
import { readRunbookStamp, hooksInstalled, listVerifyRuns } from '../../core/bootstrap/status.ts';
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 { VERSION as GBRAIN_BINARY_VERSION } from '../../version.ts';
import type { Check } from '../doctor.ts';
@@ -50,9 +53,21 @@ function commitsAheadOfOrigin(ws: string, branch: string): number {
} catch { return 0; }
}
-/** #5063: a recent successful push of something never certifies a tree that is still ahead. */
-function aheadOfOriginMessage(lastPush: string, ws: string, ahead: number): string {
- return `last push ok (${lastPush}), but ${ws} has ${ahead} commit(s) not on origin — recent agent memory is unpushed. Run \`gbrain sources push --path ${ws}\`.`;
+/**
+ * #5371: one bootstrap_push_health finding. A managed canonical worktree
+ * refuses legacy bulk push, so there the remedy is the managed writer's
+ * read-only status probe; severity never changes, and an unmanaged root keeps
+ * `unmanagedRemedy`.
+ */
+function pushHealthCheck(root: string | null | undefined, status: 'warn' | 'fail', finding: string, unmanagedRemedy: string): Check {
+ if (!root || !isManagedFilesystemPath(root)) return { name: 'bootstrap_push_health', status, message: `${finding}${unmanagedRemedy}` };
+ return {
+ name: 'bootstrap_push_health', status,
+ message: `${finding} — ${root} is a managed canonical worktree, where legacy bulk push is not available. Inspect the managed writer with \`gbrain sources writer status --probe --json\`; changes must be written through gbrain (put_page or capture), direct file edits here are not published.`,
+ fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--probe', '--json'],
+ 'A managed canonical worktree is published by its persistence owner, not by a workspace push; the probe shows whether that owner is running and publishing, and changes nothing.',
+ 'bootstrap_push_health'),
+ };
}
export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise<Check[]> {
@@ -266,11 +281,8 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise
const s = failing[0]!;
const target = s.repoRoot ?? ws ?? undefined;
const rest = failing.length > 1 ? ` [+${failing.length - 1} more workspace(s)]` : '';
- checks.push({
- name: 'bootstrap_push_health',
- status: 'warn',
- message: `last workspace push FAILED${target ? ` for ${target}` : ''} (${s.ts ?? 'unknown'}): ${s.reason ?? 'unknown'}${rest} — run \`gbrain sources push${target ? ` --path ${target}` : ''}\``,
- });
+ 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}` : ''}\``));
} else {
const stamps = pushStatuses.map((s) => Date.parse(s.ts ?? '')).filter((t) => Number.isFinite(t));
const stalest = stamps.length > 0 ? Math.min(...stamps) : NaN;
@@ -295,9 +307,9 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise
let dirty = false, known = false, ahead = 0;
if (ws) {
try {
- const statusOut = execFileSync('git', ['-C', ws, 'status', '--porcelain'], {
+ const statusOut = withoutPhysicalRootMetadata(execFileSync('git', ['-C', ws, 'status', '--porcelain'], {
stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000,
- }).toString();
+ }).toString());
const branch = execFileSync('git', ['-C', ws, 'branch', '--show-current'], { stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 }).toString().trim();
ahead = commitsAheadOfOrigin(ws, branch);
if (statusOut.trim() !== '') {
@@ -351,11 +363,8 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise
} catch { dirty = false; known = false; }
}
if (dirty && ws && Date.now() - Date.parse(pushStatusForWorkspace(pushStatuses, ws)?.ts ?? '') > PUSH_STALE_MS) { // #5432: this root's own receipt
- checks.push({
- name: 'bootstrap_push_health',
- status: 'fail',
- message: `last successful push ${pushStatusForWorkspace(pushStatuses, ws)?.ts} (>48h) with a DIRTY workspace tree — recent agent memory is unpushed [B4]. Run \`gbrain sources push --path ${ws}\`.`,
- });
+ checks.push(pushHealthCheck(ws, 'fail', `last successful push ${pushStatusForWorkspace(pushStatuses, ws)?.ts} (>48h) with a DIRTY workspace tree — recent agent memory is unpushed [B4]`,
+ `. Run \`gbrain sources push --path ${ws}\`.`));
} else if (stale && !targetMatchesWs) {
// Multiple tracked push targets (or the one target names a
// different repoRoot than `ws`) — the stale entry can't be
@@ -374,15 +383,13 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise
// the states that name a real fix.
checks.push({ name: 'bootstrap_push_health', status: 'ok', message: `no push activity since ${staleIso}; tree confirmed clean, nothing to push` });
} else if (stale) {
- checks.push({
- name: 'bootstrap_push_health',
- status: 'warn',
- message: ws
- ? `last successful push ${staleIso} (>48h ago); workspace tree state unverified (the git probe failed) — check ${ws} manually, or run \`gbrain sources push --path ${ws}\` to be safe`
- : `last successful push ${staleIso} (>48h ago); workspace tree state unverified (no bootstrap receipt on this machine names a workspace to check) — check the workspace manually`,
- });
+ checks.push(ws
+ ? pushHealthCheck(ws, 'warn', `last successful push ${staleIso} (>48h ago); workspace tree state unverified (the git probe failed)`,
+ ` — check ${ws} manually, or run \`gbrain sources push --path ${ws}\` to be safe`)
+ : { name: 'bootstrap_push_health', status: 'warn', message: `last successful push ${staleIso} (>48h ago); workspace tree state unverified (no bootstrap receipt on this machine names a workspace to check) — check the workspace manually` });
} else {
- checks.push(ahead > 0 ? { name: 'bootstrap_push_health', status: 'warn', message: aheadOfOriginMessage(staleIso, ws!, ahead) }
+ // #5063: a recent successful push of something never certifies a tree that is still ahead.
+ checks.push(ahead > 0 ? pushHealthCheck(ws, 'warn', `last push ok (${staleIso}), but ${ws} has ${ahead} commit(s) not on origin — recent agent memory is unpushed`, `. Run \`gbrain sources push --path ${ws}\`.`)
: { name: 'bootstrap_push_health', status: 'ok', message: `last push ok (${staleIso})` });
}
}
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index aebf339fd7..5b7992b3f8 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -109,6 +109,7 @@ import {
} from '../core/backup/status-file.ts';
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';
// ── Tunables ────────────────────────────────────────────────────────────────
@@ -848,7 +849,7 @@ async function treeNeedsPush(root: string): Promise<boolean> {
// doesn't resolve yet (never pushed), any commit past the empty tree counts
// as needs-push.
const status = await tryExecAsync('git', ['-C', root, 'status', '--porcelain']);
- if ((status ?? '') !== '') return true;
+ if (withoutPhysicalRootMetadata(status ?? '') !== '') return true;
const branch = await tryExecAsync('git', ['-C', root, 'branch', '--show-current']);
const b = (branch ?? '').trim();
if (b) {
diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.ts
index 6114267cb7..f5f04506ec 100644
--- a/src/core/persistence/physical-root-record.ts
+++ b/src/core/persistence/physical-root-record.ts
@@ -5,8 +5,9 @@ import { OperationError } from '../ops/contract.ts';
import { flushDirectory } from '../fs-durable.ts';
import { digest, sha256 } from './digest.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
+import { PHYSICAL_ROOT_MARKER } from './root-metadata.ts';
-export const PHYSICAL_ROOT_MARKER = '.gbrain-owner.json';
+export { PHYSICAL_ROOT_MARKER, isPhysicalRootMetadata } from './root-metadata.ts';
const RESERVATION_PREFIX = '.gbrain-owner-';
export interface PhysicalRootReservation {
version: 1; token: string; brainId: string; worktreeId: string; hostId: string;
@@ -17,10 +18,6 @@ const uuid = (value: unknown): value is string => typeof value === 'string' && /
export function physicalRootError(message = 'The physical checkout identity changed or belongs to another owner.'): OperationError {
return new OperationError('recovery_required', message, 'Use verified writer transfer or source recovery; do not remove ownership markers to claim this path.');
}
-export function isPhysicalRootMetadata(name: string): boolean {
- return name === PHYSICAL_ROOT_MARKER || /^\.gbrain-owner-[a-f0-9]{64}\.json$/.test(name)
- || /^\.gbrain-owner\.json\.[a-f0-9-]{36}\.tmp$/.test(name);
-}
export function physicalRootReservationPath(root: string): string {
return join(dirname(root), `${RESERVATION_PREFIX}${sha256(root)}.json`);
}
diff --git a/src/core/persistence/root-metadata.ts b/src/core/persistence/root-metadata.ts
new file mode 100644
index 0000000000..94c9061837
--- /dev/null
+++ b/src/core/persistence/root-metadata.ts
@@ -0,0 +1,22 @@
+import { basename } from 'node:path';
+
+export const PHYSICAL_ROOT_MARKER = '.gbrain-owner.json';
+
+/** Ownership metadata gbrain writes inside or beside a managed canonical root; never brain content. */
+export function isPhysicalRootMetadata(name: string): boolean {
+ return name === PHYSICAL_ROOT_MARKER || /^\.gbrain-owner-[a-f0-9]{64}\.json$/.test(name)
+ || /^\.gbrain-owner\.json\.[a-f0-9-]{36}\.tmp$/.test(name);
+}
+
+/**
+ * `git status --porcelain` (v1) output without entries whose every path is
+ * physical-root metadata, so the stamp gbrain writes does not make a managed
+ * tree look dirty. A rename or copy keeps its line unless both sides are
+ * metadata, and a quoted path never matches an exact metadata name.
+ */
+export function withoutPhysicalRootMetadata(porcelain: string): string {
+ return porcelain
+ .split('\n')
+ .filter(line => line.trim() !== '' && !line.slice(3).split(' -> ').every(path => isPhysicalRootMetadata(basename(path.trim()))))
+ .join('\n');
+}
diff --git a/test/bootstrap-doctor-checks.test.ts b/test/bootstrap-doctor-checks.test.ts
index adb9e91658..31612ce97c 100644
--- a/test/bootstrap-doctor-checks.test.ts
+++ b/test/bootstrap-doctor-checks.test.ts
@@ -14,12 +14,13 @@
* engine-shaped check gets a stub with just `getConfig`).
*/
import { describe, test, expect, afterAll, spyOn } from 'bun:test';
-import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFileSync, spawnSync } from 'node:child_process';
import { bootstrapDoctorChecks, type Check } from '../src/commands/doctor.ts';
+import { finalizeCheckFixes } from '../src/commands/doctor/check-fix.ts';
import { readBootId, readPidNs } from '../src/core/pglite-lock.ts';
import { writeHarnessReceipt } from '../src/core/bootstrap/format.ts';
import { LATEST_VERSION } from '../src/core/migrate.ts';
@@ -361,8 +362,7 @@ describe('bootstrap_push_health', () => {
writePushStatus(home, JSON.stringify({ ts: new Date().toISOString(), ok: true }));
const c = byName(await run(parent), 'bootstrap_push_health');
expect(c?.status).toBe('warn');
- expect(c?.message).toContain('1 commit(s) not on origin');
- expect(c?.message).toContain(ws);
+ expect(c?.message).toBe(`last push ok (${JSON.parse(readFileSync(join(home, 'bootstrap', 'push-status.json'), 'utf8')).ts}), but ${ws} has 1 commit(s) not on origin — recent agent memory is unpushed. Run \`gbrain sources push --path ${ws}\`.`);
}, T);
test('last push FAILED → warn naming the reason (regardless of age)', async () => {
@@ -443,6 +443,8 @@ describe('bootstrap_push_health', () => {
expect(c?.status).toBe('fail');
expect(c?.message).toContain('DIRTY');
expect(c?.message).toContain(ws);
+ expect(c?.message).toContain(`Run \`gbrain sources push --path ${ws}\`.`);
+ expect(c?.fix).toBeUndefined();
}, T);
test('unparseable ts → not stale (NaN guard) → ok', async () => {
@@ -807,3 +809,95 @@ describe('fail-soft umbrella', () => {
expect(checks.some((c) => c.status === 'fail')).toBe(false);
}, T);
});
+
+// #5371: a managed canonical worktree refuses `gbrain sources push`, and the
+// ownership stamp gbrain writes into it is not unpushed work.
+describe('bootstrap_push_health on a managed canonical worktree (#5371)', () => {
+ const stamp = (ws: string) => writeFileSync(join(ws, '.gbrain-owner.json'), '{}');
+ const MANAGED_PROBE = 'gbrain sources writer status --probe --json';
+ function expectManagedGuidance(c: Check | undefined, ws: string): void {
+ expect(c?.message).toContain(`${ws} is a managed canonical worktree`);
+ expect(c?.message).toContain('legacy bulk push is not available');
+ expect(c?.message).toContain(MANAGED_PROBE);
+ expect(c?.message).not.toContain('gbrain sources push');
+ }
+
+ test('stale push + tree whose only change is the ownership stamp → ok, confirmed clean', async () => {
+ const { parent, home } = makeHome();
+ const ws = makeWorkspace({ clean: true });
+ stamp(ws);
+ writeReceipt(home, ws);
+ writePushStatus(home, JSON.stringify({ ts: STALE_TS, ok: true }));
+ const c = byName(await run(parent), 'bootstrap_push_health');
+ expect(c?.status).toBe('ok');
+ expect(c?.message).toContain('confirmed clean');
+ }, T);
+
+ test('stale push + a real page beside the stamp → still fail, with the managed-writer remedy', async () => {
+ const { parent, home } = makeHome();
+ const ws = makeWorkspace({ clean: true });
+ stamp(ws);
+ writeFileSync(join(ws, 'unpushed-note.md'), 'recent agent memory\n');
+ writeReceipt(home, ws);
+ writePushStatus(home, JSON.stringify({ ts: STALE_TS, ok: true }));
+ const c = byName(await run(parent), 'bootstrap_push_health');
+ expect(c?.status).toBe('fail');
+ expect(c?.message).toContain('DIRTY');
+ expectManagedGuidance(c, ws);
+ expect(c?.message).toContain('direct file edits here are not published');
+ }, T);
+
+ test('a recorded managed-writer refusal stays warn and points at the writer status probe', async () => {
+ const { parent, home } = makeHome();
+ const ws = makeWorkspace({ clean: true });
+ stamp(ws);
+ writePushStatus(home, JSON.stringify({
+ ts: new Date().toISOString(), ok: false, repoRoot: ws,
+ reason: 'writer_coordinator_required: This path belongs to the managed canonical worktree.',
+ }));
+ const c = byName(await run(parent), 'bootstrap_push_health');
+ expect(c?.status).toBe('warn');
+ expect(c?.message).toContain('FAILED');
+ expectManagedGuidance(c, ws);
+ }, T);
+
+ test('fresh push but AHEAD of origin (wave 9 path) → warn with the managed-writer remedy', async () => {
+ const { parent, home } = makeHome();
+ const ws = makeWorkspace({ ahead: true });
+ stamp(ws);
+ writeReceipt(home, ws);
+ writePushStatus(home, JSON.stringify({ ts: new Date().toISOString(), ok: true }));
+ const c = byName(await run(parent), 'bootstrap_push_health');
+ expect(c?.status).toBe('warn');
+ expect(c?.message).toContain('1 commit(s) not on origin');
+ expectManagedGuidance(c, ws);
+ }, T);
+
+ test('stale push + failed git probe → still warn "unverified", never ok, with the managed-writer remedy', async () => {
+ const { parent, home } = makeHome();
+ const ws = makeWorkspace();
+ stamp(ws);
+ writeReceipt(home, ws);
+ writePushStatus(home, JSON.stringify({ ts: STALE_TS, ok: true }));
+ const c = byName(await run(parent), 'bootstrap_push_health');
+ expect(c?.status).toBe('warn');
+ expect(c?.message).toContain('git probe failed');
+ expectManagedGuidance(c, ws);
+ }, T);
+
+ test('the managed finding renders the agent contract: a read-only probe with a doctor verify', async () => {
+ const { parent, home } = makeHome();
+ const ws = makeWorkspace({ dirty: true });
+ stamp(ws);
+ writeReceipt(home, ws);
+ writePushStatus(home, JSON.stringify({ ts: STALE_TS, ok: true }));
+ const [c] = finalizeCheckFixes((await run(parent)).filter((x) => x.name === 'bootstrap_push_health'));
+ expect(c?.status).toBe('fail');
+ expect(c?.fix_unavailable_reason).toBeUndefined();
+ expect(c?.fix).toMatchObject({
+ next: 'run', command: MANAGED_PROBE, consent: [], actor: 'agent',
+ verify: { argv: ['gbrain', 'doctor', '--only', 'bootstrap_push_health', '--json'] },
+ });
+ expect(String((c?.fix as { why?: string }).why)).toContain('changes nothing');
+ }, T);
+});
diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.ts
index 6f73744403..acd5fa2822 100644
--- a/test/hook-command.serial.test.ts
+++ b/test/hook-command.serial.test.ts
@@ -1264,6 +1264,24 @@ describe('stop-hook per-turn push [D3]', () => {
expect(existsSync(join(home(), 'transcripts', 'live', 'sess-stop-push.txt'))).toBe(false);
});
+ test('#5371: tree whose only change is the managed ownership stamp: push_clean, no spawn', async () => {
+ const repo = bootRepo('stop-stamp-only', { clean: true });
+ writeFileSync(join(repo, '.gbrain-owner.json'), '{}');
+ const spawned: string[] = [];
+ await runHook(['stop'], stopIo(repo, spawned));
+ expect(spawned).toEqual([]);
+ expect((await lastHeartbeat())?.reason).toBe('push_clean');
+ });
+
+ test('#5371: a real change beside the ownership stamp still spawns the 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);
+ });
+
test('corrupt per-root state file is treated as due (fail-open)', async () => {
process.env.GBRAIN_STOP_PUSH_DEBOUNCE_MIN = '5';
const repo = bootRepo('stop-corrupt');
diff --git a/test/persistence-root-metadata.test.ts b/test/persistence-root-metadata.test.ts
new file mode 100644
index 0000000000..ae8d4f241e
--- /dev/null
+++ b/test/persistence-root-metadata.test.ts
@@ -0,0 +1,38 @@
+/**
+ * #5371: the porcelain filter behind the doctor `bootstrap_push_health` and
+ * stop-hook dirty probes drops only exact physical-root ownership metadata, so
+ * the stamp gbrain writes is not unpushed work while real changes still count.
+ */
+import { describe, expect, test } from 'bun:test';
+import { isPhysicalRootMetadata, withoutPhysicalRootMetadata } from '../src/core/persistence/root-metadata.ts';
+import { isPhysicalRootMetadata as viaPhysicalRoot } from '../src/core/persistence/physical-root.ts';
+
+describe('withoutPhysicalRootMetadata', () => {
+ const reservation = `.gbrain-owner-${'a'.repeat(64)}.json`;
+ const tmpStamp = `.gbrain-owner.json.${'0'.repeat(8)}-0000-0000-0000-${'0'.repeat(12)}.tmp`;
+
+ test('drops the ownership stamp, reservation and stamp temp entries at any depth', () => {
+ expect(withoutPhysicalRootMetadata(`?? .gbrain-owner.json\n?? brain/.gbrain-owner.json\n?? ${reservation}\n?? ${tmpStamp}\n`)).toBe('');
+ });
+
+ test('keeps real changes next to the stamp', () => {
+ expect(withoutPhysicalRootMetadata(' M notes/a.md\n?? .gbrain-owner.json\n?? b.md\n')).toBe(' M notes/a.md\n?? b.md');
+ });
+
+ test('a rename onto or away from the stamp is still a real change', () => {
+ expect(withoutPhysicalRootMetadata('R notes/a.md -> .gbrain-owner.json\n')).toBe('R notes/a.md -> .gbrain-owner.json');
+ expect(withoutPhysicalRootMetadata('R .gbrain-owner.json -> notes/a.md\n')).toBe('R .gbrain-owner.json -> notes/a.md');
+ });
+
+ test('does not treat look-alike or quoted names as metadata', () => {
+ expect(isPhysicalRootMetadata('.gbrain-owner.json.bak')).toBe(false);
+ expect(isPhysicalRootMetadata('.gbrain-owner-xyz.json')).toBe(false);
+ expect(isPhysicalRootMetadata('.gbrain-managed')).toBe(false);
+ expect(withoutPhysicalRootMetadata('?? gbrain-owner.json')).toBe('?? gbrain-owner.json');
+ expect(withoutPhysicalRootMetadata('?? ".gbrain-owner.json "')).toBe('?? ".gbrain-owner.json "');
+ });
+
+ test('the physical-root facade re-exports the same predicate', () => {
+ expect(viaPhysicalRoot).toBe(isPhysicalRootMetadata);
+ });
+});