Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): a file-drift apply parses its preview artifact once and reports each page on stderr (GBRA-133)
garrytanc6b84c4ca659
diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 26c206a36e..f247e7e5b3 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2166,7 +2166,7 @@ gbrain repair file-drift --source <id> --held --side deleted --state file_gone -gbrain repair file-drift --source <id> --held --side deleted --state file_gone --cursor <next_cursor> --prefer database # window 2```-Apply each window (or decide not to), then preview the next one. Pages the+The apply reports each page on stderr as well. Apply each window (or decide not to), then preview the next one. Pages theapply resolved leave the held set, so rerunning without `--cursor` alsostarts from the first page still held.diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex b64888ccd3..aba8d4c074 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -417,7 +417,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),...(k === kind && k === 'visibility' && driftClass ? { driftClass } : {}),...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}), ...(cursor ? { cursor } : {}),- ...(apply ? {} : { progress: createProgress(cliOptsToProgressOptions(getCliOptions())) }) } : {}),+ progress: createProgress(cliOptsToProgressOptions(getCliOptions())) } : {}),...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}) }));diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 1c4e9e1524..32d5f2ad5c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1085,7 +1085,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.351.0', text: 'Remote (MCP and HTTP) page reads now hide a page marked private only by a privacy alias (`access: private|restricted|confidential` or `confidentiality: confidential|secret|private|restricted`, with no `visibility`), as they hide `visibility: private` pages; local CLI reads are unchanged. To keep showing such pages to remote callers: `gbrain config set visibility.honor_aliases false`.' },{ since: '0.60.351.0', text: '`gbrain repair visibility` previews one class at a time, in the order remote callers are exposed: world facts from a private page (remotely readable ones first), Life Chronicle events, alias-only pages, then atoms and concepts; only that last class (`--class lineage`) reads concept-provenance links, and `--class facts|events|aliases|lineage` previews one. A preview lists one window (1,000 items, `--limit` up to 10,000), reports progress on stderr and prints `--apply --expect <hash>`, which applies exactly that window and resumes after its last applied item; apply it, then preview again for the next window. A bare `--apply` (`--all`, the remediation plan) still applies every class. Each plan statement is bounded at 120 s; a class that overruns is reported and skipped while the others are listed. The fact and concept-lineage plans are set-based now (a large brain timed out on them), and doctor `derived_visibility` counts facts first and reports derived-page counts as unknown when they overrun the same bound. A doctor rerun hint capped to fit an agent tool call also names the uncapped `--budget-ms` to use in a terminal.' },// GBRA-133 (held file-drift preview windows). `since` is stamped at the merge slot.- { since: 'TBD', text: '`gbrain repair file-drift --held` previews one window of the selected holds at a time, in held-path order: at most 200 pages, starting no page after 60 seconds of work, with each page reported on stderr. The hash and apply command cover only that window; a partial window prints `next_cursor` and the next preview command (`--cursor <next_cursor>`). Before, the preview prepared every held page (up to 1,000, silently dropping the rest) before printing anything, so a large held set against a remote database printed nothing for an hour.' },+ { since: 'TBD', text: '`gbrain repair file-drift --held` previews one window of the selected holds at a time, in held-path order: at most 200 pages, starting no page after 60 seconds of work, with each page reported on stderr. The hash and apply command cover only that window; a partial window prints `next_cursor` and the next preview command (`--cursor <next_cursor>`). Before, the preview prepared every held page (up to 1,000, silently dropping the rest) before printing anything, so a large held set against a remote database printed nothing for an hour. The apply reports each page on stderr too, and reads the preview artifact once instead of parsing it again for every page (seconds per page with large pages).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex ce5e97f91d..aed4ebe862 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -108,7 +108,7 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbsince?: string;/** #6712 PR 4b `file-drift`: the source's held `file_drift` pages, of one side and (for `deleted`) one state. */held?: boolean; side?: string; state?: string;- /** `file-drift --held`: the window starts after the held file this `next_cursor` names (`--cursor`); `progress` reports the preview's pages on stderr. */+ /** `file-drift --held`: the window starts after the held file this `next_cursor` names (`--cursor`); `progress` reports the preview's pages, and an apply's items, on stderr. */cursor?: string; progress?: ProgressReporter;/** `stuck-recovery`: the version an apply keeps, and the one request a run selects. */keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string;@@ -379,6 +379,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, scconst finish = async (): Promise<RepairResult> => {if (failedItems.length && handler.onItemFailures && result.stopped?.reason !== 'item_failures_systemic') await handler.onItemFailures(ctx, failedItems);if (handler.report) Object.assign(result, await handler.report(ctx, scope, result, planOpts));+ if (opts.apply) opts.progress?.finish();return result;};if (!opts.apply) {@@ -424,8 +425,10 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, scresult.stopped = stopped;return finish();};+ if (opts.apply) opts.progress?.start(`repair.${handler.kind}.apply`, pending.length);for (const [index, item] of pending.entries()) {const remaining = pending.length - index;+ opts.progress?.tick(1, `${item.source_id}:${item.slug}`);// A preview-bound kind may retire its approved set with its last item, so every earlier receipt settles before that item runs.const lastApproved = !!opts.expect && index === plan.items.length - 1;if (unresolved.length && (unresolved.length >= window || lastApproved) && !await settle(lastApproved ? 0 : window - 1)) {diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.tsindex f8bf8ff7c0..90f85be0ab 100644--- a/src/core/repair/file-drift.ts+++ b/src/core/repair/file-drift.ts@@ -219,13 +219,24 @@ function writeArtifact(hash: string, value: unknown): string {return path;}-function readArtifact(hash: string, command: string): Map<string, PlannedPage> {+/**+ * The parsed artifact of the newest preview read, keyed by its path and file identity. An apply reads the artifact once per+ * page, and a preview of large pages writes hundreds of megabytes, so parsing it again for every page cost seconds each.+ */+let artifactMemo: { key: string; pages: Map<string, PlannedPage> } | null = null;++/** The preview artifact's pages by slug; the same parsed map while the file is unchanged. Exported for its test. */+export function readArtifact(hash: string, command: string): Map<string, PlannedPage> {const path = join(artifactDirectory(), `${hash}.json`);try {const stat = lstatSync(path);if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('not a regular file');+ const key = `${path}\0${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;+ if (artifactMemo?.key === key) return artifactMemo.pages;const parsed = JSON.parse(readFileSync(path, 'utf8')) as { pages?: PlannedPage[] };- return new Map((parsed.pages ?? []).map(page => [page.slug, page]));+ const pages = new Map((parsed.pages ?? []).map(page => [page.slug, page]));+ artifactMemo = { key, pages };+ return pages;} catch { throw previewChangedError(hash, command); }}diff --git a/test/repair-file-drift-held-window-gbra133.test.ts b/test/repair-file-drift-held-window-gbra133.test.tsindex 25abb1524e..ebc3e12f52 100644--- a/test/repair-file-drift-held-window-gbra133.test.ts+++ b/test/repair-file-drift-held-window-gbra133.test.ts@@ -28,6 +28,7 @@ import { SYNC_ORIGIN_DELETED_OP } from '../src/core/persistence/sync-pass-row.tsimport { gitHoldItem, readGitHold, writeGitHold, type FileDriftDeletedState, type FileDriftSide } from '../src/core/persistence/sync-holds.ts';import { repairRunner } from '../src/core/repair/registry.ts';import { resolveRepairScope } from '../src/core/repair/core.ts';+import { readArtifact } from '../src/core/repair/file-drift.ts';import { withEnv } from './helpers/with-env.ts';import type { ProgressReporter } from '../src/core/progress.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';@@ -146,6 +147,23 @@ for (const backend of testBackends()) describe(`GBRA-133: a held file-drift prevexpect(elsewhere.code).toBe('preview_changed');}), 240_000);+ test('an apply parses the preview artifact once while it is unchanged, and reports each item to its progress reporter', () => fixture(async f => {+ const slugs = await fileGone(f, 3);+ const preview = await run(f.sourceId, {});+ const hash = preview.preview_hash!;+ const command = `gbrain repair file-drift --source ${f.sourceId}`;+ const first = readArtifact(hash, command);+ expect([...first.keys()]).toEqual(slugs);+ expect(readArtifact(hash, command)).toBe(first);+ const ticks: string[] = [];+ const progress = { start: (phase: string, total?: number) => ticks.push(`start ${phase} ${total}`), tick: (_n?: number, note?: string) => ticks.push(`tick ${note}`),+ heartbeat() {}, finish: () => ticks.push('finish'), child: () => progress } as unknown as ProgressReporter;+ const applied = await run(f.sourceId, { expect: hash, progress });+ expect(applied.outcomes).toEqual({ repaired: 3 });+ expect(ticks).toEqual(['start repair.file-drift.apply 3', ...slugs.map(slug => `tick ${f.sourceId}:${slug}`), 'finish']);+ for (const slug of slugs) expect(existsSync(join(f.root, `${slug}.md`))).toBe(true);+ }), 240_000);+test('a window stops at 200 pages and the next one previews the rest', () => fixture(async f => {const slugs = await fileGone(f, 203);const first = await run(f.sourceId, {});