Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sources): retire a zero-page sole-member source whose checkout vanished (#5219)
garrytan83a05825e65c
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex f355db9d42..82c14a8c9a 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -58,6 +58,7 @@ of making a duplicate.| <a id="writer_admin_locked"></a>`writer_admin_locked` | `writer_admin_locked` | The operator set the brain's writer admin lock (`gbrain sources writer lock`), so writer claim, activate, transfer prepare and transfer accept refuse for every caller. Ordinary writes are not affected. | Agents: stop and ask the operator; do not unlock it yourself. The operator runs, on the brain host, `gbrain sources writer unlock`, re-reads `gbrain sources writer status <source> --json`, administers, then `gbrain sources writer lock` again. See the [writer admin lock](../architecture/topologies.md#writer-admin-lock). || <a id="writer_not_quiesced"></a>`writer_not_quiesced` | `writer_not_quiesced` | Activation found an older writer, a legacy lock, or queued, running or recovering work. When work blocks it, the message names the blocking effect id, kind, source, page and request id. | Stop the writers named in the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook), inspect the named work with `gbrain sources writer status <source> --json`, let it finish, then retry. A committed write whose embedding effect is stuck queued or failed is settled by `gbrain repair embedding-effects --source <source>` (preview), then the same command with `--apply`; see [stale queued embedding effects](repair.md#stale-queued-embedding-effects). || <a id="activation_source_path_missing"></a>`source_path_missing` | `source_changed` | `gbrain sources writer activate` (with or without `--dry-run`) found a source whose recorded `local_path` no longer exists on this host, for example a checkout that lived in a temporary directory. Activation cannot verify that source's canonical directory, so nothing changed. The message names the source and the missing path. Claiming the source at another directory does not help while the stale path stays recorded. | Run the command the suggestion prints: `gbrain sources set-path <source> <directory>` to point the source at its checkout (the suggestion fills in the claimed directory when the source is claimed), or `gbrain sources remove <source> --confirm-destructive` when the source is no longer needed (`gbrain sources archive <source>` keeps a 72-hour grace period). Then `gbrain sources writer activate --confirm-quiesced --dry-run` and activate. |+| <a id="source_checkout_missing"></a>canonical checkout missing | `recovery_required` | A managed source lifecycle command (`gbrain sources archive`, `remove`, `purge`, `restore`, `rebind`) found that the source's canonical checkout directory was deleted out of band. A source with **no pages** that is the **only** source on that checkout is retired anyway: archive, remove and purge succeed and the receipt records `retired_without_checkout` with the missing path. Otherwise nothing changed; the message names the path, the page count and how many other sources share the checkout. Recreating an empty directory at the same path does not help (its physical identity differs). | Restore the checkout (for example from a backup) and retry. If it is gone for good, switch the brain to classic mode with `gbrain sources writer deactivate --dry-run`, then the printed `apply_command` (see the [deactivate runbook](../architecture/topologies.md#deactivate-runbook)), and retire the source there with `gbrain sources archive <source>`. || <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. || <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull --retry-failed`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). || unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex fc666eea70..02cac53292 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -39,6 +39,7 @@ export const ERROR_CATALOGUE = {embedding_auth_failed: { code: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed' },activation_source_path_missing: { code: 'source_changed', docs: 'docs/guides/write-refusals.md#activation_source_path_missing' },facts_absorb_write_refused: { code: 'facts_absorb_write_refused', docs: 'docs/guides/write-refusals.md#facts_absorb_write_refused' },+ source_checkout_missing: { code: 'recovery_required', docs: 'docs/guides/write-refusals.md#source_checkout_missing' },managed_pull_skipped: { code: 'managed_pull_skipped', docs: 'docs/guides/write-refusals.md#managed_pull_skipped' },} as const satisfies Record<string, CatalogueEntry>;diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex 4f074d811d..31b59fcd93 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -4,6 +4,7 @@ import { existsSync, mkdirSync, realpathSync, statSync } from 'node:fs';import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';+import { catalogueError } from '../error-catalogue.ts';import { isValidSourceId } from '../source-id.ts';import { parseSourceConfig } from '../sources-load.ts';import { redactSourceConfig } from '../source-config-redact.ts';@@ -71,6 +72,19 @@ export async function installTopologyBinding(tx:BrainEngine,sourceId:string,incareturn id;}+/** #5219: the refusal for a vanished canonical checkout, with its exits. */+function missingCheckoutError(sourceId:string,path:string,state?:{pages:number;members:number}):OperationError{+ return catalogueError('source_checkout_missing',+ `The canonical checkout ${path} of source '${sourceId}' is missing; restore its verified manifest first.`+(state+ ?` Only a source with no pages that is its checkout's sole member can be retired without it (pages: ${state.pages}, other sources on the checkout: ${state.members}).`:''),+ `Restore the checkout at ${path} and retry, or switch the brain to classic mode with gbrain sources writer deactivate --dry-run (then the printed apply_command) and retire the source there with gbrain sources archive ${sourceId}.`);+}+async function assertRetirableWithoutCheckout(tx:BrainEngine,sourceId:string,path:string):Promise<void>{+ const [state]=await tx.executeRaw<{pages:number;members:number}>(`SELECT (SELECT count(*)::int FROM pages WHERE source_id=$1) AS pages,+ (SELECT count(*)::int FROM persistence_source_bindings b JOIN persistence_source_bindings o ON o.worktree_id=b.worktree_id AND o.source_id<>b.source_id WHERE b.source_id=$1) AS members`,[sourceId]);+ if(Number(state.pages)>0||Number(state.members)>0) throw missingCheckoutError(sourceId,path,{pages:Number(state.pages),members:Number(state.members)});+}+/** One source transition; shared-root members are fenced and invalidated together. */export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLifecycleInput, admission?: {before(tx: BrainEngine): Promise<void>;@@ -105,8 +119,14 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL// Hash canonical bytes while holding native exclusion, without a database// connection checked out. The final transaction rejects new pending mirrors.const manifests=new Map<string,WorktreeManifest>();+ let missingCheckout:string|undefined;for(const path of new Set([...bindings.map(binding=>binding.local_path!).filter(Boolean),...(root?[root.worktree]:[])])) {- if(!existsSync(path)) {if(input.operation==='add'&&input.createDirectory&&path===root?.worktree)continue;throw new OperationError('recovery_required','The canonical checkout is missing; restore its verified manifest first.');}+ if(!existsSync(path)) {+ if(input.operation==='add'&&input.createDirectory&&path===root?.worktree)continue;+ // #5219: retiring may skip a vanished checkout; the transaction proves the source is empty and its sole member.+ if(['archive','remove','purge'].includes(input.operation)&&!root){missingCheckout=path;continue;}+ throw missingCheckoutError(input.sourceId,path);+ }const manifest=worktreeManifest(path,{progress:humanManifestProgress()});if(Buffer.byteLength(JSON.stringify(manifest))>1_048_576) throw new OperationError('request_too_large','The verified source manifest exceeds the 1 MiB administration metadata bound.');manifests.set(path,manifest);@@ -125,6 +145,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLif(input.operation==='add'&&source&&(!root||source.local_path!==null)) throw new OperationError('source_id_taken','Source ID is already registered.');if(input.operation==='purge'&&!input.expiredOnly&&!source?.archived) throw new OperationError('invalid_params','Only an archived source can be purged.');if(['remove','purge'].includes(input.operation)&&!input.confirmDestructive) throw new OperationError('invalid_params','Source removal requires explicit destructive confirmation.');+ if(missingCheckout) await assertRetirableWithoutCheckout(tx,input.sourceId,missingCheckout);const worktrees=bindings.map(binding=>binding.worktree_id);const currentBinding=bindings.find(binding=>binding.source_id===input.sourceId);const sameBinding=!!root&&!!currentBinding?.local_path&¤tBinding.local_path===root.worktree@@ -189,6 +210,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL// stale installations cannot write after a source moved or disappeared.await refreshManagedFilesystemRoots(tx,managedFilesystemDatastorePath(engine));return {operation:input.operation,source_id:input.sourceId,source_incarnation:incarnation,invalidated_requests:invalidated,+ ...(missingCheckout?{retired_without_checkout:missingCheckout}:{}),...(root?{local_path:root.source}:{}),...(['remove','purge'].includes(input.operation)?{storage_retained:true,local_path:ownedSourcePath??null,pages_deleted:pagesDeleted}:{}),...(input.operation==='add'?{name:input.name??source?.name??input.sourceId,config:redactSourceConfig({...source?.config,...input.config}),id:input.sourceId}: {})};});diff --git a/test/source-retire-missing-checkout.test.ts b/test/source-retire-missing-checkout.test.tsnew file mode 100644index 0000000000..b246993b41--- /dev/null+++ b/test/source-retire-missing-checkout.test.ts@@ -0,0 +1,109 @@+/**+ * #5219: on a managed brain, archive/remove/purge of a source whose canonical+ * checkout was deleted out of band succeeds for a zero-page source that is its+ * checkout's sole member (the receipt records `retired_without_checkout`). A+ * source with pages, or one sharing its checkout, keeps refusing+ * `recovery_required`, now naming the counts and the exits.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { flagRejection, gbrainInvocations, liveCliVerbs } from './helpers/cli-command-surface.ts';++function expectRunnableFix(fix: string) {+ const invocations = [...fix.matchAll(/gbrain [^,;()]+/g)].flatMap(m => gbrainInvocations(m[0].replace(/\.$/, '').trim()));+ expect(invocations.length).toBeGreaterThan(1);+ for (const inv of invocations) {+ expect(liveCliVerbs().has(inv.verb)).toBe(true);+ expect(flagRejection(inv)).toBeNull();+ }+}++const databaseUrl = process.env.DATABASE_URL;+for (const flavor of ['pglite', ...(databaseUrl ? ['postgres'] : [])] as const) describe(`retire a source whose checkout vanished (${flavor})`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (flavor === 'postgres') { const pg = await isolatedPersistencePostgres(databaseUrl!); engine = pg.engine; closePostgres = pg.close; }+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => { if (!engine) return; await disposePersistenceConsumer(engine); if (closePostgres) await closePostgres(); else await engine.disconnect(); });++ /** Claims each source at its own directory (or a shared Git root), seeds while classic, activates, then deletes the checkout. */+ async function fixture(sources: string[], opts: { shared?: boolean; seed?: (source: string) => Promise<void> }, run: (home: string, gone: string) => Promise<void>) {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-retire-missing-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ if (flavor === 'pglite') await resetPgliteState(engine as PGLiteEngine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await registerLocalWriter(engine, 'cli');+ const checkout = join(home, 'profile');+ mkdirSync(checkout);+ if (opts.shared) execFileSync('git', ['init', '--quiet', checkout]);+ for (const source of sources) {+ const root = opts.shared ? join(checkout, source) : checkout;+ mkdirSync(root, { recursive: true });+ writeFileSync(join(root, 'example.md'), '---\ntitle: Example\ntype: note\n---\n\nCanonical\n');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);+ await claimWorktree(engine, source, root);+ await opts.seed?.(source);+ }+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ rmSync(checkout, { recursive: true, force: true });+ try { await run(home, checkout); }+ finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const source of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [source]);+ }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }++ test('a zero-page sole-member source archives, then purges, with a receipt naming the missing checkout', () => fixture(['empty-profile'], {}, async (_home, gone) => {+ const archived = await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'empty-profile' });+ expect(archived).toMatchObject({ operation: 'archive', source_id: 'empty-profile', retired_without_checkout: gone });+ expect((await engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', ['empty-profile']))[0].archived).toBe(true);+ const purged = await runManagedSourceLifecycle(engine, { operation: 'purge', sourceId: 'empty-profile', confirmDestructive: true });+ expect(purged).toMatchObject({ operation: 'purge', pages_deleted: 0, retired_without_checkout: gone });+ expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', ['empty-profile'])).toEqual([]);+ }), 60_000);++ test('a zero-page sole-member source can be removed directly', () => fixture(['empty-remove'], {}, async (_home, gone) => {+ const removed = await runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: 'empty-remove', confirmDestructive: true });+ expect(removed).toMatchObject({ operation: 'remove', pages_deleted: 0, retired_without_checkout: gone });+ expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', ['empty-remove'])).toEqual([]);+ expect(await engine.executeRaw('SELECT source_id FROM persistence_source_bindings WHERE source_id=$1', ['empty-remove'])).toEqual([]);+ }), 60_000);++ test('a source with pages keeps refusing, naming its page count and the exits', () => fixture(['with-pages'], {+ seed: async source => { await engine.putPage('notes/kept', { type: 'note', title: 'Kept', compiled_truth: 'Still here.' }, { sourceId: source }); },+ }, async (_home, gone) => {+ const error = await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'with-pages' }).catch((e: Error) => e) as Error & Record<string, string>;+ expect(error).toMatchObject({ code: 'recovery_required', docs: 'docs/guides/write-refusals.md#source_checkout_missing' });+ expect(error.message).toContain(`The canonical checkout ${gone} of source 'with-pages' is missing`);+ expect(error.message).toContain('(pages: 1, other sources on the checkout: 0)');+ expect(error.suggestion).toContain('gbrain sources writer deactivate --dry-run');+ expect(error.suggestion).toContain('gbrain sources archive with-pages');+ expectRunnableFix(error.suggestion);+ expect((await engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', ['with-pages']))[0].archived).toBe(false);+ }), 60_000);++ test('an empty source sharing its vanished checkout with another source keeps refusing', () => fixture(['shared-first', 'shared-second'], { shared: true }, async () => {+ const error = await runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: 'shared-first', confirmDestructive: true }).catch((e: Error) => e) as Error & Record<string, string>;+ expect(error).toMatchObject({ code: 'recovery_required' });+ expect(error.message).toContain('(pages: 0, other sources on the checkout: 1)');+ expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', ['shared-first'])).toHaveLength(1);+ }), 60_000);+});