Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(schema-pack): pack_upgrade_available tells the truth on managed brains; empty retypes switch the pack (#6196)
garrytan21bf5d665653
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex 13ad9a5bd5..3b8a6b1986 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -9,6 +9,7 @@ Key files:- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `atomic-long-staging.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.- `src/core/fs-durable.ts` — the shared durable-flush leaf (imports only `node:fs`). `flushFile(path)` fsyncs a file nobody holds open through `'r+'` on win32 (Windows `FlushFileBuffers` needs write access) and `'r'` elsewhere (a 0444 file stays flushable); a read-only file on win32 cannot be opened writable and is left to the OS. `flushDirectory(path, { bestEffort })` is strict by default: every error propagates except the win32 no-directory-flush codes (`EISDIR`/`EPERM`/`EINVAL`/`ENOTSUP`), a non-directory path fails `ENOTDIR`, and `bestEffort` swallows everything. `sameFileMode(actual, expected)` compares every permission bit on POSIX and only the owner write bit on win32, whose stat reports 0444/0666. A writer that still holds its descriptor sets the mode with `fchmodSync(fd)` and fsyncs that descriptor instead (atomic-write, skill-bundle staging). Callers: atomic-write, the persistence coordinator, identity, root registry, physical-root records, reconcile backups, recovery staging, topology checkouts (`flushTopologyDirectory` re-export, `flushTopologyTree`), skill bundles, agent-install state (`syncDirectory` re-export), `sources reconcile` previews and attendance-repair checkpoints. `scripts/check-durable-flush.ts` keeps new read-handle flushes out of `src/` (docs/TESTING.md#durable-flush-guard). Tests: `test/fs-durable.test.ts`, `test/persistence-windows-flush-5595.test.ts`, `test/bundle-files-windows-5475.test.ts`, `test/init-packaged-skills-native.test.ts`, run natively on windows-latest in the test.yml security-regressions job.- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique short hidden tmp sibling from `atomicStagingPath` (`.<sha256(full target path)>.tmp.<uuid>`, so a valid basename near NAME_MAX still stages, #5861; `validateAtomicStagingPath` also accepts the historical `<target>.tmp.<uuid>` journal form, and recovery (`persistence/staging.ts` `upgradeRecoveryStaging`) durably swaps in a short stage only for a recorded historical leaf that returns ENAMETOOLONG; `timeline-write-through.ts` reuses the same allocator) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → parent-directory fsync through `fs-durable.ts` `flushDirectory` (rename durability; strict under `durable`, the journaled-publication flag, best-effort otherwise). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.+- `src/core/schema-pack/unify-types-handler.ts` + `src/core/onboard/checks.ts` (`checkPackUpgradeAvailable`) — pack-upgrade retype (`runUnifyTypes`, the `unify-types` job). #6196: on a managed brain apply runs the dry run first (`applyOnManagedBrain`): with nothing to retype, link or alias it only switches the active pack (`flipActivePack`, DB + file plane); otherwise it refuses `writer_coordinator_required` with the counts and a read-only `gbrain onboard --check --explain` fix before any lock or write, and the dry run warns that apply waits for coordinated retype. `pack_upgrade_available` on a managed brain is an info row (`readiness_state: degraded`) with that preview as its fix and no `unify-types` apply remediation it could not run. Coordinated retype (D2) is deferred.- `src/core/schema-pack/pack-lock.ts` — Atomic `O_CREAT|O_EXCL` per-pack lock. DELIBERATELY NOT the `existsSync + writeFileSync` TOCTOU shape from `src/core/page-lock.ts`. Default 60s TTL, refresh every 10s while `withPackLock(fn)` runs, `--force` semantics = "steal stale lock" NOT "skip locking." Lock path per-pack so two packs never block each other.- `src/core/schema-pack/write-vocabulary.ts` — write-time pack-vocabulary enforcement shared by the write surfaces (capture op, `add_link` op, `gbrain capture` CLI). `loadActivePackForWriteVocabulary(ctx)` pairs the engine's DB-plane `schema_pack` key with FILE-ONLY config (the `loadActivePackForLocalEngine` posture) while threading `remote` (fail-closed: anything not strictly false is remote) + `sourceId`; NEVER throws — null means "no resolvable pack", which callers MUST treat as "no vocabulary to enforce" (the write proceeds exactly as before). `packDeclaresPageType`/`packDeclaresLinkType` + message/suggestion formatters reject an EXPLICIT undeclared name with the pack's declared vocabulary in the error so agents self-correct without a `gbrain schema explain` round-trip. The DEFAULT `note` path is never checked here — callers validate EXPLICIT names only, so bare `gbrain capture` works under a pack that doesn't declare `note`. `loadActivePackForWriteVocabulary` also swallows a rejecting `getConfig`; `previewNames` bounds the vocabulary preview in the error (the first 12 names + `(N total)`). Pinned by `test/write-vocabulary.test.ts`.- `src/core/schema-pack/mutate-audit.ts` — ISO-week JSONL at `~/.gbrain/audit/schema-mutations-YYYY-Www.jsonl`. Privacy-redacted: type names → sha8, prefixes → first slug segment only, matches `candidate-audit.ts` privacy posture. Logs BOTH success AND failure events so a future `schema_pack_writability` doctor check has signal. `summarizeMutations()` is the cross-surface parity primitive.diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex a8dd5d4657..2a551463ac 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -51,7 +51,6 @@ src/core/ops/facts.ts recall.handler 348 seed: W5 baseline, refactor wave 1 (decsrc/core/ops/search.ts query.handler 332 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 GBRA-49 explain_target: one TargetTrace prep line and its HybridSearchOpts thread (diagnosis/meta live in prepareExplainTarget/finishExplainTarget)src/core/progressive-batch/orchestrator.ts runProgressiveBatch 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/remediation/run.ts runRemediation 428 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/schema-pack/unify-types-handler.ts runUnifyTypes 310 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/skillopt/orchestrator.ts runOptimizationLoop 704 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/skillopt/orchestrator.ts runOptimizationLoop>withBudgetTracker(#1) 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/sources-ops.ts addSource 317 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 6a72819002..cf31038418 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -261,6 +261,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.0.0-wave11', text: 'On a managed canonical worktree the session hooks no longer start `gbrain sources push` (it refuses there; heartbeat reason `push_managed_coordinator`), backup check no longer counts gbrain\'s `.gbrain-owner.json` as uncommitted work and points managed roots at `gbrain sources writer status --probe --json`, a root with no origin remote reads `no_remote` even after a recorded push refusal, and doctor `bootstrap_push_health` reports ok once a recorded push failure\'s tree matches its origin branch.' },{ since: '0.0.0-wave11', text: 'The MCP initialize instructions are reordered so harnesses that read only the first 2,048 characters (Claude Code) get the essentials: with ambient writeback on, a one-line writeback contract now sits in the memory clause (the full rules stay last), the error protocol follows the data-not-instructions clause in a shorter form, and the forget caveat moved after the scope clause.' },{ since: '0.0.0-wave11', text: '`gbrain skillpack scaffold --harness` prints its Update lens and remove hints with the `--dest`, `--scope` and `--workspace` you passed, and `gbrain skillpack reference --harness <h>` with no slug no longer exits 2 on the shared-dependency ledger entry.' },+ { since: '0.0.0-wave11', text: 'On a managed brain, doctor `pack_upgrade_available` is now an info row with a read-only preview instead of an apply step it could not run, and `unify-types` apply switches the pack when nothing needs retyping (it still refuses, now naming the counts, when pages would change).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.tsindex de60ff9030..581710f0eb 100644--- a/src/core/onboard/checks.ts+++ b/src/core/onboard/checks.ts@@ -572,6 +572,19 @@ export async function checkPackUpgradeAvailable(};}const successor = successors[0];+ const { managedPersistenceEnabled } = await import('../persistence/ownership.ts');+ if (await managedPersistenceEnabled(engine)) {+ // #6196: retype runs outside the persistence coordinator, so a managed brain cannot run the apply job.+ return {+ check: {+ name: 'pack_upgrade_available', status: 'ok', severity: 'info', readiness_state: 'degraded',+ message: `Active pack: ${active.identity}. Successor available: ${successor.identity}. On a managed brain unify-types switches the pack only when no page needs retyping, linking or aliasing; coordinated retype is not available yet, so do not submit the apply job while the preview shows pages to change. Preview: \`gbrain onboard --check --explain\``,+ fix: { argv: ['gbrain', 'onboard', '--check', '--explain'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Previews the pack upgrade read-only. Applying it on a managed brain waits for coordinated retype unless the preview shows nothing to change.' },+ },+ remediations: [],+ };+ }return {check: {name: 'pack_upgrade_available',diff --git a/src/core/schema-pack/unify-types-handler.ts b/src/core/schema-pack/unify-types-handler.tsindex 8537f78d6c..6ff1996f83 100644--- a/src/core/schema-pack/unify-types-handler.ts+++ b/src/core/schema-pack/unify-types-handler.ts@@ -37,7 +37,8 @@ import { runStatsCore } from './stats.ts';import { runSyncCore } from './sync.ts';import { tryAcquireDbLock, type DbLockHandle } from '../db-lock.ts';import type { PackMappingRule } from './manifest-v1.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';export interface UnifyTypesInput {@@ -70,19 +71,58 @@ export interface UnifyTypesResult {warnings: string[];}+const MANAGED_PREVIEW_WARNING = 'unify-types apply is not supported on a managed brain while pages need retyping, linking or aliasing; with nothing to change, apply only switches the pack. This dry run is a preview.';+/**- * #5634: the retype, link and alias phases write canonical tables outside the- * persistence coordinator, which a managed brain refuses mid-run. Apply is- * refused before the lock or any write; the dry run still previews.+ * #5634 / #6196: the retype, link and alias phases write canonical tables+ * outside the persistence coordinator, which a managed brain refuses mid-run.+ * A managed apply runs the dry run first: with nothing to change it only+ * switches the active pack (config writes are allowed there); otherwise it+ * refuses with the counts before the lock or any write.*/-async function managedApplyWarnings(ctx: OperationContext, targetPack: string, apply: boolean): Promise<string[]> {- if (!await managedPersistenceEnabled(ctx.engine)) return [];- if (apply) {- throw new OperationError('writer_coordinator_required',- 'unify-types apply is not supported on a managed brain: its retype runs outside the persistence coordinator. No page was changed.',- `Preview the plan with gbrain jobs submit unify-types --params '${JSON.stringify({ target_pack: targetPack })}'. Coordinated retype is not available yet.`);+async function applyOnManagedBrain(ctx: OperationContext, input: UnifyTypesInput): Promise<UnifyTypesResult> {+ const preview = await runUnifyTypes(ctx, { ...input, apply: false });+ const p = preview.per_phase;+ const counts = [+ [p.retype_explicit.would_apply + p.retype_catch_all.would_apply + p.final_sync.total_would_apply, 'to retype'],+ [p.page_to_link.would_convert, 'to convert to links'],+ [p.page_to_alias.would_alias, 'to convert to aliases'],+ ] as const;+ if (counts.some(([n]) => n > 0)) {+ throw opError('writer_coordinator_required',+ `unify-types apply is not supported on a managed brain while pages need changing (${counts.filter(([n]) => n > 0).map(([n, what]) => `${n} page(s) ${what}`).join(', ')}): its retype runs outside the persistence coordinator. No page was changed.`,+ 'Coordinated retype is not available yet; keep the current pack and preview the upgrade read-only.',+ { fix: readFix('Previews the pack upgrade read-only; applying waits for coordinated retype on a managed brain.', { argv: ['gbrain', 'onboard', '--check', '--explain'] }) });}- return ['unify-types apply is not supported on a managed brain; this dry run is a preview only.'];+ const warnings = preview.warnings.filter((w) => w !== MANAGED_PREVIEW_WARNING);+ const pack_identity_after = await flipActivePack(ctx, input.target_pack, warnings, input.onProgress ?? (() => {}), preview.pack_identity_before);+ return { ...preview, apply: true, pack_identity_after, active_pack_flipped: true, warnings };+}++/** D13: write schema_pack to the DB config and the file plane; returns the new pack identity. */+async function flipActivePack(ctx: OperationContext, targetPack: string, warnings: string[], onProgress: (msg: string) => void, identityBefore: string | null): Promise<string> {+ // Write to BOTH:+ // - DB config (engine.setConfig) — covers federated/multi-source brains+ // where future loadActivePack calls thread dbConfig from `config` table.+ // - File-plane config (saveConfig) — covers loadActivePack({ cfg, ... })+ // callers that read from ~/.gbrain/config.json (homeConfig tier).+ // Without the file-plane write the local CLI loadActivePack callers+ // wouldn't see the flip and pack_upgrade_available would keep firing.+ await ctx.engine.setConfig('schema_pack', targetPack);+ try {+ const { loadConfigFileOnly, saveConfig } = await import('../config.ts');+ const existing = loadConfigFileOnly() ?? ({} as Record<string, unknown>);+ saveConfig({ ...existing, schema_pack: targetPack } as never);+ } catch (e) {+ warnings.push(+ `Active-pack flip wrote to DB but file-plane saveConfig failed: ` ++ `${(e as Error).message}. Run \`gbrain schema use ${targetPack}\` ` ++ `manually to ensure local CLI sees the flip.`,+ );+ }+ const activeAfter = await loadActivePack({ cfg: { schema_pack: targetPack } as never, remote: false });+ onProgress(`[unify-types] active pack flipped: ${identityBefore} → ${activeAfter.identity}`);+ return activeAfter.identity;}/**@@ -100,7 +140,9 @@ export async function runUnifyTypes(const apply = input.apply === true;const sourceId = input.sourceId;const onProgress = input.onProgress ?? (() => {});- const warnings = await managedApplyWarnings(ctx, input.target_pack, apply);+ const managed = await managedPersistenceEnabled(ctx.engine);+ if (managed && apply) return applyOnManagedBrain(ctx, input);+ const warnings = managed ? [MANAGED_PREVIEW_WARNING] : [];onProgress(`[unify-types] starting (apply=${apply}, target_pack=${input.target_pack})`);@@ -286,32 +328,8 @@ export async function runUnifyTypes(let active_pack_flipped = false;let pack_identity_after = pack_identity_before;if (apply) {- // Write to BOTH:- // - DB config (engine.setConfig) — covers federated/multi-source brains- // where future loadActivePack calls thread dbConfig from `config` table.- // - File-plane config (saveConfig) — covers loadActivePack({ cfg, ... })- // callers that read from ~/.gbrain/config.json (homeConfig tier).- // Without the file-plane write the local CLI loadActivePack callers- // wouldn't see the flip and pack_upgrade_available would keep firing.- await ctx.engine.setConfig('schema_pack', input.target_pack);- try {- const { loadConfigFileOnly, saveConfig } = await import('../config.ts');- const existing = loadConfigFileOnly() ?? ({} as Record<string, unknown>);- saveConfig({ ...existing, schema_pack: input.target_pack } as never);- } catch (e) {- warnings.push(- `Active-pack flip wrote to DB but file-plane saveConfig failed: ` +- `${(e as Error).message}. Run \`gbrain schema use ${input.target_pack}\` ` +- `manually to ensure local CLI sees the flip.`,- );- }+ pack_identity_after = await flipActivePack(ctx, input.target_pack, warnings, onProgress, pack_identity_before);active_pack_flipped = true;- const activeAfter = await loadActivePack({- cfg: { schema_pack: input.target_pack } as never,- remote: false,- });- pack_identity_after = activeAfter.identity;- onProgress(`[unify-types] active pack flipped: ${pack_identity_before} → ${pack_identity_after}`);}// 7. Verifydiff --git a/test/onboard-pack-upgrade-checks.test.ts b/test/onboard-pack-upgrade-checks.test.tsindex fb4e3f3d2c..f1367ac81f 100644--- a/test/onboard-pack-upgrade-checks.test.ts+++ b/test/onboard-pack-upgrade-checks.test.ts@@ -75,6 +75,23 @@ describe('checkPackUpgradeAvailable', () => {});});+ it('#6196: a managed brain gets an honest info row and no apply remediation it cannot run', async () => {+ await withEnv({ GBRAIN_HOME: emptyHome(), GBRAIN_SCHEMA_PACK: undefined }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ const result = await checkPackUpgradeAvailable(engine);+ expect(result.check.status).toBe('ok');+ expect(result.check.severity).toBe('info');+ expect(result.check.message).toContain('gbrain-base-v2');+ expect(result.check.message).toContain('managed brain');+ expect(result.remediations).toEqual([]);+ expect(result.check.fix?.argv).toEqual(['gbrain', 'onboard', '--check', '--explain']);+ } finally {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ });+ });+it('honors file-plane schema_pack when DB config is unset', async () => {const home = mkdtempSync(join(tmpdir(), 'gbrain-pack-upgrade-'));const configDir = join(home, '.gbrain');diff --git a/test/unify-types-managed-refusal.test.ts b/test/unify-types-managed-refusal.test.tsindex ee0930e6fe..e570921b32 100644--- a/test/unify-types-managed-refusal.test.ts+++ b/test/unify-types-managed-refusal.test.ts@@ -76,3 +76,41 @@ test('an unmanaged dry run carries no managed warning', async () => {_resetPackCacheForTests();}}, 60_000);++test('#6196: on a managed brain with nothing to retype, apply switches the pack without touching a page', async () => {+ const unifyHome = mkdtempSync(join(tmpdir(), 'gbrain-unify-managed-empty-'));+ try {+ await managedBrain(async ({ ctx, engine }) => {+ _resetPackCacheForTests();+ const before = await types(engine);+ await withEnv({ GBRAIN_HOME: unifyHome }, async () => {+ const r = await runUnifyTypes(ctx, { target_pack: 'gbrain-base-v2', apply: true });+ expect(r.active_pack_flipped).toBe(true);+ expect(r.per_phase.retype_explicit.applied).toBe(0);+ expect(await engine.getConfig('schema_pack')).toBe('gbrain-base-v2');+ });+ expect(await types(engine)).toEqual(before);+ });+ } finally {+ rmSync(unifyHome, { recursive: true, force: true });+ _resetPackCacheForTests();+ }+}, 120_000);++test('#6196: a managed refusal names what would change and how to preview it', async () => {+ const unifyHome = mkdtempSync(join(tmpdir(), 'gbrain-unify-managed-counts-'));+ try {+ await managedBrain(async ({ ctx }) => {+ _resetPackCacheForTests();+ await withEnv({ GBRAIN_HOME: unifyHome }, async () => {+ const error = await runUnifyTypes(ctx, { target_pack: 'gbrain-base-v2', apply: true }).catch((e: unknown) => e) as { code?: string; message?: string; fix?: { argv?: string[] } };+ expect(error.code).toBe('writer_coordinator_required');+ expect(error.message).toMatch(/\d+ page\(s\) to retype/);+ expect(error.fix?.argv).toEqual(['gbrain', 'onboard', '--check', '--explain']);+ });+ }, { setup: seed });+ } finally {+ rmSync(unifyHome, { recursive: true, force: true });+ _resetPackCacheForTests();+ }+}, 120_000);