Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): the refresh owner check never mints a host identity; gbrain state follows GBRAIN_HOME
garrytancca3e3143214
diff --git a/src/commands/features.ts b/src/commands/features.tsindex 6e2349544f..3a6c48fd15 100644--- a/src/commands/features.ts+++ b/src/commands/features.ts@@ -5,6 +5,7 @@* gbrain features [--json] [--auto-fix] [--help]*/+import { gbrainPath } from '../core/config.ts';import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';import { join } from 'path';import type { BrainEngine } from '../core/engine.ts';@@ -60,7 +61,7 @@ export const RECIPE_META = [// --- Persistence ---function offersPath(): string {- return join(process.env.HOME || '', '.gbrain', 'feature-offers.json');+ return gbrainPath('feature-offers.json');}function loadOffers(): FeatureOffersFile {@@ -74,8 +75,7 @@ function loadOffers(): FeatureOffersFile {function saveOffers(offers: FeatureOffersFile) {try {- const dir = join(process.env.HOME || '', '.gbrain');- mkdirSync(dir, { recursive: true });+ mkdirSync(gbrainPath(), { recursive: true });writeFileSync(offersPath(), JSON.stringify(offers, null, 2));} catch { /* best-effort */ }}diff --git a/src/commands/mounts.ts b/src/commands/mounts.tsindex 61f4961b8f..84b720b413 100644--- a/src/commands/mounts.ts+++ b/src/commands/mounts.ts@@ -22,9 +22,9 @@* gbrain mounts add --mcp-url — HTTP MCP transport + OAuth (PR 2)*/+import { configDir } from '../core/config.ts';import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync, renameSync } from 'fs';import { join, resolve } from 'path';-import { homedir } from 'os';import {loadMounts,validateMountId,@@ -37,7 +37,7 @@ import { findRepoRoot } from '../core/repo-root.ts';import { writeMountsCache, clearMountsCache } from '../core/mounts-cache.ts';import { GBrainError } from '../core/types.ts';-function getMountsDir(): string { return join(homedir(), '.gbrain'); }+function getMountsDir(): string { return configDir(); }// v0.40.3.0: GBRAIN_MOUNTS_PATH override exists for tests (libuv caches// homedir() at startup on some platforms; HOME mutation alone isn't// reliably picked up). Production callers don't set this.diff --git a/src/commands/notability-eval.ts b/src/commands/notability-eval.tsindex 0b87895238..153497c6a7 100644--- a/src/commands/notability-eval.ts+++ b/src/commands/notability-eval.ts@@ -28,11 +28,11 @@* if precision@HIGH < 0.75; fail PR if < 0.50.*/+import { gbrainPath } from '../core/config.ts';import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'fs';import { isInteractive, readLine } from '../core/interaction.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { join, resolve } from 'path';-import { homedir } from 'os';import type { BrainEngine } from '../core/engine.ts';const DEFAULT_TARGETS = { high: 20, medium: 20, low: 10 } as const;@@ -68,12 +68,12 @@ interface MineOpts {/** Resolve the path where mining writes its candidates JSONL. */export function defaultMiningOutPath(): string {- return join(homedir(), '.gbrain', 'eval', 'notability-mining-candidates.jsonl');+ return gbrainPath('eval', 'notability-mining-candidates.jsonl');}/** Resolve the path where review writes confirmed cases. */export function defaultReviewOutPath(): string {- return join(homedir(), '.gbrain', 'eval', 'notability-real.jsonl');+ return gbrainPath('eval', 'notability-real.jsonl');}/**diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 80a5cd3eba..a0715e1a48 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -11,7 +11,7 @@ import type { InteractiveProbe } from '../core/interaction.ts';import { forwardProgressPast, migrationLedgerSummary, wedgedLedgerHint } from '../core/migration-ledger.ts';import { loadCompletedMigrations } from '../core/preferences.ts';import { MIGRATIONS_RUNNING_EXIT_CODE, readMigrationLockHolder } from '../core/migration-orchestration-lock.ts';-import { loadConfig } from '../core/config.ts';+import { loadConfig, gbrainPath } from '../core/config.ts';import { clearSnooze, clearUpdateCache, writeJustUpgraded, writeSwapReceipt } from '../core/self-upgrade.ts';import { MOVEMENT_SUPERVISOR_STEP } from './movement-step.ts';import {@@ -603,7 +603,7 @@ export function recordUpgradeError(record: {hint: string;}): void {try {- const dir = join(process.env.HOME || '', '.gbrain');+ const dir = gbrainPath();mkdirSync(dir, { recursive: true });const path = join(dir, 'upgrade-errors.jsonl');const line = JSON.stringify({@@ -623,7 +623,7 @@ export function recordUpgradeError(record: {function saveUpgradeState(oldVersion: string, newVersion: string) {try {- const dir = join(process.env.HOME || '', '.gbrain');+ const dir = gbrainPath();mkdirSync(dir, { recursive: true });const statePath = join(dir, 'upgrade-state.json');const state: Record<string, unknown> = existsSync(statePath)@@ -759,7 +759,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {await applySelfUpgradeSetup(noAutopilotInstall);// Cosmetic: print feature pitches for migrations newer than the prior binary.try {- const statePath = join(process.env.HOME || '', '.gbrain', 'upgrade-state.json');+ const statePath = gbrainPath('upgrade-state.json');if (existsSync(statePath)) {const state = JSON.parse(readFileSync(statePath, 'utf-8'));const from = state?.last_upgrade?.from;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 785b441888..ac7f635ece 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1219,6 +1219,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'On a managed brain, a cycle extract phase with no changed-page list from sync (sync left out of the phases, as for a source with sync disabled, or a sync that failed) now stops its stale-page pass after the cycle\'s 3-minute stale-drain budget instead of running over every stale page of the source. The rest stays stale and drains across later cycles, and the phase reports `stale_backlog`. `gbrain extract` and `gbrain extract --stale --catch-up` still run to the end.' },{ since: 'TBD', text: 'The job stall sweep now deletes a drain-lease holder record (queue `gbrain-drain-lease`) whose lease lock is gone or expired. Such a record is left when the process holding a source\'s drain lease is killed before it releases the lease, and it used to stay `active` until the next sync of that source, shown as a stalled sync job. A live holder\'s record is never touched.' },{ since: 'TBD', text: 'A Git effect whose target file a .gitignore rule excludes now parks on its first attempt as `git_target_ignored`, naming the rule (`<file>:<line>: <pattern>`), instead of retrying and then parking as `git_target_unsafe`. doctor `parked_effects` and `gbrain sources writer status` (`parked_groups`) group parked Git targets per source and code, each group with one bulk command: `--parked-pushes` for push codes and the new `gbrain sources writer retry-effects <source> --parked-code <code>` otherwise. An ignored target gets no per-request retry suggestion, because a retry parks it again while the rule stands. Nothing already parked changes on upgrade.' },+ { since: 'TBD', text: 'The worktree refresh owner check (`refresh_not_owner`) no longer creates a host identity file. A process whose gbrain home has no `persistence/host.json` (for example one started under another HOME or GBRAIN_HOME) used to mint a new identity there and then refuse as a different host; it now refuses without writing anything, and the refusal names the identity file it read, the HOME and GBRAIN_HOME it resolved and the owner it expected. A process that already owns the source refreshes as before.' },+ { since: 'TBD', text: 'More gbrain state follows GBRAIN_HOME: feature offers (`feature-offers.json`), the upgrade state and error log, `mounts.json` and the mounts cache, the brain-pull log (including the log paths a newly installed launchd pull job writes), the default supervisor pid file, skillopt captures, the transcript harvest pattern file, notability eval files and the greenfield import audit directory now live under `<GBRAIN_HOME>/.gbrain` when GBRAIN_HOME is set. Before, they were written under `$HOME/.gbrain` whatever GBRAIN_HOME said. With GBRAIN_HOME unset nothing moves. A host that sets GBRAIN_HOME keeps its old copies under `$HOME/.gbrain`: move them by hand if you want the old offers, mounts or upgrade history, and restart a supervisor that was started before the upgrade so `gbrain jobs supervisor status` finds its pid file.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/brain-registry.ts b/src/core/brain-registry.tsindex 5c50b558e4..f2c7998c1e 100644--- a/src/core/brain-registry.ts+++ b/src/core/brain-registry.ts@@ -24,11 +24,10 @@import { readFileSync, existsSync } from 'fs';import { join, resolve } from 'path';-import { homedir } from 'os';import type { BrainEngine } from './engine.ts';import type { EngineConfig } from './types.ts';import { GBrainError } from './types.ts';-import { loadConfig, type GBrainConfig } from './config.ts';+import { loadConfig, type GBrainConfig, gbrainPath } from './config.ts';/** Host brain id. Reserved — users cannot create a mount with this id. */export const HOST_BRAIN_ID = 'host';@@ -46,7 +45,7 @@ const BRAIN_ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;function getMountsPath(): string {const override = process.env.GBRAIN_MOUNTS_PATH;if (override) return override;- return join(homedir(), '.gbrain', 'mounts.json');+ return gbrainPath('mounts.json');}/**diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.tsindex 8b6ae051f0..e2c716bc99 100644--- a/src/core/brain-repo-durability.ts+++ b/src/core/brain-repo-durability.ts@@ -875,7 +875,7 @@ export function durabilityJobStatus(}let logFresh: boolean | undefined;try {- const log = join(process.env.HOME || '', '.gbrain', 'brain-pull.log');+ const log = join(gbrainHome(), 'brain-pull.log');if (existsSync(log)) {logFresh = Date.now() - statSync(log).mtimeMs <= 2 * intervalSec * 1000;}@@ -912,7 +912,7 @@ function writeCronWrapper(sourceId: string, repoPath: string, branch: string): sreturn wrapper;}-export function generateBrainPullPlist(label: string, wrapperPath: string, home: string, intervalSec: number): string {+export function generateBrainPullPlist(label: string, wrapperPath: string, gbrainDir: string, intervalSec: number): string {const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');return `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">@@ -921,8 +921,8 @@ export function generateBrainPullPlist(label: string, wrapperPath: string, home:<key>Label</key><string>${esc(label)}</string><key>ProgramArguments</key><array><string>${esc(wrapperPath)}</string></array><key>StartInterval</key><integer>${intervalSec}</integer>- <key>StandardOutPath</key><string>${esc(home)}/.gbrain/brain-pull.log</string>- <key>StandardErrorPath</key><string>${esc(home)}/.gbrain/brain-pull.err</string>+ <key>StandardOutPath</key><string>${esc(gbrainDir)}/brain-pull.log</string>+ <key>StandardErrorPath</key><string>${esc(gbrainDir)}/brain-pull.err</string></dict></plist>`;}@@ -949,12 +949,11 @@ export function installDurabilityCron(};}const wrapper = dryRun ? cronWrapperPath(sourceId) : writeCronWrapper(sourceId, repoPath, branch);- const home = process.env.HOME || '';if (platform === 'darwin') {const plistPath = launchdPlistPath(sourceId);if (dryRun) return { status: 'fixed', detail: `would install launchd ${cronLabel(sourceId)} every ${intervalSec}s (dry-run)` };mkdirSync(dirname(plistPath), { recursive: true });- writeFileSync(plistPath, generateBrainPullPlist(cronLabel(sourceId), wrapper, home, intervalSec));+ writeFileSync(plistPath, generateBrainPullPlist(cronLabel(sourceId), wrapper, gbrainHome(), intervalSec));try { execSync(`launchctl unload "${plistPath}" 2>/dev/null`, { stdio: 'ignore' }); } catch { /* */ }try { execSync(`launchctl load "${plistPath}"`, { stdio: 'ignore' }); } catch { /* loaded best-effort */ }return { status: 'fixed', detail: `launchd ${cronLabel(sourceId)} every ${intervalSec}s` };diff --git a/src/core/ingestion/sources/markdown-greenfield.ts b/src/core/ingestion/sources/markdown-greenfield.tsindex f1733b9772..d5dda31b63 100644--- a/src/core/ingestion/sources/markdown-greenfield.ts+++ b/src/core/ingestion/sources/markdown-greenfield.ts@@ -43,6 +43,7 @@* ideas/. Defaults to ~/git/brain when omitted.*/+import { gbrainPath } from '../../config.ts';import { readFileSync, readdirSync, existsSync, statSync, appendFileSync, mkdirSync } from 'node:fs';import { join, relative, dirname } from 'node:path';import { homedir } from 'node:os';@@ -113,7 +114,7 @@ export class MarkdownGreenfieldSource implements IngestionSource {repoPath: opts.repoPath ?? join(homedir(), 'git', 'brain'),dryRun: opts.dryRun ?? false,limit: opts.limit,- auditDir: opts.auditDir ?? join(homedir(), '.gbrain', 'audit'),+ auditDir: opts.auditDir ?? gbrainPath('audit'),_readFile: opts._readFile ?? ((p) => readFileSync(p, 'utf-8')),_existsSync: opts._existsSync ?? existsSync,_readdirSync: opts._readdirSync ?? ((p) => readdirSync(p)),diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.tsindex f7221690b4..7fb5f629e8 100644--- a/src/core/minions/supervisor.ts+++ b/src/core/minions/supervisor.ts@@ -49,6 +49,7 @@ import type { BrainEngine } from '../engine.ts';import { tryAcquireDbLock, waitForDbLockTakeover, inspectLock, isLockHolderLive, type DbLockHandle } from '../db-lock.ts';import { currentBrainId, readWorkers, workerRegistryReadFailure } from './worker-registry.ts';import { autopilotOperatorPauseMarkerPath, autopilotPaused } from '../autopilot-paths.ts';+import { gbrainPath } from '../config.ts';import { registerSignalOwner, triggerCleanupAndExit } from '../process-cleanup.ts';import { resolveEnvNumber } from '../env-number.ts';import { pidFileContents, processStartStamp } from './supervisor-pid.ts';@@ -76,7 +77,7 @@ export interface SupervisorOpts {concurrency: number;/** Queue name (passed to child). Default: 'default'. */queue: string;- /** PID file path. Default: `${HOME}/.gbrain/supervisor.pid` (parent dir auto-created). */+ /** PID file path. Default: `<gbrain home>/supervisor-<brain-id>.pid`, GBRAIN_HOME honoured (parent dir auto-created). */pidFile: string;/** Max consecutive crashes before giving up. Default: 10. */maxCrashes: number;@@ -145,7 +146,6 @@ export interface SupervisorOpts {export const DEFAULT_PID_FILE: string = (() => {const envOverride = process.env.GBRAIN_SUPERVISOR_PID_FILE;if (envOverride && envOverride.length > 0) return envOverride;- const home = process.env.HOME ?? '/tmp';// #1849: key the default pidfile on the brain id so two DIFFERENT brains// under one HOME don't share `supervisor.pid` and falsely block each other's// pidfile guard. Derived from config (no DB connect), so it's safe to@@ -154,7 +154,7 @@ export const DEFAULT_PID_FILE: string = (() => {// singleton authority; this just removes the common-case footgun.let brainId = 'default';try { brainId = currentBrainId(); } catch { /* fallback 'default' */ }- return `${home}/.gbrain/supervisor-${brainId}.pid`;+ return gbrainPath(`supervisor-${brainId}.pid`);})();const DEFAULTS: Omit<SupervisorOpts, 'cliPath'> = {diff --git a/src/core/mounts-cache.ts b/src/core/mounts-cache.tsindex eb7ea4ef9a..cbfdd5e0bc 100644--- a/src/core/mounts-cache.ts+++ b/src/core/mounts-cache.ts@@ -24,16 +24,16 @@* Only writeMountsCache touches disk.*/+import { gbrainPath } from './config.ts';import { readFileSync, existsSync, mkdirSync, writeFileSync, rmSync, renameSync } from 'fs';import { join } from 'path';-import { homedir } from 'os';import { parseResolverEntries } from './check-resolvable.ts';import { loadSkillTriggerIndex } from './skill-trigger-index.ts';import { HOST_BRAIN_ID, type MountEntry } from './brain-registry.ts';/** Default location of the aggregated cache directory. */function getMountsCacheDir(): string {- return join(homedir(), '.gbrain', 'mounts-cache');+ return gbrainPath('mounts-cache');}/** A composed resolver entry with full provenance for audit + dispatch. */diff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.tsindex 5b4e68e23d..49dcdc4447 100644--- a/src/core/persistence/engine-graduation.ts+++ b/src/core/persistence/engine-graduation.ts@@ -17,7 +17,6 @@*/import { createHash, randomUUID } from 'node:crypto';import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync } from 'node:fs';-import { homedir } from 'node:os';import { dirname, join } from 'node:path';import { spawnSync } from 'node:child_process';import type { BrainEngine } from '../engine.ts';@@ -169,7 +168,7 @@ export function defaultGraduationDeps(): GraduationDeps {}},hostId: () => localHostId(),- mountsPath: () => process.env.GBRAIN_MOUNTS_PATH || join(homedir(), '.gbrain', 'mounts.json'),+ mountsPath: () => process.env.GBRAIN_MOUNTS_PATH || join(configDir(), 'mounts.json'),};}diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.tsindex 48e33ce532..582eef5fa1 100644--- a/src/core/persistence/worktree-refresh.ts+++ b/src/core/persistence/worktree-refresh.ts@@ -30,7 +30,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 { localHostId, persistenceHome } from './identity.ts';+import { existingLocalHostId, localHostId, persistenceHome } 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';@@ -73,6 +73,19 @@ function refusal(name: CatalogueName, cause: string, fix: string, refreshId?: stif (refreshId) error.detail = `refresh_id=${refreshId}`;return error;}+/**+ * 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();+ 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)`;+ throw refusal('refresh_not_owner',+ `Only the registered owner host (${binding.owner_host_id}) of source ${sourceId} may ${action}; this process has ${self}, resolved from HOME=${process.env.HOME ?? '(unset)'} and GBRAIN_HOME=${process.env.GBRAIN_HOME?.trim() || '(unset)'}.`,+ `Run it on the owner host with the HOME or GBRAIN_HOME its writer uses (a cron job often runs with a different HOME, so set GBRAIN_HOME explicitly); check the owner with gbrain sources writer status ${sourceId}`);+}const writerStatusFix = (why: string, sourceId?: string): Action => readFix(why,{ argv: ['gbrain', 'sources', 'writer', 'status', ...(sourceId ? ['--source', sourceId] : []), '--json'] });const q = (value: string) => /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;@@ -190,12 +203,10 @@ interface Plan {async function precheck(engine: BrainEngine, git: Git, sourceId: string, fetchTimeoutMs: number): 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);+ const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());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}`);- if (binding.owner_host_id !== localHostId() || !binding.local_path) throw refusal('refresh_not_owner',- `Only the registered owner host of source ${sourceId} may move its checkout; this host is not that owner.`,- `Run gbrain sources refresh ${sourceId} on the owner host; check which host owns it with gbrain sources writer status ${sourceId}`);+ assertRefreshOwner(binding, sourceId, 'move its checkout');const root = binding.local_path;const active = await readActiveRefresh(engine, binding.worktree_id);if (active) throw refusal('refresh_in_progress', `Refresh ${active.id} of this worktree is ${active.state}; only one refresh per worktree runs at a time.`,@@ -563,11 +574,10 @@ export async function resumeWorktreeRefreshes(engine: BrainEngine, opts: { hostI}async function resumeOrAbandon(engine: BrainEngine, sourceId: string, opts: RefreshOptions): Promise<WorktreeRefreshResult> {- const binding = await getWorktreeBinding(engine, sourceId);+ const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());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}`);- if (binding.owner_host_id !== localHostId() || !binding.local_path) throw refusal('refresh_not_owner',- `Only the registered owner host of source ${sourceId} may resume its refresh.`, `Run it on the owner host; check it with gbrain sources writer status ${sourceId}`);+ assertRefreshOwner(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],diff --git a/src/core/post-upgrade-notice.ts b/src/core/post-upgrade-notice.tsindex cf3979e7c6..72db51c129 100644--- a/src/core/post-upgrade-notice.ts+++ b/src/core/post-upgrade-notice.ts@@ -31,7 +31,7 @@ export function postUpgradeNotice(from: string | undefined, to: string = VERSION/** The last upgrade gbrain recorded (`~/.gbrain/upgrade-state.json`, written by `gbrain upgrade`). */function lastUpgrade(): { from?: string; to?: string } | null {try {- const path = join(process.env.HOME || '', '.gbrain', 'upgrade-state.json');+ const path = gbrainPath('upgrade-state.json');if (!existsSync(path)) return null;const state = JSON.parse(readFileSync(path, 'utf8')) as { last_upgrade?: { from?: string; to?: string } };return state.last_upgrade ?? null;diff --git a/src/core/self-upgrade-recovery.ts b/src/core/self-upgrade-recovery.tsindex 1415e2a9a6..dfa2a85e96 100644--- a/src/core/self-upgrade-recovery.ts+++ b/src/core/self-upgrade-recovery.ts@@ -12,7 +12,7 @@import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';-import { loadConfig } from './config.ts';+import { loadConfig, gbrainPath } from './config.ts';import { readAllSelfUpgrades } from './audit/self-upgrade-audit.ts';import { CRASH_ON_LAUNCH_REASON_PREFIX, SWAPPED_REASON } from './self-upgrade.ts';@@ -79,7 +79,7 @@ export function neverInstalledFailedVersions(/** `last_upgrade` from `~/.gbrain/upgrade-state.json` (where `gbrain upgrade` writes it), or null. */function readLastUpgrade(): LastUpgrade | null {try {- const path = join(process.env.HOME || '', '.gbrain', 'upgrade-state.json');+ const path = gbrainPath('upgrade-state.json');if (!existsSync(path)) return null;const u = (JSON.parse(readFileSync(path, 'utf8')) as { last_upgrade?: Record<string, unknown> }).last_upgrade;return u && typeof u.from === 'string' && typeof u.to === 'string' && typeof u.ts === 'string' ? { from: u.from, to: u.to, ts: u.ts } : null;diff --git a/src/core/skillopt/held-out.ts b/src/core/skillopt/held-out.tsindex 63267b925a..0a23b2b8ca 100644--- a/src/core/skillopt/held-out.ts+++ b/src/core/skillopt/held-out.ts@@ -32,6 +32,7 @@ import type { BrainEngine } from '../engine.ts';import type { OperationContext } from '../ops/contract.ts';import { loadBenchmark } from './benchmark.ts';import { D_SEL_MIN_SIZE } from './types.ts';+import { gbrainPath } from '../config.ts';import type { BenchmarkTask } from './types.ts';import { scoreSkillOnTasks } from './validate-gate.ts';@@ -47,8 +48,7 @@ const CAPTURE_CONFIG_KEY = 'skillopt.capture_enabled';export const MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE;export function capturesDir(): string {- const home = process.env.GBRAIN_HOME ?? process.env.HOME ?? '';- return path.join(home, '.gbrain', 'skillopt-captures');+ return gbrainPath('skillopt-captures');}export function capturePath(skillName: string, runId: string): string {diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.tsindex 1040111bfe..5df732a303 100644--- a/src/core/transcripts/render.ts+++ b/src/core/transcripts/render.ts@@ -30,8 +30,8 @@* per-session id would make parts 2..N skip as cross-slug duplicates.*/+import { gbrainPath } from '../config.ts';import { dumpFrontmatterYaml } from '../data-frontmatter.ts';-import { homedir } from 'node:os';import { join } from 'node:path';import { DEFAULT_BYTES_WARN } from '../content-sanity.ts';import { applyRedaction, planRedaction, type EchoDictionary, type RedactionPlan } from '../secret-scan.ts';@@ -82,7 +82,7 @@ export const TRANSCRIPT_IMPORT_VERSION = 1;/** Default user-pattern file — the same convention skillpack harvest uses. */export function defaultUserPatternsPath(): string {- return join(homedir(), '.gbrain', 'harvest-private-patterns.txt');+ return gbrainPath('harvest-private-patterns.txt');}/**diff --git a/test/durability-cron.test.ts b/test/durability-cron.test.tsindex 84e9e9ba69..379a49bd0d 100644--- a/test/durability-cron.test.ts+++ b/test/durability-cron.test.ts@@ -40,7 +40,7 @@ describe('renderCronWrapper (D2 DB-free)', () => {});describe('generateBrainPullPlist (D12 launchd)', () => {- const plist = generateBrainPullPlist('com.gbrain.brain-pull.wiki', '/home/u/.gbrain/brain-pull-wiki.sh', '/home/u', 1800);+ const plist = generateBrainPullPlist('com.gbrain.brain-pull.wiki', '/home/u/.gbrain/brain-pull-wiki.sh', '/home/u/.gbrain', 1800);test('is periodic (StartInterval), not a KeepAlive daemon', () => {expect(plist).toContain('<key>StartInterval</key><integer>1800</integer>');@@ -124,7 +124,7 @@ describe('durabilityJobStatus — presence + liveness [D7]', () => {writeFileSync(log, 'old\n');const old = new Date(Date.now() - 3 * 60 * 60 * 1000);utimesSync(log, old, old);- await withEnv({ PATH: empty, HOME: home }, async () => {+ await withEnv({ PATH: empty, HOME: home, GBRAIN_HOME: home }, async () => {const s = durabilityJobStatus('wiki', 1800, 'linux');expect(s.logFresh).toBe(false);});diff --git a/test/features.test.ts b/test/features.test.tsindex b241d86144..201156bd64 100644--- a/test/features.test.ts+++ b/test/features.test.ts@@ -197,7 +197,7 @@ describe('runFeatures behavior', () => {writeFileSync(join(dir, 'heartbeat.jsonl'), JSON.stringify({ ts: new Date().toISOString(), event: 'setup_complete' }) + '\n');}- const offersFile = () => join(home, '.gbrain', 'feature-offers.json');+ const offersFile = () => join(gbrainHome, '.gbrain', 'feature-offers.json');async function features(env: Record<string, string | undefined> = {}) {const lines: string[] = [];@@ -229,7 +229,7 @@ describe('runFeatures behavior', () => {const saved = JSON.parse(readFileSync(offersFile(), 'utf-8'));expect(saved.lastVersion).toBe(VERSION);- expect(existsSync(join(gbrainHome, '.gbrain', 'feature-offers.json'))).toBe(false);+ expect(existsSync(join(home, '.gbrain', 'feature-offers.json'))).toBe(false);});it('a healthy, fully configured brain recommends nothing and writes no offers file', async () => {@@ -278,7 +278,7 @@ describe('runFeatures behavior', () => {it('a declined priority-2 offer is suppressed for the current version; priority-1 offers are always pitched', async () => {await seedPages(6);await seedChunks('notes/feature-0', [false]);- mkdirSync(join(home, '.gbrain'), { recursive: true });+ mkdirSync(join(gbrainHome, '.gbrain'), { recursive: true });const declinedAt = { at: '2026-01-01', version: VERSION };writeFileSync(offersFile(), JSON.stringify({lastVersion: VERSION, lastScan: '', accepted: {},diff --git a/test/gbrain-home-isolation.test.ts b/test/gbrain-home-isolation.test.tsindex 5b0440ad96..31612f52bb 100644--- a/test/gbrain-home-isolation.test.ts+++ b/test/gbrain-home-isolation.test.ts@@ -15,7 +15,7 @@*/import { describe, test, expect } from 'bun:test';-import { mkdtempSync, existsSync, readdirSync, statSync, rmSync } from 'fs';+import { mkdtempSync, mkdirSync, existsSync, readdirSync, statSync, rmSync } from 'fs';import { homedir, tmpdir } from 'os';import { join } from 'path';@@ -149,3 +149,61 @@ describe('GBRAIN_HOME write-side isolation', () => {}});});++// GBRA-133: the writers that used to build paths from homedir() run in a child+// process whose HOME is a scratch dir (so homedir() really is that dir, with no+// libuv homedir cache from this process) and whose GBRAIN_HOME is another one.+// Every file must land under <GBRAIN_HOME>/.gbrain and nothing under $HOME/.gbrain.+describe('GBRA-133: HOME=<tmp> with GBRAIN_HOME set writes nothing under $HOME/.gbrain', () => {+ test('routed writers and default paths follow GBRAIN_HOME', () => {+ const home = fresh();+ const parent = fresh();+ const gb = join(parent, '.gbrain');+ const src = join(import.meta.dir, '..', 'src');+ const script = `+ const out = {};+ const { recordUpgradeError } = await import('${src}/commands/upgrade.ts');+ recordUpgradeError({ phase: 'probe', fromVersion: '0.0.1', toVersion: '0.0.2', error: 'e', hint: 'h' });+ const mounts = await import('${src}/commands/mounts.ts');+ mounts.__testing.writeMountsFile({ version: 1, mounts: [] });+ out.mounts = mounts.__testing.getMountsPath();+ const registry = await import('${src}/core/brain-registry.ts');+ out.registryMounts = registry.__testing.getMountsPath();+ const { writeMountsCache } = await import('${src}/core/mounts-cache.ts');+ out.cache = writeMountsCache(process.env.SKILLS_DIR, []).resolverPath;+ const { appendPushLog } = await import('${src}/core/brain-repo-durability.ts');+ appendPushLog('ok', 'main', 'abcdef0123');+ const { localHostId, existingLocalHostId } = await import('${src}/core/persistence/identity.ts');+ out.host = localHostId() === existingLocalHostId();+ out.pid = (await import('${src}/core/minions/supervisor.ts')).DEFAULT_PID_FILE;+ out.captures = (await import('${src}/core/skillopt/held-out.ts')).capturesDir();+ out.patterns = (await import('${src}/core/transcripts/render.ts')).defaultUserPatternsPath();+ const eval_ = await import('${src}/commands/notability-eval.ts');+ out.mining = eval_.defaultMiningOutPath();+ out.review = eval_.defaultReviewOutPath();+ console.log(JSON.stringify(out));+ `;+ try {+ const skills = join(parent, 'skills');+ mkdirSync(skills, { recursive: true });+ const env: Record<string, string> = { ...process.env as Record<string, string>, HOME: home, GBRAIN_HOME: parent, SKILLS_DIR: skills };+ for (const k of ['GBRAIN_MOUNTS_PATH', 'GBRAIN_SUPERVISOR_PID_FILE', 'GBRAIN_AUDIT_DIR', 'USERPROFILE']) delete env[k];+ const proc = Bun.spawnSync([process.execPath, '-e', script], { env, cwd: parent });+ expect(proc.stderr.toString()).not.toContain('error:');+ expect(proc.exitCode).toBe(0);+ const out = JSON.parse(proc.stdout.toString().trim().split('\n').pop()!);+ expect(out.host).toBe(true);+ for (const key of ['mounts', 'registryMounts', 'cache', 'pid', 'captures', 'patterns', 'mining', 'review']) {+ expect(out[key].startsWith(gb + '/')).toBe(true);+ }+ for (const file of ['upgrade-errors.jsonl', 'mounts.json', 'mounts-cache/RESOLVER.md', 'brain-push.log', 'persistence/host.json']) {+ expect(existsSync(join(gb, file))).toBe(true);+ }+ expect(existsSync(join(home, '.gbrain'))).toBe(false);+ } finally {+ rmSync(home, { recursive: true, force: true });+ rmSync(parent, { recursive: true, force: true });+ }+ });+});+diff --git a/test/persistence-worktree-refresh.test.ts b/test/persistence-worktree-refresh.test.tsindex 15190f16f8..6a5b1ba1ae 100644--- a/test/persistence-worktree-refresh.test.ts+++ b/test/persistence-worktree-refresh.test.ts@@ -18,7 +18,7 @@import { afterAll, beforeAll, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';-import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';@@ -77,6 +77,24 @@ test('refresh timer bounds reject overflow and accept the maximum delay', () =>expect((await refreshWorktree(f.engine, f.alpha, drain)).status).toBe('dry_run');expect((await refreshWorktree(f.engine, f.alpha, { fetchTimeoutMs: 2 ** 31 - 1, dryRun: true })).status).toBe('dry_run');}));+test('GBRA-133: another HOME refuses refresh_not_owner naming the identity file and HOME it read, and mints no identity', () => each(async f => {+ const other = mkdtempSync(join(tmpdir(), 'gbrain-refresh-other-home-'));+ try {+ const identity = join(other, '.gbrain', 'persistence', 'host.json');+ await withEnv({ GBRAIN_HOME: other, HOME: other }, async () => {+ const missing = await refusedWith(refreshWorktree(f.engine, f.alpha, { dryRun: true }), 'refresh_not_owner');+ expect(missing.message).toContain(`no host identity at ${identity} (none was created)`);+ expect(missing.message).toContain(`HOME=${other} and GBRAIN_HOME=${other}`);+ expect(existsSync(identity)).toBe(false);+ mkdirSync(join(other, '.gbrain', 'persistence'), { recursive: true });+ const foreign = randomUUID();+ writeFileSync(identity, JSON.stringify({ version: 1, id: foreign }));+ const mismatch = await refusedWith(refreshWorktree(f.engine, f.alpha, { dryRun: true }), 'refresh_not_owner');+ expect(mismatch.message).toContain(`this process has host identity ${foreign} from ${identity}`);+ });+ expect((await refreshWorktree(f.engine, f.alpha, { dryRun: true })).status).toBe('dry_run');+ } finally { rmSync(other, { recursive: true, force: true }); }+}));/** Requeue a committed git effect so the drain must wait for the consumer to process it again. */async function requeueGitEffect(f: RefreshFixture, delayMs: number): Promise<number> {const [effect] = await f.engine.executeRaw<{ id: number }>(`SELECT id FROM persistence_effects WHERE worktree_id=$1::uuid AND kind='git' ORDER BY id DESC LIMIT 1`, [f.worktreeId]);