Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes (pass 2)
garrytan9e9ca6177cab
diff --git a/src/core/repair/private-labels.ts b/src/core/repair/private-labels.tsindex 664289e16c..b8137e1576 100644--- a/src/core/repair/private-labels.ts+++ b/src/core/repair/private-labels.ts@@ -153,7 +153,7 @@ async function planRestore(engine: BrainEngine, scope: RepairScope, selection: Sconst entries: Approved[] = [];for (const line of removals) {const page = byId.get(line.page_id);- if (!page || page.source_id !== line.source_id || page.slug !== line.slug) { counts.page_gone++; continue; }+ if (!page || page.source_id !== line.source_id) { counts.page_gone++; continue; }if (Object.keys(line.removed!).some(key => Object.hasOwn(page.frontmatter ?? {}, key))) { counts.already_restored++; continue; }counts.restorable++;entries.push({ mode: 'restore', class: 'restore', brain_id: scope.brain_id, source_id: page.source_id, slug: page.slug, page_id: Number(page.id),@@ -267,7 +267,12 @@ export const privateLabelsRepair: RepairHandler = {if (authority) await publishMaintenancePage(ctx.engine, authority, entry.slug, content, { expectedRevision: snapshot.revision, requestId, keepTrust: true });else if (!await importAtRevision(ctx.engine, entry, snapshot.revision, content, opts?.embed === true)) return changed;} catch (error) {- if (acceptedPendingReceipt(error)) item.ledger.record(line);+ if (acceptedPendingReceipt(error)) {+ try { item.ledger.record(line); } catch (ledgerError) {+ ctx.logger?.warn?.(`private-labels: ${entry.source_id}:${entry.slug} was accepted but its ledger line was not saved (${ledgerError instanceof Error ? ledgerError.message : String(ledgerError)}). `+ + `Keep these values to undo it by hand: ${describeLabels(entry.labels)}.`);+ }+ }throw error;}const outcome = entry.mode === 'clear' ? 'cleared' : 'restored';diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 0c03bf86a4..5df44750c1 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -661,7 +661,7 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'The preview lists one window (--limit, default 1000) by class (alias, alias-and-visibility) with every category\'s count before and after; '+ '--apply --expect <hash> applies exactly that window, one revision-bound page write each; a bare --apply is refused. Pages in git-canonical sources '+ '(git-publish: clearing commits them into Git) run only with --class git-publish. Each cleared label is recorded in '- + '$GBRAIN_HOME/repair/private-labels/<brain>.jsonl, and --class restore re-adds it. Runs only when named; never on upgrade.',+ + '~/.gbrain/repair/private-labels/<brain>.jsonl (under $GBRAIN_HOME/.gbrain/ if set), and --class restore re-adds it. Runs only when named; never on upgrade.',},'generations': {handler: generationsRepair, embeds: 'effect', checks: ['generation_retirements', 'generation_held', 'generation_pending'], explicit_only: true, preview_bound: true, consent: 'destructive',diff --git a/test/repair-private-labels.test.ts b/test/repair-private-labels.test.tsindex 53e3237b7c..e222e8c2db 100644--- a/test/repair-private-labels.test.ts+++ b/test/repair-private-labels.test.ts@@ -16,7 +16,7 @@*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -349,6 +349,7 @@ describe('repair private-labels --class git-publish on a git-canonical source',execFileSync('git', ['init', '-q'], { cwd: root });execFileSync('git', ['-c', 'user.name=example', '-c', '[email protected]', 'commit', '-q', '--allow-empty', '-m', 'init'], { cwd: root });await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2) ON CONFLICT (id) DO NOTHING', [source, root]);+ await seed('notes/nofile', 'note', { topic: 'shared' }, source);await engine.executeRaw('UPDATE sources SET config = $2::jsonb WHERE id = $1', [source, JSON.stringify({ canonical: 'git' })]);await engine.setConfig('sync.write_through', 'true');await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');@@ -361,6 +362,9 @@ describe('repair private-labels --class git-publish on a git-canonical source',await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/g', request_id: crypto.randomUUID(),content: serializeMarkdown({ access: 'private', topic: 'kept' }, body('notes/g'), '', { type: 'note' as never, title: 'notes/g', tags: ['t1'] }) } });expect(existsSync(join(root, 'notes', 'g.md'))).toBe(false);+ const missing = await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/nofile', request_id: crypto.randomUUID(), expected_revision: (await row('notes/nofile', source)).revision,+ content: serializeMarkdown({ topic: 'edited' }, body('notes/nofile'), '', { type: 'note' as never, title: 'notes/nofile', tags: ['t1'] }) } }).then(() => null, (error: unknown) => error);+ expect(String((missing as Error | null)?.message)).toContain('The canonical file was removed outside coordinated publication.');const before = await row('notes/g', source);const preview = await json(['private-labels', '--source', source, '--class', 'git-publish']);expect(preview.listing).toEqual([{ item: source + ':notes/g', class: 'git-publish', detail: 'remove access: private' }]);@@ -393,26 +397,29 @@ describe('repair private-labels --class git-publish on a git-canonical source',});describe('repair private-labels when the undo ledger cannot record', () => {- test('a clear whose ledger line fails to save still reports the page as applied and names the removed values', async () => {+ test('a clear whose ledger line fails to save still reports the page as applied and names the removed values; restore then says where to run', async () => {const source = 'source-h';- await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);- await seed('notes/h', 'note', { access: 'private' }, source);- const preview = await json(['private-labels', '--source', source]);- const ledger = preview.details.ledger as string;- chmodSync(ledger, 0o400);+ const home = mkdtempSync(join(tmpdir(), 'gbrain-private-labels-ledger-'));+ mkdirSync(join(home, '.gbrain', 'repair'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'repair', 'private-labels'), 'a file where the ledger directory belongs');+ const runIn = async (argv: string[]) => {+ const out = JSON.parse(await withEnv({ GBRAIN_HOME: home, GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() => runRepairCommand(engine, [...argv, '--json'])))).results[0];+ _resetCliExitVerdictForTests();+ return out;+ };try {- const applied = await json(['private-labels', '--source', source, '--apply', '--expect', preview.preview_hash]);+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);+ await seed('notes/h', 'note', { access: 'private' }, source);+ const preview = await runIn(['private-labels', '--source', source]);+ const applied = await runIn(['private-labels', '--source', source, '--apply', '--expect', preview.preview_hash]);expect(applied.failed).toEqual([]);expect(applied.applied).toBe(1);expect(JSON.stringify(applied)).toContain('access: private');expect('access' in (await row('notes/h', source)).frontmatter).toBe(false);- } finally { chmodSync(ledger, 0o600); }- });-- test('a restore preview with no ledger line for this brain says where restore has to run', async () => {- const preview = await json(['private-labels', '--source', 'source-h', '--class', 'restore']);- expect(preview.listing ?? []).toEqual([]);- expect(preview.warnings.some((w: string) => w.includes('has no line for brain') && w.includes(preview.details.ledger))).toBe(true);+ const restore = await runIn(['private-labels', '--source', source, '--class', 'restore']);+ expect(restore.listing ?? []).toEqual([]);+ expect(restore.warnings.some((w: string) => w.includes('has no line for brain') && w.includes(restore.details.ledger))).toBe(true);+ } finally { rmSync(home, { recursive: true, force: true }); }});});