Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): two_consumers_on_host, consumers_without_heartbeat and host_identity_mismatch checks; host.json minted_under; writer status host.consumers (#6317 T-08)
garrytan0976d8942bee
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex b1a368dfa5..aa3ab25c1f 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -582,6 +582,14 @@ More: [docs/guides/write-refusals.md#concurrent_write](../../docs/guides/write-rMore: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### consumers_without_heartbeat++<a id="consumers_without_heartbeat"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A process holds live write claims on this host without a consumer heartbeat row. | Only a gbrain older than the heartbeat release, or a consumer whose renewals keep failing, claims without a row; the consumer election cannot see such a process, so a new process beside it starts a second full consumer. | Restart the named process on this gbrain version; its claims resume under the new owner. Run: gbrain sources writer status --json | agent | `gbrain doctor --json` | 1 | no |+### content_rejected<a id="content_rejected"></a>@@ -1292,6 +1300,14 @@ More: [docs/guides/bootstrap.md#harness_hook_unowned](../../docs/guides/bootstra|---|---|---|---|---|---|---|| Held out required for bundled. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### host_identity_mismatch++<a id="host_identity_mismatch"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A managed worktree on this filesystem belongs to another host.json identity. | Host identity is a file under GBRAIN_HOME; a process started with another HOME or GBRAIN_HOME (a job worker in a container, for example) mints a new identity, sees the binding as another host's, and every write it submits reports owner_unavailable while its maintenance never runs. Doctor names both files and the home each was minted under; nothing is re-identified. | Set GBRAIN_HOME on that process's supervisor to the owner's home (the parent of its .gbrain directory) and restart it; never delete or regenerate either host.json. Run: gbrain sources writer status --json | agent | `gbrain doctor --json` | 1 | no |+### idempotency_conflict<a id="idempotency_conflict"></a>@@ -2554,6 +2570,14 @@ More: [docs/guides/data-ingestion.md#credential-redaction](../../docs/guides/dat|---|---|---|---|---|---|---|| The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it. | Only the operator of the brain host can change what blocks this. | Ask the user to run the named gbrain command on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |+### two_consumers_on_host++<a id="two_consumers_on_host"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Two resident processes on one host have each run a full persistence consumer for over 30 seconds. | One full consumer per host is a preference the consumer election keeps (persistence.single_consumer); two consumers on one host preceded every #6317 wedge, so a persistent overlap is reported from the heartbeat rows rather than bounded. | Stop one of the two (the sync CLI or jobs worker, never the serve), or let the shorter-lived one finish; a process started with --no-delegate or before the owner keeps its own consumer until it exits. Run: gbrain sources writer status --json | agent | `gbrain doctor --json` | 1 | no |+### unavailable<a id="unavailable"></a>diff --git a/src/commands/doctor/checks/persistence-consumers.ts b/src/commands/doctor/checks/persistence-consumers.tsnew file mode 100644index 0000000000..dc45194909--- /dev/null+++ b/src/commands/doctor/checks/persistence-consumers.ts@@ -0,0 +1,108 @@+/**+ * #6317: the persistence consumers of this host and the identity they run+ * under. Three checks, all read-only:+ *+ * - `two_consumers_on_host` (B3): two resident-kind full consumers (`serve`,+ * `sync`, `jobs`, `autopilot`, `mcp`) both alive for longer than 30 s on+ * this host. Every wedge in #6317 had two consumers on the host; one+ * consumer per host is a preference the election keeps, so a persistent+ * overlap is reported, not bounded. Short-lived rows (`put`, `cli`) and+ * rows younger than 30 s are listed only.+ * - `consumers_without_heartbeat` (T1c): owners stamped on this host's live+ * running claims that have no heartbeat row: an older gbrain build, which+ * never writes one, or a consumer whose renewals fail.+ * - `host_identity_mismatch` (I1): a worktree this filesystem holds whose+ * binding belongs to another `host.json` identity (same machine id, or the+ * managed worktree at the binding's path plus a `host.json` minted later+ * under a different `HOME`/`GBRAIN_HOME`). Names both files and the one-line+ * `GBRAIN_HOME` fix; never re-identifies anything.+ */+import type { Check } from '../../doctor.ts';+import type { BrainEngine } from '../../../core/engine.ts';+import { listHostConsumers } from '../../../core/persistence/consumer-heartbeat.ts';+import { consumerOverlap, hostIdentityMismatches, ownersWithoutHeartbeat, OVERLAP_MIN_AGE_MS } from '../../../core/persistence/consumer-diagnostics.ts';+import { localHostIdentity } from '../../../core/persistence/identity.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';++const DOCS = 'docs/guides/troubleshooting.md#two-consumers-on-host';+const IDENTITY_DOCS = 'docs/guides/troubleshooting.md#host-identity-mismatch';+const STATUS_ARGV = ['gbrain', 'sources', 'writer', 'status', '--json'];++export async function twoConsumersOnHostCheck(engine: BrainEngine, hostId: string): Promise<Check> {+ if (engine.kind === 'pglite') return { name: 'two_consumers_on_host', status: 'ok', message: 'PGLite admits one process; no consumer heartbeat rows are kept.', details: { count: 0, consumers: [], docs: DOCS } };+ try {+ const consumers = await listHostConsumers(engine, hostId);+ const overlap = consumerOverlap(consumers);+ const listed = consumers.map(row => ({ kind: row.kind, pid: row.pid, nonce: row.nonce, pid_ns: row.pid_ns, mode: row.mode, version: row.version, started_at: row.started_at,+ age_ms: row.age_ms, renewed_age_ms: row.renewed_age_ms, liveness: row.liveness, restart_required: row.restart_required, root_barrier_age_ms: row.root_barrier_age_ms, pool: row.pool, self: row.self }));+ const details = { count: overlap.length, min_age_ms: OVERLAP_MIN_AGE_MS, consumers: listed, docs: DOCS };+ if (!overlap.length) return { name: 'two_consumers_on_host', status: 'ok', details,+ message: consumers.length ? `${consumers.length} consumer process(es) on this host (${listed.map(row => `${row.kind} pid ${row.pid}, ${row.liveness}`).join('; ')}); at most one resident full consumer is alive.`+ : 'No persistence consumer is running on this host.' };+ return { name: 'two_consumers_on_host', status: 'warn', details,+ message: `two_consumers_on_host: ${overlap.length} resident processes have each run a full persistence consumer on this host for over ${OVERLAP_MIN_AGE_MS / 1000} s `+ + `(${overlap.map(row => `${row.kind} pid ${row.pid}, started ${row.started_at}`).join('; ')}). Two consumers on one host preceded every #6317 wedge. `+ + 'With persistence.single_consumer on, the later resident process defers to the first; a process started with --no-delegate or before the owner keeps its own consumer until it exits. '+ + 'Stop one of them (the sync CLI or jobs worker, not the serve), or leave both and watch writer status until one exits.',+ fix: agentFix(STATUS_ARGV, 'Read-only: lists host.consumers with each process\'s mode, age and wedge report, and every running claim\'s owner.', 'two_consumers_on_host', { docs: DOCS }) };+ } catch (error) {+ return checkError('two_consumers_on_host', 'read the consumer heartbeat rows', error, { details: { count: 'unknown', health: 'unknown', docs: DOCS } });+ }+}++export async function consumersWithoutHeartbeatCheck(engine: BrainEngine, hostId: string): Promise<Check> {+ if (engine.kind === 'pglite') return { name: 'consumers_without_heartbeat', status: 'ok', message: 'PGLite admits one process; no consumer heartbeat rows are kept.', details: { count: 0, owners: [], docs: DOCS } };+ try {+ const owners = await ownersWithoutHeartbeat(engine, hostId);+ const details = { count: owners.length, owners, docs: DOCS };+ if (!owners.length) return { name: 'consumers_without_heartbeat', status: 'ok', details, message: 'Every owner of a live running claim on this host has a consumer heartbeat row.' };+ return { name: 'consumers_without_heartbeat', status: 'warn', details,+ message: `consumers_without_heartbeat: ${owners.length} process(es) hold live claims on this host without a consumer heartbeat row `+ + `(${owners.map(owner => `${owner.kind ?? 'unknown'} pid ${owner.pid}${owner.version ? ` v${owner.version}` : ''}: ${owner.requests} claim(s) on ${owner.sources.join(', ')}`).join('; ')}). `+ + 'A gbrain older than this release writes no heartbeat, so the consumer election cannot see it and a new process beside it starts a second full consumer. '+ + 'Restart that process on this gbrain version.',+ fix: agentFix(STATUS_ARGV, 'Read-only: shows each running claim\'s owner (kind, pid, build) next to host.consumers.', 'consumers_without_heartbeat', { docs: DOCS }) };+ } catch (error) {+ return checkError('consumers_without_heartbeat', 'compare running claims with the consumer heartbeat rows', error, { details: { count: 'unknown', health: 'unknown', docs: DOCS } });+ }+}++export async function hostIdentityMismatchCheck(engine: BrainEngine): Promise<Check> {+ try {+ const me = localHostIdentity();+ const mismatches = await hostIdentityMismatches(engine, me);+ // The ok details carry no `minted_under`: the machine id and hostname differ per machine, and the doctor goldens pin this shape.+ const details = { count: mismatches.length, host_id: me.id, host_json_path: me.path, mismatches, docs: IDENTITY_DOCS };+ if (!mismatches.length) return { name: 'host_identity_mismatch', status: 'ok', details, message: `This process's host identity (${me.path}) owns every binding this filesystem holds.` };+ const first = mismatches[0]!;+ const minted = (value: Record<string, unknown> | 'unknown' | null) => value && value !== 'unknown'+ ? `HOME=${String(value.home ?? '')} GBRAIN_HOME=${value.gbrain_home == null ? '(unset)' : String(value.gbrain_home)}` : 'minted_under: unknown';+ return { name: 'host_identity_mismatch', status: 'warn', details: { ...details, minted_under: me.minted_under ?? 'unknown' },+ message: `host_identity_mismatch: ${mismatches.length} managed worktree(s) on this filesystem belong to another host identity. `+ + `This process reads ${me.path} (host ${me.id}, ${minted(me.minted_under)}); the binding for ${first.source_ids.join(', ') || first.worktree_id} at ${first.local_path} `+ + `is owned by host ${first.owner_host_id} (${first.owner_host.host_json_path}, ${minted(first.owner_host.minted_under)})`+ + `${first.reason === 'same_machine_id' ? ', minted on this same machine' : ', and this process\'s identity was minted after that binding under a different home'}. `+ + 'Every write from this process on that source reports owner_unavailable (host_mismatch) and its maintenance never runs. '+ + `Fix on the supervisor of this process: ${first.fix_env ?? 'set GBRAIN_HOME to the owner\'s home (the parent of its .gbrain directory)'}, then restart it; never delete or regenerate either host.json.`,+ fix: agentFix(STATUS_ARGV, 'Read-only: shows local_host_id, each binding\'s owner_host_id and host.consumers with the owner\'s identity file path.', 'host_identity_mismatch', { docs: IDENTITY_DOCS }) };+ } catch (error) {+ return checkError('host_identity_mismatch', 'compare the host identity with the binding owners', error, { details: { count: 'unknown', health: 'unknown', docs: IDENTITY_DOCS } });+ }+}++async function runPersistenceConsumers(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ const hostId = localHostIdentity().id;+ checks.push(await twoConsumersOnHostCheck(engine, hostId));+ checks.push(await consumersWithoutHeartbeatCheck(engine, hostId));+ checks.push(await hostIdentityMismatchCheck(engine));+ return checks;+}++export const persistenceConsumersEntry: DoctorEntry = {+ name: 'two_consumers_on_host',+ emits: ['two_consumers_on_host', 'consumers_without_heartbeat', 'host_identity_mismatch'],+ run: runPersistenceConsumers,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 8219954d4e..7d8fc86cb9 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -83,6 +83,7 @@ import { globalMaintenanceTimeoutsEntry } from './checks/global-maintenance-timeimport { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';+import { persistenceConsumersEntry } from './checks/persistence-consumers.ts';import { gitConvergenceEntry } from './checks/git-convergence.ts';import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';import { transcriptSecretExposureEntry } from './checks/transcript-secrets.ts';@@ -176,6 +177,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [revisionBackfillEntry,coreMemoryEntry,fenceIntegrityEntry,+ persistenceConsumersEntry,searchModeEntry,];diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 0343dd14a7..7150197be3 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -249,6 +249,10 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['persistence_request_indexes','persistence_write_stall','persistence_session_timeouts',+ // #6317: consumer heartbeat rows and host identity (doctor/checks/persistence-consumers.ts).+ 'two_consumers_on_host',+ 'consumers_without_heartbeat',+ 'host_identity_mismatch','stale_embedding_effects','vector_plan','writer_version',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 11f5189066..36e4080a0c 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -263,6 +263,9 @@ export const CODES = {pattern_claims_pending: { class: 'retryable', summary: "An existing pattern page is waiting on the rewrite that de-duplicates its claim sources, so no patterns child was submitted this run.", why: "The patterns child reads existing pattern pages; until their claim records reference one shared reflection list, the pages can overflow the model's window and the run pays for nothing.", fix: { argv: ['gbrain', 'write-requests', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Lists the write receipts of the source, newest first, so the held rewrites show, read-only.', requires_exclusive: false } },pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },+ two_consumers_on_host: { class: 'host_only', summary: "Two resident processes on one host have each run a full persistence consumer for over 30 seconds.", why: "One full consumer per host is a preference the consumer election keeps (persistence.single_consumer); two consumers on one host preceded every #6317 wedge, so a persistent overlap is reported from the heartbeat rows rather than bounded.", suggestion: 'Stop one of the two (the sync CLI or jobs worker, never the serve), or let the shorter-lived one finish; a process started with --no-delegate or before the owner keeps its own consumer until it exits.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: "Lists host.consumers with each process's mode, age and wedge report, read-only.", requires_exclusive: false } },+ consumers_without_heartbeat: { class: 'host_only', summary: "A process holds live write claims on this host without a consumer heartbeat row.", why: "Only a gbrain older than the heartbeat release, or a consumer whose renewals keep failing, claims without a row; the consumer election cannot see such a process, so a new process beside it starts a second full consumer.", suggestion: 'Restart the named process on this gbrain version; its claims resume under the new owner.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: "Shows each running claim's owner (kind, pid, build) next to host.consumers, read-only.", requires_exclusive: false } },+ host_identity_mismatch: { class: 'host_only', summary: "A managed worktree on this filesystem belongs to another host.json identity.", why: "Host identity is a file under GBRAIN_HOME; a process started with another HOME or GBRAIN_HOME (a job worker in a container, for example) mints a new identity, sees the binding as another host's, and every write it submits reports owner_unavailable while its maintenance never runs. Doctor names both files and the home each was minted under; nothing is re-identified.", suggestion: "Set GBRAIN_HOME on that process's supervisor to the owner's home (the parent of its .gbrain directory) and restart it; never delete or regenerate either host.json.", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: "Shows local_host_id, each binding's owner_host_id and the owner's identity file path from host.consumers, read-only.", requires_exclusive: false } },persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },pglite_busy: { class: 'retryable', summary: "Another gbrain process holds this PGLite brain's single-writer lock.", reasons: ['timeout', 'live_serve'], suggestion: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' },plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 1c30196e57..6503390b45 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -228,6 +228,8 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatiohost_id: existingLocalHostId(), local_host_id: existingLocalHostId(), bindings, admin_state: adminState,admin_lock: { locked: adminLock.locked, set_at: adminLock.set_at, host_id: adminLock.host_id }, blocking_effects: blockingEffects,writer_versions: writerVersions, onboarding, shared_skills: sharedSkills, ...(native ? { native_lock: native } : {}),+ // #6317 (B3): every process holding a consumer on this host, from the heartbeat rows (kind, pid, nonce, mode, age, wedge report).+ host: { host_id: existingLocalHostId(), ...await (await import('./consumer-diagnostics.ts')).hostConsumersReport(engine, existingLocalHostId()) },worktree_refreshes: await (await import('./worktree-refresh.ts')).activeWorktreeRefreshes(engine, params.source_id as string | undefined) };}if (operation === 'writer_claim') {diff --git a/src/core/persistence/consumer-diagnostics.ts b/src/core/persistence/consumer-diagnostics.tsnew file mode 100644index 0000000000..965ad967f4--- /dev/null+++ b/src/core/persistence/consumer-diagnostics.ts@@ -0,0 +1,141 @@+/**+ * #6317 (B3, I1): what doctor and `writer status --json` read from the+ * consumer heartbeat rows and the host identity file.+ *+ * - `consumerOverlap`: two resident-kind full consumers both alive on one host+ * for longer than `OVERLAP_MIN_AGE_MS` (doctor `two_consumers_on_host`); a+ * `put`, `import` or `cli` row, or a row younger than that, is listed, never+ * warned about: short-lived commands keep their own consumer by design and+ * two starters within one renewal may both start full (a preference, not a+ * fenced role).+ * - `ownersWithoutHeartbeat`: the owner identities stamped on this host's+ * running claims that have no heartbeat row (doctor+ * `consumers_without_heartbeat`): an older gbrain writes no row, so this is+ * the only evidence such a process leaves.+ * - `hostIdentityMismatches`: a worktree this filesystem holds whose binding+ * belongs to another host identity (doctor `host_identity_mismatch`): the+ * same machine id in both `host.json` files, or (containers without a+ * machine id) the binding's local path exists here with its managed marker+ * and this process's `host.json` was minted after the binding under a+ * different `HOME`/`GBRAIN_HOME`. A re-minted identity never re-owns a+ * binding; the fix is `GBRAIN_HOME` on the supervisor.+ */+import { existsSync, statSync } from 'node:fs';+import { dirname } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { CONSUMER_LAPSED_MS, RESIDENT_CONSUMER_KINDS, listHostConsumers, type ListedConsumer } from './consumer-heartbeat.ts';+import type { LocalHostIdentity } from './identity.ts';+import { hasManagedRootMarker } from './root-registry.ts';++/** Both rows must be older than this before an overlap is a warning: two starters within one renewal are a known residual. */+export const OVERLAP_MIN_AGE_MS = 30_000;++/** The rows that make a persistent overlap: live, resident-kind, full or promoted, older than `OVERLAP_MIN_AGE_MS`. Empty or one row means no overlap. */+export function consumerOverlap(rows: readonly ListedConsumer[], minAgeMs = OVERLAP_MIN_AGE_MS): ListedConsumer[] {+ const resident = rows.filter(row => row.liveness === 'live' && RESIDENT_CONSUMER_KINDS.includes(row.kind) && (row.mode === 'full' || row.mode === 'promoted') && row.age_ms >= minAgeMs);+ return resident.length >= 2 ? resident : [];+}++export interface OwnerWithoutHeartbeat { kind: string | null; pid: number; nonce: string | null; version: string | null; requests: number; sources: string[]; lapsed: boolean }+/**+ * Owners stamped on running claims of worktrees this host owns (and of database-only requests, which any process of+ * this host may hold) that have no heartbeat row for this host. Only claims whose lease is still renewed count: a lapsed+ * claim's owner is gone, which `persistence_write_stall` and the drain already report.+ */+export async function ownersWithoutHeartbeat(engine: BrainEngine, hostId: string, rows?: readonly ListedConsumer[]): Promise<OwnerWithoutHeartbeat[]> {+ if (engine.kind === 'pglite') return [];+ const consumers = rows ?? await listHostConsumers(engine, hostId);+ const claims = await engine.executeRaw<{ source_id: string; owner: unknown; lapsed: boolean | null }>(+ `SELECT r.source_id,r.claim_phase->'owner' AS owner,r.claim_expires_at<now() AS lapsed FROM persistence_requests r+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id+ WHERE r.state='running' AND r.claim_phase->'owner' IS NOT NULL AND (r.worktree_id IS NULL OR w.owner_host_id=$1::uuid)+ ORDER BY r.sequence LIMIT 500`, [hostId]);+ const seen = new Map<string, OwnerWithoutHeartbeat>();+ for (const claim of claims) {+ const owner = (typeof claim.owner === 'string' ? JSON.parse(claim.owner) : claim.owner) as { kind?: string; pid?: number; nonce?: string; version?: string } | null;+ if (!owner || typeof owner.pid !== 'number' || claim.lapsed) continue;+ const nonce = typeof owner.nonce === 'string' ? owner.nonce : null;+ if (consumers.some(row => row.pid === owner.pid && (nonce === null || row.nonce === nonce))) continue;+ const key = `${owner.pid}:${nonce ?? ''}`;+ const entry = seen.get(key) ?? { kind: owner.kind ?? null, pid: owner.pid, nonce, version: owner.version ?? null, requests: 0, sources: [], lapsed: false };+ entry.requests++;+ if (!entry.sources.includes(claim.source_id)) entry.sources.push(claim.source_id);+ seen.set(key, entry);+ }+ return [...seen.values()];+}++export interface HostIdentityMismatch {+ worktree_id: string;+ source_ids: string[];+ owner_host_id: string;+ local_path: string;+ /** Which predicate fired. */+ reason: 'same_machine_id' | 'worktree_on_this_filesystem';+ /** This process's identity file and where it was minted. */+ this_host: { host_id: string; host_json_path: string; minted_under: Record<string, unknown> | null };+ /** The owner's identity file, from its heartbeat row when one exists (`unknown` otherwise). */+ owner_host: { host_id: string; host_json_path: string | 'unknown'; persistence_home: string | 'unknown'; minted_under: Record<string, unknown> | 'unknown'; last_seen: string | null };+ /** The one-line fix for the supervisor: `GBRAIN_HOME=<owner's home>` (the parent value; config appends `.gbrain`). */+ fix_env: string | null;+}++type OwnerBinding = { worktree_id: string; owner_host_id: string; local_path: string; created_at: string; source_ids: string[] | null };+type OwnerRow = { host_id: string; host_json_path: string; persistence_home: string; minted_under: unknown; renewed_at: string };++/** The `GBRAIN_HOME` parent value a supervisor sets so this process mints under the owner's home: the owner's `gbrain_home`, else its persistence home's grandparent (`<home>/.gbrain/persistence`). */+function fixEnv(owner: OwnerRow | undefined): string | null {+ const minted = owner ? parse(owner.minted_under) : null;+ if (typeof minted?.gbrain_home === 'string' && minted.gbrain_home) return `GBRAIN_HOME=${minted.gbrain_home}`;+ if (owner?.persistence_home) return `GBRAIN_HOME=${dirname(dirname(owner.persistence_home))}`;+ return null;+}+function parse(value: unknown): Record<string, unknown> | null {+ if (value == null) return null;+ if (typeof value === 'string') { try { return JSON.parse(value) as Record<string, unknown>; } catch { return null; } }+ return typeof value === 'object' ? value as Record<string, unknown> : null;+}+function mintedAt(path: string): number | null {+ try { const stat = statSync(path); return Math.min(stat.birthtimeMs || stat.mtimeMs, stat.mtimeMs); } catch { return null; }+}++/**+ * Bindings owned by another host identity that this filesystem can see. `now` and `exists`/`marked` are seams for tests.+ */+export async function hostIdentityMismatches(engine: BrainEngine, me: LocalHostIdentity,+ seams: { now?: number; exists?: (path: string) => boolean; marked?: (path: string) => boolean; hostJsonMintedAt?: number | null } = {}): Promise<HostIdentityMismatch[]> {+ const exists = seams.exists ?? (path => { try { return existsSync(path) && statSync(path).isDirectory(); } catch { return false; } });+ const marked = seams.marked ?? hasManagedRootMarker;+ const bindings = await engine.executeRaw<OwnerBinding>(`SELECT w.id::text AS worktree_id,w.owner_host_id::text AS owner_host_id,h.local_path,w.created_at::text AS created_at,+ (SELECT array_agg(b.source_id ORDER BY b.source_id) FROM persistence_source_bindings b WHERE b.worktree_id=w.id) AS source_ids+ FROM persistence_worktrees w JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=w.owner_host_id+ WHERE w.owner_host_id IS NOT NULL AND w.owner_host_id<>$1::uuid AND w.state<>'recovering' ORDER BY w.created_at`, [me.id]);+ if (!bindings.length) return [];+ const owners = engine.kind === 'pglite' ? [] : await engine.executeRaw<OwnerRow>(`SELECT DISTINCT ON (host_id) host_id::text AS host_id,host_json_path,persistence_home,minted_under,renewed_at::text AS renewed_at+ FROM persistence_consumers WHERE host_id=ANY($1::uuid[]) ORDER BY host_id,renewed_at DESC`, [[...new Set(bindings.map(b => b.owner_host_id))]]);+ const myMintedAt = seams.hostJsonMintedAt === undefined ? mintedAt(me.path) : seams.hostJsonMintedAt;+ const out: HostIdentityMismatch[] = [];+ for (const binding of bindings) {+ const owner = owners.find(row => row.host_id === binding.owner_host_id);+ const ownerMinted = owner ? parse(owner.minted_under) : null;+ const sameMachine = !!me.minted_under?.machine_id && ownerMinted?.machine_id === me.minted_under.machine_id;+ const differentHome = !ownerMinted || ownerMinted.home !== me.minted_under?.home || ownerMinted.gbrain_home !== me.minted_under?.gbrain_home;+ const mintedAfter = myMintedAt !== null && myMintedAt > Date.parse(binding.created_at);+ const onThisFilesystem = !sameMachine && exists(binding.local_path) && marked(binding.local_path) && mintedAfter && differentHome;+ if (!sameMachine && !onThisFilesystem) continue;+ out.push({ worktree_id: binding.worktree_id, source_ids: binding.source_ids ?? [], owner_host_id: binding.owner_host_id, local_path: binding.local_path,+ reason: sameMachine ? 'same_machine_id' : 'worktree_on_this_filesystem',+ this_host: { host_id: me.id, host_json_path: me.path, minted_under: me.minted_under },+ owner_host: { host_id: binding.owner_host_id, host_json_path: owner?.host_json_path ?? 'unknown', persistence_home: owner?.persistence_home ?? 'unknown',+ minted_under: ownerMinted ?? 'unknown', last_seen: owner?.renewed_at ?? null },+ fix_env: fixEnv(owner) });+ }+ return out;+}++/** The rows `writer status --json` prints as `host.consumers`, oldest first, plus the overlap verdict and the lapsed window. */+export async function hostConsumersReport(engine: BrainEngine, hostId: string | null) {+ const consumers = hostId && engine.kind !== 'pglite' ? await listHostConsumers(engine, hostId) : [];+ return { consumers, overlap: consumerOverlap(consumers).map(row => ({ kind: row.kind, pid: row.pid, nonce: row.nonce })), lapsed_after_ms: CONSUMER_LAPSED_MS,+ ...(engine.kind === 'pglite' ? { scope: 'PGLite admits one process; no heartbeat rows are kept.' } : {}) };+}diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.tsindex 9373d1a2e5..279e4987af 100644--- a/src/core/persistence/identity.ts+++ b/src/core/persistence/identity.ts@@ -60,7 +60,7 @@ function privateJson<T>(path: string, create: () => T): T {* reject any other version, so the version never changes); a file minted* before this release reads as `minted_under: null`, reported as unknown.*/-export interface HostIdentityMintedUnder { home: string | null; gbrain_home: string | null; hostname: string; machine_id: string | null }+export interface HostIdentityMintedUnder extends Record<string, unknown> { home: string | null; gbrain_home: string | null; hostname: string; machine_id: string | null }export interface HostIdentityFile { version: number; id: string; minted_under?: HostIdentityMintedUnder }export interface LocalHostIdentity { id: string; path: string; persistence_home: string; minted_under: HostIdentityMintedUnder | null }const MACHINE_ID_FILES = ['/etc/machine-id', '/var/lib/dbus/machine-id'];diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 67bc112862..019206967e 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -518,7 +518,7 @@},{"category": "meta",- "message": "986 column(s) verified against live schema",+ "message": "1001 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -1794,6 +1794,41 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "ops",+ "details": {+ "consumers": [],+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#two-consumers-on-host"+ },+ "message": "PGLite admits one process; no consumer heartbeat rows are kept.",+ "name": "two_consumers_on_host",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#two-consumers-on-host",+ "owners": []+ },+ "message": "PGLite admits one process; no consumer heartbeat rows are kept.",+ "name": "consumers_without_heartbeat",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#host-identity-mismatch",+ "host_id": "<uuid>",+ "host_json_path": "<home>/.gbrain/persistence/host.json",+ "mismatches": []+ },+ "message": "This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.",+ "name": "host_identity_mismatch",+ "status": "ok"+ },{"category": "ops","message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 9816694ecb..47e9d0e92e 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -521,7 +521,7 @@},{"category": "meta",- "message": "986 column(s) verified against live schema",+ "message": "1001 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -1871,6 +1871,41 @@"name": "fence_integrity","status": "ok"},+ {+ "category": "ops",+ "details": {+ "consumers": [],+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#two-consumers-on-host"+ },+ "message": "PGLite admits one process; no consumer heartbeat rows are kept.",+ "name": "two_consumers_on_host",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#two-consumers-on-host",+ "owners": []+ },+ "message": "PGLite admits one process; no consumer heartbeat rows are kept.",+ "name": "consumers_without_heartbeat",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/troubleshooting.md#host-identity-mismatch",+ "host_id": "<uuid>",+ "host_json_path": "<home>/.gbrain/persistence/host.json",+ "mismatches": []+ },+ "message": "This process's host identity (<home>/.gbrain/persistence/host.json) owns every binding this filesystem holds.",+ "name": "host_identity_mismatch",+ "status": "ok"+ },{"category": "ops","message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 12c25cb20b..ac0e22ded9 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -705,6 +705,18 @@"category": "brain","name": "fence_integrity"},+ {+ "category": "ops",+ "name": "two_consumers_on_host"+ },+ {+ "category": "ops",+ "name": "consumers_without_heartbeat"+ },+ {+ "category": "ops",+ "name": "host_identity_mismatch"+ },{"category": "ops","name": "search_mode"