Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
doctor: foreign_ownership_marker finding names the stale ownership marker blocking a claim (#5808)
garrytan7360af66d2da
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex a59a1fc1a7..9b2bc853bc 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -523,6 +523,38 @@ after binding it warns, because those pages sit outside the canonical files.There is no command yet that turns them into files; to move one, save itscontent under a new slug and delete the database-only page.+## Foreign ownership marker++<a id="foreign-ownership-marker"></a>++When a host claims a source checkout, gbrain writes two private ownership+markers: `.gbrain-owner.json` inside the checkout and+`.gbrain-owner-<sha256 of the path>.json` beside it. Both record the brain id+and the worktree id they belong to. A claim of a checkout whose markers name+another brain refuses `recovery_required` ("The physical checkout identity+changed or belongs to another owner"), because removing a live brain's marker+to claim its files would let two brains write the same checkout.++A marker left behind by a brain that no longer exists (a PGLite brain later+moved to Postgres with `gbrain move-to-postgres`, a `gbrain init` that was+redone, a database dropped by hand) refuses the same way, and the refusal does+not say which file or which brain. `gbrain doctor` reports the+`foreign_ownership_marker` check for every source checkout and owner binding+on this host: the marker's path, the brain id it records, and whether this+brain knows the worktree. The check is read-only and runs only on the brain+host.++Clearing it is the operator's decision, in this order:++1. Confirm with the user that the recorded brain is retired: it was moved into+ this database, or it was deleted on purpose. `gbrain doctor --json` on the+ old brain's home, if it still exists, shows its `brain_id`.+2. Remove exactly the file doctor names on the brain host. Do not remove a+ marker of a brain that is still in use; transfer ownership with+ `gbrain sources writer transfer prepare|accept` instead.+3. Claim again: `gbrain sources writer claim <source> --path <checkout> --dry-run`,+ then the printed apply command.+## Secret scan refusals and redactionGBrain runs one secret scanner in several places. Depending on where adiff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 3b1c5f8a31..f201659c6c 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -292,6 +292,7 @@ export const timelineHistoryEntry: DoctorEntry = {'git_held_files','frontmatter_hook','orphan_persistence_bindings',+ 'foreign_ownership_marker','unbound_source','writer_version','self_capture',diff --git a/src/commands/doctor/checks/orphan-bindings.ts b/src/commands/doctor/checks/orphan-bindings.tsindex 5a688d8009..6bfc53da0c 100644--- a/src/commands/doctor/checks/orphan-bindings.ts+++ b/src/commands/doctor/checks/orphan-bindings.ts@@ -26,3 +26,57 @@ export async function checkOrphanBindings(engine: BrainEngine): Promise<Check> {details: { count: 'unknown', truncated: true } };}}++/**+ * #5808: ownership markers (`.gbrain-owner.json` inside a source checkout and+ * the private `.gbrain-owner-<sha>.json` reservation beside it) that name a+ * brain other than this one, or a worktree this brain does not know. An+ * earlier brain on the same checkout (a PGLite brain later moved to Postgres,+ * a re-init) leaves them behind, and every claim then refuses+ * `recovery_required` without saying which file or which brain. Read-only:+ * doctor names the file and the brain it records; removing a marker is the+ * operator's decision, and only once the recorded brain is retired.+ */+export async function checkForeignOwnershipMarkers(engine: BrainEngine): Promise<Check> {+ const name = 'foreign_ownership_marker';+ try {+ const { readPhysicalRootReservation, readPhysicalRootStamp, physicalRootReservationPath, PHYSICAL_ROOT_MARKER } = await import('../../../core/persistence/physical-root-record.ts');+ const { existingLocalHostId } = await import('../../../core/persistence/identity.ts');+ const { existsSync } = await import('node:fs');+ const { join } = await import('node:path');+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id::text AS brain_id FROM persistence_brain WHERE singleton=1');+ const worktrees = new Set((await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_worktrees')).map(row => row.id));+ const roots = await engine.executeRaw<{ root: string; source_id: string | null }>(`+ SELECT DISTINCT local_path AS root,id AS source_id FROM sources WHERE local_path IS NOT NULL AND NOT COALESCE(archived,false)+ UNION SELECT DISTINCT h.local_path,NULL FROM persistence_host_bindings h WHERE h.host_id=$1::uuid`, [existingLocalHostId()]);+ const markers: Array<{ path: string; source_id: string | null; kind: 'stamp' | 'reservation'; recorded_brain: string | null; worktree_known: boolean | null; problem: string }> = [];+ for (const { root, source_id } of roots) {+ if (!existsSync(root)) continue;+ const candidates: Array<{ kind: 'stamp' | 'reservation'; path: string; read: () => { brainId: string; worktreeId: string } | null }> = [+ { kind: 'stamp', path: join(root, PHYSICAL_ROOT_MARKER), read: () => readPhysicalRootStamp(root) },+ { kind: 'reservation', path: physicalRootReservationPath(root), read: () => readPhysicalRootReservation(root) },+ ];+ for (const candidate of candidates) {+ let value: { brainId: string; worktreeId: string } | null;+ try { value = candidate.read(); }+ catch { markers.push({ path: candidate.path, source_id, kind: candidate.kind, recorded_brain: null, worktree_known: null, problem: 'unreadable: not a private, well-formed ownership marker' }); continue; }+ if (!value) continue;+ const foreignBrain = brain ? value.brainId !== brain.brain_id : false;+ const unknownWorktree = !worktrees.has(value.worktreeId);+ if (!foreignBrain && !unknownWorktree) continue;+ markers.push({ path: candidate.path, source_id, kind: candidate.kind, recorded_brain: value.brainId, worktree_known: !unknownWorktree,+ problem: foreignBrain ? `records brain ${value.brainId}, not this brain (${brain?.brain_id ?? 'unknown'})` : `records worktree ${value.worktreeId}, which this brain does not know` });+ }+ }+ const details = { count: markers.length, markers, docs: 'docs/guides/write-refusals.md#foreign-ownership-marker' };+ if (!markers.length) return { name, status: 'ok', message: 'Every ownership marker beside a source checkout belongs to this brain.', details };+ return { name, status: 'warn', details,+ message: `${markers.length} ownership marker(s) beside source checkouts do not belong to this brain: `+ + markers.slice(0, 5).map(marker => `${marker.path} (${marker.problem})`).join('; ')+ + `. A claim of that checkout refuses recovery_required while one remains. Confirm with the user that the recorded brain is retired `+ + '(moved to this database or deleted), then remove exactly the named file on the brain host and claim again; never remove a marker of a brain that is still in use.' };+ } catch (error) {+ return { name, status: 'warn', details: { count: 'unknown' },+ message: `Ownership markers could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex df02457b27..e0dda56911 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -178,6 +178,14 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'Some persistence source bindings belong to a removed source or an earlier source incarnation',run: async engine => (await import('./checks/orphan-bindings.ts')).checkOrphanBindings(engine),},+ {+ id: 'foreign_ownership_marker', resolution: 'operator', registration: 'wave',+ hostOnly: 'Ownership markers are private files beside the source checkouts on the brain host.',+ count: d => Number(d.count ?? 0),+ impact: 'An ownership marker beside a source checkout names another brain or an unknown worktree, so claiming that checkout refuses recovery_required',+ instruction: 'Confirm with the user that the recorded brain is retired, then remove exactly the marker file doctor names on the brain host and claim again (docs/guides/write-refusals.md#foreign-ownership-marker); never remove a marker of a brain still in use.',+ run: async engine => (await import('./checks/orphan-bindings.ts')).checkForeignOwnershipMarkers(engine),+ },{id: 'unbound_source', resolution: 'operator', registration: 'wave',count: d => (d.sources ?? []).filter((source: { bound?: boolean }) => source.bound).reduce((sum: number, source: { pages?: number }) => sum + Number(source.pages ?? 0), 0),diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex c15aae6b6d..9f7ac78e34 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -74,6 +74,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['loop_facts_drift','ontology_facts_fenced','orphan_persistence_bindings',+ 'foreign_ownership_marker','safe_index_pending','self_capture','brain_score',diff --git a/test/doctor-foreign-ownership-marker.test.ts b/test/doctor-foreign-ownership-marker.test.tsnew file mode 100644index 0000000000..17a729df0e--- /dev/null+++ b/test/doctor-foreign-ownership-marker.test.ts@@ -0,0 +1,71 @@+/**+ * #5808: `foreign_ownership_marker` names the ownership marker files beside a+ * source checkout that record another brain or an unknown worktree, so the+ * operator learns which file blocks the claim instead of a bare+ * `recovery_required`. A marker of this brain's own claim is not reported.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { checkForeignOwnershipMarkers } from '../src/commands/doctor/checks/orphan-bindings.ts';+import { WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';+import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath, reservePhysicalRootRecord, writePhysicalRootStamp } from '../src/core/persistence/physical-root-record.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let home: string;+beforeAll(async () => {+ home = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-foreign-marker-')));+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+}, 120_000);+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++const isolated = <T>(run: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, run);++test('the finding is an operator-resolved wave check with a docs anchor', () => {+ const spec = WAVE_CHECKS.find(check => check.id === 'foreign_ownership_marker');+ expect(spec).toMatchObject({ resolution: 'operator', registration: 'wave' });+ expect(spec!.hostOnly).toBeTruthy();+ expect(spec!.instruction).toContain('write-refusals.md#foreign-ownership-marker');+ expect(spec!.count({ count: 3 })).toBe(3);+});++test('markers of this brain are ok; a retired brain\'s stamp and reservation are named with their file and brain id', () => isolated(async () => {+ await registerLocalWriter(engine, 'cli');+ const own = join(home, 'own'); mkdirSync(own);+ const ownId = `own-${randomUUID().slice(0, 6)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [ownId, own]);+ await claimWorktree(engine, ownId, own, localHostId());+ expect(await checkForeignOwnershipMarkers(engine)).toMatchObject({ name: 'foreign_ownership_marker', status: 'ok', details: { count: 0 } });++ // A checkout an earlier brain claimed: its reservation and stamp survive the brain.+ const stale = join(home, 'stale'); mkdirSync(stale);+ const staleId = `stale-${randomUUID().slice(0, 6)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [staleId, stale]);+ const retiredBrain = randomUUID();+ const reservation = reservePhysicalRootRecord(stale, { brainId: retiredBrain, worktreeId: randomUUID(), hostId: randomUUID(), coordinationPath: join(home, 'coordination') });+ writePhysicalRootStamp(stale, reservation);+ await expect(claimWorktree(engine, staleId, stale, localHostId())).rejects.toMatchObject({ code: 'recovery_required' });++ const check = await checkForeignOwnershipMarkers(engine);+ expect(check.status).toBe('warn');+ const markers = (check.details as { markers: Array<Record<string, unknown>> }).markers;+ expect(markers.map(marker => marker.path).sort()).toEqual([join(stale, PHYSICAL_ROOT_MARKER), physicalRootReservationPath(stale)].sort());+ for (const marker of markers) expect(marker).toMatchObject({ source_id: staleId, recorded_brain: retiredBrain, worktree_known: false, problem: expect.stringContaining(`records brain ${retiredBrain}`) });+ expect(check.message).toContain(join(stale, PHYSICAL_ROOT_MARKER));+ expect(check.message).toContain('never remove a marker of a brain that is still in use');+ expect(check.message).toContain('recovery_required');++ // A marker that is not a private, well-formed file is reported as unreadable rather than crashing the check.+ const broken = join(home, 'broken'); mkdirSync(broken);+ const brokenId = `broken-${randomUUID().slice(0, 6)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [brokenId, broken]);+ writeFileSync(join(broken, PHYSICAL_ROOT_MARKER), '{"version":1}', { mode: 0o644 });+ const unreadable = (await checkForeignOwnershipMarkers(engine)).details as { markers: Array<Record<string, unknown>> };+ expect(unreadable.markers.find(marker => marker.source_id === brokenId)).toMatchObject({ problem: expect.stringContaining('unreadable') });+}));diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex 9fbe13dbee..ad694fbea8 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -64,7 +64,7 @@" [OK] pglite_scale: PGLite at 5 pages — comfortable below the 1000-page threshold"," [OK] rls: Skipped (PGLite — no PostgREST exposure, RLS not applicable)"," [OK] schema_version: Version <latest> (latest: <latest>)",- " [OK] schema_columns: 1066 column(s) verified against live schema",+ " [OK] schema_columns: 1067 column(s) verified against live schema"," [OK] rls_event_trigger: Skipped (PGLite — no event trigger support)"," [INFO] embeddings: Not applicable: embeddings are disabled on this brain (keyword search keeps working)."," [INFO] embedding_provider: Not probed: embeddings are disabled on this brain by choice (keyword search keeps working).",@@ -94,6 +94,7 @@" [OK] git_held_files: No Git source files are held."," [OK] frontmatter_hook: No outdated gbrain frontmatter pre-commit hook is installed."," [OK] orphan_persistence_bindings: Every persistence source binding belongs to an existing source.",+ " [OK] foreign_ownership_marker: Every ownership marker beside a source checkout belongs to this brain."," [OK] unbound_source: No page was written database-only to an unbound source."," [OK] writer_version: Every writer that admitted or published a request in the last 7 days is v0.60.5.0 or newer."," [OK] self_capture: No session corpus is configured; nothing to classify.",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex a8440c4d6d..7c67d555fe 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -535,7 +535,7 @@},{"category": "meta",- "message": "1066 column(s) verified against live schema",+ "message": "1067 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -956,6 +956,17 @@"name": "orphan_persistence_bindings","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": 0,+ "docs": "docs/guides/write-refusals.md#foreign-ownership-marker",+ "markers": []+ },+ "message": "Every ownership marker beside a source checkout belongs to this brain.",+ "name": "foreign_ownership_marker",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 7283975275..c161e6a22d 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -537,7 +537,7 @@},{"category": "meta",- "message": "1066 column(s) verified against live schema",+ "message": "1067 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -1066,6 +1066,17 @@"name": "orphan_persistence_bindings","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": 0,+ "docs": "docs/guides/write-refusals.md#foreign-ownership-marker",+ "markers": []+ },+ "message": "Every ownership marker beside a source checkout belongs to this brain.",+ "name": "foreign_ownership_marker",+ "status": "ok"+ },{"category": "brain","details": {@@ -3544,7 +3555,7 @@},{"category": "meta",- "message": "1066 column(s) verified against live schema",+ "message": "1067 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -4073,6 +4084,17 @@"name": "orphan_persistence_bindings","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": 0,+ "docs": "docs/guides/write-refusals.md#foreign-ownership-marker",+ "markers": []+ },+ "message": "Every ownership marker beside a source checkout belongs to this brain.",+ "name": "foreign_ownership_marker",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex ee2affe2a7..4dee1deb8c 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -417,6 +417,10 @@"category": "brain","name": "orphan_persistence_bindings"},+ {+ "category": "brain",+ "name": "foreign_ownership_marker"+ },{"category": "brain","name": "unbound_source"