Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

repair private-labels: batched window publish, declines fail alone, carried declines skip the breaker, 10-minute refresh wait

garrytan5a1ad15681f2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aaeac36dfc..6814092e0f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -59,6 +59,14 @@ An apply that ends with a failure, a stop or a pending write keeps its approved
Restore no longer lists a page whose label was removed by hand after a restore landed. The preview counts it as `removed_after_restore` and says so (GST-2128).
+### Faster private-labels windows that finish despite declined pages
+
+`gbrain repair private-labels --apply --expect <hash>` on a brain with managed persistence now admits a window's pages together and publishes them in groups, instead of one page and one wait at a time. On a 1,000-page window with Git commits and a second queue consumer (`scripts/bench/private-labels-apply.ts`), it went from 181.4 to 1365.3 pages a minute with no added database latency, and from 19.9 to 37.1 pages a minute with 20 ms added to each database round trip. Git commits for the window dropped from 990 to 22. The preview no longer claims a re-embed for every page: only pages stored under per-chunk synopsis count.
+
+A page whose own state declines the write (its file changed outside gbrain, `source_changed`, or its body is stored in segments) fails alone and the rest of its group lands. A preview-bound apply of any repair kind that completes with only such declines now exits 0 and counts them under `declined`. The next private-labels preview lists pages an earlier apply tried and that did not change after every page not tried yet, and such a page declining again no longer counts toward the `item_failures_systemic` stop, so windows that carry declines forward keep finishing; pages not tried yet that all fail the same way still stop the run. The apply result names its ledger (`details.ledger`, `details.ledger_rows_written`).
+
+A preview-bound repair apply now waits out a `gbrain sources refresh` for up to 10 minutes per step instead of 10 seconds. A refresh that runs longer ends the apply with `worktree_refreshing`, naming the refresh and how long it has run; rerunning the same apply resumes it (GBRA-443).
+
### Federating a source names the member pages it exposes
**`gbrain sources federate` now names the pages it makes readable to everyone that a member's credential wrote.** A token or OAuth client bound to a member and granted its own source (the documented `--sources private-<member>,default` shape) writes there without `readable_by`, which is right while that source is not federated: only credentials granted it read it. Federating the source adds it to what every connection with no source grant reads, so each such page became readable by every unbound token and agent connection, and nothing said so. `sources federate <id>` still federates exactly as before, with the same exit code, and then prints on stderr how many pages in the source a remote token or OAuth client wrote that name no readers and no folder rule, up to five slugs with the member each credential is bound to now, `gbrain access who-can-read <slug> --source <id>` to check one, and `gbrain access rule add --prefix <folder/> --readers <member> --source <id>` (which previews before `--yes`) to keep a folder to its member; every command is shell-quoted. No record keeps which member a credential was bound to when it wrote, so pages from a credential unbound, rebound or deleted since then are listed too. A page whose remote author was followed only by a tag change (which moves the revision attribution without a version snapshot) is not listed. `sources federate --json` prints one object (`id`, `federated`, and `pages_exposed` when there are such pages) and moves the human lines to stderr. `sources restore`, which re-federates by default, prints the same list, and a managed restore returns it as `pages_exposed`. The pages are read from the database's write attribution after the change commits, so a repo-less brain reports them the same way. Writes made through an attested actor (`x-qm-actor`) carry the attesting system's credential and are listed under it.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 6e3f917084..300467a031 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2145,6 +2145,37 @@ it resumes after the last applied page. You need a new preview only after the
window has been applied in full, or when the preview hash changed
([`preview_changed`](#preview-changed)).
+**Batches, declines and the exit code.** On a brain with managed persistence the
+apply admits a window's pages together, up to 64 at a time (fewer when the
+writer's outstanding-request cap is low), and the owner
+publishes them in groups of up to 8, instead of one page and one wait at a time.
+Each page still has its own fate: a page whose write is declined fails alone and
+the rest of its group lands. A decline is the page's own state refusing the
+write: its file differs from the database or is gone (`source_changed`), or its
+body is stored in segments. The page is left unchanged, the result counts it
+under `declined` by reason, and when every failure of a complete run is a
+decline the command exits 0, so a script working through windows carries on.
+Any other failure, or a stop, still exits 1. The next preview lists pages an
+earlier apply tried and that didn't change after every page not tried yet
+(`details.window.tried_before` counts them), so they stop heading each window.
+Clearing a declined page is a separate choice per page: see
+[file drift](#file-drift). Such a page declining again doesn't count toward the
+run's systemic-failure stop (`item_failures_systemic`), so a window whose tail,
+or whole listing, is carried declines completes; pages not tried yet that all
+fail the same way, as a dirty checkout makes them, still stop the run.
+
+An apply that meets a `gbrain sources refresh` waits for the refresh to
+finish, for up to 10 minutes per step, instead of being refused after 10
+seconds. A refresh that runs longer ends the apply with `worktree_refreshing`
+(exit 1): the message names the refresh, its phase, how long it has run and how
+long the apply waited. The pages already published stay published, each with its
+undo line, the rest are unchanged, and rerunning the same
+`--apply --expect <hash>` after the refresh resumes the window.
+
+A brain without managed persistence (repo-less included) writes one page at a
+time, as before; the ordering, the exit code, the decline rule and the ledger
+fields below apply there too.
+
**Git-canonical sources.** Private pages there are database-only, so clearing
one commits it into the source's Git history for the first time. That class,
`git-publish`, is never in the default preview. Run it only by name:
@@ -2157,7 +2188,12 @@ earlier commit, and any remote it was pushed to, keeps the page's content.
set) on the host that ran it. Each page gets an `intent` line with the exact
removed values before its write and a `committed` line after it. A run that
stops between the two can still be undone. If the ledger can't take the intent
-line, the apply refuses with `storage_error` and changes nothing.
+line, the apply refuses with `storage_error` and changes nothing. An apply
+result names the ledger (`details.ledger`) and the lines it appended:
+`details.ledger_rows_written`, split into `details.ledger_rows.intent` and
+`.committed`. The file grows by exactly `ledger_rows_written`, and `committed`
+equals `applied` unless a commit line could not be saved, which the item's
+outcome then says.
```bash
gbrain repair private-labels --source <id> --class restore --json
diff --git a/scripts/bench/private-labels-apply.ts b/scripts/bench/private-labels-apply.ts
new file mode 100644
index 0000000000..dfb015ac7b
--- /dev/null
+++ b/scripts/bench/private-labels-apply.ts
@@ -0,0 +1,176 @@
+#!/usr/bin/env bun
+/**
+ * gbrain repair private-labels apply throughput on a managed Git source, with a second consumer running beside it.
+ * Opt-in, never run in CI.
+ *
+ * bun scripts/bench/private-labels-apply.ts [--pages 1000] [--rtt 0] [--cli <path to src/cli.ts>] [--no-worker]
+ * [--label <name>] [--out <file.json>] [--database-url <admin url>] [--pg-port 55432] [--proxy-port 55433] [--api-port 58474] [--keep]
+ *
+ * Builds a synthetic brain on Postgres (Docker pgvector behind a toxiproxy with --rtt ms of round trip, the
+ * managed-sync-catchup harness): one managed Git source whose --pages pages each carry an over-stamped access: private,
+ * committed and synced. A `gbrain jobs work` process runs beside the apply, so its persistence consumer competes to
+ * claim the apply's requests as a resident worker would. Then one preview of a window of every page and one
+ * `--apply --expect`, timed. --cli runs another checkout's gbrain (the same binary runs the worker), so the same script
+ * measures a branch before and after a change. The report has the apply's wall time and pages per minute, the gaps
+ * between consecutive requests' admission, each request's admission-to-completion time, how many distinct
+ * publication transactions and Git commits carried the pages, and the apply's own result counts.
+ */
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { randomBytes } from 'node:crypto';
+import postgres from '#postgres';
+import { measureRtt, pct, round1, startHarness, type Harness } from './managed-sync-catchup-lib.ts';
+
+const REPO = resolve(import.meta.dir, '../..');
+const SOURCE = 'bench';
+function flag(name: string, fallback: string): string {
+ const i = process.argv.indexOf('--' + name);
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1]! : fallback;
+}
+const PAGES = Number(flag('pages', '1000'));
+const RTT = Number(flag('rtt', '0'));
+const CLI = resolve(flag('cli', join(REPO, 'src/cli.ts')));
+const WORKER = !process.argv.includes('--no-worker');
+const KEEP = process.argv.includes('--keep');
+const describeCheckout = (root: string) => {
+ try { return execFileSync('git', ['-C', root, 'rev-parse', '--short', 'HEAD'], { encoding: 'utf8' }).trim(); } catch { return 'unknown'; }
+};
+const CLI_COMMIT = describeCheckout(dirname(dirname(CLI)));
+const LABEL = flag('label', CLI_COMMIT);
+const OUT = resolve(flag('out', join(REPO, '.context', 'bench', 'private-labels-apply-' + LABEL.replace(/[^\w.-]/g, '_') + '-' + Date.now() + '.json')));
+const log = (msg: string) => console.error('[private-labels-bench ' + new Date().toISOString().slice(11, 19) + '] ' + msg);
+const work = mkdtempSync(join(tmpdir(), 'gbrain-private-labels-bench-'));
+const created: string[] = [];
+let harness: Harness;
+
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+}
+function childEnv(home: string): Record<string, string | undefined> {
+ const env: Record<string, string | undefined> = { ...process.env };
+ for (const key of Object.keys(env)) if (/_API_KEY$|_API_TOKEN$|^DATABASE_URL$|^GBRAIN_DATABASE_URL$|^OPENAI_BASE_URL$/.test(key)) delete env[key];
+ return { ...env, GBRAIN_HOME: home, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_SKILLS_DIR: join(home, 'skills'), GBRAIN_INTERACTIVE: '0', NO_COLOR: '1' };
+}
+async function cli(home: string, args: string[], okExits = [0]): Promise<{ json: any; code: number; ms: number }> {
+ const start = performance.now();
+ const child = Bun.spawn([process.execPath, CLI, ...args], { cwd: home, env: childEnv(home), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ const ms = performance.now() - start;
+ if (!okExits.includes(code)) throw new Error('gbrain ' + args.join(' ') + ' exited ' + code + '\nstdout: ' + stdout.slice(-1500) + '\nstderr: ' + stderr.slice(-1500));
+ let json: any = null;
+ try { json = JSON.parse(stdout); } catch { /* not JSON */ }
+ return { json, code, ms };
+}
+function writeConfig(home: string, url: string): void {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ mkdirSync(join(home, 'skills'), { recursive: true });
+ writeFileSync(join(home, 'skills', 'RESOLVER.md'), '# Bench fixture skills\n');
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: url, self_upgrade: { mode: 'off' }, embedding_disabled: true }, null, 2) + '\n');
+}
+async function admin<T>(fn: (sql: ReturnType<typeof postgres>) => Promise<T>, db = 'postgres'): Promise<T> {
+ const sql = postgres(harness.directUrl(db), { max: 1, onnotice: () => {} });
+ try { return await fn(sql); } finally { await sql.end(); }
+}
+
+async function setup(): Promise<{ home: string; db: string; root: string }> {
+ const db = 'gbrain_plbench_' + randomBytes(4).toString('hex');
+ await admin(sql => sql.unsafe('CREATE DATABASE ' + db));
+ created.push(db);
+ const home = mkdtempSync(join(work, 'home-'));
+ writeConfig(home, harness.directUrl(db));
+ process.env.GBRAIN_HOME = home;
+ const { PostgresEngine } = await import('../../src/core/postgres-engine.ts');
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: harness.directUrl(db), poolSize: 2 });
+ await engine.initSchema();
+ await engine.disconnect();
+ const root = join(home, 'repo-' + SOURCE);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ git(root, 'init', '-q');
+ writeFileSync(join(root, 'README.md'), '# Bench source\n');
+ for (let i = 0; i < PAGES; i++) {
+ writeFileSync(join(root, 'notes', 'labelled-' + String(i).padStart(5, '0') + '.md'),
+ '---\ntitle: Labelled note ' + i + '\ntype: note\naccess: private\ntopic: bench\n---\nSynthetic note ' + i + ' stamped private by a writer template.\n\nA second paragraph so the page has two chunks of text, ' + i + '.\n');
+ }
+ git(root, 'config', 'user.name', 'Bench Example');
+ git(root, 'config', 'user.email', '[email protected]');
+ git(root, 'add', '-A');
+ git(root, 'commit', '-qm', 'seed');
+ // A durability-hardened checkout with no remote, so every page's Git effect commits for real (as on a brain that pushes).
+ writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n');
+ chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755);
+ await cli(home, ['sources', 'add', SOURCE, '--path', root, '--no-federated']);
+ await cli(home, ['sync', '--source', SOURCE, '--no-pull', '--no-embed', '--json']);
+ let state = (await cli(home, ['sources', 'writer', 'status', '--json'])).json.admin_state as string;
+ await cli(home, ['sources', 'writer', 'claim', SOURCE, '--path', root, '--admin-intent', 'writer_claim', '--expected-state', state, '--json']);
+ state = (await cli(home, ['sources', 'writer', 'status', '--json'])).json.admin_state as string;
+ const activated = (await cli(home, ['sources', 'writer', 'activate', '--confirm-quiesced', '--admin-intent', 'writer_activate', '--expected-state', state, '--json'])).json;
+ if (activated?.enabled !== true) throw new Error('activation did not enable managed persistence: ' + JSON.stringify(activated));
+ writeConfig(home, harness.proxyUrl(db));
+ return { home, db, root };
+}
+
+harness = await startHarness({ pgPort: Number(flag('pg-port', '55432')), proxyPort: Number(flag('proxy-port', '55433')), apiPort: Number(flag('api-port', '58474')),
+ adminUrl: process.argv.includes('--database-url') ? flag('database-url', '') : undefined, keep: KEEP });
+const report: Record<string, unknown> = { schema: 'gbrain.bench.private-labels-apply/v1', label: LABEL, cli: CLI, cli_commit: CLI_COMMIT, started_at: new Date().toISOString(),
+ params: { pages: PAGES, rtt_ms: RTT, second_consumer: WORKER ? 'gbrain jobs work' : null }, rerun: 'bun scripts/bench/private-labels-apply.ts ' + process.argv.slice(2).join(' ') };
+let worker: ReturnType<typeof Bun.spawn> | null = null;
+try {
+ log('building a managed source with ' + PAGES + ' labelled pages');
+ const brain = await setup();
+ await harness.setRtt(RTT);
+ report.measured_rtt_ms = round1(await measureRtt(harness.proxyUrl(brain.db)));
+ if (WORKER) {
+ worker = Bun.spawn([process.execPath, CLI, 'jobs', 'work'], { cwd: brain.home, env: childEnv(brain.home), stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' });
+ await Bun.sleep(5000);
+ if (worker.exitCode !== null) throw new Error('the second consumer (gbrain jobs work) exited ' + worker.exitCode);
+ }
+ const preview = await cli(brain.home, ['repair', 'private-labels', '--source', SOURCE, '--limit', String(PAGES), '--json']);
+ const planned = preview.json.results[0];
+ if (planned.listing?.length !== PAGES) throw new Error('the preview listed ' + planned.listing?.length + ' pages, expected ' + PAGES);
+ report.preview = { ms: Math.round(preview.ms), embedding_pages: planned.cost.embedding_pages };
+ const [{ seq }] = await admin(sql => sql.unsafe('SELECT COALESCE(max(sequence), 0)::text AS seq FROM persistence_requests'), brain.db) as Array<{ seq: string }>;
+ const commitsBefore = Number(git(brain.root, 'rev-list', '--count', 'HEAD'));
+ log('applying the window (' + PAGES + ' pages; measured RTT ' + report.measured_rtt_ms + ' ms; second consumer ' + (WORKER ? 'on' : 'off') + ')');
+ const applied = await cli(brain.home, ['repair', 'private-labels', '--source', SOURCE, '--apply', '--expect', planned.preview_hash, '--json'], [0, 1]);
+ const result = applied.json.results[0];
+ const rows = await admin(sql => sql.unsafe(`SELECT state, extract(epoch FROM created_at) * 1000 AS created_ms, extract(epoch FROM completed_at) * 1000 AS completed_ms,
+ published_at::text AS published FROM persistence_requests WHERE sequence > $1::bigint AND intent->>'kind' = 'managed_maintenance_page' ORDER BY sequence`, [seq]), brain.db) as Array<{ state: string; created_ms: number; completed_ms: number | null; published: string | null }>;
+ const gaps = rows.slice(1).map((row, i) => Number(row.created_ms) - Number(rows[i]!.created_ms));
+ const latency = rows.filter(row => row.completed_ms !== null).map(row => Number(row.completed_ms) - Number(row.created_ms));
+ const minutes = applied.ms / 60_000;
+ // Git publication runs as an effect after each request commits: wait (bounded) for it before counting commits.
+ for (let waited = 0; waited < 120_000; waited += 1000) {
+ const [{ open }] = await admin(sql => sql.unsafe("SELECT count(*)::int AS open FROM persistence_effects WHERE kind='git' AND state<>'committed'"), brain.db) as Array<{ open: number }>;
+ if (!open) break;
+ await Bun.sleep(1000);
+ }
+ report.apply = {
+ exit: applied.code, wall_s: round1(applied.ms / 1000), pages_per_minute: round1(result.applied / minutes),
+ applied: result.applied, skipped: result.skipped, failed: result.failed.length, declined: result.declined ?? null, complete: result.complete, stopped: result.stopped?.reason ?? null,
+ requests: rows.length, committed: rows.filter(row => row.state === 'committed').length,
+ admission_gap_ms: { p50: pct(gaps, 50), p90: pct(gaps, 90), max: pct(gaps, 100) },
+ admission_to_completion_ms: { p50: pct(latency, 50), p90: pct(latency, 90), max: pct(latency, 100) },
+ publication_transactions: new Set(rows.map(row => row.published).filter(Boolean)).size,
+ git_commits_after_effects_settled: Number(git(brain.root, 'rev-list', '--count', 'HEAD')) - commitsBefore,
+ ledger_rows: result.details?.ledger_rows ?? null,
+ };
+ const a = report.apply as Record<string, any>;
+ log('applied ' + a.applied + ' of ' + PAGES + ' in ' + a.wall_s + ' s: ' + a.pages_per_minute + ' pages/min (exit ' + a.exit + '); admission gap p50 ' + a.admission_gap_ms.p50
+ + ' ms; admission to completion p50 ' + a.admission_to_completion_ms.p50 + ' ms; ' + a.publication_transactions + ' publication transactions, ' + a.git_commits_after_effects_settled + ' Git commits');
+} finally {
+ worker?.kill();
+ await worker?.exited;
+ report.finished_at = new Date().toISOString();
+ mkdirSync(dirname(OUT), { recursive: true });
+ writeFileSync(OUT, JSON.stringify(report, null, 2) + '\n');
+ log('report: ' + OUT);
+ if (!KEEP) {
+ for (const datname of created) await admin(sql => sql.unsafe('DROP DATABASE IF EXISTS ' + datname + ' WITH (FORCE)')).catch(() => undefined);
+ rmSync(work, { recursive: true, force: true });
+ }
+ harness.stop();
+}
+process.exit(0);
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 822ee87e32..7e76cffd51 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -25,7 +25,7 @@ import { shellQuote } from '../core/agent-output.ts';
import { OLDER_THAN_RE } from '../cli/strict-args.ts';
import { parseSince } from '../core/since.ts';
import { generationsSelectionArgv, generationsSelectionRefusal, type GenerationMode, type GenerationsSelection } from '../core/generations/repair.ts';
-import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult, type RepairScope } from '../core/repair/core.ts';
+import { REPAIR_DECLINE_CODES, REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult, type RepairScope } from '../core/repair/core.ts';
import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';
import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, LLM_REPAIR_REGISTRY, PREVIEW_BOUND_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMayEmbed, repairMaySpend,
repairPreviewCommand, repairRunner, repairSpec, type RepairKindSpec } from '../core/repair/registry.ts';
@@ -438,6 +438,7 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }
if (result.mode === 'apply' && result.failed.length) {
lines.push(` ${result.failed.length} item(s) left unchanged; a resumed run skips past them, the next full scan retries them: ${result.apply_command}`);
}
+ if (result.mode === 'apply' && result.declined) lines.push(` declined (the page refused the write; left unchanged): ${Object.entries(result.declined).map(([k, v]) => `${k}=${v}`).join(', ')}`);
if (result.mode === 'apply' && result.repaired !== undefined) {
const left = Object.entries(result.remaining ?? {}).map(([k, v]) => `${k}=${v}`).join(', ');
lines.push(` repaired ${result.repaired}; ${left ? `still waiting: ${left}` : 'nothing left in this selection'}`);
@@ -556,7 +557,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
}
if (explicitKindsNotRun.length) console.log(`Explicit-only kinds (not run without their name; preview each): ${explicitKindsNotRun.map(n => n.preview_command).join('; ')}`);
}
- if (repairExitVerdict(results) !== 0) setCliExitVerdict(1);
+ if (repairExitVerdict(results, { previewBound: apply && expect !== undefined }) !== 0) setCliExitVerdict(1);
}
/**
@@ -586,7 +587,14 @@ export async function runRepairKinds(kinds: readonly RepairKind[], scope: Repair
return results;
}
-/** Exit 1 when any kind stopped early or refused an item; 0 only when every pending item was attempted and applied or skipped. */
-export function repairExitVerdict(results: ReadonlyArray<Pick<RepairResult, 'stopped' | 'failed'>>): 0 | 1 {
- return results.some(r => r.stopped || r.failed.length > 0) ? 1 : 0;
+/**
+ * Exit 1 when any kind stopped early or refused an item; 0 when every pending item was attempted and applied or skipped.
+ * GBRA-443: a preview-bound apply (`--expect`) that attempted every item, stopped for nothing, and whose every failure is the
+ * page declining the write (REPAIR_DECLINE_CODES) exits 0: those pages were left unchanged, `declined` counts them by reason
+ * and the next preview lists them again, so the caller working through windows moves on. An apply bound to no preview
+ * keeps exit 1 for them: nobody approved its set, and the exit is often its caller's only sign that pages were left.
+ */
+export function repairExitVerdict(results: ReadonlyArray<Pick<RepairResult, 'stopped' | 'failed' | 'complete'>>, opts: { previewBound?: boolean } = {}): 0 | 1 {
+ const declinedOnly = (r: Pick<RepairResult, 'failed' | 'complete'>) => opts.previewBound === true && r.complete && r.failed.every(failed => REPAIR_DECLINE_CODES.has(failed.reason));
+ return results.some(r => r.stopped || (r.failed.length > 0 && !declinedOnly(r))) ? 1 : 0;
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3e5551d43b..852f1d3ccc 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1498,6 +1498,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.628.0', id: 'federated_member_writes_8982', text: 'A token or OAuth client bound to a member whose write source is a federated source (`gbrain sources federate <id>`) now writes the pages it creates with `readable_by: [member:<id>]`, as one writing to `default` does, because every credential without a source grant reads federated sources too; `POST /ingest` refuses such a credential. Before this, other members\' no-grant tokens and unbound tokens read those pages. A write source that is not federated is unchanged, and pages written before the upgrade keep their readers (`gbrain access who-can-read <slug>`).' },
{ since: 'TBD', id: 'owner_private_facts_gst2089', text: 'The brain owner\'s remote credentials now get private facts in the `query` facts arm, `think` trajectories, hot memory, `delta` and `context_pack` hot facts, and from `recall` with a `question`, under the same rule as its private pages: no audience, or an audience of the owner alone. Facts taken from a page the owner cannot read and facts outside its source grant stay hidden. Facts on `entity` and `context_pack` cards stay world-only. Every other remote caller is unchanged.' },
{ since: 'TBD', id: 'private_labels_write_ahead_gst2092', text: '`gbrain repair private-labels` writes its undo ledger ahead of each page: an `intent` line before the write and a `committed` line after it, so a run that stops between them can still be undone with `--class restore`, and a ledger that cannot take the intent line refuses the apply (`storage_error`) before anything changes. Restore re-adds only `access` and `visibility: private` from well-formed ledger lines (others are counted unreadable) and no longer lists a page whose label was removed after a restore landed (`removed_after_restore`). The preview counts the derived_from pages and life-chronicle events each window would expose along with its pages; on a brain without managed persistence a page whose file sits in its source\'s checkout is held (`file_backed`) instead of being cleared in the database only; and an apply that ends with a failure keeps its approved preview, so the same `--apply --expect` resumes it.' },
+ { since: 'TBD', id: 'private_labels_batch_exit_gbra443', text: '`gbrain repair private-labels --apply --expect` on a brain with managed persistence admits a window\'s pages together and publishes them in groups instead of one page and one wait at a time; a page whose write is declined fails alone. `gbrain repair <kind> --apply --expect <hash>` (every preview-bound kind) now exits 0 when the run is complete, nothing stopped, and every failed item is its page declining the write (`source_changed`, `page_body_segmented`); the result counts them in `declined` by reason, and any other failure or a stop still exits 1. An apply bound to no preview keeps exit 1 for them. The private-labels preview lists pages an earlier apply tried and that did not change after every page not tried yet (`details.window.tried_before`), no longer claims a re-embed for every page (only pages stored under per-chunk synopsis count), and an apply result carries `details.ledger`, `details.ledger_rows_written` and `details.ledger_rows`. A page an earlier apply tried that declines again no longer counts toward `item_failures_systemic`, so a window of carried declines completes; pages not tried yet still trip it. A preview-bound repair apply waits out a `gbrain sources refresh` for up to 10 minutes per step instead of 10 s, and past that ends with `worktree_refreshing` (exit 1) naming the refresh and its running time; rerunning the same apply resumes. Other interactive writes keep 10 s.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.ts
index a302c15c37..ca98cbb7a7 100644
--- a/src/core/persistence/admission-retry.ts
+++ b/src/core/persistence/admission-retry.ts
@@ -93,10 +93,19 @@ export function outstandingCapacityOf(error: OperationError): { outstanding: num
* remote timeout); past it the refusal is returned with `fix.next: wait` and its `retry_after_ms`, never a success.
*/
export const REFRESH_FENCE_WAIT_MS = 10_000;
+/**
+ * GBRA-443: how long one step of a preview-bound repair apply (`--expect`) waits out a refresh fence. Its items are the
+ * operator's approved set, so a refusal costs a fresh run rather than one retried call; a refresh of a large checkout
+ * can run several minutes, so the step follows it to its end up to this ceiling. Nothing is held across a pause.
+ */
+export const REPAIR_REFRESH_WAIT_MS = 10 * 60_000;
const REFRESH_FENCE_BACKOFF_MS = [250, 500, 1000, 2000] as const;
let refreshFenceWaitMs = REFRESH_FENCE_WAIT_MS;
+let repairRefreshWaitMs = REPAIR_REFRESH_WAIT_MS;
/** Test seam: the wait cap, or null for the default. */
export function _setRefreshFenceWaitForTests(ms: number | null): void { refreshFenceWaitMs = ms ?? REFRESH_FENCE_WAIT_MS; }
+/** Test seam: the preview-bound repair wait (withRepairRefreshWait), or null for the default. */
+export function _setRepairRefreshWaitForTests(ms: number | null): void { repairRefreshWaitMs = ms ?? REPAIR_REFRESH_WAIT_MS; }
/**
* One wait budget shared by every admission inside it (a remember batch waits once, not once per item). Its clock starts
@@ -108,6 +117,14 @@ export function withRefreshFenceBudget<T>(fn: () => Promise<T>, capMs?: number):
return refreshFenceDeadline.getStore() ? fn() : refreshFenceDeadline.run({ capMs: Math.min(refreshFenceWaitMs, capMs ?? Infinity) }, fn);
}
+/**
+ * GBRA-443: a wait budget of its own (REPAIR_REFRESH_WAIT_MS) for one preview-bound repair step; an outer budget does
+ * not shorten it. Only an interactive admission inside it waits.
+ */
+export function withRepairRefreshWait<T>(fn: () => Promise<T>): Promise<T> {
+ return refreshFenceDeadline.run({ capMs: repairRefreshWaitMs }, fn);
+}
+
export function isRefreshFenceRefusal(error: unknown): error is OperationError {
return error instanceof OperationError && error.code === 'worktree_refreshing';
}
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 81a86bb3de..f55fd99edc 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -18,7 +18,8 @@ import { getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } f
import { checkOwner, ownerUnavailableError } from './owner-refusal.ts';
import { admitWrite, admitWriteInTransaction, assertReplayIntent, getWriteRequest, intentDigest, type WriteAdmission } from './journal.ts';
import { assertRefusalBreakerClosed } from './refusal-breaker.ts';
-import { retryWriteAdmission } from './admission-retry.ts';
+import { retryWriteAdmission, waitOutRefreshFence } from './admission-retry.ts';
+import { resolveAdmissionOrigin } from './admission-origin.ts';
import { declareDurablePersistence } from './protocol.ts';
import { CANONICAL_FILE_MISSING } from './publication-failure.ts';
import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';
@@ -264,12 +265,15 @@ export async function publishMaintenancePage(engine: BrainEngine, authority: Mai
* before any is waited on, each carrying the batch id, so the owner claims them as one contiguous run and publishes them
* in groups of up to PAGE_BATCH_GROUP_MAX on Postgres (journal.ts publicationGroupKey: an independent group, one page's
* failure never cancels another). The batch id is derived from its pages, so a rerun over the same pages and revisions
- * replays the same requests. Each page settles on its own: its receipt, or the error publishMaintenancePage would throw.
+ * replays the same requests; a caller that names each page's request id passes a `batch` id that a rerun over a different
+ * split of the same pages repeats (GBRA-443: a repair window resumed mid-window). An interactive admission waits out a
+ * refresh fence like a single write does (admission-retry.ts). Each page settles on its own: its receipt, or the error
+ * publishMaintenancePage would throw.
*/
export async function publishMaintenancePages(engine: BrainEngine, authority: MaintenanceAuthority,
- pages: Array<{ slug: string; content: string } & Omit<MaintenancePageOptions, 'requestId'>>): Promise<Array<{ receipt: Record<string, unknown> } | { error: unknown }>> {
+ pages: Array<{ slug: string; content: string } & MaintenancePageOptions>, opts: { batch?: string } = {}): Promise<Array<{ receipt: Record<string, unknown> } | { error: unknown }>> {
if (new Set(pages.map(page => page.slug)).size !== pages.length) throw new TypeError('A maintenance batch publishes each page once.');
- const batch = digest(['maintenance-batch-v1', authority.writer.sourceId, pages.map(page => [page.slug, page.expectedRevision, sha256(page.content)])]);
+ const batch = opts.batch ?? digest(['maintenance-batch-v1', authority.writer.sourceId, pages.map(page => [page.slug, page.expectedRevision, sha256(page.content)])]);
const prepared: Array<{ prior: WriteRequest } | { admission: WriteAdmission } | { error: unknown }> = [];
for (const page of pages) {
const { intent, requestId } = maintenancePageRequest(authority, page.slug, page.content, page, batch);
@@ -277,12 +281,13 @@ export async function publishMaintenancePages(engine: BrainEngine, authority: Ma
}
const fresh = prepared.flatMap(entry => 'admission' in entry ? [entry.admission] : []);
// One admission transaction, retried on contention as admitWrite is; when it fails, every page it carried fails with it.
- const admitted: WriteRequest[] | { error: unknown } = !fresh.length ? [] : await retryWriteAdmission(`maintenance batch ${batch}`, remaining => engine.transaction(async tx => {
- await declareDurablePersistence(tx, `${Math.min(1000, remaining)}ms`, `${remaining}ms`);
- const rows: WriteRequest[] = [];
- for (const admission of fresh) rows.push(await admitWriteInTransaction(tx, admission));
- return rows;
- }), 30_000, error => engine.reconnect({ error })).catch(error => ({ error }));
+ const admitted: WriteRequest[] | { error: unknown } = !fresh.length ? [] : await waitOutRefreshFence(resolveAdmissionOrigin() === 'interactive',
+ () => retryWriteAdmission(`maintenance batch ${batch}`, remaining => engine.transaction(async tx => {
+ await declareDurablePersistence(tx, `${Math.min(1000, remaining)}ms`, `${remaining}ms`);
+ const rows: WriteRequest[] = [];
+ for (const admission of fresh) rows.push(await admitWriteInTransaction(tx, admission));
+ return rows;
+ }), 30_000, error => engine.reconnect({ error }))).catch(error => ({ error }));
const out: Array<{ receipt: Record<string, unknown> } | { error: unknown }> = [];
let next = 0;
for (const entry of prepared) {
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 346ed9c9d5..c507f7ab53 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -30,6 +30,7 @@
* thrown with its own code (a refused choice, a conflict, a crash).
*/
import { withAdmissionOrigin } from '../persistence/admission-origin.ts';
+import { withRepairRefreshWait } from '../persistence/admission-retry.ts';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import type { OperationContext } from '../ops/contract.ts';
@@ -70,6 +71,12 @@ export interface RepairItem {
* the run's allowance instead of starting a call the allowance cannot cover.
*/
llm_usd?: number;
+ /**
+ * GBRA-443: an earlier run tried this item and its page declined the write. A decline of it again (REPAIR_DECLINE_CODES)
+ * is recorded in `failed` and `declined` as any other, but not counted by the run's systemic-failure breaker, so pages
+ * carried from window to window cannot stop a window of pages not tried yet; any other failure of it counts as usual.
+ */
+ retried?: boolean;
}
export interface RepairPlan {
@@ -91,6 +98,11 @@ export interface RepairPlan {
llm?: { usd: number | null; cap_remaining_usd: number | null };
/** Discovery kinds: when the scan the plan read last finished (`fresh_at`) and whether it is still partial. */
scan?: { fresh_at: string | null; partial: boolean };
+ /**
+ * The items whose write re-embeds, when the kind knows which do (GBRA-443: private-labels re-embeds only a page stored
+ * under per-chunk synopsis); the cost counts the pending ones among them. Default: every pending item, none under embeds: false.
+ */
+ embedding_items?: RepairItem[];
}
export interface RepairListing { item: string; class: string; detail?: string; fix?: Action }
@@ -154,6 +166,15 @@ export interface RepairHandler {
* kind bounds its own provider calls by it. `noLlm` and `expect` repeat the run's options.
*/
apply(ctx: OperationContext, item: RepairItem, opts?: { embed: boolean; runId?: string; llmAllowanceUsd?: number; deadline?: number; noLlm?: boolean; expect?: string }): Promise<boolean | RepairItemOutcome>;
+ /**
+ * GBRA-443: apply a run of consecutive items at once (at most the run's admission window, each page once), so their writes
+ * are admitted together and published in groups instead of one admission and wait per item. One settlement per item, in
+ * order: what `apply` would return, or what it would throw; one item's refusal never fails another. Not used by
+ * `spends: 'llm'` kinds.
+ */
+ applyBatch?(ctx: OperationContext, items: RepairItem[], opts: { embed: boolean; runId?: string; expect?: string }): Promise<RepairSettlement[]>;
+ /** GBRA-443: an item whose write was still pending when its apply returned committed later in this run. */
+ onCommitted?(ctx: OperationContext, item: RepairItem, requestId: string): Promise<void>;
/** How many per-item outcomes the result lists (default 20). */
outcomeItemsLimit?: number;
/** Human lines for the plan's `details`; `diff` asks for every per-item diff, not one sample per class. */
@@ -162,7 +183,7 @@ export interface RepairHandler {
* Kind-specific result fields, computed once the dry run or apply finished (for example a verification re-check
* of the selected scope). Runs only when the run ended without an exception.
*/
- report?(ctx: OperationContext, scope: RepairScope, result: RepairResult, opts: RepairPlanOptions): Promise<Partial<Pick<RepairResult, 'repaired' | 'remaining' | 'verification' | 'stopped'>>>;
+ report?(ctx: OperationContext, scope: RepairScope, result: RepairResult, opts: RepairPlanOptions): Promise<Partial<Pick<RepairResult, 'repaired' | 'remaining' | 'verification' | 'stopped' | 'details'>>>;
/**
* The items whose apply threw an item-scoped failure this run, with the classified failure. Called once before the
* result is reported, never for a run the breaker stopped (`item_failures_systemic`) or one a run-scoped error ended.
@@ -188,6 +209,17 @@ export interface RepairItemOutcome { applied: boolean; outcome: string; reason?:
*/
export const REPAIR_ITEM_FAILURE_CODES: ReadonlySet<string> = new Set(['invalid_params', 'source_changed', 'page_body_segmented']);
+/**
+ * GBRA-443: the item failures that are the page's own state declining the write (its file differs from the database or is
+ * gone, or its body is stored in segments), never a fault of the run: nothing was written, and the next preview lists the
+ * item again with its state. A preview-bound apply whose only failures are these is complete (`gbrain repair` exits 0)
+ * and counts them in `declined`.
+ */
+export const REPAIR_DECLINE_CODES: ReadonlySet<string> = new Set(['source_changed', 'page_body_segmented']);
+
+/** GBRA-443: one item's result inside an `applyBatch`: what `apply` returned, or what it threw. */
+export type RepairSettlement = { value: boolean | RepairItemOutcome } | { error: unknown };
+
/**
* An item whose apply failed item-scoped; its page, file and rows are exactly as before. The next full scan retries it.
* `fix` previews the kind for the item's source (read-only), which lists the item again with its current state.
@@ -213,6 +245,8 @@ export interface RepairResult {
skipped: number;
/** Items that failed item-scoped and were left unchanged; `complete` still means every pending item was attempted. */
failed: RepairFailedItem[];
+ /** GBRA-443, apply: the failed items whose page declined the write (REPAIR_DECLINE_CODES), counted by reason; absent when none did. */
+ declined?: Record<string, number>;
complete: boolean;
/** `code`: with reason `error` (a kind that threw inside a multi-kind loop), the classified error code. */
stopped?: { reason: string; message: string; fix?: Action; code?: string };
@@ -377,6 +411,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;
const counters = await capacity(ctx);
const admits = (handler.publication ?? 'coordinated') === 'coordinated' ? pending.length : 0;
+ const embedded = plan.embedding_items ? pending.filter(item => plan.embedding_items!.includes(item)) : handler.embeds === false ? [] : pending;
const llm = spec?.spends === 'llm';
const llmLeft = (spent: number): number | null => {
const caps = [plan.llm?.cap_remaining_usd, opts.maxLlmUsd].filter((cap): cap is number => typeof cap === 'number');
@@ -385,8 +420,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
const result: RepairResult = {
kind: handler.kind, mode: opts.apply ? 'apply' : 'dry_run', scope, affected: plan.items.length,
sample: plan.items.slice(0, SAMPLE).map(item => `${item.source_id}:${item.slug}`), residuals: plan.residuals,
- cost: { lifetime_ids: admits, receipt_bytes: admits * RECEIPT_RESERVATION_FLOOR, embedding_pages: handler.embeds === false ? 0 : pending.length,
- embedding_usd: embeddingUsd(pending.reduce((sum, item) => sum + item.chars, 0), opts.embeddingModel),
+ cost: { lifetime_ids: admits, receipt_bytes: admits * RECEIPT_RESERVATION_FLOOR, embedding_pages: embedded.length,
+ embedding_usd: embeddingUsd((plan.embedding_items ? embedded : pending).reduce((sum, item) => sum + item.chars, 0), opts.embeddingModel),
...(llm ? { llm_usd: opts.apply || !plan.llm ? 0 : plan.llm.usd === null ? null
: pending.some(item => item.llm_usd !== undefined) ? pending.reduce((sum, item) => sum + (item.llm_usd ?? 0), 0) : plan.llm.usd,
llm_cap_remaining_usd: llmLeft(0) } : {}) },
@@ -407,7 +442,12 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
};
const items = new ItemRun('repair.apply_items');
const failedItems: Array<{ item: RepairItem; failure: ItemFailure }> = [];
+ // GBRA-443: settlements an applyBatch returned for items the loop has not reached yet; a stop takes them into the result first.
+ let absorbBatched = () => {};
const finish = async (): Promise<RepairResult> => {
+ absorbBatched();
+ const declined = result.failed.filter(failed => REPAIR_DECLINE_CODES.has(failed.reason));
+ if (opts.apply && declined.length) result.declined = declined.reduce<Record<string, number>>((counts, failed) => ({ ...counts, [failed.reason]: (counts[failed.reason] ?? 0) + 1 }), {});
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();
@@ -436,6 +476,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
unresolved.splice(unresolved.findIndex(open => open.request_id === done.request_id), 1);
if (done.state === 'committed') {
result.applied++;
+ await handler.onCommitted?.(ctx, done.item, done.request_id);
if (result.outcomes) result.outcomes = { ...result.outcomes, committed_after_wait: (result.outcomes.committed_after_wait ?? 0) + 1 };
} else if (done.error_code === 'revision_conflict') result.skipped++;
else result.failed.push({ item: `${done.item.source_id}:${done.item.slug}`, source_id: done.item.source_id, slug: done.item.slug, reason: done.error_code ?? done.state,
@@ -444,7 +485,30 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
if (latest) await writeCursor(ctx.engine, handler.kind, scope, cursorNow(), runId, opts.expect);
return unresolved.length <= target;
};
+ const batched = new Map<number, RepairSettlement>();
+ absorbBatched = () => {
+ for (const [index, settled] of [...batched].sort(([a], [b]) => a - b)) {
+ batched.delete(index);
+ if ('error' in settled) {
+ const receipt = acceptedPendingReceipt(settled.error);
+ if (receipt) unresolved.push({ index, item: pending[index]!, request_id: receipt.request_id });
+ continue;
+ }
+ const value = settled.value;
+ if (typeof value === 'object') {
+ result.outcomes = { ...result.outcomes, [value.outcome]: (result.outcomes?.[value.outcome] ?? 0) + 1 };
+ if ((result.outcome_items ??= []).length < (handler.outcomeItemsLimit ?? SAMPLE * 2)) {
+ result.outcome_items.push({ item: `${pending[index]!.source_id}:${pending[index]!.slug}`, outcome: value.outcome, ...(value.reason ? { reason: value.reason } : {}), ...(value.detail ? { detail: value.detail } : {}) });
+ }
+ }
+ if (typeof value === 'object' ? value.applied : value) result.applied++;
+ else result.skipped++;
+ }
+ };
+ // GBRA-443: a preview-bound apply waits out a refresh fence as long as managed sync's drain does; every other write keeps its own wait.
+ const step = <T>(fn: () => Promise<T>): Promise<T> => opts.expect ? withRepairRefreshWait(fn) : fn();
const pendingStop = (why: string) => {
+ absorbBatched();
result.pending = unresolved.map(({ item, request_id }) => ({ item: `${item.source_id}:${item.slug}`, request_id }));
const [first] = unresolved;
return { reason: 'write_pending', message: (unresolved.length === 1 ? `The repair of ${first.item.source_id}:${first.item.slug} was accepted and is still pending publication`
@@ -452,6 +516,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
+ `${why}. Rerun \`${result.apply_command}\` to resume; the same ${unresolved.length === 1 ? 'request is' : 'requests are'} replayed.` };
};
const stopAfterSettle = async (stopped: NonNullable<RepairResult['stopped']>): Promise<RepairResult> => {
+ absorbBatched();
if (!await settle(0)) stopped = { ...stopped, message: `${stopped.message} ${pendingStop('').message}` };
result.stopped = stopped;
return finish();
@@ -460,39 +525,62 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
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;
- // An item on a page this run's pending write is still changing waits for it, so it writes the page's new revision.
- const samePage = unresolved.some(open => open.item.source_id === item.source_id && open.item.slug === item.slug);
- if (unresolved.length && (unresolved.length >= window || lastApproved || samePage) && !await settle(lastApproved || samePage ? 0 : window - 1)) {
- result.stopped = pendingStop(settleMs ? `; nothing published for ${Math.round(settleMs / 1000)}s` : '');
- return finish();
- }
- if (opts.stop?.aborted) {
- return stopAfterSettle({ reason: 'interrupted', message: `Stopped before ${item.source_id}:${item.slug}: this process received ${String(opts.stop.reason ?? 'a termination signal')} `
- + `(${remaining} item(s) still pending; the items before it stay applied). Rerun \`${result.apply_command}\` to resume.` });
- }
- if (opts.deadline !== undefined && now() >= opts.deadline) {
- return stopAfterSettle({ reason: 'time_budget', message: `Stopped before ${item.source_id}:${item.slug}: this run reached its time budget (${remaining} item(s) still pending). `
- + `The next run resumes; rerun \`${result.apply_command}\` to continue now.` });
- }
- const allowanceLeft = opts.maxLlmUsd !== undefined ? opts.maxLlmUsd - llmSpent : undefined;
- if (llm && allowanceLeft !== undefined && (llmSpent >= opts.maxLlmUsd! || (item.llm_usd !== undefined && item.llm_usd > allowanceLeft + 1e-9))) {
- return stopAfterSettle({ reason: 'budget_exhausted', message: `Stopped before ${item.source_id}:${item.slug}: this run's paid-model allowance `
- + `${llmSpent >= opts.maxLlmUsd! ? 'is used up' : `cannot cover its estimate ($${item.llm_usd!.toFixed(4)})`} `
- + `($${llmSpent.toFixed(4)} spent of $${opts.maxLlmUsd!.toFixed(4)}; ${remaining} item(s) still pending). Rerun \`${result.apply_command}\` to resume.` });
- }
- const full = admits ? (await capacity(ctx)).find(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR) > c.stop_at) : undefined;
- if (full) {
- const perItem = full.resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR;
- const needed = Math.ceil((full.used + remaining * perItem) / STOP_RATIO) + 1;
- return stopAfterSettle({ reason: 'capacity', message: `Stopped before crossing 90% of ${full.scope} ${full.resource} (${full.used} of ${full.limit} used; `
- + `${remaining} item(s) still need ${remaining * perItem} more). Run: gbrain config set ${full.config_key} ${needed} — then rerun \`${result.apply_command}\` to resume.` });
+ // Items an applyBatch already settled were checked before it ran (GBRA-443); they are only recorded below.
+ if (!batched.has(index)) {
+ // 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;
+ // An item on a page this run's pending write is still changing waits for it, so it writes the page's new revision.
+ const samePage = unresolved.some(open => open.item.source_id === item.source_id && open.item.slug === item.slug);
+ if (unresolved.length && (unresolved.length >= window || lastApproved || samePage) && !await settle(lastApproved || samePage ? 0 : window - 1)) {
+ result.stopped = pendingStop(settleMs ? `; nothing published for ${Math.round(settleMs / 1000)}s` : '');
+ return finish();
+ }
+ if (opts.stop?.aborted) {
+ return stopAfterSettle({ reason: 'interrupted', message: `Stopped before ${item.source_id}:${item.slug}: this process received ${String(opts.stop.reason ?? 'a termination signal')} `
+ + `(${remaining} item(s) still pending; the items before it stay applied). Rerun \`${result.apply_command}\` to resume.` });
+ }
+ if (opts.deadline !== undefined && now() >= opts.deadline) {
+ return stopAfterSettle({ reason: 'time_budget', message: `Stopped before ${item.source_id}:${item.slug}: this run reached its time budget (${remaining} item(s) still pending). `
+ + `The next run resumes; rerun \`${result.apply_command}\` to continue now.` });
+ }
+ const allowanceLeft = opts.maxLlmUsd !== undefined ? opts.maxLlmUsd - llmSpent : undefined;
+ if (llm && allowanceLeft !== undefined && (llmSpent >= opts.maxLlmUsd! || (item.llm_usd !== undefined && item.llm_usd > allowanceLeft + 1e-9))) {
+ return stopAfterSettle({ reason: 'budget_exhausted', message: `Stopped before ${item.source_id}:${item.slug}: this run's paid-model allowance `
+ + `${llmSpent >= opts.maxLlmUsd! ? 'is used up' : `cannot cover its estimate ($${item.llm_usd!.toFixed(4)})`} `
+ + `($${llmSpent.toFixed(4)} spent of $${opts.maxLlmUsd!.toFixed(4)}; ${remaining} item(s) still pending). Rerun \`${result.apply_command}\` to resume.` });
+ }
+ const counters = admits ? await capacity(ctx) : [];
+ const full = counters.find(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR) > c.stop_at);
+ if (full) {
+ const perItem = full.resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR;
+ const needed = Math.ceil((full.used + remaining * perItem) / STOP_RATIO) + 1;
+ return stopAfterSettle({ reason: 'capacity', message: `Stopped before crossing 90% of ${full.scope} ${full.resource} (${full.used} of ${full.limit} used; `
+ + `${remaining} item(s) still need ${remaining * perItem} more). Run: gbrain config set ${full.config_key} ${needed} — then rerun \`${result.apply_command}\` to resume.` });
+ }
+ // GBRA-443: the items from here that fit the admission window, the capacity stop line and one write per page, applied as one run.
+ if (handler.applyBatch && !llm) {
+ const room = Math.min(Math.max(1, window - unresolved.length), ...counters.map(c => Math.floor((c.stop_at - c.used) / (c.resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR))));
+ const pages = new Set([...unresolved.map(open => open.item), item].map(other => other.source_id + '\0' + other.slug));
+ let end = index + 1;
+ for (; end < pending.length && end - index < room; end++) {
+ const key = pending[end]!.source_id + '\0' + pending[end]!.slug;
+ if (pages.has(key) || (opts.expect && end === plan.items.length - 1 && unresolved.length)) break;
+ pages.add(key);
+ }
+ const run = pending.slice(index, end);
+ // A thrown batch is the first item's failure, classified below like a single apply's; the rest run again from the next item.
+ const settled = await step(() => handler.applyBatch!({ ...ctx, sourceId: item.source_id }, run, { embed: opts.embed === true, runId, ...(opts.expect ? { expect: opts.expect } : {}) }))
+ .catch((error: unknown): RepairSettlement[] => [{ error }]);
+ settled.slice(0, run.length).forEach((entry, offset) => batched.set(index + offset, entry));
+ }
}
+ const prefetched = batched.get(index);
+ batched.delete(index);
try {
- const applied = await handler.apply({ ...ctx, sourceId: item.source_id, ...(unresolved.length ? { writeWaitMs: 0 } : {}) }, item, { embed: opts.embed === true, runId,
- ...(llm && opts.maxLlmUsd !== undefined ? { llmAllowanceUsd: opts.maxLlmUsd - llmSpent } : {}),
- ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.expect ? { expect: opts.expect } : {}) });
+ const applied = prefetched ? await ('error' in prefetched ? Promise.reject(prefetched.error) : prefetched.value)
+ : await step(() => handler.apply({ ...ctx, sourceId: item.source_id, ...(unresolved.length ? { writeWaitMs: 0 } : {}) }, item, { embed: opts.embed === true, runId,
+ ...(llm && opts.maxLlmUsd !== undefined ? { llmAllowanceUsd: opts.maxLlmUsd - llmSpent } : {}),
+ ...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.expect ? { expect: opts.expect } : {}) }));
if (llm && typeof applied === 'object' && applied.llm_usd) {
llmSpent += applied.llm_usd;
result.cost = { ...result.cost, llm_usd: llmSpent, llm_cap_remaining_usd: llmLeft(llmSpent) };
@@ -554,7 +642,9 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
}
// An apply bound to an approved preview (`--expect`) applies that set or answers why not; only the kinds' own refusals continue it.
if (opts.expect && !(error instanceof OperationError && REPAIR_ITEM_FAILURE_CODES.has(error.code))) throw error;
- const { failure, systemic: stop } = items.record(`${item.source_id}:${item.slug}`, error);
+ const carried = item.retried === true && error instanceof OperationError && REPAIR_DECLINE_CODES.has(error.code);
+ const { failure, systemic: stop } = carried ? { failure: { ...classifyItemFailure(error), key: `${item.source_id}:${item.slug}` }, systemic: null }
+ : items.record(`${item.source_id}:${item.slug}`, error);
if (stop) {
return stopAfterSettle({ reason: stop.code, message: redactConnectionInfo(`${stop.message} Fix the shared cause, then rerun \`${result.apply_command}\` to resume.`),
fix: readFix(`Previews ${handler.kind} again (read-only) to show whether the shared cause is gone.`, { argv: ['gbrain', 'repair', handler.kind, ...(opts.sourceFlag ? ['--source', opts.sourceFlag] : []), '--json'] }) });
diff --git a/src/core/repair/private-labels.ts b/src/core/repair/private-labels.ts
index 9030671c13..545f06fcd4 100644
--- a/src/core/repair/private-labels.ts
+++ b/src/core/repair/private-labels.ts
@@ -49,16 +49,21 @@
*/
import type { BrainEngine } from '../engine.ts';
import { serializePageToMarkdown } from '../markdown.ts';
-import { opError } from '../ops/contract.ts';
+import { opError, type OperationContext } from '../ops/contract.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { withTrustKeep } from '../persistence/context.ts';
-import { maintenancePreflight, publishMaintenancePage } from '../persistence/prepared-maintenance.ts';
+import { maintenancePreflight, publishMaintenancePage, publishMaintenancePages, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { getWriteRequest } from '../persistence/journal.ts';
+import { isTerminal } from '../persistence/model.ts';
+import { requestPrincipalForContext } from '../persistence/page-mutations.ts';
+import { digest } from '../persistence/digest.ts';
+import { modeRequiresSynopsis } from '../embedding-context.ts';
import { importFromContent } from '../import-file.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import { PRIVACY_ALIASES, privacyAliasSql, privacyPartSql, privateSnapshotFilterFragment, readHonorAliases } from '../search/private-visibility.ts';
-import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';
+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope, type RepairSettlement } from './core.ts';
export type ClearClass = 'alias' | 'alias-and-visibility' | 'git-publish';
export type KeepClass = 'pinned_question' | 'derived' | 'strong_alias' | 'explicit_visibility';
@@ -76,7 +81,8 @@ const bounded = { timeoutMs: 120_000 };
type Labels = { access?: string; visibility?: string };
interface LabelRow { id: number; source_id: string; slug: string; type: string; frontmatter: Record<string, unknown> | null; revision: string | null; chars: number; git: boolean }
interface Selection { source_ids: string[]; class: LabelsClass | null }
-interface Approved { mode: 'clear' | 'restore'; class: LabelsClass; brain_id: string; source_id: string; slug: string; page_id: number; revision: string | null; labels: Labels; chars: number; selection: Selection; exposes?: number[] }
+/** `tried` (GBRA-443): an earlier apply tried this page and it did not change; its decline again does not count toward the breaker. */
+interface Approved { mode: 'clear' | 'restore'; class: LabelsClass; brain_id: string; source_id: string; slug: string; page_id: number; revision: string | null; labels: Labels; chars: number; selection: Selection; exposes?: number[]; tried?: true }
interface LabelsItem extends RepairItem { entry: Approved; ledger: PrivateLabelsLedger }
/**
* One ledger line. `phase`: `intent` is appended before the page write, `committed` after it landed, with the revision it
@@ -159,7 +165,7 @@ const hashParts = (scope: RepairScope, selection: Selection, entries: Approved[]
items: entries.map(e => [e.mode, e.class, e.source_id, e.page_id, e.slug, e.revision, Object.entries(e.labels).sort(), e.exposes ?? []]) });
/** Every category's count over the scope and the clear entries of the selected classes, in (class, page id) order. */
-async function planClear(engine: BrainEngine, scope: RepairScope, selection: Selection, classes: readonly ClearClass[]) {
+async function planClear(engine: BrainEngine, scope: RepairScope, selection: Selection, classes: readonly ClearClass[], ledger?: PrivateLabelsLedger) {
const counts = Object.fromEntries([...KEEP_CLASSES, ...CLEAR_CLASSES].map(cls => [cls, 0])) as Record<KeepClass | ClearClass, number>;
const entries: Approved[] = [];
await scanLabelled(engine, scope.source_ids, row => {
@@ -170,7 +176,10 @@ async function planClear(engine: BrainEngine, scope: RepairScope, selection: Sel
if (classes.includes(decided.clear)) entries.push({ mode: 'clear', class: decided.clear, brain_id: scope.brain_id, source_id: row.source_id, slug: row.slug,
page_id: Number(row.id), revision: row.revision, labels: decided.removed, chars: Number(row.chars), selection });
});
- entries.sort((a, b) => CLEAR_CLASSES.indexOf(a.class as ClearClass) - CLEAR_CLASSES.indexOf(b.class as ClearClass) || a.page_id - b.page_id);
+ const tried = triedBefore(ledger, scope.brain_id);
+ for (const entry of entries) if (tried.has(entry.source_id + '\0' + entry.page_id)) entry.tried = true;
+ const retry = (entry: Approved) => Number(entry.tried === true);
+ entries.sort((a, b) => retry(a) - retry(b) || CLEAR_CLASSES.indexOf(a.class as ClearClass) - CLEAR_CLASSES.indexOf(b.class as ClearClass) || a.page_id - b.page_id);
return { counts: counts as Record<string, number>, entries, unreadable: 0 };
}
@@ -294,8 +303,121 @@ async function importAtRevision(engine: BrainEngine, entry: Approved, revision:
});
}
+/** GBRA-443: lines this run appended to each ledger, by phase (the apply result's ledger_rows_written and ledger_rows). */
+const ledgerRows = new WeakMap<PrivateLabelsLedger, { intent: number; committed: number }>();
+function recordLine(ledger: PrivateLabelsLedger, line: LedgerLine & { phase: 'intent' | 'committed' }): void {
+ ledger.record(line);
+ const rows = ledgerRows.get(ledger) ?? { intent: 0, committed: 0 };
+ rows[line.phase]++;
+ ledgerRows.set(ledger, rows);
+}
+
+/**
+ * GBRA-443: the pages (brain, source, page id) whose latest ledger line is a removal's intent line with nothing after it:
+ * an earlier apply tried to clear them and the write did not land (a declined page; a crash before its write, too). The
+ * preview lists them after every page not tried yet, so a page that keeps declining stops heading each new window.
+ */
+function triedBefore(ledger: PrivateLabelsLedger | undefined, brainId: string): Set<string> {
+ const latest = new Map<string, LedgerLine>();
+ for (const raw of ledger?.lines ?? []) {
+ const line = readableLine(raw);
+ if (line && line.brain_id === brainId) latest.set(line.source_id + '\0' + line.page_id, line);
+ }
+ return new Set([...latest].flatMap(([key, line]) => line.removed && line.phase === 'intent' ? [key] : []));
+}
+
+/** GBRA-443: the listed items whose write re-embeds: a label-only edit keeps every stored vector except on a page stored under per-chunk synopsis. */
+async function reembedding(engine: BrainEngine, items: LabelsItem[]): Promise<LabelsItem[]> {
+ if (!items.length) return [];
+ const rows = await engine.executeRaw<{ id: number; mode: string }>(`SELECT id, contextual_retrieval_mode AS mode FROM pages
+ WHERE id = ANY($1::integer[]) AND contextual_retrieval_mode IS NOT NULL`, [items.map(item => item.entry.page_id)], bounded);
+ const synopsis = new Set(rows.filter(row => modeRequiresSynopsis(row.mode as Parameters<typeof modeRequiresSynopsis>[0])).map(row => Number(row.id)));
+ return items.filter(item => synopsis.has(item.entry.page_id));
+}
+
+const CHANGED: RepairItemOutcome = { applied: false, outcome: 'changed_since_preview' };
+interface Ready { revision: string; content: string; labels: Labels }
+
+/**
+ * One approved item re-decided against its live page: the page write it needs, or the outcome that leaves it alone (moved
+ * since the preview, segmented, no longer this class, or held as file_backed on an unmanaged brain).
+ */
+async function prepareWrite(ctx: OperationContext, item: LabelsItem): Promise<Ready | { outcome: RepairItemOutcome }> {
+ const { entry } = item;
+ const snapshot = await ctx.engine.readPageSnapshot(entry.slug, { sourceId: entry.source_id });
+ if (!snapshot || Number(snapshot.page.id) !== entry.page_id || snapshot.revision !== entry.revision) return { outcome: CHANGED };
+ if (isSegmentedPage(snapshot.page)) return { outcome: { applied: false, outcome: 'segmented_page', reason: 'The page body is stored in segments; edit its frontmatter by hand on the brain host.' } };
+ const frontmatter = snapshot.page.frontmatter ?? {};
+ const labels = ledgerLabels(entry.labels);
+ if (!labels) return { outcome: CHANGED };
+ let next: Record<string, unknown>;
+ if (entry.mode === 'clear') {
+ let decided: Decision = null;
+ await scanLabelled(ctx.engine, [entry.source_id], row => { decided = classifyPrivateLabel(row); }, [entry.page_id]);
+ const current = decided as Decision;
+ if (!current || !('clear' in current) || current.clear !== entry.class || !sameLabels(current.removed, labels)) return { outcome: CHANGED };
+ next = Object.fromEntries(Object.entries(frontmatter).filter(([key]) => !Object.hasOwn(labels, key)));
+ } else {
+ if (Object.keys(labels).some(key => Object.hasOwn(frontmatter, key))) return { outcome: CHANGED };
+ next = { ...frontmatter, ...labels };
+ }
+ const file = (await filesInCheckout(ctx.engine, [entry.page_id])).get(entry.page_id);
+ if (file) {
+ return { outcome: { applied: false, outcome: 'file_backed', detail: { path: file },
+ reason: `${entry.source_id}:${entry.slug} has a file in its source's checkout (${file}); on a brain without managed persistence this repair writes only the database, `
+ + `so the next sync or re-import would undo it from the file. ${entry.mode === 'clear' ? `Remove ${describeLabels(labels)} from that file's frontmatter`
+ : `Add ${describeLabels(labels)} back to that file's frontmatter if it is missing`}, commit it, then run: gbrain sync --source ${entry.source_id}` } };
+ }
+ return { revision: snapshot.revision, content: serializePageToMarkdown({ ...snapshot.page, frontmatter: next }, snapshot.tags), labels };
+}
+
+/** The item's ledger line under its deterministic request id (a resumed run replays the same request). */
+async function ledgerLine(ctx: OperationContext, item: LabelsItem, ready: Ready): Promise<LedgerLine> {
+ const { entry } = item;
+ return { at: new Date().toISOString(), brain_id: entry.brain_id, source_id: entry.source_id, slug: entry.slug, page_id: entry.page_id,
+ revision_before: ready.revision, request_id: await repairRequestId(ctx, 'private-labels', item, ready.revision),
+ ...(entry.mode === 'clear' ? { removed: ready.labels } : { restored: ready.labels }) };
+}
+
+/** Write-ahead: the intent line lands before the page write, or the item is refused with nothing written. */
+function recordIntent(item: LabelsItem, line: LedgerLine): void {
+ try { recordLine(item.ledger, { ...line, phase: 'intent' }); } catch (error) {
+ throw opError('storage_error', `${line.source_id}:${line.slug} was not written: the undo ledger ${item.ledger.path} did not take its intent line (${error instanceof Error ? error.message : String(error)}).`,
+ `Make ${item.ledger.path} writable by this user, then rerun the same apply command; nothing was changed and the approved preview is kept.`);
+ }
+}
+
+/** The landed write's committed line, with the revision it wrote; a ledger that cannot take it still leaves the intent line restore reads. */
+function committedOutcome(item: LabelsItem, line: LedgerLine, written: string | null): RepairItemOutcome {
+ const outcome = item.entry.mode === 'clear' ? 'cleared' : 'restored';
+ try { recordLine(item.ledger, { ...line, at: new Date().toISOString(), phase: 'committed', ...(written ? { revision_after: written } : {}) }); } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return { applied: true, outcome, reason: `The page was written and its intent line is in the ledger, so --class restore finds it, but its commit line was not saved (${message}).`,
+ detail: { ledger: item.ledger.path, ledger_error: message, labels: line.removed ?? line.restored } };
+ }
+ return { applied: true, outcome, detail: { ledger: item.ledger.path } };
+}
+
+const writtenRevision = async (engine: BrainEngine, entry: Approved) => (await engine.readPageSnapshot(entry.slug, { sourceId: entry.source_id }))?.revision ?? null;
+
+/** One item's page write after its intent line: the maintenance door on a managed brain, the legacy import under the page lock otherwise. */
+async function writeOne(ctx: OperationContext, item: LabelsItem, ready: Ready, line: LedgerLine, authority: MaintenanceAuthority | null, embed: boolean): Promise<RepairItemOutcome> {
+ recordIntent(item, line);
+ let written: string | null;
+ if (authority) {
+ await publishMaintenancePage(ctx.engine, authority, item.entry.slug, ready.content, { expectedRevision: ready.revision, requestId: line.request_id, keepTrust: true });
+ written = await writtenRevision(ctx.engine, item.entry);
+ } else {
+ written = await importAtRevision(ctx.engine, item.entry, ready.revision, ready.content, embed);
+ if (!written) return CHANGED;
+ }
+ return committedOutcome(item, line, written);
+}
+
export const privateLabelsRepair: RepairHandler = {
kind: 'private-labels',
+ /** GBRA-443: a label-only edit keeps every stored vector; the plan names the pages that re-embed anyway (embedding_items). */
+ embeds: false,
async plan(engine, scope, after, opts): Promise<RepairPlan> {
const selection: Selection = { source_ids: scope.source_ids, class: selectedClass(opts) };
const command = previewCommand(scope, selection);
@@ -304,7 +426,8 @@ export const privateLabelsRepair: RepairHandler = {
throw opError('invalid_params', 'gbrain repair private-labels needs its undo ledger to apply or restore, and this caller passed none.', `Run it from the CLI on the brain host: ${command}`);
}
const toItems = (entries: Approved[]) => entries.map((entry, index): LabelsItem => ({ cursor: { phase: 0, id: index }, source_id: entry.source_id, slug: entry.slug,
- chars: entry.chars, action: `${entry.mode === 'clear' ? 'remove' : 're-add'} ${describeLabels(entry.labels)}`, entry, ledger: ledger! }));
+ chars: entry.chars, action: `${entry.mode === 'clear' ? 'remove' : 're-add'} ${describeLabels(entry.labels)}`, entry, ledger: ledger!,
+ ...(entry.tried ? { retried: true } : {}) }));
if (opts?.apply) {
if (!opts.expect) {
throw opError('invalid_params', 'gbrain repair private-labels --apply changes only the set a preview printed (clearing a label widens remote reads).',
@@ -317,13 +440,16 @@ export const privateLabelsRepair: RepairHandler = {
}
const approvedExposes = new Set(approved.items.flatMap(entry => entry.exposes ?? []));
if ([...(await windowDependents(engine, approved.items)).exposes.values()].flat().some(id => !approvedExposes.has(id))) throw previewChangedError(opts.expect, command);
- return { items: toItems(approved.items).filter(item => afterCursor(item.cursor, after)), preview_hash: opts.expect, residuals: {} };
+ ledgerRows.set(ledger!, { intent: 0, committed: 0 });
+ const items = toItems(approved.items).filter(item => afterCursor(item.cursor, after));
+ return { items, preview_hash: opts.expect, residuals: {}, embedding_items: await reembedding(engine, items) };
}
const size = Math.min(Math.max(1, opts?.limit ?? PRIVATE_LABELS_WINDOW), PRIVATE_LABELS_WINDOW_MAX);
const restore = selection.class === 'restore';
const planned = restore ? await planRestore(engine, scope, selection, ledger!)
- : await planClear(engine, scope, selection, selection.class ? [selection.class as ClearClass] : DEFAULT_CLASSES);
+ : await planClear(engine, scope, selection, selection.class ? [selection.class as ClearClass] : DEFAULT_CLASSES, ledger);
const window = planned.entries.slice(0, size);
+ const retried = window.filter(entry => entry.tried).length;
const pastWindow = planned.entries.length - window.length;
const before = { ...planned.counts };
const projected = { ...before };
@@ -355,84 +481,115 @@ export const privateLabelsRepair: RepairHandler = {
+ 'can read them once this window applies (readable_by and folder rules still apply). To keep one private, give it its own label first; --class restore re-hides them with their origins.'] : []),
...(fileBacked ? [`${fileBacked} listed page(s) have a file in their source's checkout on a brain without managed persistence. This repair writes only the database there, `
+ 'and the next sync or re-import would put the label back from the file, so the apply holds each (outcome file_backed) with the file to edit.'] : []),
+ ...(retried ? [`${retried} listed page(s) were tried by an earlier apply and did not change (the ledger has their intent line and nothing after it); `
+ + 'they are listed after every page not tried yet. Each is tried again and, if its page still declines, left unchanged with its reason; '
+ + 'such a decline does not count toward the run\'s systemic-failure stop.'] : []),
...(planned.unreadable ? [`${planned.unreadable} ledger line(s) could not be read and are not planned.`] : []),
...(restore && before.removed_after_restore ? [`${before.removed_after_restore} page(s) had their label removed after a restore landed (the page changed since the revision the restore wrote), `
+ 'so they are not listed; re-add the label by hand if that edit was a mistake.'] : []),
...(restore && !Object.values(before).some(Boolean) ? [`The ledger ${ledger!.path} has no line for brain ${scope.brain_id} in this scope. Restore reads only the ledger on the host `
+ 'and GBRAIN_HOME that ran the clear; run it there.'] : []),
];
- return { items: toItems(window), preview_hash: hash, residuals: {}, warnings,
+ const items = toItems(window);
+ return { items, preview_hash: hash, residuals: {}, warnings, embedding_items: await reembedding(engine, items),
listing: window.map(entry => ({ item: `${entry.source_id}:${entry.slug}`, class: entry.class,
detail: entry.mode === 'restore' ? `re-add ${describeLabels(entry.labels)}` : entry.labels.visibility ? 'remove access: private, visibility: private' : 'remove access: private' })),
- details: { counts: { before, after: projected }, window: { size, listed: window.length, pending_past_window: pastWindow, next_preview: command, file_backed: fileBacked },
+ details: { counts: { before, after: projected }, window: { size, listed: window.length, pending_past_window: pastWindow, next_preview: command, file_backed: fileBacked, tried_before: retried },
...(dependents ? { dependents } : {}),
ledger: ledger?.path ?? null, class: selection.class } };
},
async apply(ctx, raw, opts): Promise<RepairItemOutcome> {
const item = raw as LabelsItem;
- const { entry } = item;
- const changed: RepairItemOutcome = { applied: false, outcome: 'changed_since_preview' };
- const snapshot = await ctx.engine.readPageSnapshot(entry.slug, { sourceId: entry.source_id });
- if (!snapshot || Number(snapshot.page.id) !== entry.page_id || snapshot.revision !== entry.revision) return changed;
- if (isSegmentedPage(snapshot.page)) return { applied: false, outcome: 'segmented_page', reason: 'The page body is stored in segments; edit its frontmatter by hand on the brain host.' };
- const frontmatter = snapshot.page.frontmatter ?? {};
- const labels = ledgerLabels(entry.labels);
- if (!labels) return changed;
- let next: Record<string, unknown>;
- if (entry.mode === 'clear') {
- let decided: Decision = null;
- await scanLabelled(ctx.engine, [entry.source_id], row => { decided = classifyPrivateLabel(row); }, [entry.page_id]);
- const current = decided as Decision;
- if (!current || !('clear' in current) || current.clear !== entry.class || !sameLabels(current.removed, labels)) return changed;
- next = Object.fromEntries(Object.entries(frontmatter).filter(([key]) => !Object.hasOwn(labels, key)));
- } else {
- if (Object.keys(labels).some(key => Object.hasOwn(frontmatter, key))) return changed;
- next = { ...frontmatter, ...labels };
+ const ready = await prepareWrite(ctx, item);
+ if ('outcome' in ready) return ready.outcome;
+ const authority = await maintenancePreflight(ctx.engine, item.entry.source_id);
+ return writeOne(ctx, item, ready, await ledgerLine(ctx, item, ready), authority, opts?.embed === true);
+ },
+ /**
+ * GBRA-443: a run of approved items at once. Each is re-decided as apply does; on a managed brain every page of a source
+ * gets its intent line first (write-ahead for the whole run), then the pages are admitted together and the owner publishes
+ * them in groups (publishMaintenancePages), each page its own fate: a declined page fails alone. The batch id is the
+ * approval hash, so a window resumed at any item replays its pending requests. An unmanaged source writes one page at a
+ * time, as apply does.
+ */
+ async applyBatch(ctx, raw, opts) {
+ const items = raw as LabelsItem[];
+ const out: RepairSettlement[] = new Array(items.length);
+ const settle = (index: number, write: () => Promise<RepairItemOutcome>) => write().then(value => { out[index] = { value }; }, error => { out[index] = { error }; });
+ const ready: Array<Ready | null> = [];
+ for (const [index, item] of items.entries()) {
+ const prepared = await prepareWrite(ctx, item).catch((error: unknown) => ({ error }));
+ ready.push('revision' in prepared ? prepared : null);
+ if ('error' in prepared) out[index] = { error: prepared.error };
+ else if ('outcome' in prepared) out[index] = { value: prepared.outcome };
}
- const file = (await filesInCheckout(ctx.engine, [entry.page_id])).get(entry.page_id);
- if (file) {
- return { applied: false, outcome: 'file_backed', detail: { path: file },
- reason: `${entry.source_id}:${entry.slug} has a file in its source's checkout (${file}); on a brain without managed persistence this repair writes only the database, `
- + `so the next sync or re-import would undo it from the file. ${entry.mode === 'clear' ? `Remove ${describeLabels(labels)} from that file's frontmatter`
- : `Add ${describeLabels(labels)} back to that file's frontmatter if it is missing`}, commit it, then run: gbrain sync --source ${entry.source_id}` };
+ const principal = await requestPrincipalForContext(ctx);
+ for (const sourceId of new Set(items.map(item => item.entry.source_id))) {
+ const indices = items.flatMap((item, index) => item.entry.source_id === sourceId && ready[index] ? [index] : []);
+ if (!indices.length) continue;
+ const preflight = await maintenancePreflight(ctx.engine, sourceId).then(authority => ({ authority }), (error: unknown) => ({ error }));
+ if ('error' in preflight) { for (const index of indices) out[index] = { error: preflight.error }; continue; }
+ const { authority } = preflight;
+ const batch: Array<{ index: number; line: LedgerLine }> = [];
+ for (const index of indices) {
+ const line = await ledgerLine(ctx, items[index]!, ready[index]!);
+ // An unmanaged source, or a request a single-page apply admitted before batching (its intent has no batch id), writes on its own.
+ const prior = authority ? await getWriteRequest(ctx.engine, principal, line.request_id) : null;
+ if (!authority || (prior && !isTerminal(prior) && typeof prior.intent?.maintenance_batch !== 'string')) {
+ await settle(index, () => writeOne(ctx, items[index]!, ready[index]!, line, authority, opts.embed));
+ continue;
+ }
+ batch.push({ index, line });
+ }
+ if (!batch.length || !authority) continue;
+ const admitted: typeof batch = [];
+ for (const [position, entry] of batch.entries()) {
+ try { recordIntent(items[entry.index]!, entry.line); admitted.push(entry); } catch (error) {
+ // A ledger that refuses one intent line refuses the rest too: nothing after it is written.
+ for (const rest of batch.slice(position)) out[rest.index] = { error };
+ break;
+ }
+ }
+ if (!admitted.length) continue;
+ const published = await publishMaintenancePages(ctx.engine, authority, admitted.map(({ index, line }) => ({ slug: items[index]!.entry.slug, content: ready[index]!.content,
+ expectedRevision: ready[index]!.revision, requestId: line.request_id, keepTrust: true as const })), { batch: digest(['private-labels-batch-v1', opts.expect ?? opts.runId ?? '', sourceId]) });
+ for (const [position, { index, line }] of admitted.entries()) {
+ const settled = published[position]!;
+ if ('error' in settled) { out[index] = { error: settled.error }; continue; }
+ out[index] = { value: committedOutcome(items[index]!, line, await writtenRevision(ctx.engine, items[index]!.entry)) };
+ }
}
- const authority = await maintenancePreflight(ctx.engine, entry.source_id);
- const requestId = await repairRequestId(ctx, 'private-labels', item, snapshot.revision);
+ return out;
+ },
+ /** GBRA-443: a write still pending when its run moved on, committed later in the run: its committed line, as apply writes for one that landed in its wait. */
+ async onCommitted(ctx, raw, requestId) {
+ const item = raw as LabelsItem;
+ const { entry } = item;
const line: LedgerLine = { at: new Date().toISOString(), brain_id: entry.brain_id, source_id: entry.source_id, slug: entry.slug, page_id: entry.page_id,
- revision_before: snapshot.revision, request_id: requestId, ...(entry.mode === 'clear' ? { removed: labels } : { restored: labels }) };
- try { item.ledger.record({ ...line, phase: 'intent' }); } catch (error) {
- throw opError('storage_error', `${entry.source_id}:${entry.slug} was not written: the undo ledger ${item.ledger.path} did not take its intent line (${error instanceof Error ? error.message : String(error)}).`,
- `Make ${item.ledger.path} writable by this user, then rerun the same apply command; nothing was changed and the approved preview is kept.`);
- }
- const content = serializePageToMarkdown({ ...snapshot.page, frontmatter: next }, snapshot.tags);
- let written: string | null;
- if (authority) {
- await publishMaintenancePage(ctx.engine, authority, entry.slug, content, { expectedRevision: snapshot.revision, requestId, keepTrust: true });
- written = (await ctx.engine.readPageSnapshot(entry.slug, { sourceId: entry.source_id }))?.revision ?? null;
- } else {
- written = await importAtRevision(ctx.engine, entry, snapshot.revision, content, opts?.embed === true);
- if (!written) return changed;
- }
- const outcome = entry.mode === 'clear' ? 'cleared' : 'restored';
- try { item.ledger.record({ ...line, at: new Date().toISOString(), phase: 'committed', ...(written ? { revision_after: written } : {}) }); } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- return { applied: true, outcome, reason: `The page was written and its intent line is in the ledger, so --class restore finds it, but its commit line was not saved (${message}).`,
- detail: { ledger: item.ledger.path, ledger_error: message, labels } };
- }
- return { applied: true, outcome, detail: { ledger: item.ledger.path } };
+ revision_before: entry.revision ?? '', request_id: requestId, ...(entry.mode === 'clear' ? { removed: entry.labels } : { restored: entry.labels }) };
+ committedOutcome(item, line, await writtenRevision(ctx.engine, entry));
},
- /** GST-2128 item 7: the approved set is retired only by an apply that attempted every item with no failure, stop or pending write. */
+ /**
+ * GST-2128 item 7: the approved set is retired only by an apply that attempted every item with no failure, stop or pending write.
+ * GBRA-443: an apply reports where its ledger is and how many lines it appended (intent and committed), so a caller can
+ * check the file grew by ledger_rows_written and that every applied page has its committed line.
+ */
async report(ctx, _scope, result, opts) {
if (result.mode === 'apply' && opts.expect && result.complete && !result.stopped && !result.failed.length && !result.pending?.length) {
await clearApprovedSet(ctx.engine, { command: 'private-labels', hash: opts.expect });
}
- return {};
+ const ledger = opts.privateLabelsLedger;
+ if (result.mode !== 'apply' || !ledger) return {};
+ const rows = ledgerRows.get(ledger) ?? { intent: 0, committed: 0 };
+ return { details: { ...result.details, ledger: ledger.path, ledger_rows_written: rows.intent + rows.committed, ledger_rows: { ...rows } } };
},
render(details) {
const counts = details.counts as { before: Record<string, number>; after: Record<string, number> } | undefined;
const line = (values: Record<string, number>) => Object.entries(values).map(([key, value]) => `${key}=${value}`).join(', ');
const dependents = details.dependents as Record<string, number> | undefined;
+ const rows = details.ledger_rows as { intent: number; committed: number } | undefined;
return [...(counts ? [` before: ${line(counts.before)}`, ` after (this window applied): ${line(counts.after)}`] : []),
- ...(dependents ? [` also exposed by this window: ${line(dependents)}`] : []), ...(details.ledger ? [` ledger: ${String(details.ledger)}`] : [])];
+ ...(dependents ? [` also exposed by this window: ${line(dependents)}`] : []),
+ ...(details.ledger ? [` ledger: ${String(details.ledger)}${rows ? ` (this run appended ${rows.intent + rows.committed} line(s): ${rows.intent} intent, ${rows.committed} committed)` : ''}`] : [])];
},
};
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 6c89ff23f5..440e68a989 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -660,7 +660,9 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ '(atoms, synthesized concepts, chronicle events), access restricted or confidential, a confidentiality value, and visibility: private with no alias. '
+ 'The preview lists one window (--limit, default 1000) by class (alias, alias-and-visibility) with every category\'s count before and after, and counts '
+ 'the derived_from pages and chronicle events the window would also expose; --apply --expect <hash> applies exactly that window, one revision-bound page '
- + 'write each (a run that fails keeps the preview, so the same command resumes); a bare --apply is refused. Pages in git-canonical sources '
+ + 'write each, admitted together and published in groups on a managed brain (a run that fails keeps the preview, so the same command resumes; a page '
+ + 'that declines, its file drifted or gone, fails alone, is counted in declined and is listed after untried pages next time, and a complete run whose '
+ + 'only failures are declines exits 0); a bare --apply is refused. Pages in git-canonical sources '
+ '(git-publish: clearing commits them into Git) run only with --class git-publish; without managed persistence a page with a file in its checkout is held '
+ '(file_backed). Each change is recorded ahead of its write in ~/.gbrain/repair/private-labels/<brain>.jsonl (under $GBRAIN_HOME/.gbrain/ if set), '
+ 'and --class restore re-adds access and visibility: private from it. Runs only when named; never on upgrade.',
diff --git a/test/repair-private-labels-batch.test.ts b/test/repair-private-labels-batch.test.ts
new file mode 100644
index 0000000000..6d0a542338
--- /dev/null
+++ b/test/repair-private-labels-batch.test.ts
@@ -0,0 +1,346 @@
+/**
+ * gbrain repair private-labels, applied a window at a time (GBRA-443).
+ *
+ * 1. Protects: a managed window is admitted as one maintenance batch and published in groups; a page whose write is
+ * declined (its file drifted before admission, or a refusal inside its publication group) fails alone and every other
+ * page of the group lands; every page's intent line is in the ledger before any page of the group is published, so
+ * each cleared label has its undo line even when the process dies after the group published; a ledger written before
+ * the write-ahead ledger (v0.60.641.0, no phase) still restores; the preview claims no re-embeds except for pages stored
+ * under per-chunk synopsis; pages an earlier apply tried and that did not change are listed after the rest; a
+ * preview-bound apply whose only failures are declines exits 0 with a declined summary; an apply result names its
+ * ledger and how many lines it appended; a preview-bound apply waits out a source refresh past the 10 s an
+ * interactive write gets, up to its own 10-minute ceiling, and past it is refused whole and resumes; a page an earlier
+ * apply tried that declines again does not count toward the systemic-failure stop, while fresh pages still do.
+ * 2. Fails when: a decline fails or blocks another page, the batch path is not taken, the ledger is written after a page
+ * of its run, restore misses a page, the cost claims re-embeds, the order puts retried pages first, the exit is 1 for
+ * declines only (or 0 for anything else), the ledger fields are missing or wrong, or a refresh refuses the apply early.
+ * 3. Real seams: PGLite and Postgres, repo-less and managed (a claimed worktree with Git), the gbrain repair command entry.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { runRepairCommand, repairExitVerdict } from '../src/commands/repair.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';
+import { privateLabelsLedger } from '../src/commands/repair-private-labels.ts';
+import type { PrivateLabelsLedgerLine } from '../src/core/repair/private-labels.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { persistenceHome } from '../src/core/persistence/identity.ts';
+import { tryAcquireNativeLock } from '../src/core/persistence/native-lock.ts';
+import { _setRepairRefreshWaitForTests, _setRefreshFenceWaitForTests } from '../src/core/persistence/admission-retry.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { durableGitRepo } from './helpers/git-publication.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const NL = String.fromCharCode(10);
+const logger = { info() {}, warn() {}, error() {} };
+
+async function capture(fn: () => Promise<void>): Promise<string> {
+ let printed = '';
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { printed += parts.map(String).join(' ') + NL; };
+ try { await fn(); } finally { console.log = original; }
+ return printed;
+}
+
+/** One gbrain repair run through the command entry: its JSON result and the exit code it set. */
+async function cli(engine: BrainEngine, argv: string[], env: Record<string, string> = {}): Promise<{ result: any; exit: number }> {
+ _resetCliExitVerdictForTests();
+ try {
+ const printed = await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1', ...env }, () => capture(() => runRepairCommand(engine, [...argv, '--json'])));
+ return { result: JSON.parse(printed).results[0], exit: currentExitCode() };
+ } finally { _resetCliExitVerdictForTests(); process.exitCode = 0; }
+}
+
+const lines = (path: string): PrivateLabelsLedgerLine[] => existsSync(path) ? readFileSync(path, 'utf8').trim().split(NL).filter(Boolean).map(line => JSON.parse(line)) : [];
+const labelled = (slug: string, extra: Record<string, unknown> = {}) => serializeMarkdown({ access: 'private', topic: 'kept', ...extra }, slug + ' body text.' + NL + NL + 'Second paragraph of ' + slug + '.', '',
+ { type: 'note' as never, title: slug, tags: ['t1'] });
+const put = (ctx: OperationContext, slug: string, content: string) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content } });
+const frontmatter = async (engine: BrainEngine, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page.frontmatter as Record<string, unknown>;
+const lastSequence = async (engine: BrainEngine) => String((await engine.executeRaw<{ s: string | null }>('SELECT max(sequence)::text AS s FROM persistence_requests'))[0]?.s ?? '0');
+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), NL); durableGitRepo(root, ['.gitignore']); };
+
+afterAll(() => { installFaultHook(undefined); _setRefreshFenceWaitForTests(null); _setRepairRefreshWaitForTests(null); });
+
+describe('gbrain repair exit verdict (GBRA-443)', () => {
+ const base = { stopped: undefined, complete: true, failed: [] as RepairResult['failed'] };
+ const failed = (reason: string) => ({ item: 'default:notes/a', source_id: 'default', slug: 'notes/a', reason, message: 'x', retry: 'next_full_scan' as const });
+ test('a preview-bound apply that is complete with only declines exits 0; anything else keeps exit 1', () => {
+ expect(repairExitVerdict([{ ...base, failed: [failed('source_changed'), failed('page_body_segmented')] }], { previewBound: true })).toBe(0);
+ expect(repairExitVerdict([{ ...base, failed: [failed('source_changed')] }])).toBe(1);
+ expect(repairExitVerdict([{ ...base, failed: [failed('source_changed'), failed('internal')] }], { previewBound: true })).toBe(1);
+ expect(repairExitVerdict([{ ...base, failed: [failed('source_changed')], complete: false }], { previewBound: true })).toBe(1);
+ expect(repairExitVerdict([{ ...base, failed: [failed('source_changed')], stopped: { reason: 'capacity', message: 'x' } }], { previewBound: true })).toBe(1);
+ expect(repairExitVerdict([base], { previewBound: true })).toBe(0);
+ });
+});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ describe('[' + backend + '] repair private-labels on a repo-less brain (GBRA-443)', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-private-labels-batch-'));
+ const env = { GBRAIN_HOME: home };
+ beforeAll(async () => {
+ if (databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; close = () => pglite.disconnect(); }
+ }, 120_000);
+ afterAll(async () => { await disposePersistenceConsumer(engine); await close(); rmSync(home, { recursive: true, force: true }); });
+ const seed = async (source: string, slug: string, extra: Record<string, unknown> = {}) => {
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);
+ const result = await importFromContent(engine, slug, labelled(slug, extra), { noEmbed: true, forceRechunk: true, sourceId: source });
+ expect(result.status).toBe('imported');
+ };
+ const pageId = async (source: string, slug: string) => Number((await engine.readPageSnapshot(slug, { sourceId: source }))!.page.id);
+
+ test('the preview claims no re-embeds for a label-only edit, except for a page stored under per-chunk synopsis', async () => {
+ await seed('source-e', 'notes/e0');
+ await seed('source-e', 'notes/e1');
+ const plain = (await cli(engine, ['private-labels', '--source', 'source-e'], env)).result;
+ expect(plain.listing.length).toBe(2);
+ expect(plain.cost.embedding_pages).toBe(0);
+ await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode='per_chunk_synopsis' WHERE source_id='source-e' AND slug='notes/e1'");
+ const synopsis = (await cli(engine, ['private-labels', '--source', 'source-e'], env)).result;
+ expect(synopsis.cost.embedding_pages).toBe(1);
+ });
+
+ test('pages an earlier apply tried and that did not change are listed after every page not tried yet; the apply names its ledger and the lines it appended', async () => {
+ const source = 'source-o';
+ const slugs = [0, 1, 2, 3].map(i => 'notes/o' + i);
+ for (const slug of slugs) await seed(source, slug);
+ const { brain_id: brain } = await resolveRepairScope(engine, source);
+ const path = await withEnv(env, async () => privateLabelsLedger(brain).path);
+ mkdirSync(dirname(path), { recursive: true });
+ // What an apply leaves for a page that declined: its intent line and nothing after it.
+ for (const slug of slugs.slice(0, 2)) {
+ const id = await pageId(source, slug);
+ appendFileSync(path, JSON.stringify({ at: new Date().toISOString(), brain_id: brain, source_id: source, slug, page_id: id, revision_before: 'r', request_id: randomUUID(),
+ removed: { access: 'private' }, phase: 'intent' }) + NL);
+ }
+ const preview = (await cli(engine, ['private-labels', '--source', source], env)).result;
+ expect(preview.listing.map((entry: { item: string }) => entry.item)).toEqual([2, 3, 0, 1].map(i => source + ':' + slugs[i]));
+ expect(preview.details.window.tried_before).toBe(2);
+ expect(preview.warnings.some((w: string) => w.includes('2 listed page(s) were tried by an earlier apply'))).toBe(true);
+ const before = lines(path).length;
+ const { result: applied, exit } = await cli(engine, ['private-labels', '--source', source, '--apply', '--expect', preview.preview_hash], env);
+ expect(exit).toBe(0);
+ expect(applied.applied).toBe(4);
+ expect(applied.declined).toBeUndefined();
+ expect(applied.details.ledger).toBe(path);
+ expect(applied.details.ledger_rows).toEqual({ intent: 4, committed: 4 });
+ expect(applied.details.ledger_rows_written).toBe(8);
+ expect(lines(path).length - before).toBe(applied.details.ledger_rows_written);
+ for (const slug of slugs) expect('access' in ((await engine.readPageSnapshot(slug, { sourceId: source }))!.page.frontmatter as object)).toBe(false);
+ });
+
+ test('a ledger written by v0.60.641.0 (one line per landed write, no phase) still restores', async () => {
+ const source = 'source-v';
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);
+ for (const slug of ['notes/v0', 'notes/v1']) {
+ await importFromContent(engine, slug, serializeMarkdown({ topic: 'kept' }, slug + ' body.', '', { type: 'note' as never, title: slug, tags: [] }), { noEmbed: true, sourceId: source });
+ }
+ const { brain_id: brain } = await resolveRepairScope(engine, source);
+ const path = await withEnv(env, async () => privateLabelsLedger(brain).path);
+ mkdirSync(dirname(path), { recursive: true });
+ appendFileSync(path, JSON.stringify({ at: '2026-11-09T00:00:00.000Z', brain_id: brain, source_id: source, slug: 'notes/v0', page_id: await pageId(source, 'notes/v0'),
+ revision_before: '1', request_id: randomUUID(), removed: { access: 'private' } }) + NL);
+ appendFileSync(path, JSON.stringify({ at: '2026-11-09T00:00:01.000Z', brain_id: brain, source_id: source, slug: 'notes/v1', page_id: await pageId(source, 'notes/v1'),
+ revision_before: '1', request_id: randomUUID(), removed: { access: 'private', visibility: 'private' } }) + NL);
+ const preview = (await cli(engine, ['private-labels', '--source', source, '--class', 'restore'], env)).result;
+ expect(preview.listing).toEqual([
+ { item: source + ':notes/v0', class: 'restore', detail: 're-add access: private' },
+ { item: source + ':notes/v1', class: 'restore', detail: 're-add access: private, visibility: private' },
+ ]);
+ const { result: restored, exit } = await cli(engine, ['private-labels', '--source', source, '--class', 'restore', '--apply', '--expect', preview.preview_hash], env);
+ expect(exit).toBe(0);
+ expect(restored.applied).toBe(2);
+ expect((await engine.readPageSnapshot('notes/v0', { sourceId: source }))!.page.frontmatter).toEqual({ topic: 'kept', access: 'private' });
+ expect((await engine.readPageSnapshot('notes/v1', { sourceId: source }))!.page.frontmatter).toEqual({ topic: 'kept', access: 'private', visibility: 'private' });
+ });
+ });
+
+ describe('[' + backend + '] repair private-labels on a managed brain (GBRA-443)', () => {
+ test('a window publishes as one maintenance batch; a page whose file drifted and a page refused inside its group decline alone; the run exits 0 and the next preview lists them last', () => managedBrain(async ({ engine, ctx, root }) => {
+ const slugs = [0, 1, 2, 3, 4, 5].map(i => 'notes/label-' + i);
+ for (const slug of slugs) await put(ctx, slug, labelled(slug));
+ await settleManagedGitEffects(engine);
+ const preview = (await cli(engine, ['private-labels', '--limit', '4'])).result;
+ expect(preview.listing.map((entry: { item: string }) => entry.item)).toEqual(slugs.slice(0, 4).map(slug => 'default:' + slug));
+ expect(preview.cost.embedding_pages).toBe(0);
+ const drifted = join(root, slugs[0] + '.md');
+ writeFileSync(drifted, readFileSync(drifted, 'utf8') + NL + 'An edit made outside gbrain.' + NL);
+ installFaultHook(async (point, detail) => {
+ if (point !== 'consumer:preparing') return;
+ const [row] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE id=$1::uuid', [detail.writeId]);
+ if (row?.slug === slugs[1]) throw new OperationError('source_changed', 'Forced decline inside the publication group.', 'Fixture.');
+ });
+ const after = await lastSequence(engine);
+ let run;
+ try { run = await cli(engine, ['private-labels', '--apply', '--expect', preview.preview_hash]); } finally { installFaultHook(undefined); }
+ const { result: applied, exit } = run;
+ expect(applied.failed.map((failed: { slug: string; reason: string }) => [failed.slug, failed.reason])).toEqual([[slugs[0], 'source_changed'], [slugs[1], 'source_changed']]);
+ expect(applied.applied).toBe(2);
+ expect(applied.complete).toBe(true);
+ expect(applied.stopped).toBeUndefined();
+ expect(applied.declined).toEqual({ source_changed: 2 });
+ expect(exit).toBe(0);
+ for (const slug of slugs.slice(0, 2)) expect((await frontmatter(engine, slug)).access).toBe('private');
+ for (const slug of slugs.slice(2, 4)) expect('access' in await frontmatter(engine, slug)).toBe(false);
+ const rows = await engine.executeRaw<{ slug: string; state: string; batch: string | null; published: string | null }>(`SELECT slug, state, intent->>'maintenance_batch' AS batch,
+ published_at::text AS published FROM persistence_requests WHERE sequence>$1::bigint AND intent->>'kind'='managed_maintenance_page' ORDER BY sequence`, [after]);
+ const landed = rows.filter(row => row.state === 'committed');
+ expect(landed.map(row => row.slug)).toEqual(slugs.slice(2, 4));
+ expect(landed.every(row => row.batch !== null)).toBe(true);
+ expect(new Set(rows.map(row => row.batch)).size).toBe(1);
+ // Postgres publishes a batch's pages in groups: the declined member left the group and the other two still published together.
+ if (backend === 'postgres') expect(landed[0]!.published).toBe(landed[1]!.published);
+ const path = applied.details.ledger as string;
+ expect(applied.details.ledger_rows).toEqual({ intent: 4, committed: 2 });
+ expect(lines(path).length).toBe(applied.details.ledger_rows_written);
+ const next = (await cli(engine, ['private-labels', '--limit', '4'])).result;
+ expect(next.listing.map((entry: { item: string }) => entry.item)).toEqual([4, 5, 0, 1].map(i => 'default:' + slugs[i]));
+ expect(next.details.window.tried_before).toBe(2);
+ }, { databaseUrl, setup }), 180_000);
+
+ test('carried declines never stop a window: at half of its attempts at the tail, or as the whole window (complete, declined, exit 0); fresh pages that all decline still stop the run', () => managedBrain(async ({ engine, ctx, root }) => {
+ const first = Array.from({ length: 16 }, (_, i) => 'notes/w1-' + String(i).padStart(2, '0'));
+ for (const slug of first) await put(ctx, slug, labelled(slug));
+ await settleManagedGitEffects(engine);
+ const drift = (slug: string) => { const file = join(root, slug + '.md'); writeFileSync(file, readFileSync(file, 'utf8') + NL + 'An edit made outside gbrain.' + NL); };
+ // Five drifted pages spread through the first window, so it completes with five declines.
+ const declined = [1, 4, 7, 10, 13].map(i => first[i]!);
+ for (const slug of declined) drift(slug);
+ const one = (await cli(engine, ['private-labels', '--limit', '16'])).result;
+ const w1 = await cli(engine, ['private-labels', '--apply', '--expect', one.preview_hash]);
+ expect(w1.result.applied).toBe(11);
+ expect(w1.result.failed.map((f: { reason: string }) => f.reason)).toEqual(Array(5).fill('source_changed'));
+ // The next window holds five new pages and the five carried declines at its tail: one code has five hits and half of
+ // the attempts, the breaker's third rule, yet the window applies the five and completes, because carried declines do not count.
+ const second = Array.from({ length: 5 }, (_, i) => 'notes/w2-' + i);
+ for (const slug of second) await put(ctx, slug, labelled(slug));
+ await settleManagedGitEffects(engine);
+ const two = (await cli(engine, ['private-labels', '--limit', '16'])).result;
+ const w2 = await cli(engine, ['private-labels', '--apply', '--expect', two.preview_hash]);
+ expect(w2.result.stopped).toBeUndefined();
+ expect(w2.result.applied).toBe(5);
+ expect(w2.result.complete).toBe(true);
+ expect(two.listing.map((entry: { item: string }) => entry.item)).toEqual([...second, ...declined].map(slug => 'default:' + slug));
+ expect(two.details.window.tried_before).toBe(5);
+ expect(w2.result.declined).toEqual({ source_changed: 5 });
+ expect(w2.exit).toBe(0);
+ for (const slug of second) expect('access' in await frontmatter(engine, slug)).toBe(false);
+ // A window of carried declines alone completes too, applies nothing and exits 0: none of them counts toward the breaker.
+ const carried = (await cli(engine, ['private-labels', '--limit', '16'])).result;
+ expect(carried.listing.length).toBe(5);
+ const w3 = await cli(engine, ['private-labels', '--apply', '--expect', carried.preview_hash]);
+ expect(w3.result.stopped).toBeUndefined();
+ expect(w3.result.complete).toBe(true);
+ expect(w3.result.applied).toBe(0);
+ expect(w3.result.declined).toEqual({ source_changed: 5 });
+ expect(w3.exit).toBe(0);
+ // Pages not tried yet that all decline (as a dirty checkout makes them) still trip the breaker: the run stops and exits 1.
+ const fresh = Array.from({ length: 6 }, (_, i) => 'notes/w3-' + i);
+ for (const slug of fresh) await put(ctx, slug, labelled(slug));
+ await settleManagedGitEffects(engine);
+ for (const slug of fresh) drift(slug);
+ const four = (await cli(engine, ['private-labels', '--limit', '16'])).result;
+ const w4 = await cli(engine, ['private-labels', '--apply', '--expect', four.preview_hash]);
+ expect(w4.result.stopped?.reason).toBe('item_failures_systemic');
+ expect(w4.result.applied).toBe(0);
+ expect(w4.exit).toBe(1);
+ }, { databaseUrl, setup }), 240_000);
+
+ test('every page of a run has its intent line before any of them is published, and a crash after the group published still restores each', () => managedBrain(async ({ engine, ctx, root }) => {
+ const slugs = [0, 1, 2].map(i => 'notes/crash-' + i);
+ for (const slug of slugs) await put(ctx, slug, labelled(slug));
+ await settleManagedGitEffects(engine);
+ const preview = (await cli(engine, ['private-labels'])).result;
+ expect(preview.listing.length).toBe(3);
+ const scope = await resolveRepairScope(engine);
+ const real = privateLabelsLedger(scope.brain_id);
+ const phases: string[] = [];
+ const filesLabelledAtIntent: boolean[] = [];
+ const crashing = { ...real, record(line: PrivateLabelsLedgerLine) {
+ if (line.phase === 'intent') filesLabelledAtIntent.push(slugs.every(slug => /^access: private$/m.test(readFileSync(join(root, slug + '.md'), 'utf8'))));
+ // The process dies after the group published and before this page's commit line: the throw stands in for it.
+ if (line.phase === 'committed' && line.slug === slugs[1]) throw new Error('forced crash after the group published');
+ phases.push(line.phase!);
+ real.record(line);
+ } };
+ const applied = await (await repairRunner(engine, { apply: true, logger })).run('private-labels', scope, { explicit: true, expect: preview.preview_hash, privateLabelsLedger: crashing });
+ expect(applied.failed).toEqual([]);
+ expect(applied.applied).toBe(3);
+ expect(filesLabelledAtIntent).toEqual([true, true, true]);
+ expect(phases).toEqual(['intent', 'intent', 'intent', 'committed', 'committed']);
+ for (const slug of slugs) expect('access' in await frontmatter(engine, slug)).toBe(false);
+ const restorePreview = (await cli(engine, ['private-labels', '--class', 'restore'])).result;
+ expect(restorePreview.listing.map((entry: { item: string }) => entry.item)).toEqual(slugs.map(slug => 'default:' + slug));
+ const restored = (await cli(engine, ['private-labels', '--class', 'restore', '--apply', '--expect', restorePreview.preview_hash])).result;
+ expect(restored.applied).toBe(3);
+ for (const slug of slugs) expect((await frontmatter(engine, slug)).access).toBe('private');
+ }, { databaseUrl, setup }), 180_000);
+
+ test('a preview-bound apply waits out a source refresh past the interactive wait, up to its own ceiling; past it the step is refused whole and the same apply resumes; an interactive write keeps its own wait', () => managedBrain(async ({ engine, ctx }) => {
+ await put(ctx, 'notes/fenced', labelled('notes/fenced'));
+ await settleManagedGitEffects(engine);
+ const preview = (await cli(engine, ['private-labels'])).result;
+ expect(preview.listing.length).toBe(1);
+ const binding = (await getWorktreeBinding(engine, 'default'))!;
+ const fence = async () => {
+ const lock = await tryAcquireNativeLock(join(persistenceHome(), 'locks', 'refresh-' + binding.worktree_id + '.lock'));
+ expect(lock).not.toBeNull();
+ const [row] = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_worktree_refreshes (worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref)
+ VALUES ($1::uuid,ARRAY['default'],gen_random_uuid(),$2,$3,'fenced','a','b','origin/main') RETURNING id::text AS id`, [binding.worktree_id, binding.owner_epoch, binding.topology_generation]);
+ return async () => {
+ await engine.executeRaw("UPDATE persistence_worktree_refreshes SET state='completed', completed_at=now(), updated_at=now() WHERE id=$1::uuid", [row!.id]);
+ await lock!.release();
+ };
+ };
+ _setRefreshFenceWaitForTests(300);
+ try {
+ const release = await fence();
+ const interactive = await put(ctx, 'notes/other', labelled('notes/other')).then(() => null, (error: unknown) => error as OperationError);
+ expect(interactive?.code).toBe('worktree_refreshing');
+ const pending = cli(engine, ['private-labels', '--apply', '--expect', preview.preview_hash]);
+ await Bun.sleep(1500);
+ await release();
+ const { result: applied, exit } = await pending;
+ expect(applied.applied).toBe(1);
+ expect(exit).toBe(0);
+ expect('access' in await frontmatter(engine, 'notes/fenced')).toBe(false);
+
+ const held = ['notes/held', 'notes/held-b', 'notes/held-c'];
+ for (const slug of held) await put(ctx, slug, labelled(slug));
+ await settleManagedGitEffects(engine);
+ const second = (await cli(engine, ['private-labels'])).result;
+ _setRepairRefreshWaitForTests(400);
+ const releaseHeld = await fence();
+ const refused = await cli(engine, ['private-labels', '--apply', '--expect', second.preview_hash]).then(() => null, (error: unknown) => error as OperationError);
+ await releaseHeld();
+ // A refresh that outlasts the wait refuses the step whole: the refusal names the refresh and what it waited, and no page changed.
+ expect(refused?.code).toBe('worktree_refreshing');
+ expect(refused?.message).toMatch(/refresh [0-9a-f-]+ is fast-forwarding .*This call waited \d+ ms/);
+ for (const slug of held) expect((await frontmatter(engine, slug)).access).toBe('private');
+ // The same approved apply resumes once the refresh ended, although the refused pages now have intent lines.
+ const resumed = (await cli(engine, ['private-labels', '--apply', '--expect', second.preview_hash])).result;
+ expect(resumed.applied).toBe(3);
+ expect(resumed.complete).toBe(true);
+ } finally { _setRefreshFenceWaitForTests(null); _setRepairRefreshWaitForTests(null); }
+ }, { databaseUrl, setup }), 180_000);
+ });
+}