Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(persistence): resolve every core host-id read through hostIdFor(engine)

garrytan90bcfa75df0a
diff --git a/src/core/company-brain/admission.ts b/src/core/company-brain/admission.ts
index 2f8af7e181..20e06a2646 100644
--- a/src/core/company-brain/admission.ts
+++ b/src/core/company-brain/admission.ts
@@ -9,7 +9,7 @@ import { isValidSourceId } from '../source-id.ts';
import { assertNoOverlappingPath } from '../sources-ops.ts';
import { checkApprovedSchemaForEngine } from '../schema-pack/engine-resolution.ts';
import { getWorktreeBinding, managedPersistenceEnabled, readPersistenceBrain } from '../persistence/ownership.ts';
-import { registerLocalWriter, localHostId, currentVerifiedLocalWriter } from '../persistence/identity.ts';
+import { registerLocalWriter, currentVerifiedLocalWriter, hostIdFor } from '../persistence/identity.ts';
import { isWriteRequestId } from '../persistence/types.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { topologyTransaction } from '../persistence/topology-transaction.ts';
@@ -104,7 +104,7 @@ export function assertCompanyBrainCaller(input: CompanyBrainDestination): void {
export async function ingestionFence(engine: BrainEngine, sourceId: string): Promise<SourceIngestionFence> {
if (!await managedPersistenceEnabled(engine)) return { mode: 'unmanaged' };
const binding = await getWorktreeBinding(engine, sourceId);
- if (!binding?.owner_host_id || binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) {
+ if (!binding?.owner_host_id || binding.owner_host_id !== hostIdFor(engine) || binding.state !== 'active' || !binding.local_path) {
throw opError('owner_unavailable', 'The managed source must run on its active registered local owner.',
`Source ${sourceId} is managed and this host is not its active owner. Check the owner, then run the command on that host or wait until its owner is active again.`,
{ fix: ownerStatusFix(sourceId) });
diff --git a/src/core/fence-repair/repair-io.ts b/src/core/fence-repair/repair-io.ts
index 7c775ff6a7..97c4552b0f 100644
--- a/src/core/fence-repair/repair-io.ts
+++ b/src/core/fence-repair/repair-io.ts
@@ -37,7 +37,7 @@ import { folderRestricted } from '../search/private-visibility.ts';
import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { resolveSlugForPath } from '../sync.ts';
import { sha256 } from '../persistence/digest.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
import { checkOwner, ownerRefusal, type OwnerRefusal } from '../persistence/owner-refusal.ts';
import { loadRepairBusySet, type RepairBusySet } from '../persistence/repair-busy.ts';
@@ -92,7 +92,7 @@ export async function loadFenceSource(engine: BrainEngine, sourceId: string, opt
const binding = await getWorktreeBinding(engine, sourceId);
// A source with no binding at all has no checkout anywhere: it is repaired in the database (db mode), not refused.
if (binding) {
- const hostId = localHostId();
+ const hostId = hostIdFor(engine);
const checked = checkOwner(binding, row.incarnation, hostId);
if (checked.reason) owner = ownerRefusal({ sourceId, reason: checked.reason, binding, incarnation: row.incarnation, hostId, remote: opts.remote !== false, work: opts.work ?? 'fence repair' });
else root = join(checked.binding.local_path, checked.binding.relative_path);
diff --git a/src/core/ghost-pages.ts b/src/core/ghost-pages.ts
index d6f1ce6d4f..1efcade833 100644
--- a/src/core/ghost-pages.ts
+++ b/src/core/ghost-pages.ts
@@ -46,7 +46,7 @@ import type { PageSnapshot } from './page-state/types.ts';
import { resolveRecordedSourceFilePath, resolveSourceLocalFilePath, sourceGitScope } from './markdown.ts';
import { recordedPathFromFileUri, scannerSlugRootMode } from './write-through.ts';
import { isOpPageSlug } from './ops/context.ts';
-import { existingLocalHostId } from './persistence/identity.ts';
+import { existingHostIdFor } from './persistence/identity.ts';
import { getWorktreeBinding } from './persistence/ownership.ts';
import { sourceMirrorReadOnly } from './persistence/mirror-read-only.ts';
import { publishesDatabaseOnly } from './persistence/page-prepare.ts';
@@ -124,7 +124,7 @@ export type SourceContext = { ok: true; root: string; owner: GhostOwner; mode: A
const missing = (error: unknown) => ['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException)?.code ?? '');
export async function sourceContext(engine: BrainEngine, sourceId: string): Promise<SourceContext> {
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding) return { ok: false, status: 'not_applicable', reason: 'not_applicable' };
if (!hostId || !binding.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') {
diff --git a/src/core/notifier/resident.ts b/src/core/notifier/resident.ts
index 99bac6789f..cb798151bb 100644
--- a/src/core/notifier/resident.ts
+++ b/src/core/notifier/resident.ts
@@ -16,7 +16,7 @@ import type { BrainEngine } from '../engine.ts';
import { gbrainPath } from '../config.ts';
import { registerCleanup } from '../process-cleanup.ts';
import { SYNC_ON_COMMIT_KEY } from '../sync-config-keys.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
import {
notifierDisabledByEnv, parseExcludedSources, parseOnCommit, startCommitNotifier,
type CommitNotifier, type CommitNotifierOptions, type NotifierSource, type NotifierStore, type ResidentKind, type SkippedSource,
@@ -163,7 +163,7 @@ export type ResidentNotifierOptions = Partial<Omit<CommitNotifierOptions, 'resid
export function residentNotifierOptions(engine: BrainEngine, opts: ResidentNotifierOptions): CommitNotifierOptions {
const env = opts.env ?? process.env;
// Host identity: the persistence host id (minted on first use, as a managed claim or a recorded classic sync does).
- const hostId = opts.hostId ?? localHostId();
+ const hostId = opts.hostId ?? hostIdFor(engine);
const defaults: Omit<CommitNotifierOptions, 'resident' | 'log' | 'hostId'> = {
store: sqlNotifierStore(engine),
maxConcurrent: 1,
diff --git a/src/core/notifier/status.ts b/src/core/notifier/status.ts
index d6bba81451..7cf4cb6a48 100644
--- a/src/core/notifier/status.ts
+++ b/src/core/notifier/status.ts
@@ -9,7 +9,7 @@
*/
import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
import { missingTable, type DetectionMode, type NotifierState } from './store.ts';
import { residentNotifier } from './resident.ts';
import { parseOnCommit } from '../commit-notifier.ts';
@@ -86,7 +86,7 @@ function ownerLive(engine: Exec, row: Pick<Row, 'owner_host_id' | 'owner_pid' |
if (!row.owner_host_id) return false;
if (engine.kind !== 'pglite') return truthy(row.lease_live);
const pid = row.owner_pid === null || row.owner_pid === undefined ? null : Number(row.owner_pid);
- if (pid === null || row.owner_host_id !== localHostId()) return false;
+ if (pid === null || row.owner_host_id !== hostIdFor(engine)) return false;
if (pid === process.pid) return residentNotifier() !== null;
try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }
}
diff --git a/src/core/notifier/store.ts b/src/core/notifier/store.ts
index 00fcc45ad3..0d6df0d414 100644
--- a/src/core/notifier/store.ts
+++ b/src/core/notifier/store.ts
@@ -20,7 +20,7 @@
* it as "no markers, nothing monitored".
*/
import type { BrainEngine } from '../engine.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
type Exec = Pick<BrainEngine, 'executeRaw'>;
@@ -286,7 +286,7 @@ export async function recordSyncerHost(engine: Exec, sourceId: string, hostId: s
* source's syncer, so this host's resident notifier watches it, and clears the markers that head satisfies. Best effort: a sync never fails on it.
*/
export async function recordLocalSyncer(engine: Exec, sourceId: string): Promise<void> {
- try { await recordSyncerHost(engine, sourceId, localHostId()); } catch { /* the notifier reports the source as unrecorded */ }
+ try { await recordSyncerHost(engine, sourceId, hostIdFor(engine)); } catch { /* the notifier reports the source as unrecorded */ }
// The CLI's re-check (GBRA-133 PR 2a.3): a run that reached a marker's head clears it, whoever ran it.
try { await pruneSatisfiedMarkers(engine, [sourceId]); } catch { /* the residents' marker scan prunes it */ }
}
diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.ts
index eadcb5bf5c..1b55061ca5 100644
--- a/src/core/persistence/activation.ts
+++ b/src/core/persistence/activation.ts
@@ -5,7 +5,7 @@ import type { Action } from '../agent-output.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { acquireWorktree, getWorktreeBinding, readManagedMode, type WorktreeBinding } from './ownership.ts';
-import { localHostId, existingLocalHostId, persistenceHome, registerLocalWriter } from './identity.ts';
+import { persistenceHome, registerLocalWriter, hostIdFor, existingHostIdFor } from './identity.ts';
import { nativeLockCapability, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';
@@ -192,7 +192,7 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQu
JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation WHERE NOT s.archived`);
return { enabled: true, activated: false, filesystem_sources: count.count, native_lock: native, ...ALREADY_ENABLED };
}
- const hostId = opts.dryRun ? existingLocalHostId() : localHostId();
+ const hostId = opts.dryRun ? existingHostIdFor(engine) : hostIdFor(engine);
const sources = await configuredSources(engine);
const writeThrough = writeThroughConfigured(await engine.getConfig('sync.write_through'));
const { bindings: initial, databaseOnly } = await validatedBindings(engine, sources, hostId, writeThrough);
diff --git a/src/core/persistence/admin-lock.ts b/src/core/persistence/admin-lock.ts
index ced4ae2d27..1b69b528a9 100644
--- a/src/core/persistence/admin-lock.ts
+++ b/src/core/persistence/admin-lock.ts
@@ -2,7 +2,7 @@
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { WRITER_ADMIN_LOCK_KEY } from './admin-contract.ts';
-import { existingLocalHostId, localHostId } from './identity.ts';
+import { hostIdFor, existingHostIdFor } from './identity.ts';
import type { SqlEngine } from './model.ts';
export { WRITER_ADMIN_LOCK_KEY };
@@ -56,7 +56,7 @@ export async function writeWriterAdminLock(tx: SqlEngine, locked: boolean): Prom
'Finish the prepared transfer with gbrain sources writer transfer accept, inspect gbrain sources writer status --json, then lock.');
}
const [now] = await tx.executeRaw<{ at: string }>(`SELECT to_char(now() AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS at`);
- const next: WriterAdminLock = { locked, set_at: now.at, host_id: localHostId(), generation: current.generation + 1 };
+ const next: WriterAdminLock = { locked, set_at: now.at, host_id: hostIdFor(tx), generation: current.generation + 1 };
await tx.executeRaw(`INSERT INTO config(key,value) VALUES($1,$2) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value`,
[WRITER_ADMIN_LOCK_KEY, JSON.stringify(next)]);
return { admin_lock: next, changed: true };
@@ -64,5 +64,5 @@ export async function writeWriterAdminLock(tx: SqlEngine, locked: boolean): Prom
export async function setWriterAdminLock(engine: BrainEngine, locked: boolean): Promise<{ admin_lock: WriterAdminLock; changed: boolean; local_host_id: string | null }> {
const result = await engine.transaction(tx => writeWriterAdminLock(tx, locked));
- return { ...result, local_host_id: existingLocalHostId() };
+ return { ...result, local_host_id: existingHostIdFor(engine) };
}
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index 5eb8a37080..5c219fad52 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -10,7 +10,7 @@ import { isWriteRequestId } from './types.ts';
import { writerDiagnostics } from './control.ts';
import { acceptWriterTransfer, claimWorktree, getWorktreeBinding, humanManifestProgress, prepareWriterTransfer, readManagedMode, storedManifestScope, worktreeManifest, type StoredWorktreeManifest } from './ownership.ts';
import { inspectPersistenceBrain } from './managed-mode.ts';
-import { existingLocalHostId, currentVerifiedLocalWriter, persistenceHome, readLocalWriter, registerLocalWriter, revokeLocalWriter, type LocalGrant } from './identity.ts';
+import { currentVerifiedLocalWriter, persistenceHome, readLocalWriter, registerLocalWriter, revokeLocalWriter, type LocalGrant, existingHostIdFor } from './identity.ts';
import type { PersistenceAdminOperation } from './admin-contract.ts';
import { operationScopesAllowed } from '../scope.ts';
import { assertWriterAdminState, requireWriterAdminIntent, writerAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';
@@ -282,7 +282,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
CASE h.git_durability WHEN 'enabled' THEN 'on' WHEN 'disabled' THEN 'off' ELSE 'unknown' END AS git_durability_state FROM persistence_source_bindings b
JOIN persistence_worktrees w ON w.id=b.worktree_id
LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid
- WHERE ($2::text IS NULL OR b.source_id=$2) ORDER BY b.source_id`, [existingLocalHostId(), params.source_id === undefined ? null : source(params.source_id)]);
+ WHERE ($2::text IS NULL OR b.source_id=$2) ORDER BY b.source_id`, [existingHostIdFor(engine), params.source_id === undefined ? null : source(params.source_id)]);
let native: unknown;
if (params.probe === true) {
const { nativeLockCapability, tryAcquireNativeLock } = await import('./native-lock.ts');
@@ -308,14 +308,14 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
return { ...diagnostics, mode: !mode.row ? 'unknown' : mode.row.enabled ? 'managed' : 'classic', mode_epoch: Number(mode.row?.mode_epoch ?? 1),
...(mode.problem ? { mode_problem: mode.problem } : {}),
local_markers: await cleanupRetiredManagedMarkers(engine),
- host_id: existingLocalHostId(), local_host_id: existingLocalHostId(), bindings, admin_state: adminState,
+ host_id: existingHostIdFor(engine), local_host_id: existingHostIdFor(engine), bindings, admin_state: adminState,
admin_lock: { locked: adminLock.locked, set_at: adminLock.set_at, host_id: adminLock.host_id }, blocking_effects: blockingEffects,
// GBRA-133: effects that have waited on a busy canonical worktree for over 10 minutes.
stalled_catchups: await (await import('./effect-catchup.ts')).readStalledCatchups(engine, params.source_id ? [params.source_id as string] : undefined),
parked_groups: await (await import('./parked-groups.ts')).readParkedGroups(engine, params.source_id ? [params.source_id as string] : undefined),
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()) },
+ host: { host_id: existingHostIdFor(engine), ...await (await import('./consumer-diagnostics.ts')).hostConsumersReport(engine, existingHostIdFor(engine)) },
worktree_refreshes: await (await import('./worktree-refresh.ts')).activeWorktreeRefreshes(engine, params.source_id as string | undefined),
// Q1: each canonical checkout on this host against its last fetched upstream: commits it holds that the upstream lacks, and its porcelain.
checkouts: await writerStatusCheckouts(bindings as Array<{ source_id: string; local_path: string | null }>),
@@ -327,7 +327,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
const sourceId = source(params.source_id), root = path(params.path);
// #5198: say at claim time what the claim retires, before and after the fact.
const notice = await readManagedMode(engine) ? {} : { activation_required: CLAIM_BEFORE_ACTIVATION_NOTICE };
- if (params.dry_run) return { dry_run: true, action: operation, source_id: sourceId, path: root, current: await getWorktreeBinding(engine, sourceId, existingLocalHostId()), ...notice };
+ if (params.dry_run) return { dry_run: true, action: operation, source_id: sourceId, path: root, current: await getWorktreeBinding(engine, sourceId, existingHostIdFor(engine)), ...notice };
const expectedState = await requireWriterAdminIntent(engine, operation, params);
return { claimed: true, binding: await claimWorktree(engine, sourceId, root, undefined, expectedState), ...notice };
}
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 0ff6312003..6f889c781c 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -19,7 +19,7 @@ import { materializeTimeline, prepareCanonicalProjections } from './canonical-pr
import { digest, sha256 } from './digest.ts';
import { admitWriteInTransaction, assertReplayIntent, getWriteRequest, getWriteRequestById, intentDigest, receiptFor } from './journal.ts';
import { acquireWorktree, containsPath, getWorktreeBinding, probeWorktreeWriter, readManagedMode, type WorktreeBinding } from './ownership.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { assertPersistenceAccepting, startPersistenceConsumer, waitForWrite, writeResponse } from './service.ts';
import { maintenancePublishWaitMs } from './maintenance-wait.ts';
import { AGENT_WRITE_WAIT_MS, configuredWriteWaitMs } from './write-wait.ts';
@@ -174,8 +174,8 @@ function connectorPublicationRefusal(code: RegistryCode, message: string, row: W
}
/** The connector binding's owner and incarnation checks; returns the paths they prove present. */
-function checkedConnectorBinding(sourceId: string, source: ConnectorSource, binding: WorktreeBinding) {
- if (binding.owner_host_id !== localHostId() || !binding.local_path || !binding.coordination_path) {
+function checkedConnectorBinding(engine: object, sourceId: string, source: ConnectorSource, binding: WorktreeBinding) {
+ if (binding.owner_host_id !== hostIdFor(engine) || !binding.local_path || !binding.coordination_path) {
throw opError('owner_unavailable', 'The connector canonical owner is unavailable on this host.',
`Source ${sourceId} is owned by another host or its worktree binding is incomplete; run its connector sync on the owner host that gbrain sources writer status --source ${sourceId} --json names.`,
{ fix: ownerStatusFix(sourceId, 'Shows which host owns the source and whether its binding records a local and coordination path.') });
@@ -188,9 +188,9 @@ function checkedConnectorBinding(sourceId: string, source: ConnectorSource, bind
return { localPath: binding.local_path, coordinationPath: binding.coordination_path, sourcePath: source.local_path };
}
-function connectorBindingRoot(sourceId: string, source: ConnectorSource, binding: WorktreeBinding | null): string | null {
+function connectorBindingRoot(engine: object, sourceId: string, source: ConnectorSource, binding: WorktreeBinding | null): string | null {
if (!binding) return null;
- const { localPath, coordinationPath, sourcePath } = checkedConnectorBinding(sourceId, source, binding);
+ const { localPath, coordinationPath, sourcePath } = checkedConnectorBinding(engine, sourceId, source, binding);
assertPhysicalRoot(localPath, { worktreeId: binding.worktree_id, coordinationPath });
try {
const root = realpathSync(join(localPath, binding.relative_path));
@@ -298,9 +298,9 @@ export async function beginConnectorSync(engine: BrainEngine, sourceId: string,
const authority = await managedSyncAuthority(engine, sourceId, source.incarnation, source.local_path ?? '');
const binding = await getWorktreeBinding(engine, sourceId);
// The locked acquisition re-stamps a device-only physical-root change (#5604) before the root is asserted.
- if (binding) { checkedConnectorBinding(sourceId, source, binding); await probeWorktreeWriter(binding, engine); }
+ if (binding) { checkedConnectorBinding(engine, sourceId, source, binding); await probeWorktreeWriter(binding, engine); }
else authority.writer.databaseOnlyReason = 'connector_database';
- const canonicalRoot = connectorBindingRoot(sourceId, source, binding);
+ const canonicalRoot = connectorBindingRoot(engine, sourceId, source, binding);
const session = new ManagedConnectorSync(engine, sourceId, identity, source, authority, binding, canonicalRoot, opts.noEmbed === true, opts.noSchemaPack === true,
opts.retryFailed === true, lease, opts.resetCheckpoint === true, opts.githubItem !== undefined, opts.full === true);
await session.load();
@@ -547,7 +547,7 @@ export class ManagedConnectorSync {
const binding = await getWorktreeBinding(engine, this.sourceId);
if ((binding?.worktree_id ?? null) !== (this.binding?.worktree_id ?? null) ||
String(binding?.owner_epoch) !== String(this.binding?.owner_epoch) ||
- connectorBindingRoot(this.sourceId, source, binding) !== this.canonicalRoot) {
+ connectorBindingRoot(engine, this.sourceId, source, binding) !== this.canonicalRoot) {
throw opError('source_changed', 'The connector ownership changed during the sweep.',
`The owner binding or canonical root of ${this.sourceId} changed while this sweep ran; writes it already admitted keep their receipts. Inspect the owner before running gbrain sync --source ${this.sourceId} again.`,
{ fix: ownerStatusFix(this.sourceId, 'Shows the current owner, epoch and canonical root of the source.') });
@@ -1118,7 +1118,7 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe
throw connectorPublicationRefusal('source_changed', 'The connector ownership binding changed after admission.', row,
`The owner binding of ${row.source_id} changed after this write was admitted.`);
}
- if (connectorBindingRoot(row.source_id, source, binding) !== p.canonicalRoot) throw connectorPublicationRefusal('source_changed', 'The connector canonical root changed after admission.', row,
+ if (connectorBindingRoot(engine, row.source_id, source, binding) !== p.canonicalRoot) throw connectorPublicationRefusal('source_changed', 'The connector canonical root changed after admission.', row,
`The canonical root of ${row.source_id} changed after this write was admitted.`);
if (p.filePath !== null && (!p.canonicalRoot || !isWriteTargetContained(p.filePath, p.canonicalRoot) || persistenceFileHash(p.filePath) !== p.fileBeforeHash)) {
throw connectorPublicationRefusal('source_changed', 'The connector canonical file changed after admission.', row,
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index 8b4e453d4e..f81c7ccdac 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -34,7 +34,7 @@ import { configDir } from '../config.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { acquireWorktree, getWorktreeBinding, readPersistenceBrain, type PersistenceBrainRow } from './ownership.ts';
-import { existingLocalHostId } from './identity.ts';
+import { existingHostIdFor } from './identity.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { assertWriterAdminState } from './admin-intent.ts';
import { assertWriterAdminUnlocked, readWriterAdminLock, WRITER_ADMIN_LOCKED_DOCS } from './admin-lock.ts';
@@ -130,7 +130,7 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
}
// Managed connector holds live in the managed checkpoint, which classic mode does not read. Deactivation copies
// them into each source's classic state file; only a source whose holds have nowhere to go blocks it.
- for (const carry of await planHoldCarry(engine, existingLocalHostId())) {
+ for (const carry of await planHoldCarry(engine, existingHostIdFor(engine))) {
if (!holdCarryBlocked(carry)) continue;
const resolve = `gbrain sources status ${carry.source_id} names each item's error; fix its cause, then gbrain sources retry-held ${carry.source_id} and gbrain sync --source ${carry.source_id} (a successful re-attempt clears the hold)`;
blockers.push({ kind: 'connector_holds', id: carry.source_id, source_id: carry.source_id,
@@ -183,7 +183,7 @@ export async function failedEffectHistory(engine: BrainEngine): Promise<FailedEf
* Each preview therefore lists what its own real run would refuse on.
*/
export async function physicalRootBlockers(engine: BrainEngine, mode: 'managed' | 'classic'): Promise<DeactivationBlocker[]> {
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const sources = mode === 'managed'
? await engine.executeRaw<{ id: string }>('SELECT source_id AS id FROM persistence_source_bindings ORDER BY source_id')
: (await preActivationClaims(engine)).map(claim => ({ id: claim.source_id }));
@@ -257,13 +257,13 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
}
const blockers = [...await deactivationBlockers(engine), ...await physicalRootBlockers(engine, 'managed')];
if (opts.dryRun) {
- const carried_holds = (await planHoldCarry(engine, existingLocalHostId())).filter(c => c.items > 0 && !holdCarryBlocked(c));
+ const carried_holds = (await planHoldCarry(engine, existingHostIdFor(engine))).filter(c => c.items > 0 && !holdCarryBlocked(c));
return { ...base, mode: 'managed', deactivated: false, mode_epoch: Number(brain.mode_epoch), blockers, carried_holds, failed_effects: await failedEffectHistory(engine) };
}
if (blockers.length) throw blockedError(blockers);
const principal = await topologyPrincipal(engine);
const requestId = opts.requestId ?? randomUUID();
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const locks: NativeLockHandle[] = [];
let report: DeactivationReport;
try {
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index d903876356..9344b5c60d 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -184,8 +184,8 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
max_transient_retries: snapshot.preparation.transientRetries } : null;
const { persistenceConsumerStatus } = await import('./service.ts');
// #6317 (C1): the heartbeat rows of this host, read once, so each running claim can name its owner's liveness and pool.
- const { existingLocalHostId } = await import('./identity.ts');
- const hostId = existingLocalHostId();
+ const { existingHostIdFor } = await import('./identity.ts');
+ const hostId = existingHostIdFor(engine);
const consumerRows = hostId ? await listHostConsumers(engine, hostId).catch(() => []) : [];
const tracked = (engine as { getPoolDiagnostics?: () => { tracked?: unknown } | null }).getPoolDiagnostics?.()?.tracked ?? null;
const claimStates = blockers.map(row => claimStateOf({ state: row.state, claim_phase: row.claim_phase, execution_token: row.execution_token, claim_lapsed: row.claim_lapsed, publication_started: row.publication_started }));
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index 3dac43e0bb..d5bd2bab51 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -64,7 +64,7 @@ import { parseFenceRepairReceipt, type FenceRepairReceipt } from '../fence-repai
import { parseContentRepairReceipt, type ContentRepairReceipt } from '../content-repair/receipt.ts';
import { prepareCanonicalProjections } from './canonical-projections.ts';
import { digest, sha256 } from './digest.ts';
-import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
+import { currentVerifiedLocalWriter, hostIdFor } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
import { checkOwner, ownerUnavailableError } from './owner-refusal.ts';
import { loadRepairBusySet, repairBusy, repairBusyError } from './repair-busy.ts';
@@ -272,7 +272,7 @@ function assertTrustedRepairCaller(ctx: Pick<OperationContext, 'remote'>): void
export async function managedRepairRoot(engine: BrainEngine, sourceId: string, kind: FileRepairKind = 'frontmatter', opts: { remote?: boolean } = {}): Promise<{ root: string; ownerEpoch: string; incarnation: string }> {
const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
const binding = await getWorktreeBinding(engine, sourceId);
- const hostId = localHostId();
+ const hostId = hostIdFor(engine);
const owner = checkOwner(binding, source?.incarnation ?? '', hostId);
if (owner.reason) throw ownerUnavailableError({ sourceId, reason: owner.reason, binding, incarnation: source?.incarnation ?? '', hostId, remote: opts.remote !== false, work: `the ${WORK[kind]} repair` });
return { root: join(owner.binding.local_path, owner.binding.relative_path), ownerEpoch: String(owner.binding.owner_epoch), incarnation: owner.binding.source_incarnation };
diff --git a/src/core/persistence/git-conversion.ts b/src/core/persistence/git-conversion.ts
index a12c64dbef..4a57acde65 100644
--- a/src/core/persistence/git-conversion.ts
+++ b/src/core/persistence/git-conversion.ts
@@ -58,7 +58,7 @@ import { compareInlineExportFile, ignoredPaths, readBlobs, type DeclaredClass, t
import { commitThroughDoor } from './git-door.ts';
import { gitRootAhead, pushGitRoot } from './effect-git.ts';
import { DURABILITY_NOT_ENABLED_REASON, gitDurabilityPolicy } from './git-durability-policy.ts';
-import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
+import { currentVerifiedLocalWriter, hostIdFor } from './identity.ts';
import { acquireWorktree, getWorktreeBinding, readManagedMode } from './ownership.ts';
import { inspectDurabilityCheckout } from './git-durability-administration.ts';
import { classifyGitCheckout } from '../git-checkout.ts';
@@ -228,7 +228,7 @@ const strictContext = (context: ManagedSyncContext): ManagedSyncContext => ({ ..
/** The read-only plan of `--to git`; its preview is what the CLI prints and the apply binds to. */
export async function planGitConversion(engine: BrainEngine, sourceId: string): Promise<GitConversionPlan> {
const binding = await getWorktreeBinding(engine, sourceId);
- if (binding?.local_path && binding.owner_host_id === localHostId() && binding.state === 'active') await assertConversionCheckout(sourceId, resolve(binding.local_path, binding.relative_path));
+ if (binding?.local_path && binding.owner_host_id === hostIdFor(engine) && binding.state === 'active') await assertConversionCheckout(sourceId, resolve(binding.local_path, binding.relative_path));
const context = await resolveManagedSyncContext(engine, { sourceId, noPull: true, dryRun: true });
const pages: GitGapPage[] = [];
const equal = new Map<string, PageRevision>();
@@ -795,7 +795,7 @@ async function settleParked(engine: BrainEngine, sourceId: string, parked: Parke
const result = await retryParkedEffects(engine, sourceId, item.request, false, { parkedOnly: true });
if ((result?.effects as Array<{ action?: string }> | undefined)?.some(effect => effect.action === 'retry_queued')) retried++;
}
- if (retried) await runPersistenceEffects(engine, loadConfig() ?? { engine: engine.kind }, { hostId: localHostId(), limit: 50 });
+ if (retried) await runPersistenceEffects(engine, loadConfig() ?? { engine: engine.kind }, { hostId: hostIdFor(engine), limit: 50 });
return { retried, reclassified };
}
diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.ts
index 9d7b9a86c7..6ad171bc28 100644
--- a/src/core/persistence/git-durability-administration.ts
+++ b/src/core/persistence/git-durability-administration.ts
@@ -27,7 +27,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
import type { BrainEngine } from '../engine.ts';
-import { existingLocalHostId } from './identity.ts';
+import { existingHostIdFor } from './identity.ts';
import { getWorktreeBinding, type GitDurabilitySetting, type WorktreeBinding } from './ownership.ts';
import { requireWriterAdminIntent, assertWriterAdminState, writerAdminState } from './admin-intent.ts';
import { gitDurabilityPolicy, planGitDurabilityCatchUp, requeueGitDurabilityCatchUp } from './git-durability-policy.ts';
@@ -258,7 +258,7 @@ export async function retrySourceParkedCode(engine: BrainEngine, sourceId: strin
}
async function ownedBinding(engine: BrainEngine, sourceId: string): Promise<WorktreeBinding & { local_path: string }> {
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding) {
throw opError('writer_registration_required', `Source ${sourceId} has no canonical owner on this brain.`,
diff --git a/src/core/persistence/onboarding.ts b/src/core/persistence/onboarding.ts
index 7edce72ec2..87cacdb01f 100644
--- a/src/core/persistence/onboarding.ts
+++ b/src/core/persistence/onboarding.ts
@@ -1,7 +1,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
-import { existingLocalHostId, persistenceHome } from './identity.ts';
+import { persistenceHome, existingHostIdFor } from './identity.ts';
import { containsPath, getWorktreeBinding, readManagedMode, type WorktreeBinding } from './ownership.ts';
import { verifyOwnerRoot } from './owner-verification.ts';
import { readPhysicalRootReservation, readWedgedPhysicalRootReservation } from './physical-root-record.ts';
@@ -55,7 +55,7 @@ export async function writerOnboardingPreflight(engine: BrainEngine, sourceId?:
const managed = await readManagedMode(engine);
const rows = await engine.executeRaw<{ id: string; local_path: string | null; incarnation: string; kind: string | null }>(
"SELECT id,local_path,incarnation,config->>'kind' AS kind FROM sources WHERE NOT archived AND ($1::text IS NULL OR id=$1) ORDER BY id", [sourceId ?? null]);
- const fallback = await engine.getConfig('sync.repo_path'), host = existingLocalHostId();
+ const fallback = await engine.getConfig('sync.repo_path'), host = existingHostIdFor(engine);
const writeThrough = writeThroughConfigured(await engine.getConfig('sync.write_through'));
const sources = [];
for (const row of rows) {
diff --git a/src/core/persistence/pre-activation-release.ts b/src/core/persistence/pre-activation-release.ts
index 629849eb56..7a117e4946 100644
--- a/src/core/persistence/pre-activation-release.ts
+++ b/src/core/persistence/pre-activation-release.ts
@@ -18,7 +18,7 @@ import type { BrainEngine } from '../engine.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { acquireWorktree, getWorktreeBinding, readPersistenceBrain } from './ownership.ts';
-import { currentVerifiedLocalWriter, existingLocalHostId, registerLocalWriter } from './identity.ts';
+import { currentVerifiedLocalWriter, registerLocalWriter, existingHostIdFor } from './identity.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { assertWriterAdminState } from './admin-intent.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
@@ -53,7 +53,7 @@ export async function releasePreActivationClaims(engine: BrainEngine, opts: { ex
if (!currentVerifiedLocalWriter()) await registerLocalWriter(engine, 'cli');
const principal = await topologyPrincipal(engine);
const requestId = opts.requestId ?? randomUUID();
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const locks: NativeLockHandle[] = [];
try {
// Native worktree locks precede the transaction, as in activation and deactivation.
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index 275cdfb5fa..6ae96b2f9b 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -16,7 +16,7 @@ import { wholeBodySnapshot } from './segmented-apply.ts';
import { sharedOriginExit } from './sync-origin.ts';
import { originTwinsPreviewArgv } from './origin-twins.ts';
export { fileClaimCandidatesQuery } from './file-claims.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { isDatabaseOnlyPage, recordsNoFileOrigin, slugDerivedOrigin } from './unbound-pages.ts';
import { isUnboundSourcePage } from './unbound-source.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
@@ -136,7 +136,7 @@ export type DeletedDriftChange = 'file_gone' | 'live_page' | 'no_deletion' | 'de
export async function readDeletedDriftTarget(engine: BrainEngine, sourceId: string, input: { path: string; sourcePath: string; pageId?: number | null }):
Promise<DeletedDriftTarget | { changed: DeletedDriftChange }> {
const binding = await getWorktreeBinding(engine, sourceId);
- if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {
+ if (!binding?.local_path || binding.owner_host_id !== hostIdFor(engine) || binding.state !== 'active') {
throw new OperationError('owner_unavailable', 'Reconciliation requires the existing active owner on this host.', 'Run repair on the current owner; repair never claims or activates a source.');
}
const root = realpathSync(join(binding.local_path, binding.relative_path));
@@ -220,7 +220,7 @@ async function assertSoleFileClaim(engine: BrainEngine, target: FileClaimTarget)
export async function readReconcileState(engine: BrainEngine, sourceId: string, slug: string, assessmentAt = new Date().toISOString(),
opts: { adoptSlugPath?: boolean; fileGone?: boolean } = {}): Promise<ReconcileState> {
const binding = await getWorktreeBinding(engine, sourceId);
- if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {
+ if (!binding?.local_path || binding.owner_host_id !== hostIdFor(engine) || binding.state !== 'active') {
throw new OperationError('owner_unavailable', 'Reconciliation requires the existing active owner on this host.', 'Run repair on the current owner; repair never claims or activates a source.');
}
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
diff --git a/src/core/persistence/skill-activation.ts b/src/core/persistence/skill-activation.ts
index 7c4dc0a84b..3645bcd732 100644
--- a/src/core/persistence/skill-activation.ts
+++ b/src/core/persistence/skill-activation.ts
@@ -1,7 +1,7 @@
import type { BrainEngine } from '../engine.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { activatePersistence, type ActivationReport } from './activation.ts';
-import { existingLocalHostId, localHostId } from './identity.ts';
+import { hostIdFor, existingHostIdFor } from './identity.ts';
import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { declarePersistenceProtocol } from './protocol.ts';
@@ -17,7 +17,7 @@ export async function activateSharedSkillPersistence(engine: BrainEngine,
'Stop and exclude older canonical writers and direct-file skill servers before enabling shared skill publication.',
'Run this activation on every canonical owner only after verifying process shutdown and canonical-root write access.');
if (options.confirmQuiesced !== true) throw quiescence();
- const hostId = options.dryRun || options.expectedState !== undefined ? existingLocalHostId() : localHostId();
+ const hostId = options.dryRun || options.expectedState !== undefined ? existingHostIdFor(engine) : hostIdFor(engine);
const loadBindings = async (tx: BrainEngine): Promise<WorktreeBinding[]> => {
const roots = await tx.executeRaw<{ source_id: string }>(`SELECT b.source_id FROM persistence_source_bindings b
JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation WHERE NOT s.archived ORDER BY b.worktree_id,b.source_id`);
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index a4fc456ce1..3e86f491bc 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -15,7 +15,7 @@ import { discoverGitRoot } from '../sync-git.ts';
import { isInsideGitRepo, hasTrackedContent } from '../git-remote.ts';
import { containsPath, getWorktreeBinding, humanManifestProgress, type WorktreeBinding, type WorktreeManifest, worktreeManifest } from './ownership.ts';
import { manifestDifferences, storedManifestScope, type WorktreeManifestScope } from './worktree-manifest.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { advanceTopology, inspectTopologyPhysicalRoot, lockTopologyPrincipal, lockTopologyRows, settleTopologyRequests, topologyCanonicalStamp, topologyPrincipal, withTopologyLocks } from './topology-locks.ts';
import { priorTopologyChange, recordTopologyChange, topologyReceipt } from './topology-receipts.ts';
import { isWriteRequestId } from './types.ts';
@@ -68,7 +68,7 @@ function localRoot(path:string,create=false):{source:string;worktree:string}{
export async function installTopologyBinding(tx:BrainEngine,sourceId:string,incarnation:string,root:{source:string;worktree:string},bindings:WorktreeBinding[]):Promise<string>{
const others=await tx.executeRaw<{source_id:string;relative_path:string;local_path:string}>(`SELECT b.source_id,b.relative_path,h.local_path
FROM persistence_source_bindings b JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid
- WHERE b.source_id<>$2`,[localHostId(),sourceId]);
+ WHERE b.source_id<>$2`,[hostIdFor(tx),sourceId]);
const sourcePath=nativeFilesystemPath(root.source);
const overlap=others.find(other=>{const path=nativeFilesystemPath(join(other.local_path,other.relative_path));return containsPath(path,sourcePath)||containsPath(sourcePath,path);});
if(overlap) throw opError('overlapping_path','Sources cannot claim overlapping canonical directories.',
@@ -80,13 +80,13 @@ export async function installTopologyBinding(tx:BrainEngine,sourceId:string,inca
`The directory for '${sourceId}' contains the checkout of source '${overlapping.source_id}'. Move that source first with gbrain sources set-path ${overlapping.source_id} and its verified new directory (a topology change the user decides), or choose a directory that does not enclose it.`,
{fix:ownerStatusFix(overlapping.source_id)});
const worktree=compatible?.local_path??root.worktree;
- const physical=await claimPhysicalRoot(tx,worktree,{hostId:localHostId(),
+ const physical=await claimPhysicalRoot(tx,worktree,{hostId:hostIdFor(tx),
...(compatible?{worktreeId:compatible.worktree_id,coordinationPath:compatible.coordination_path!}:{})});
const id=physical.worktreeId;
const [existing]=await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid',[id]);
- if(!existing)await tx.executeRaw('INSERT INTO persistence_worktrees(id,owner_host_id,owner_epoch) VALUES($1::uuid,$2::uuid,1)',[id,localHostId()]);
+ if(!existing)await tx.executeRaw('INSERT INTO persistence_worktrees(id,owner_host_id,owner_epoch) VALUES($1::uuid,$2::uuid,1)',[id,hostIdFor(tx)]);
await tx.executeRaw(`INSERT INTO persistence_host_bindings(worktree_id,host_id,local_path,coordination_path) VALUES($1::uuid,$2::uuid,$3,$4)
- ON CONFLICT(worktree_id,host_id) DO NOTHING`,[id,localHostId(),worktree,physical.coordinationPath]);
+ ON CONFLICT(worktree_id,host_id) DO NOTHING`,[id,hostIdFor(tx),worktree,physical.coordinationPath]);
const rel=relative(nativeFilesystemPath(worktree),nativeFilesystemPath(root.source)).split(sep).join('/');
await tx.executeRaw(`INSERT INTO persistence_source_bindings(source_id,source_incarnation,worktree_id,relative_path,topology_generation)
SELECT $1,$2::uuid,$3::uuid,$4,topology_generation FROM persistence_worktrees WHERE id=$3::uuid
@@ -265,7 +265,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
// and its ownership records move to the real path (reservation under the new sha256(root) name, stamp naming it).
const moved=relocatePhysicalRoot(currentBinding!.local_path!,root!.worktree,relocated);
await tx.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1',[input.sourceId,root!.source]);
- await tx.executeRaw('UPDATE persistence_host_bindings SET local_path=$3 WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[currentBinding!.worktree_id,localHostId(),moved.root]);
+ await tx.executeRaw('UPDATE persistence_host_bindings SET local_path=$3 WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[currentBinding!.worktree_id,hostIdFor(tx),moved.root]);
const rel=relative(nativeFilesystemPath(moved.root),nativeFilesystemPath(root!.source)).split(sep).join('/');
await tx.executeRaw('UPDATE persistence_source_bindings SET relative_path=$2 WHERE source_id=$1',[input.sourceId,rel]);
manifests.set(moved.root,manifests.get(root!.worktree)!);
@@ -282,10 +282,10 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
await tx.executeRaw('DELETE FROM sources WHERE id=$1 AND incarnation=$2::uuid',[input.sourceId,incarnation]);
await tx.executeRaw('DELETE FROM persistence_source_bindings WHERE source_id=$1 AND source_incarnation=$2::uuid',[input.sourceId,incarnation]);
}
- const contentReceipts=input.operation==='rebind'?await rebindContentReceipts(tx,worktrees,localHostId(),relocated?undefined:[input.sourceId]):[];
+ const contentReceipts=input.operation==='rebind'?await rebindContentReceipts(tx,worktrees,hostIdFor(tx),relocated?undefined:[input.sourceId]):[];
await advanceTopology(tx,worktrees);
for(const id of worktrees){
- const [host]=await tx.executeRaw<{local_path:string}>('SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[id,localHostId()]);
+ const [host]=await tx.executeRaw<{local_path:string}>('SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[id,hostIdFor(tx)]);
if(host&&manifests.has(host.local_path)) await tx.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid',[id,JSON.stringify({...manifests.get(host.local_path),canonical_stamp:await topologyCanonicalStamp(tx,id)})]);
else if(!manifestRequired&&host) await tx.executeRaw(`UPDATE persistence_worktrees SET manifest=COALESCE(manifest,'{}'::jsonb)||jsonb_build_object('canonical_stamp',$2::text) WHERE id=$1::uuid`,[id,await topologyCanonicalStamp(tx,id)]);
}
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 0731cfec23..5b0b198572 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -19,7 +19,7 @@ import { resolveSlugRootMode } from '../sync-anchor.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { unboundBindCommand } from './unbound-source.ts';
-import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
+import { currentVerifiedLocalWriter, hostIdFor } from './identity.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { trustedCliRequired } from '../ops/op-fix.ts';
import { ownerUnavailableReason } from './owner-refusal.ts';
@@ -280,12 +280,12 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncO
const source = read && opts.canonicalOverride === 'git' ? { ...read, config: { ...read.config, canonical: 'git' } } : read;
if (source?.config?.canonical === 'git' && managedForbiddenFlag(opts, true)) throw managedSyncFlagRefusal('--working-tree', sourceId, ['--source', sourceId, '--no-pull', '--working-tree']);
if (!source || source.archived || !binding || binding.source_incarnation !== source.incarnation ||
- binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) {
+ binding.owner_host_id !== hostIdFor(engine) || binding.state !== 'active' || !binding.local_path) {
// #6449: a rooted source with no owner at all is the database-only one activation listed; the exit is a deliberate claim.
const unbound = source && !source.archived && !binding && source.local_path && source.config?.kind == null;
// #7239: a missing, archived or re-registered source, or a checkout another host id owns, refuses the same way on every
// retry from this host, so a sync job ends at once; a transfer or clone in progress can finish, so it stays retryable.
- const reason = source && !source.archived ? ownerUnavailableReason(binding, source.incarnation, localHostId()) : null;
+ const reason = source && !source.archived ? ownerUnavailableReason(binding, source.incarnation, hostIdFor(engine)) : null;
const deterministic = !source || source.archived || (reason !== null && reason !== 'transfer_in_progress' && reason !== 'clone_in_progress');
throw opError('owner_unavailable', 'Sync must run on the active registered worktree owner.',
unbound
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 93284368be..ba495d4e9e 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -740,8 +740,8 @@ export function engineStallProbe(engine: BrainEngine, sourceId?: string): StallP
};
let budgets: Promise<{ syncMs: number; maintenanceMs: number; ceilingMs: number }> | undefined;
const describe = async (requestId: string, row: NonNullable<Awaited<ReturnType<typeof read>>>['row']): Promise<Omit<DrainStall, 'stalled_seconds'>> => {
- const { localHostId } = await import('./identity.ts');
- const host = localHostId();
+ const { hostIdFor } = await import('./identity.ts');
+ const host = hostIdFor(engine);
return { request_id: requestId, state: row.state, blocked_reason: row.blocked_reason, head_request_id: row.head_id, head_state: row.head_state,
...await headClaimability(engine, { id: row.head_id, state: row.head_state }, host, { timeoutMs: HEAD_READ_TIMEOUT_MS }), consumer: await describeHostConsumer(engine),
owner_is_this_host: row.owner_host_id === null ? null : row.owner_host_id === host };
@@ -767,18 +767,18 @@ export function engineStallProbe(engine: BrainEngine, sourceId?: string): StallP
// #6317: the owner's heartbeat row by pid (and nonce when both sides have one); a consumer here that could reclaim a lapsed head.
async owner(claim) {
if (claim.owner_pid === null) return null;
- const { localHostId } = await import('./identity.ts');
+ const { hostIdFor } = await import('./identity.ts');
const { listHostConsumers } = await import('./consumer-heartbeat.ts');
- const rows = await listHostConsumers(engine, localHostId()).catch(() => []);
+ const rows = await listHostConsumers(engine, hostIdFor(engine)).catch(() => []);
const row = rows.find(r => r.pid === claim.owner_pid && (claim.owner_nonce === null || r.nonce === claim.owner_nonce));
return row ? { kind: row.kind, pid: row.pid, nonce: row.nonce, mode: row.mode, live: row.liveness === 'live', restart_required: row.restart_required, root_barrier_age_ms: row.root_barrier_age_ms } : null;
},
async reclaimableHere() {
const { persistenceConsumerStatus } = await import('./service.ts');
if (persistenceConsumerStatus(engine).state === 'open') return true;
- const { localHostId } = await import('./identity.ts');
+ const { hostIdFor } = await import('./identity.ts');
const { listHostConsumers } = await import('./consumer-heartbeat.ts');
- return (await listHostConsumers(engine, localHostId()).catch(() => [])).some(row => (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live');
+ return (await listHostConsumers(engine, hostIdFor(engine)).catch(() => [])).some(row => (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live');
},
...(sourceId ? { async head() {
const [row] = await engine.executeRaw<{ head_state: string; head_claim_phase: unknown; head_token: string | null; head_lapsed: boolean | null; head_kind: string | null; head_request_id: string | null;
@@ -791,10 +791,10 @@ export function engineStallProbe(engine: BrainEngine, sourceId?: string): StallP
WHERE e.worktree_id = b.worktree_id AND e.state IN ('queued','running','recovering') ORDER BY (e.state <> 'running'), e.sequence LIMIT 1) h ON true
WHERE b.source_id = $1`, [sourceId], { timeoutMs: HEAD_READ_TIMEOUT_MS, signal: AbortSignal.timeout(HEAD_READ_TIMEOUT_MS + 500) });
if (!row) return null;
- const { localHostId } = await import('./identity.ts');
+ const { hostIdFor } = await import('./identity.ts');
const bound = { timeoutMs: HEAD_READ_TIMEOUT_MS, signal: AbortSignal.timeout(HEAD_READ_TIMEOUT_MS + 500) };
return { head_state: row.head_state, request_id: row.head_request_id, write_request_id: row.head_write_request_id, claim: drainClaimOf(row, await (budgets ??= readPreparationBudgets(engine))),
- ...await headClaimability(engine, { id: row.head_request_id, state: row.head_state }, localHostId(), bound), consumer: await describeHostConsumer(engine, { signal: bound.signal }) };
+ ...await headClaimability(engine, { id: row.head_request_id, state: row.head_state }, hostIdFor(engine), bound), consumer: await describeHostConsumer(engine, { signal: bound.signal }) };
} } : {}),
};
}
diff --git a/src/core/persistence/sync-freshness.ts b/src/core/persistence/sync-freshness.ts
index 82e2fd2a3f..2303f77482 100644
--- a/src/core/persistence/sync-freshness.ts
+++ b/src/core/persistence/sync-freshness.ts
@@ -101,11 +101,11 @@ interface AggregateRow { samples: number | string; s50: unknown; s95: unknown; e
/** The freshness of every bound managed source (or of `sourceIds`); a source without a binding is omitted. */
export async function readSyncFreshness(engine: BrainEngine, opts: { sourceIds?: string[]; commitTimes?: CommitTimeReader; behind?: BehindReader } = {}): Promise<SourceFreshness[]> {
- const { existingLocalHostId } = await import('./identity.ts');
+ const { existingHostIdFor } = await import('./identity.ts');
const bindings = await engine.executeRaw<BindingRow>(`SELECT b.source_id, b.worktree_id::text AS worktree_id, b.source_incarnation::text AS source_incarnation, COALESCE(h.local_path, s.local_path) AS root, s.last_commit
FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation
LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id::text=$2
- WHERE ($1::text[] IS NULL OR b.source_id=ANY($1::text[])) ORDER BY b.source_id`, [opts.sourceIds ?? null, existingLocalHostId()]);
+ WHERE ($1::text[] IS NULL OR b.source_id=ANY($1::text[])) ORDER BY b.source_id`, [opts.sourceIds ?? null, existingHostIdFor(engine)]);
const commitTimes = opts.commitTimes ?? readGitCommitTimes;
const behindOf = opts.behind ?? readGitBehind;
const out: SourceFreshness[] = [];
diff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.ts
index a19c7446d6..067625fa63 100644
--- a/src/core/persistence/sync-movement.ts
+++ b/src/core/persistence/sync-movement.ts
@@ -149,10 +149,10 @@ export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?
}
const backlog = new Map(backlogRows.map(b => [b.source_id, b]));
const policy = await readPreparationPolicy(engine);
- const { localHostId } = await import('./identity.ts');
+ const { hostIdFor } = await import('./identity.ts');
const { persistenceConsumerStatus } = await import('./service.ts');
const { liveSyncStatus } = await import('../db-lock.ts');
- const host = localHostId();
+ const host = hostIdFor(engine);
const localConsumer = persistenceConsumerStatus(engine).state === 'open';
let heartbeat: Promise<boolean> | undefined;
const liveHeartbeat = () => heartbeat ??= listHostConsumers(engine, host).then(rows => rows.some(row => (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live'), () => false);
diff --git a/src/core/persistence/topology-clone.ts b/src/core/persistence/topology-clone.ts
index a4c898a240..c23894f707 100644
--- a/src/core/persistence/topology-clone.ts
+++ b/src/core/persistence/topology-clone.ts
@@ -12,7 +12,7 @@ import { parseSourceConfig } from '../sources-load.ts';
import type { SourceLifecycleInput } from './source-lifecycle.ts';
import type { TopologyCloneRecovery } from './topology-clone-model.ts';
import { compactStoredManifest, getWorktreeBinding, humanManifestProgress, storedManifestScope, worktreeManifest } from './ownership.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { resolveCoordinationLock } from './coordination-lock.ts';
import { acquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { canonicalFilesystemPath, recordManagedRoots } from './root-registry.ts';
@@ -51,7 +51,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
`Source ${input.sourceId} is ${source?`now incarnation ${source.incarnation}`:'no longer registered'}, not the expected ${input.expectedIncarnation}; nothing was cloned. Re-read the source and confirm the ${input.operation} still applies before passing the current incarnation.`,
{fix:writerStatusFix(input.sourceId)});
const binding=input.operation==='reclone'?await getWorktreeBinding(engine,input.sourceId):null;
- if(input.operation==='reclone'&&(!binding?.local_path||binding.owner_host_id!==localHostId()||binding.relative_path!==''))
+ if(input.operation==='reclone'&&(!binding?.local_path||binding.owner_host_id!==hostIdFor(engine)||binding.relative_path!==''))
throw opError('owner_unavailable','Reclone must run on the owner of the complete canonical worktree.',
`This host does not own source ${input.sourceId}'s whole canonical worktree (it is unclaimed, owned elsewhere, or a subdirectory of a shared root), so nothing was recloned. Check the owner and run the reclone on that host.`,
{fix:writerStatusFix(input.sourceId)});
@@ -86,7 +86,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
{fix:writerStatusFix(input.sourceId)});
const reservedIdentity=readPhysicalRootReservation(target);
const worktreeId=currentBinding?.worktree_id??reservedIdentity?.worktreeId??randomUUID();
- const coordination=resolveCoordinationLock(target,worktreeId,{reservation:reservedIdentity?.coordinationPath,binding:currentBinding?.coordination_path}).path;
+ const coordination=resolveCoordinationLock(target,worktreeId,{reservation:reservedIdentity?.coordinationPath,binding:currentBinding?.coordination_path},hostIdFor(engine)).path;
let newLock:NativeLockHandle|null=null;
if(!bindings.some(binding=>binding.worktree_id===worktreeId)){newLock=await acquireNativeLock(coordination!,{timeoutMs:5000});if(!newLock)throw opError('writer_lock_unavailable','The new clone coordination lock is busy.',
`Another gbrain process holds the coordination lock for ${target}, so source ${input.sourceId} was not cloned. Run the command again once that process has finished.`,
@@ -106,8 +106,8 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
if(preparedOwner){
const members=await tx.executeRaw('SELECT source_id FROM persistence_source_bindings WHERE worktree_id=$1::uuid LIMIT 1',[worktreeId]);
const [host]=await tx.executeRaw<{local_path:string;coordination_path:string}>(
- 'SELECT local_path,coordination_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[worktreeId,localHostId()]);
- if(preparedOwner.owner_host_id!==localHostId()||preparedOwner.state!=='active'||members.length
+ 'SELECT local_path,coordination_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[worktreeId,hostIdFor(engine)]);
+ if(preparedOwner.owner_host_id!==hostIdFor(engine)||preparedOwner.state!=='active'||members.length
||host?.local_path!==target||host.coordination_path!==coordination)
throw opError('recovery_required','The reserved checkout is still bound, recovering, or has a different physical identity.',
`${target} is reserved by worktree ${worktreeId}, which is still bound to a source, recovering, or owned elsewhere, so source ${input.sourceId} was not cloned. Show the user the writer status; an interrupted clone there must finish recovery first.`,
@@ -130,7 +130,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
`Source ${input.sourceId} has no manifest matching its current canonical content, so a fresh clone could not be verified and nothing was recloned. Show the user the writer status; restoring the checkout from a verified copy is their decision (docs/architecture/topologies.md).`,
{fix:writerStatusFix(input.sourceId)});
const recovery:TopologyCloneRecovery={version:1,kind:'clone',phase:'reserved',operation:input.operation as 'add'|'reclone',sourceId:input.sourceId,
- incarnation,worktreeId,ownerHostId:localHostId(),ownerEpoch:String(currentBinding?.owner_epoch??preparedOwner?.owner_epoch??1),target,stage,aside,
+ incarnation,worktreeId,ownerHostId:hostIdFor(engine),ownerEpoch:String(currentBinding?.owner_epoch??preparedOwner?.owner_epoch??1),target,stage,aside,
beforeHash:before?.digest??null,afterHash:null,manifest,...(manifest?{hashScope:storedManifestScope(manifest)}:{}),canonicalStamp,checkpoint:source?.last_commit??null,sourceRemoteUrl:source?.config.remote_url as string??null,input,cloneBudget:0};
recovery.cloneBudget=reserved-oldBytes-Buffer.byteLength(JSON.stringify(recovery))-65_536;
if(recovery.cloneBudget<65_536)throw opError('request_too_large','The old checkout leaves insufficient configured recovery space for a staged clone.',
@@ -138,8 +138,8 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
{fix:recoveryCapacityFix()});
if(!currentBinding){
if(preparedOwner)await tx.executeRaw("UPDATE persistence_worktrees SET state='recovering' WHERE id=$1::uuid",[worktreeId]);
- else await tx.executeRaw("INSERT INTO persistence_worktrees(id,owner_host_id,owner_epoch,state) VALUES($1::uuid,$2::uuid,1,'recovering')",[worktreeId,localHostId()]);
- await tx.executeRaw('INSERT INTO persistence_host_bindings(worktree_id,host_id,local_path,coordination_path) VALUES($1::uuid,$2::uuid,$3,$4) ON CONFLICT(worktree_id,host_id) DO NOTHING',[worktreeId,localHostId(),target,coordination]);
+ else await tx.executeRaw("INSERT INTO persistence_worktrees(id,owner_host_id,owner_epoch,state) VALUES($1::uuid,$2::uuid,1,'recovering')",[worktreeId,hostIdFor(engine)]);
+ await tx.executeRaw('INSERT INTO persistence_host_bindings(worktree_id,host_id,local_path,coordination_path) VALUES($1::uuid,$2::uuid,$3,$4) ON CONFLICT(worktree_id,host_id) DO NOTHING',[worktreeId,hostIdFor(engine),target,coordination]);
await tx.executeRaw('INSERT INTO persistence_source_bindings(source_id,source_incarnation,worktree_id) VALUES($1,$2::uuid,$3::uuid)',[input.sourceId,incarnation,worktreeId]);
}else await tx.executeRaw("UPDATE persistence_worktrees SET state='recovering',manifest=$2::text::jsonb WHERE id=$1::uuid",[worktreeId,JSON.stringify(manifest)]);
const [brain]=await tx.executeRaw<{brain_id:string}>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
@@ -155,7 +155,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
mkdirSync(dirname(target),{recursive:true});flushTopologyDirectory(dirname(target));
await topologyTransaction(engine,async tx=>{
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
- await reservePhysicalRoot(tx,target,{hostId:localHostId(),worktreeId,coordinationPath:coordination!});
+ await reservePhysicalRoot(tx,target,{hostId:hostIdFor(tx),worktreeId,coordinationPath:coordination!});
});
if(existsSync(recovery.stage))throw opError('recovery_required','The recorded staging path is already occupied.',
`Staging directory ${recovery.stage} already exists, so source ${input.sourceId}'s clone stopped without touching it and is rolled back. Show the user that path; lifecycle request ${requestId}'s receipt records the failure.`,
@@ -180,7 +180,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
{fix:recoveryCapacityFix()});
await topologyTransaction(engine,async tx=>{
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
- await preparePhysicalRootReplacement(tx,recovery.stage,target,{hostId:localHostId(),worktreeId,coordinationPath:coordination!});
+ await preparePhysicalRootReplacement(tx,recovery.stage,target,{hostId:hostIdFor(tx),worktreeId,coordinationPath:coordination!});
await tx.executeRaw("UPDATE persistence_topology_changes SET recovery=$2::text::jsonb,updated_at=now() WHERE id=$1::uuid AND state='recovering'",[accepted!.id,JSON.stringify(recovery)]);
});
await hooks.boundary?.('prepared');
diff --git a/src/core/persistence/topology-locks.ts b/src/core/persistence/topology-locks.ts
index db1083cd6c..82ffdd8796 100644
--- a/src/core/persistence/topology-locks.ts
+++ b/src/core/persistence/topology-locks.ts
@@ -6,7 +6,7 @@ import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
-import { localHostId, persistenceHome, currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter } from './identity.ts';
+import { persistenceHome, currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter, hostIdFor } from './identity.ts';
import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { containsPath, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { completeWrite, lockCounters } from './journal.ts';
@@ -58,7 +58,7 @@ export async function withTopologyLocks<T>(engine: BrainEngine, sourceId: string
const bindings:TopologyBinding[] = binding ? [binding] : [];
if (additionalRoot) {
const local = await engine.executeRaw<TopologyBinding>(`SELECT w.id AS worktree_id,w.owner_host_id,w.owner_epoch,w.state,w.topology_generation,
- h.local_path,h.coordination_path FROM persistence_host_bindings h JOIN persistence_worktrees w ON w.id=h.worktree_id WHERE h.host_id=$1::uuid`,[localHostId()]);
+ h.local_path,h.coordination_path FROM persistence_host_bindings h JOIN persistence_worktrees w ON w.id=h.worktree_id WHERE h.host_id=$1::uuid`,[hostIdFor(engine)]);
for (const row of local) if (row.local_path&&(containsPath(row.local_path,additionalRoot) || containsPath(additionalRoot,row.local_path))) {
const [member]=await engine.executeRaw<{source_id:string}>('SELECT source_id FROM persistence_source_bindings WHERE worktree_id=$1::uuid ORDER BY source_id LIMIT 1',[row.worktree_id]);
const other = member?await getWorktreeBinding(engine,member.source_id):{...row,source_id:'',source_incarnation:'00000000-0000-0000-0000-000000000000',relative_path:'',unbound:true};
@@ -66,8 +66,8 @@ export async function withTopologyLocks<T>(engine: BrainEngine, sourceId: string
}
}
for (const item of bindings.sort((a,b) => a.worktree_id.localeCompare(b.worktree_id))) {
- if (item.owner_host_id !== localHostId() || !item.coordination_path) throw opError('owner_unavailable', 'Run source lifecycle on the current registered owner.',
- `The worktree holding source ${item.source_id || sourceId} is owned by host ${item.owner_host_id}, not this host (${localHostId()}), or has no coordination path here, so nothing changed. Run the lifecycle command on the owning host; moving ownership is a separate, deliberate writer transfer.`,
+ if (item.owner_host_id !== hostIdFor(engine) || !item.coordination_path) throw opError('owner_unavailable', 'Run source lifecycle on the current registered owner.',
+ `The worktree holding source ${item.source_id || sourceId} is owned by host ${item.owner_host_id}, not this host (${hostIdFor(engine)}), or has no coordination path here, so nothing changed. Run the lifecycle command on the owning host; moving ownership is a separate, deliberate writer transfer.`,
{fix:ownerStatusFix(sourceId)});
await take(item.coordination_path);
assertBindingPhysicalRoot(item,sourceId,additionalRoot,opts);
@@ -89,7 +89,7 @@ function assertBindingPhysicalRoot(item: TopologyBinding, sourceId: string, addi
*/
export async function inspectTopologyPhysicalRoot(engine: BrainEngine, sourceId: string, additionalRoot?: string, opts: { relocation?: boolean } = {}): Promise<void> {
const binding = await getWorktreeBinding(engine, sourceId);
- if (!binding || binding.owner_host_id !== localHostId() || !binding.coordination_path) return;
+ if (!binding || binding.owner_host_id !== hostIdFor(engine) || !binding.coordination_path) return;
assertBindingPhysicalRoot(binding, sourceId, additionalRoot, opts);
}
@@ -103,7 +103,7 @@ export async function lockTopologyRows(tx: BrainEngine, sourceId: string, bindin
const ids = bindings.map(b => b.worktree_id).sort();
const owners = await tx.executeRaw<{ id: string; owner_host_id: string; state: string; owner_epoch:string;topology_generation:string }>(
'SELECT id,owner_host_id,state,owner_epoch,topology_generation FROM persistence_worktrees WHERE id=ANY($1::uuid[]) ORDER BY id FOR UPDATE', [ids]);
- if (owners.length !== ids.length || owners.some(row => row.owner_host_id !== localHostId() || row.state !== 'active')) {
+ if (owners.length !== ids.length || owners.some(row => row.owner_host_id !== hostIdFor(tx) || row.state !== 'active')) {
throw opError('recovery_required', 'The affected worktree is draining, recovering, or changed ownership.',
`A worktree holding source ${sourceId} is draining, recovering, or now owned by another host, so the lifecycle change rolled back and nothing changed. Check its state with the command in fix; once it is active on this host, run the same lifecycle command again with the same request_id.`,
{fix:ownerStatusFix(sourceId)});
@@ -120,7 +120,7 @@ export async function lockTopologyRows(tx: BrainEngine, sourceId: string, bindin
if(before.unbound){
const [member]=await tx.executeRaw('SELECT source_id FROM persistence_source_bindings WHERE worktree_id=$1::uuid LIMIT 1',[before.worktree_id]);
const [host]=await tx.executeRaw<{local_path:string;coordination_path:string}>(
- 'SELECT local_path,coordination_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[before.worktree_id,localHostId()]);
+ 'SELECT local_path,coordination_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[before.worktree_id,hostIdFor(tx)]);
const owner=owners.find(owner=>owner.id===before.worktree_id)!;
if(member||host?.local_path!==before.local_path||host.coordination_path!==before.coordination_path
||String(owner.owner_epoch)!==String(before.owner_epoch)||String(owner.topology_generation)!==String(before.topology_generation))
diff --git a/src/core/persistence/topology-recovery.ts b/src/core/persistence/topology-recovery.ts
index 60b576a248..e649f6c0de 100644
--- a/src/core/persistence/topology-recovery.ts
+++ b/src/core/persistence/topology-recovery.ts
@@ -8,7 +8,7 @@ import type { Action } from '../agent-output.ts';
import { parseSourceConfig } from '../sources-load.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots, withFilesystemPublication } from './filesystem-guard.ts';
-import { localHostId } from './identity.ts';
+import { hostIdFor } from './identity.ts';
import { compactStoredManifest, worktreeManifest } from './ownership.ts';
import { advanceTopology, lockTopologyPrincipal, settleTopologyRequests, topologyCanonicalStamp, withTopologyLocks } from './topology-locks.ts';
import { withCoordinatedWrite } from './context.ts';
@@ -41,14 +41,14 @@ function matchesCloneStage(target:string,stage:string):boolean{
const name=basename(stage),prefix=`.gbrain-clone-${basename(target)}-`;
return name.startsWith(prefix)&&/^[a-f0-9-]{36}$/.test(name.slice(prefix.length));
}
-function validateRecord(record:TopologyCloneRecovery):void{
- if(record.version!==1||record.kind!=='clone'||record.ownerHostId!==localHostId()
+function validateRecord(engine:object,record:TopologyCloneRecovery):void{
+ if(record.version!==1||record.kind!=='clone'||record.ownerHostId!==hostIdFor(engine)
||dirname(record.stage)!==dirname(record.target)||dirname(record.aside)!==dirname(record.target)
||!matchesCloneStage(record.target,record.stage)
||!record.aside.startsWith(`${record.target}.gbrain-old-`)||!/[a-f0-9-]{36}$/.test(record.aside)
||canonicalFilesystemPath(record.target)!==record.target||canonicalFilesystemPath(record.stage)!==record.stage||canonicalFilesystemPath(record.aside)!==record.aside)
throw retainedClone('The recorded clone paths no longer belong to this owner.',record,
- `The recovery record names paths or an owner host that this host (${localHostId()}) cannot vouch for.`);
+ `The recovery record names paths or an owner host that this host (${hostIdFor(engine)}) cannot vouch for.`);
}
function treeHash(path:string,scope:'git'|'tree'):string|null{
if(!existsSync(path))return null;
@@ -81,7 +81,7 @@ function removeOwnedStage(record:TopologyCloneRecovery):void{
async function guard(tx:BrainEngine,row:TopologyChange,record:TopologyCloneRecovery):Promise<string[]>{
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
const [owner]=await tx.executeRaw<{owner_host_id:string;owner_epoch:string;state:string}>('SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE',[record.worktreeId]);
- const [host]=await tx.executeRaw<{local_path:string}>('SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[record.worktreeId,localHostId()]);
+ const [host]=await tx.executeRaw<{local_path:string}>('SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[record.worktreeId,hostIdFor(tx)]);
if(!owner||owner.owner_host_id!==record.ownerHostId||String(owner.owner_epoch)!==record.ownerEpoch||owner.state!=='recovering'||host?.local_path!==record.target)
throw retainedClone('Ownership changed while the clone needed recovery.',record,
`Worktree ${record.worktreeId} no longer has owner epoch ${record.ownerEpoch} on this host in the recovering state.`);
@@ -136,7 +136,7 @@ async function abortClone(engine:BrainEngine,row:TopologyChange,record:TopologyC
/** Caller owns the recorded native lock; commit uncertainty always reads this row first. */
export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:CloneLifecycleHooks={},failure?:unknown):Promise<TopologyChange>{
let row=await readChange(engine,id);if(!row.recovery)return row;
- const record=row.recovery as unknown as TopologyCloneRecovery;validateRecord(record);
+ const record=row.recovery as unknown as TopologyCloneRecovery;validateRecord(engine,record);
return withFilesystemPublication([record.target,record.stage,record.aside],async()=>{
if(row.state!=='committed'&&(record.phase==='reserved'||record.phase==='aborting'))
return abortClone(engine,row,record,(failure as {code?:string}|undefined)?.code??record.failureCode??'clone_interrupted');
@@ -219,7 +219,7 @@ const recoveryCursors=new WeakMap<BrainEngine,string>();
* refreshing process has exited; a live refresh holds its lock and is skipped.
*/
export async function recoverSourceTopologies(engine:BrainEngine,opts:{hostId?:string;limit?:number;onAttempt?:(id:string,recovered:boolean)=>void}={}):Promise<number>{
- const host=opts.hostId??localHostId(),limit=Math.max(1,Math.min(16,opts.limit??2));
+ const host=opts.hostId??hostIdFor(engine),limit=Math.max(1,Math.min(16,opts.limit??2));
await resumeWorktreeRefreshes(engine,{hostId:host});
const scan=async(after:string|null)=>engine.executeRaw<TopologyChange>(`SELECT c.* FROM persistence_topology_changes c
JOIN persistence_worktrees w ON w.id=(c.recovery->>'worktreeId')::uuid
diff --git a/src/core/persistence/transfer-administration.ts b/src/core/persistence/transfer-administration.ts
index 5f9ad8b29b..24e942a833 100644
--- a/src/core/persistence/transfer-administration.ts
+++ b/src/core/persistence/transfer-administration.ts
@@ -8,7 +8,7 @@ import type { BrainEngine } from '../engine.ts';
import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { acceptWriterTransfer, cancelWriterTransfer, getWorktreeBinding, humanManifestProgress, prepareWriterTransfer, storedManifestScope, worktreeManifest, type StoredWorktreeManifest } from './ownership.ts';
-import { existingLocalHostId } from './identity.ts';
+import { existingHostIdFor } from './identity.ts';
import { requireWriterAdminIntent } from './admin-intent.ts';
import { bool, invalid, keys, path, source } from './administration.ts';
@@ -37,7 +37,7 @@ export async function runWriterTransferAdministration(engine: BrainEngine, opera
keys(params, ['source_id', 'expected_epoch', 'dry_run', 'admin_intent', 'expected_state']);
const sourceId = source(params.source_id), epoch = expectedEpoch(params, sourceId);
if (params.dry_run) {
- const preview = await cancelWriterTransfer(engine, sourceId, epoch, existingLocalHostId()!, undefined, { dryRun: true });
+ const preview = await cancelWriterTransfer(engine, sourceId, epoch, existingHostIdFor(engine)!, undefined, { dryRun: true });
return { dry_run: true, action: operation, source_id: sourceId, ...preview,
...(preview.cancellable ? { apply_command: `gbrain sources writer transfer cancel ${sourceId} --expected-epoch ${epoch} --admin-intent writer_transfer_cancel --expected-state <admin_state>` } : {}) };
}
@@ -51,13 +51,13 @@ export async function runWriterTransferAdministration(engine: BrainEngine, opera
bool(params, 'self_transfer');
const transfer = transferOptions(params);
if (params.dry_run) {
- const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
- if (!binding || binding.owner_host_id !== existingLocalHostId() || !binding.local_path) {
+ const binding = await getWorktreeBinding(engine, sourceId, existingHostIdFor(engine));
+ if (!binding || binding.owner_host_id !== existingHostIdFor(engine) || !binding.local_path) {
throw opError('permission_denied', 'Only the current owner can prepare a transfer.',
`This host is not source ${sourceId}'s current owner. Run the transfer prepare on the owner host that writer status names; a transfer is a deliberate topology change the operator reviews.`,
{ fix: readFix(`Shows which host owns source ${sourceId}, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });
}
- const { manifest } = await prepareWriterTransfer(engine, sourceId, existingLocalHostId()!, undefined, { ...transfer, dryRun: true });
+ const { manifest } = await prepareWriterTransfer(engine, sourceId, existingHostIdFor(engine)!, undefined, { ...transfer, dryRun: true });
return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: manifest.file_count }, ...(transfer.relocated ? { relocated: true } : {}) };
}
const expectedState = await requireWriterAdminIntent(engine, operation, params);
@@ -75,9 +75,9 @@ export async function runWriterTransferAdministration(engine: BrainEngine, opera
const epoch = expectedEpoch(params, sourceId);
if (typeof params.manifest !== 'string' || !/^[a-f0-9]{64}$/.test(params.manifest)) throw invalid('manifest must be the prepared SHA-256 manifest digest.',
`Pass --manifest with the 64-character manifest digest that gbrain sources writer transfer prepare ${sourceId} printed.`, transferStatusFix(sourceId));
- if (params.dry_run && params.self_transfer === true) await acceptWriterTransfer(engine, sourceId, root, epoch, params.manifest, existingLocalHostId()!, undefined, { ...transfer, dryRun: true });
+ if (params.dry_run && params.self_transfer === true) await acceptWriterTransfer(engine, sourceId, root, epoch, params.manifest, existingHostIdFor(engine)!, undefined, { ...transfer, dryRun: true });
if (params.dry_run) {
- const current = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
+ const current = await getWorktreeBinding(engine, sourceId, existingHostIdFor(engine));
const [prepared] = current ? await engine.executeRaw<{ manifest: StoredWorktreeManifest | null }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [current.worktree_id]) : [];
const candidate = worktreeManifest(root, { progress: humanManifestProgress(), scope: storedManifestScope(prepared?.manifest) });
return { dry_run: true, action: operation, source_id: sourceId, current, manifest_matches: candidate.digest === params.manifest, expected_epoch: epoch,
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
index 5671b55bbe..e5c32aa737 100644
--- a/src/core/persistence/worktree-refresh.ts
+++ b/src/core/persistence/worktree-refresh.ts
@@ -34,7 +34,7 @@ import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { recordUpstreamObservation } from '../sync-upstream.ts';
import { checkpointRetryCommand } from './checkpoint-validation.ts';
-import { existingLocalHostId, localHostId, persistenceHome } from './identity.ts';
+import { persistenceHome, hostIdFor, existingHostIdFor } from './identity.ts';
import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';
import { isPhysicalRootMetadata } from './physical-root-record.ts';
@@ -82,7 +82,7 @@ export interface WorktreeRefreshResult {
export interface RefreshHolder { host_id: string | null; hostname: string; pid: number; started_at: string }
/** `live`: a process holds the refresh lock; `orphaned`: none does; `unknown`: the lock is on another host, or unreadable. */
export type RefreshLiveness = 'live' | 'orphaned' | 'unknown';
-const refreshHolder = (): RefreshHolder => ({ host_id: existingLocalHostId(), hostname: hostname(), pid: process.pid,
+const refreshHolder = (engine: object): RefreshHolder => ({ host_id: existingHostIdFor(engine), hostname: hostname(), pid: process.pid,
started_at: new Date(Date.now() - process.uptime() * 1000).toISOString() });
const holderOf = (row: Pick<WorktreeRefreshRow, 'outcome'>): RefreshHolder | null => (row.outcome?.holder as RefreshHolder | undefined) ?? null;
const describeHolder = (holder: RefreshHolder | null) => holder ? `pid ${holder.pid} on ${holder.hostname} (host ${holder.host_id ?? 'unknown'}), started ${holder.started_at}` : 'a process that recorded no holder';
@@ -104,8 +104,8 @@ function refusal(name: CatalogueName, cause: string, fix: string, refreshId?: st
* GBRA-133: the owner check reads this process's host identity without minting one (a cron job with another HOME would
* otherwise become a new host silently), and its refusal names the identity file it read and the HOME it resolved from.
*/
-function assertRefreshOwner<B extends { owner_host_id: string | null; local_path: string | null }>(binding: B, sourceId: string, action: string): asserts binding is B & { local_path: string } {
- const hostId = existingLocalHostId();
+function assertRefreshOwner<B extends { owner_host_id: string | null; local_path: string | null }>(engine: object, binding: B, sourceId: string, action: string): asserts binding is B & { local_path: string } {
+ const hostId = existingHostIdFor(engine);
if (binding.owner_host_id === hostId && binding.local_path) return;
const path = join(persistenceHome(), 'host.json');
const self = hostId ? `host identity ${hostId} from ${path}` : `no host identity at ${path} (none was created)`;
@@ -239,10 +239,10 @@ export const REFRESH_PUBLISH_DIVERGED_KEY = 'sources.refresh_publish_diverged';
async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTimeoutMs: number, publishDiverged = false): Promise<Plan> {
if (!await managedPersistenceEnabled(engine)) throw refusal('refresh_not_managed',
'This brain is not managed, so gbrain sync pulls the checkout itself; there is no worktree fence to coordinate.', `gbrain sync --source ${sourceId}`);
- const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
+ const binding = await getWorktreeBinding(engine, sourceId, existingHostIdFor(engine));
if (!binding) throw refusal('refresh_not_managed',
`Source ${sourceId} has no claimed canonical worktree, so gbrain sync pulls it without a refresh.`, `gbrain sync --source ${sourceId}`);
- assertRefreshOwner(binding, sourceId, 'move its checkout');
+ assertRefreshOwner(engine, binding, sourceId, 'move its checkout');
const root = binding.local_path;
const active = await readActiveRefresh(engine, binding.worktree_id);
if (active?.state === 'recovery_required') {
@@ -616,7 +616,7 @@ async function unexpectedRefreshFailure(engine: BrainEngine, sourceId: string, o
const thrown = error instanceof Error ? error : new Error(String(error));
const code = typeof (error as { code?: unknown } | null)?.code === 'string' ? (error as { code: string }).code : null;
const lookup = await boundedLookup(engine, async reads => {
- const binding = await getWorktreeBinding(reads, sourceId, existingLocalHostId());
+ const binding = await getWorktreeBinding(reads, sourceId, existingHostIdFor(reads));
return { active: binding ? await readActiveRefresh(reads, binding.worktree_id) : null };
});
const command = `gbrain sources refresh ${sourceId}${opts.dryRun ? ' --dry-run' : ''}${opts.abandon ? ' --abandon' : opts.resume ? ' --resume' : ''}`
@@ -717,7 +717,7 @@ async function fenceDraining(engine: BrainEngine, sourceId: string, plan: Plan,
(worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref,preserved_uncommitted,outcome)
VALUES($1::uuid,$2::text[],$3::uuid,$4,$5,'draining',$6,$7,$8,$9::text[],$10::text::jsonb) RETURNING *`,
[plan.binding.worktree_id, plan.members, principal, String(current.owner_epoch), String(current.topology_generation),
- plan.oldHead, plan.targetHead, plan.upstreamRef, plan.preserved, JSON.stringify({ holder: refreshHolder() })]);
+ plan.oldHead, plan.targetHead, plan.upstreamRef, plan.preserved, JSON.stringify({ holder: refreshHolder(engine) })]);
return row;
})).catch(async error => {
if ((error as { code?: string }).code === '23505' && !classifyOriginUniqueViolation(error)) throw inProgress('Another refresh of this worktree started first.', sourceId);
@@ -827,7 +827,7 @@ async function fenceAndMerge(engine: BrainEngine, git: Git, sourceId: string, pl
return fenced;
}
-async function hostRoot(engine: BrainEngine, worktreeId: string, hostId = localHostId()): Promise<string | null> {
+async function hostRoot(engine: BrainEngine, worktreeId: string, hostId = hostIdFor(engine)): Promise<string | null> {
const [row] = await engine.executeRaw<{ local_path: string | null }>(
'SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid', [worktreeId, hostId]);
return row?.local_path ?? null;
@@ -871,7 +871,7 @@ const laggingSyncing = new Map<string, { commits: string; at: number }>();
const LAGGING_RECHECK_MS = 60_000;
export async function resumeWorktreeRefreshes(engine: BrainEngine, opts: { hostId?: string } = {}): Promise<number> {
- const host = opts.hostId ?? localHostId();
+ const host = opts.hostId ?? hostIdFor(engine);
const rows = await engine.executeRaw<WorktreeRefreshRow>(`SELECT f.* FROM persistence_worktree_refreshes f
JOIN persistence_worktrees w ON w.id=f.worktree_id WHERE w.owner_host_id=$1::uuid AND f.state IN ('draining','fenced','merged','syncing')
AND (f.state<>'syncing' OR NOT EXISTS (SELECT 1 FROM sources s WHERE s.id=ANY(f.source_ids) AND (s.last_commit IS NULL OR s.last_commit=f.old_head)))
@@ -931,10 +931,10 @@ async function membersAtTarget(engine: BrainEngine, git: Git, row: WorktreeRefre
}
async function resumeOrAbandon(engine: BrainEngine, sourceId: string, opts: RefreshOptions, syncBudgetMs: number): Promise<WorktreeRefreshResult> {
- const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
+ const binding = await getWorktreeBinding(engine, sourceId, existingHostIdFor(engine));
if (!await managedPersistenceEnabled(engine) || !binding) throw refusal('refresh_not_managed',
`Source ${sourceId} has no claimed canonical worktree on a managed brain, so there is no refresh to resume.`, `gbrain sync --source ${sourceId}`);
- assertRefreshOwner(binding, sourceId, 'resume its refresh');
+ assertRefreshOwner(engine, binding, sourceId, 'resume its refresh');
const root = binding.local_path;
const active = await readActiveRefresh(engine, binding.worktree_id);
const empty: WorktreeRefreshResult = { status: 'nothing_to_resume', refresh_id: null, worktree_id: binding.worktree_id, source_ids: [sourceId],
@@ -970,7 +970,7 @@ async function resumeOrAbandon(engine: BrainEngine, sourceId: string, opts: Refr
*/
async function resumeHeld(engine: BrainEngine, git: Git, sourceId: string, refreshId: string, root: string, head: string | null, empty: WorktreeRefreshResult, syncBudgetMs: number, unattended = false): Promise<WorktreeRefreshResult> {
await engine.executeRaw(`UPDATE persistence_worktree_refreshes SET outcome=outcome||jsonb_build_object('holder',$2::text::jsonb,'previous_holder',COALESCE(outcome->'previous_holder',outcome->'holder'))
- WHERE id=$1::uuid AND state IN ${ACTIVE_REFRESH_STATES_SQL}`, [refreshId, JSON.stringify(refreshHolder())]);
+ WHERE id=$1::uuid AND state IN ${ACTIVE_REFRESH_STATES_SQL}`, [refreshId, JSON.stringify(refreshHolder(engine))]);
let row = await withTopologyLocks(engine, sourceId, async () => recoverOne(engine, git, await readRefresh(engine, refreshId), root, unattended), undefined, 30_000);
if (row.state === 'recovery_required' && head === row.old_head) throw refusal('refresh_recovery_required',
`The checkout is back at the pre-refresh commit ${row.old_head}; nothing remains to resume.`, `gbrain sources refresh ${sourceId} --abandon`, row.id);
@@ -1000,7 +1000,7 @@ async function resumeHeld(engine: BrainEngine, git: Git, sourceId: string, refre
*/
async function adoptOrphanedRefresh(engine: BrainEngine, sourceId: string, syncBudgetMs: number): Promise<WorktreeRefreshResult | null> {
if (!await managedPersistenceEnabled(engine)) return null;
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding || !hostId || binding.owner_host_id !== hostId || !binding.local_path) return null;
const active = await readActiveRefresh(engine, binding.worktree_id);
@@ -1046,8 +1046,8 @@ export async function assertManagedSyncAllowed(engine: BrainEngine, worktreeId:
* recorded holder's, else the worktree owner's), so only that host can tell; a free lock means the refresher exited.
* The probe takes the lock for an instant and releases it; a refresh starting at that instant waits a second for it.
*/
-export async function refreshLiveness(worktreeId: string, holderHostId: string | null): Promise<RefreshLiveness> {
- const local = existingLocalHostId();
+export async function refreshLiveness(worktreeId: string, holderHostId: string | null, engine?: object): Promise<RefreshLiveness> {
+ const local = existingHostIdFor(engine);
if (!local || holderHostId !== local) return 'unknown';
const lock = await tryAcquireNativeLock(refreshLockPath(worktreeId)).catch(() => undefined);
if (lock === undefined) return 'unknown';
@@ -1061,7 +1061,7 @@ export async function refreshHolderReport(engine: BrainEngine, row: Pick<Worktre
Promise<{ holder: RefreshHolder | null; liveness: RefreshLiveness; orphaned: boolean | null; auto_recovery: 'next_refresh' | 'none' | 'unknown'; fix: Action | null }> {
const holder = holderOf(row);
const holderHost = holder?.host_id ?? row.owner_host_id;
- const liveness = await refreshLiveness(row.worktree_id, holderHost);
+ const liveness = await refreshLiveness(row.worktree_id, holderHost, engine);
const source = row.source_ids[0];
const resume = ['gbrain', 'sources', 'refresh', source, '--resume'];
const verify = { argv: ['gbrain', 'sources', 'writer', 'status', '--source', source, '--json'] };
diff --git a/src/core/repair/content-receipt-root.ts b/src/core/repair/content-receipt-root.ts
index 3e6c0606fc..8fb189b4d2 100644
--- a/src/core/repair/content-receipt-root.ts
+++ b/src/core/repair/content-receipt-root.ts
@@ -18,7 +18,7 @@ import { resolve } from 'node:path';
import type { Action } from '../agent-output.ts';
import { OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
import { inspectPersistenceBrain } from '../persistence/managed-mode.ts';
import { previewChangedError, previewHash } from '../persistence/preview-approval.ts';
import { storedManifestScope, worktreeManifest, type StoredWorktreeManifest } from '../persistence/worktree-manifest.ts';
@@ -63,7 +63,7 @@ async function verdicts(engine: Parameters<RepairHandler['plan']>[0], scope: Rep
if (!row || !ownedContentReceipt(row.value, row.brain_id, stale.sourceId, row.incarnation)) continue;
const base = { source_id: stale.sourceId, key: row.key, raw: row.value };
const was = `the receipt names ${stale.receiptRoot ?? 'no root'}`;
- if (row.owner_host_id !== localHostId()) { out.push({ ...base, class: 'not_owner_host', detail: `${was}; run this repair on the owner host, which can read its root`, fix: statusFix(stale.sourceId) }); continue; }
+ if (row.owner_host_id !== hostIdFor(engine)) { out.push({ ...base, class: 'not_owner_host', detail: `${was}; run this repair on the owner host, which can read its root`, fix: statusFix(stale.sourceId) }); continue; }
const next = rootIdentity(resolve(row.worktree_root, row.relative_path));
if (!next) { out.push({ ...base, class: 'root_missing', detail: `${was}; the owner binding's root ${resolve(row.worktree_root, row.relative_path)} cannot be read`, fix: statusFix(stale.sourceId) }); continue; }
if (rootIdentity(stale.localPath)?.root !== next.root) {
diff --git a/src/core/repair/embedding-effects.ts b/src/core/repair/embedding-effects.ts
index 2788726c10..9a3b492153 100644
--- a/src/core/repair/embedding-effects.ts
+++ b/src/core/repair/embedding-effects.ts
@@ -9,13 +9,13 @@
* retry budget.
*/
import { loadConfigWithEngine } from '../config.ts';
-import { existingLocalHostId } from '../persistence/identity.ts';
+import { existingHostIdFor } from '../persistence/identity.ts';
import { EMBEDDING_RETRY_BUDGET_ATTEMPTS, listEmbeddingCandidates, settleEmbeddingEffect, type EmbeddingCandidate } from '../persistence/embedding-settlement.ts';
import { OperationError } from '../ops/contract.ts';
import type { RepairHandler, RepairItem } from './core.ts';
-function localHost(): string {
- const hostId = existingLocalHostId();
+function localHost(engine: object): string {
+ const hostId = existingHostIdFor(engine);
if (!hostId) throw new OperationError('permission_denied', 'Settling embedding effects requires the registered local CLI host.',
'Run it on the brain host that owns the source.');
return hostId;
@@ -27,7 +27,7 @@ export const embeddingEffectsRepair: RepairHandler = {
// Effect ids order the scan, so a --limit or interrupted run resumes after the last settled effect.
async plan(engine, scope, after) {
const candidates = await listEmbeddingCandidates(engine, scope.source_ids);
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const config = await loadConfigWithEngine(engine);
const items: RepairItem[] = [];
const residuals: Record<string, number> = {};
@@ -49,7 +49,7 @@ export const embeddingEffectsRepair: RepairHandler = {
},
async apply(ctx, item, opts) {
const settled = await settleEmbeddingEffect(ctx.engine, JSON.parse(item.change!.from!),
- { dryRun: false, config: await loadConfigWithEngine(ctx.engine), hostId: localHost(), runId: opts?.runId });
+ { dryRun: false, config: await loadConfigWithEngine(ctx.engine), hostId: localHost(ctx.engine), runId: opts?.runId });
return { applied: settled.outcome !== 'blocked' && settled.outcome !== 'changed_since_preview', outcome: settled.outcome, ...(settled.reason ? { reason: settled.reason } : {}) };
},
};
diff --git a/src/core/repair/keep-db-policy.ts b/src/core/repair/keep-db-policy.ts
index d4870e23a7..33306acbae 100644
--- a/src/core/repair/keep-db-policy.ts
+++ b/src/core/repair/keep-db-policy.ts
@@ -25,7 +25,7 @@ import { trustedCliRequired } from '../ops/op-fix.ts';
import { isKeepDbSlug, loadStorageConfig } from '../storage-config.ts';
import { getWorktreeBinding } from '../persistence/ownership.ts';
import { readDriftSkips, releaseDriftSkip } from '../persistence/drift-conflicts.ts';
-import { localHostId, readLocalWriter, withVerifiedLocalRegistration } from '../persistence/identity.ts';
+import { readLocalWriter, withVerifiedLocalRegistration, hostIdFor } from '../persistence/identity.ts';
import { getWriteRequest } from '../persistence/journal.ts';
import { admitReconcileArtifact, authorizeReconcile, type ReconcileArtifact } from '../persistence/reconcile.ts';
import { reconcileBackupRetained } from '../persistence/reconcile-backup.ts';
@@ -110,7 +110,7 @@ export async function freezeKeepDbReconcile(engine: BrainEngine, input: KeepDbFr
if (!(cls === 'keep_db' || (cls === 'db_ahead' && sub === 'db_only' && keepDbWrite))) return { refused: 'not_keep_db' };
if (input.mode !== 'committed' || input.dirty !== 'clean') return { refused: 'not_committed_clean' };
let policy: KeepDbPolicy | null;
- try { policy = await readKeepDbPolicy(engine, input.sourceId, localHostId()); } catch { return { refused: 'storage_config_error' }; }
+ try { policy = await readKeepDbPolicy(engine, input.sourceId, hostIdFor(engine)); } catch { return { refused: 'storage_config_error' }; }
if (!policy || !isKeepDbSlug(input.slug, policy.keep_db)) return { refused: 'outside_keep_db' };
if (await sourceMirrorReadOnly(engine, input.sourceId)) return { refused: 'mirror_read_only' };
let preview: ReconcileArtifact;
diff --git a/src/core/repair/legacy-twins.ts b/src/core/repair/legacy-twins.ts
index 9034ad7a05..c2af225a0d 100644
--- a/src/core/repair/legacy-twins.ts
+++ b/src/core/repair/legacy-twins.ts
@@ -52,7 +52,7 @@ import { resolveSourceLocalFilePath } from '../markdown.ts';
import { slugifyPath } from '../sync.ts';
import { authorizeWrite } from '../persistence/authority.ts';
import { prepareCoreGuard } from '../persistence/core-guard.ts';
-import { existingLocalHostId } from '../persistence/identity.ts';
+import { existingHostIdFor } from '../persistence/identity.ts';
import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { liveFileDrift } from '../persistence/drift-conflicts.ts';
@@ -109,7 +109,7 @@ const sameOwner = (a: GhostOwner | undefined, b: GhostOwner) => !!a && a.host_id
const page = (row: PageRow): TwinPage => ({ page_id: Number(row.id), slug: row.slug, revision: String(row.revision) });
async function ownerContext(engine: BrainEngine, sourceId: string): Promise<OwnerContext> {
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding) return { ok: false, status: 'not_applicable', reason: 'not_applicable' };
if (!hostId || !binding.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') return { ok: false, status: 'not_applicable', reason: 'not_owner_host' };
diff --git a/src/core/repair/origin-twins.ts b/src/core/repair/origin-twins.ts
index e310aca2e3..93788428f7 100644
--- a/src/core/repair/origin-twins.ts
+++ b/src/core/repair/origin-twins.ts
@@ -30,7 +30,7 @@ import { opError, OperationError, type OperationContext } from '../ops/contract.
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { authorizeWrite } from '../persistence/authority.ts';
import { prepareCoreGuard } from '../persistence/core-guard.ts';
-import { existingLocalHostId } from '../persistence/identity.ts';
+import { existingHostIdFor } from '../persistence/identity.ts';
import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
@@ -83,7 +83,7 @@ const sameOwner = (a: GhostOwner | undefined, b: GhostOwner) => !!a && a.host_id
&& a.owner_epoch === b.owner_epoch && a.source_incarnation === b.source_incarnation;
export async function originOwnerContext(engine: BrainEngine, sourceId: string): Promise<OwnerContext> {
- const hostId = existingLocalHostId();
+ const hostId = existingHostIdFor(engine);
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding) return { ok: false, reason: 'not_applicable' };
if (!hostId || !binding.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') return { ok: false, reason: 'not_owner_host' };
diff --git a/src/core/repair/overwritten-edits.ts b/src/core/repair/overwritten-edits.ts
index 0ed99359c3..b9ebf15909 100644
--- a/src/core/repair/overwritten-edits.ts
+++ b/src/core/repair/overwritten-edits.ts
@@ -20,7 +20,7 @@ import { OperationError, opError, type OperationContext } from '../ops/contract.
import { readFix } from '../ops/op-fix.ts';
import { unifiedDiff } from '../skillpack/diff-text.ts';
import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
import { getWorktreeBinding } from '../persistence/ownership.ts';
import { fileMatchesSnapshot } from '../persistence/page-prepare.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
@@ -176,7 +176,7 @@ async function holdDivergentFile(engine: BrainEngine, edit: ApprovedEdit, reques
const snapshot = await engine.readPageSnapshot(edit.slug, { sourceId: edit.source_id });
if (!snapshot?.page.source_path) return { held: false, why: 'no_recorded_file' };
const binding = await getWorktreeBinding(engine, edit.source_id);
- if (!binding?.local_path || binding.owner_host_id !== localHostId()) return { held: false, why: 'checkout_not_on_this_host' };
+ if (!binding?.local_path || binding.owner_host_id !== hostIdFor(engine)) return { held: false, why: 'checkout_not_on_this_host' };
const root = join(binding.local_path, binding.relative_path);
const mode = await scannerSlugRootMode(engine, edit.source_id, root);
const target = resolveSourceLocalFilePath(root, snapshot.page.source_path, edit.slug, mode);
diff --git a/src/core/repair/segmented-mirror.ts b/src/core/repair/segmented-mirror.ts
index e940f35251..5f269f51ff 100644
--- a/src/core/repair/segmented-mirror.ts
+++ b/src/core/repair/segmented-mirror.ts
@@ -33,7 +33,7 @@ import { ledgerApplies, type BodyLedger } from '../page-body/segment-ledger.ts';
import { fenceTooLargeError } from '../page-body/read-range.ts';
import { FileBytes } from '../persistence/large-file.ts';
import { getWorktreeBinding } from '../persistence/ownership.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
import { prepareFileTarget, unreadPageFile } from '../persistence/page-prepare.ts';
import { loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import { admitWriteInTransaction, completeWrite, getWriteRequest } from '../persistence/journal.ts';
@@ -96,7 +96,7 @@ const heldFrom = (sourceId: string, slug: string, error: OperationError): HeldMi
/** Every listed and held page of the sources, in (source, slug) order, read on this host one page at a time. */
export async function scanSegmentedMirrors(engine: BrainEngine, sourceIds: readonly string[]): Promise<{ items: StaleMirror[]; held: HeldMirror[]; residuals: Record<string, number> }> {
- const hostId = localHostId();
+ const hostId = hostIdFor(engine);
const items: StaleMirror[] = [], held: HeldMirror[] = [];
const residuals: Record<string, number> = {};
const hold = (entry: HeldMirror) => { held.push(entry); residuals[entry.reason] = (residuals[entry.reason] ?? 0) + 1; };
@@ -139,7 +139,7 @@ export async function scanSegmentedMirrors(engine: BrainEngine, sourceIds: reado
/** The listed page as it is now: its live revision and id, and its file's streamed SHA-256, read on this host. */
async function currentState(engine: BrainEngine, stale: StaleMirror): Promise<{ revision: string | null; page_id: number | null; file_sha256: string | null }> {
const snapshot = await engine.readPageSnapshot(stale.slug, { sourceId: stale.source_id });
- const binding = await getWorktreeBinding(engine, stale.source_id, localHostId());
+ const binding = await getWorktreeBinding(engine, stale.source_id, hostIdFor(engine));
const path = binding?.local_path ? join(binding.local_path, ...stale.path.split('/')) : null;
let file_sha256: string | null = null;
if (path && existsSync(path)) {
diff --git a/src/core/repair/settle.ts b/src/core/repair/settle.ts
index c9e7e968fa..d92964e0c3 100644
--- a/src/core/repair/settle.ts
+++ b/src/core/repair/settle.ts
@@ -54,9 +54,9 @@ export async function repairPublicationOwner(engine: BrainEngine): Promise<{ ali
if (local.state === 'open' && (!mode || mode === 'full' || mode === 'promoted')) {
return local.restart_required ? { alive: false, owner: 'this process, which reports restart_required' } : { alive: true, owner: 'this process' };
}
- const { existingLocalHostId } = await import('../persistence/identity.ts');
+ const { existingHostIdFor } = await import('../persistence/identity.ts');
const { listHostConsumers } = await import('../persistence/consumer-heartbeat.ts');
- const host = existingLocalHostId();
+ const host = existingHostIdFor(engine);
const rows = host ? await listHostConsumers(engine, host).catch(() => []) : [];
const row = rows.find(r => !r.self && (r.mode === 'full' || r.mode === 'promoted') && r.liveness === 'live');
if (!row) return { alive: false, owner: 'no live consumer on this host' };
diff --git a/src/core/shared-skills/optimizer.ts b/src/core/shared-skills/optimizer.ts
index 75eb817356..806c42f7d1 100644
--- a/src/core/shared-skills/optimizer.ts
+++ b/src/core/shared-skills/optimizer.ts
@@ -10,7 +10,7 @@ import { getWriteRequest } from '../persistence/journal.ts';
import { submissionAuthority } from '../persistence/authority.ts';
import { requireUuid, sha256 } from '../persistence/digest.ts';
import { getWorktreeBinding } from '../persistence/ownership.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
import { hasScope } from '../scope.ts';
import { getWorkingTreeStatusForFile, splitFrontmatter } from '../skillopt/apply-edits.ts';
import { assertBundledMutationHeldOut, getBundledSkillContext, shouldMutateSkillFile } from '../skillopt/bundled-skill-gate.ts';
@@ -34,7 +34,7 @@ export async function sharedOptimizerSkillsDir(ctx: OperationContext, sourceId:
const binding = await getWorktreeBinding(ctx.engine, sourceId);
const ownerFix = { fix: hostFix(ctx, ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'],
`Shows source ${sourceId}'s designated canonical owner and binding; optimization runs only on that host.`) };
- if (!binding || binding.source_incarnation !== incarnation || binding.state !== 'active' || binding.owner_host_id !== localHostId() || !binding.local_path) {
+ if (!binding || binding.source_incarnation !== incarnation || binding.state !== 'active' || binding.owner_host_id !== hostIdFor(ctx.engine) || !binding.local_path) {
throw opError('owner_unavailable', 'Shared optimization must run on the active canonical owner.',
`Source ${sourceId}'s skills are optimized only on its active canonical owner host, and this host is not it (or the binding is inactive). Nothing ran and nothing was spent; run the optimization there.`, ownerFix);
}
diff --git a/src/core/shared-skills/publication.ts b/src/core/shared-skills/publication.ts
index fc5b37ae17..33428957f2 100644
--- a/src/core/shared-skills/publication.ts
+++ b/src/core/shared-skills/publication.ts
@@ -17,7 +17,7 @@ import { assertPersistenceAccepting, waitForWrite, writeResponse } from '../pers
import { digest, requireUuid, sha256, stableJson } from '../persistence/digest.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteAuthority, WriteRequest } from '../persistence/model.ts';
-import { localHostId } from '../persistence/identity.ts';
+import { hostIdFor } from '../persistence/identity.ts';
import { withCoordinatedWrite } from '../persistence/context.ts';
import { requestAttribution } from '../persistence/attribution.ts';
import { normalizeSkillFiles, skillMetadata, skillName, skillPath } from './manifest.ts';
@@ -88,7 +88,7 @@ async function sourceRoot(engine: BrainEngine, sourceId: string, incarnation: st
`Source ${sourceId} has no active designated canonical owner at this incarnation, so nothing was published. The brain host's operator inspects it with gbrain sources writer status --source ${sourceId} --json; claiming ownership is their decision.`,
{ fix: ownerStatusFix(sourceId, ctx) });
}
- if (binding.owner_host_id !== localHostId() || !binding.local_path) {
+ if (binding.owner_host_id !== hostIdFor(engine) || !binding.local_path) {
throw opError('owner_unavailable', 'The designated owner must prepare this publication.',
`Source ${sourceId}'s canonical owner is another host (or has no local checkout here), so publish through that host or a connection to its gbrain server. gbrain sources writer status --source ${sourceId} --json names the owner.`,
{ fix: ownerStatusFix(sourceId, ctx) });
diff --git a/src/core/sync-pending.ts b/src/core/sync-pending.ts
index 97224c4e77..e17aa8529b 100644
--- a/src/core/sync-pending.ts
+++ b/src/core/sync-pending.ts
@@ -200,7 +200,7 @@ export interface RosterSource extends PendingSource { managed: boolean }
* path) and classic sources with a local path, not archived and not sync-disabled. `sourceIds` confines it in SQL.
*/
export async function loadPendingRoster(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<RosterSource[]> {
- const { existingLocalHostId } = await import('./persistence/identity.ts');
+ const { existingHostIdFor } = await import('./persistence/identity.ts');
const { isSyncDisabledConfig } = await import('./sync-policy.ts');
const rows = await engine.executeRaw<{ id: string; last_commit: string | null; root: string | null; managed: unknown; config: unknown }>(
`SELECT s.id, s.last_commit, s.config, (b.source_id IS NOT NULL) AS managed, COALESCE(h.local_path, s.local_path) AS root
@@ -209,7 +209,7 @@ export async function loadPendingRoster(engine: Pick<BrainEngine, 'executeRaw'>,
LEFT JOIN persistence_host_bindings h ON h.worktree_id = b.worktree_id AND h.host_id::text = $2
WHERE s.archived IS NOT TRUE AND (b.source_id IS NOT NULL OR s.local_path IS NOT NULL)
AND ($1::text[] IS NULL OR s.id = ANY($1::text[]))
- ORDER BY s.id`, [sourceIds ?? null, existingLocalHostId()]);
+ ORDER BY s.id`, [sourceIds ?? null, existingHostIdFor(engine)]);
return rows.filter(row => !isSyncDisabledConfig(row.config))
.map(row => ({ id: row.id, last_commit: row.last_commit, root: row.root, managed: row.managed === true || row.managed === 't' }));
}
diff --git a/test/engine-open.test.ts b/test/engine-open.test.ts
index 845482a1c4..31778f8e92 100644
--- a/test/engine-open.test.ts
+++ b/test/engine-open.test.ts
@@ -325,37 +325,14 @@ describe('repo source', () => {
});
/**
- * Persistence modules that still read this process's file identity directly. Each one runs only from a CLI command on
- * the brain's own host, against a managed checkout that host owns (activation, claim, transfer, topology, checkout sync
- * and repair). An engine opened from settings owns no managed checkout: activation and claims refuse any host but the
- * owner, and `hostIdFor(engine)` answers every call an operation, publication or consumer effect makes for it.
+ * Core modules that still read this process's file identity directly. Every other core call site resolves the host id
+ * through `hostIdFor(engine)` / `existingHostIdFor(engine)`, which answer the id given at open for an engine opened
+ * from settings and `localHostId()` for every other engine. The CLI layer (src/commands) keeps the file identity: it
+ * only runs against the engine the CLI connected.
*/
const FILE_IDENTITY_ALLOWLIST: Record<string, string> = {
- 'activation.ts': 'gbrain activation mints the host identity on the brain host by design',
- 'admin-lock.ts': 'writer admin lock, set by CLI administration on the brain host',
- 'administration.ts': 'gbrain sources writer status/claim/register, local administration',
- 'connector-sync.ts': 'connector checkout sync owned by the brain host',
- 'coordination-lock.ts': 'fallback only when a caller passes no host id; claims pass hostIdFor(engine)',
- 'deactivation.ts': 'gbrain deactivation on the brain host',
- 'diagnostics.ts': 'local writer diagnostics for the CLI',
- 'engine-graduation.ts': 'PGLite to Postgres graduation, a local CLI command',
- 'file-repair.ts': 'checkout file repair on the owning host',
- 'git-conversion.ts': 'repository conversion of a local checkout',
- 'git-durability-administration.ts': 'git durability administration of a local checkout',
- 'onboarding.ts': 'local onboarding preflight',
- 'pre-activation-release.ts': 'pre-activation release on the brain host',
- 'reconcile-state.ts': 'checkout reconcile on the owning host',
- 'skill-activation.ts': 'shared skill activation, local administration',
- 'source-lifecycle.ts': 'managed source add/move/rebind on the owning host',
- 'sync-discovery.ts': 'checkout sync discovery on the owning host',
- 'sync-drain.ts': 'gbrain sync drain on the owning host',
- 'sync-freshness.ts': 'checkout sync freshness report on the owning host',
- 'sync-movement.ts': 'checkout sync movement on the owning host',
- 'topology-clone.ts': 'topology clone/reclone of a local checkout',
- 'topology-locks.ts': 'topology locks of a local checkout',
- 'topology-recovery.ts': 'topology recovery of a local checkout',
- 'transfer-administration.ts': 'writer transfer administration between hosts',
- 'worktree-refresh.ts': 'managed worktree refresh on the owning host',
+ 'persistence/coordination-lock.ts': 'fallback only when a caller passes no host id; every claim and reservation passes hostIdFor(engine)',
+ 'persistence/engine-graduation.ts': 'PGLite to Postgres graduation, run only by gbrain migrate on the brain host',
};
describe('static guards', () => {
@@ -363,12 +340,12 @@ describe('static guards', () => {
const code = (path: string) => readFileSync(join(root, path), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1');
const FILE_IDENTITY = /\b(localHostId|localHostIdentity|existingLocalHostId)\(/;
- test('persistence code resolves the host id through hostIdFor(engine), except the justified allowlist', () => {
- const dirPath = join(root, 'src/core/persistence');
+ test('core code resolves the host id through hostIdFor(engine), except the justified allowlist', () => {
+ const dirPath = join(root, 'src/core');
const callers = readdirSync(dirPath, { recursive: true, withFileTypes: true })
.filter(entry => entry.isFile() && entry.name.endsWith('.ts'))
- .map(entry => relative(dirPath, join(entry.parentPath, entry.name)))
- .filter(name => name !== 'identity.ts' && FILE_IDENTITY.test(code(join('src/core/persistence', name))))
+ .map(entry => relative(dirPath, join(entry.parentPath, entry.name)).split('\\').join('/'))
+ .filter(name => name !== 'persistence/identity.ts' && FILE_IDENTITY.test(code(join('src/core', name))))
.sort();
expect(callers.filter(name => !(name in FILE_IDENTITY_ALLOWLIST))).toEqual([]);
// A row whose file stopped reading the file identity is stale: delete it.