Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(sync): #6712 PR 4b idle tick 34 -> 12 serial round trips; a pass's second round reuses the commit's tree; #6858 bench preset
garrytanbcf9c23cbe50
diff --git a/scripts/bench/sync-convergence-lib.ts b/scripts/bench/sync-convergence-lib.tsindex 7d12f226f7..f242d653a4 100644--- a/scripts/bench/sync-convergence-lib.ts+++ b/scripts/bench/sync-convergence-lib.ts@@ -24,7 +24,11 @@ import { PGBOUNCER_IMAGE } from './managed-sync-catchup-lib.ts';/** Bump when fixture paths or bytes change, so cached fixtures are regenerated. */export const FIXTURE_CONTENT_VERSION = 1;-export const PRESETS: Record<string, number> = { '61k': 61_000, '600k': 600_000 };+/** Every every-th file (i % every === every - 1) is a large Markdown file of bytes plus up to bytes/16 more. */+export interface LargeBlobs { every: number; bytes: number }+export interface FixtureShape { files: number; large?: LargeBlobs }+export const PRESETS: Record<string, FixtureShape> = { '61k': { files: 61_000 }, '600k': { files: 600_000 },+ '6858': { files: 308_000, large: { every: 100, bytes: 2_150_000 } } };const COMMITTER = 'Bench Fixture <[email protected]>';const BASE_TIME = 1_700_000_000;@@ -40,6 +44,7 @@ const FILLER = (() => {}return out;})();+const FILLER_BYTES = Buffer.from(FILLER);/** The git path of file i: two levels of 100-way directory fan-out. */export function fixturePath(i: number): string {@@ -47,11 +52,19 @@ export function fixturePath(i: number): string {return `d${pad(i % 100)}/e${pad(Math.floor(i / 100) % 100)}/note-${i}.md`;}-/** The bytes of file i (ASCII, 1-2 KB), optionally with a drift marker appended. */-export function fixtureContent(i: number, drift?: number): Buffer {+/** The bytes of file i (ASCII, 1-2 KB, or a large file under large), optionally with a drift marker appended. */+export function fixtureContent(i: number, drift?: number, large?: LargeBlobs): Buffer {const length = 1024 + ((i * 7919) % 1024);const offset = (i * 131) % 4096;const tail = drift === undefined ? '' : `\nDrift edit ${drift}.\n`;+ if (large && i % large.every === large.every - 1) {+ const body = Buffer.alloc(large.bytes + ((i * 7919) % (large.bytes >> 4)));+ for (let at = 0, k = i; at < body.length; at += 4096) {+ k = (Math.imul(k, 1103515245) + 12345) >>> 0;+ FILLER_BYTES.copy(body, at, k % 4096, (k % 4096) + Math.min(4096, body.length - at));+ }+ return Buffer.concat([Buffer.from(`---\ntitle: Note ${i}\n---\nSynthetic body ${i}.\n\n`), body, Buffer.from(`\n${tail}`)]);+ }return Buffer.from(`---\ntitle: Note ${i}\n---\nSynthetic body ${i}.\n\n${FILLER.slice(offset, offset + length)}\n${tail}`);}@@ -95,7 +108,7 @@ function inlineFile(path: string, bytes: Buffer): Buffer[] {return [Buffer.from(`M 100644 inline ${path}\ndata ${bytes.length}\n`), bytes, Buffer.from('\n')];}-export interface Fixture { dir: string; repo: string; files: number; base: string; cached: boolean; generate_ms: number; timings_ms: Record<string, number> }+export interface Fixture { dir: string; repo: string; files: number; large?: LargeBlobs; base: string; cached: boolean; generate_ms: number; timings_ms: Record<string, number> }/*** The cached fixture repository for files files, generated on first use: one@@ -103,13 +116,13 @@ export interface Fixture { dir: string; repo: string; files: number; base: strin* materialize the worktree and an index refresh so the index is stat-clean.* A READY stamp marks a complete generation; anything else is regenerated.*/-export async function ensureFixture(cacheDir: string, files: number, log: (line: string) => void): Promise<Fixture> {- const dir = join(cacheDir, `${files}-v${FIXTURE_CONTENT_VERSION}`);+export async function ensureFixture(cacheDir: string, files: number, log: (line: string) => void, large?: LargeBlobs): Promise<Fixture> {+ const dir = join(cacheDir, `${files}${large ? `-L${large.every}x${large.bytes}` : ''}-v${FIXTURE_CONTENT_VERSION}`);const repo = join(dir, 'repo');const ready = join(dir, 'READY');if (existsSync(ready)) {const stamp = JSON.parse(readFileSync(ready, 'utf8')) as { base: string; files: number; timings_ms?: Record<string, number> };- if (stamp.files === files) return { dir, repo, files, base: stamp.base, cached: true, generate_ms: 0, timings_ms: stamp.timings_ms ?? {} };+ if (stamp.files === files) return { dir, repo, files, large, base: stamp.base, cached: true, generate_ms: 0, timings_ms: stamp.timings_ms ?? {} };}const started = performance.now();rmSync(dir, { recursive: true, force: true });@@ -119,7 +132,7 @@ export async function ensureFixture(cacheDir: string, files: number, log: (line:log(`fixture: generating ${files} files with git fast-import in ${repo}`);await fastImport(repo, async write => {await write(`commit refs/heads/main\ncommitter ${COMMITTER} ${BASE_TIME} +0000\ndata 18\nsynthetic fixture\n`);- for (let i = 0; i < files; i++) for (const part of inlineFile(fixturePath(i), fixtureContent(i))) await write(part);+ for (let i = 0; i < files; i++) for (const part of inlineFile(fixturePath(i), fixtureContent(i, undefined, large))) await write(part);await write('\n');});const imported = performance.now();@@ -129,8 +142,8 @@ export async function ensureFixture(cacheDir: string, files: number, log: (line:git(repo, ['update-index', '-q', '--refresh']);const refreshed = performance.now();const base = git(repo, ['rev-parse', 'HEAD']);- for (const i of files > 1 ? [0, files - 1] : [0]) {- const expected = gitBlobOid(fixtureContent(i), base.length === 64 ? 'sha256' : 'sha1');+ for (const i of [...new Set([0, files - 1, ...(large && files >= large.every ? [large.every - 1] : [])])]) {+ const expected = gitBlobOid(fixtureContent(i, undefined, large), base.length === 64 ? 'sha256' : 'sha1');const actual = git(repo, ['rev-parse', `HEAD:${fixturePath(i)}`]);if (actual !== expected) throw new Error(`fixture blob mismatch for ${fixturePath(i)}: git ${actual}, generator ${expected}`);}@@ -139,7 +152,7 @@ export async function ensureFixture(cacheDir: string, files: number, log: (line:index_refresh: Math.round(refreshed - materialized), total: Math.round(generate_ms) };log(`fixture: ${JSON.stringify(timings_ms)} ms`);writeFileSync(ready, JSON.stringify({ base, files, content_version: FIXTURE_CONTENT_VERSION, timings_ms }) + '\n');- return { dir, repo, files, base, cached: false, generate_ms, timings_ms };+ return { dir, repo, files, large, base, cached: false, generate_ms, timings_ms };}/** Moves main and the worktree back to the fixture's base commit (a previous run's drift commit is discarded). */@@ -156,7 +169,7 @@ export async function applyDrift(fixture: Fixture, k: number): Promise<{ head: sconst message = `drift ${indices.length}\n`;await fastImport(fixture.repo, async write => {await write(`commit refs/heads/main\ncommitter ${COMMITTER} ${BASE_TIME + 60} +0000\ndata ${message.length}\n${message}from ${from}\n`);- for (const [j, i] of indices.entries()) for (const part of inlineFile(fixturePath(i), fixtureContent(i, j))) await write(part);+ for (const [j, i] of indices.entries()) for (const part of inlineFile(fixturePath(i), fixtureContent(i, j, fixture.large))) await write(part);await write('\n');});git(fixture.repo, ['read-tree', '-u', '--reset', 'refs/heads/main']);@@ -213,7 +226,7 @@ export async function seedSource(engine: BrainEngine, input: { sourceId: string;const rows: Array<{ slug: string; title: string; body: string; path: string; revision: string }> = [];const disk = new Map<string, { sha: string; oid: string; revision: string }>();for (let i = start; i < end; i++) {- const path = fixturePath(i), bytes = fixtureContent(i), revision = randomUUID();+ const path = fixturePath(i), bytes = fixtureContent(i, undefined, fixture.large), revision = randomUUID();rows.push({ slug: resolveSlugForPath(path), title: `Note ${i}`, body: `Synthetic body ${i}.`, path, revision });disk.set(path, { sha: sha256(bytes), oid: gitBlobOid(bytes, format), revision });}diff --git a/scripts/bench/sync-convergence.ts b/scripts/bench/sync-convergence.tsindex 9976a9884e..fe9a8e0f84 100644--- a/scripts/bench/sync-convergence.ts+++ b/scripts/bench/sync-convergence.ts@@ -6,7 +6,7 @@* host it ran on.** bun scripts/bench/sync-convergence.ts --engine pglite|postgres|pgbouncer- * [--preset 61k|600k | --files N] [--rtt 57] [--idle-rounds 20] [--full-rounds 7] [--warmup 1]+ * [--preset 61k|600k|6858 | --files N] [--rtt 57] [--idle-rounds 20] [--full-rounds 7] [--warmup 1]* [--drift K] [--batch 5000] [--sample-ms 50] [--cache-dir <dir>] [--work-dir <dir>]* [--pg-port 55442] [--pooler-port 55444] [--database-url <admin url>] [--raw-idle] [--episode] [--live] [--seed-only] [--keep] [--out <file.json>]*@@ -15,6 +15,13 @@* git fast-import commit, worktree materialized with* read-tree -u --reset; cached under --cache-dir by N and the* content version (default ~/.capy/work/6712/bench-fixtures).+ * Files are 1-2 KB except under --preset 6858, the #6858 shape+ * (308k files, about 7.3 GB with large blobs): every 100th file+ * (i % 100 === 99, 3,080 files) is a large Markdown file of+ * 2,150,000 bytes plus (i * 7919) % 134,375 more (about 2.2 MB),+ * about 6.83 GB, and the other 304,920 files are the usual+ * 1-2 KB notes, about 0.48 GB. The drift file (i = 0) and the+ * first live full rounds' edits (i = 7919 k) are small files.* 2. seed a fresh brain (PGLite datastore in --work-dir, or a new* database on the Docker pgvector Postgres) gets the managed* source by direct SQL: source row at the fixture's base commit,@@ -59,7 +66,7 @@ import { LatencyProxy } from '../../test/helpers/latency-proxy.ts';import { VERSION } from '../../src/version.ts';import {PRESETS, PGBOUNCER_CONTAINER, applyDrift, breakdown, ensureFixture, ensurePostgres, fixtureContent, fixturePath, git, gitVersion, hostInfo, measureRtt, mib, readVmHwm, removeContainer,- resetFixture, seedSource, startPgbouncer, startRssSampler, summarize,+ resetFixture, seedSource, startPgbouncer, startRssSampler, summarize, type LargeBlobs,} from './sync-convergence-lib.ts';const REPO = resolve(import.meta.dir, '../..');@@ -71,7 +78,7 @@ type EngineKind = 'pglite' | 'postgres' | 'pgbouncer';type SyncPassModule = Pick<typeof import('../../src/core/persistence/sync-pass.ts'), 'shadowConvergence' | 'idleTickProbe'>;/** `target`: the HEAD the idle tick assumes converged (PR 4a writes no pass row; see idleTickProbe's assumeConverged), or null to time the raw tick. */-interface ChildConfig { engine: EngineKind; database_url?: string; database_path?: string; source_id: string; target: string | null; episode: boolean; live?: { repo: string; files: number }; idle_rounds: number; full_rounds: number; warmup: number; sample_ms: number }+interface ChildConfig { engine: EngineKind; database_url?: string; database_path?: string; source_id: string; target: string | null; episode: boolean; live?: { repo: string; files: number; large?: LargeBlobs }; idle_rounds: number; full_rounds: number; warmup: number; sample_ms: number }function flag(name: string, fallback: string): string {const i = process.argv.indexOf(`--${name}`);@@ -148,7 +155,7 @@ async function runChild(config: ChildConfig): Promise<number> {}/** --live: the PR 4b pass, timed through performManagedSync. */-async function runLive(engine: import('../../src/core/engine.ts').BrainEngine, config: ChildConfig, live: { repo: string; files: number },+async function runLive(engine: import('../../src/core/engine.ts').BrainEngine, config: ChildConfig, live: NonNullable<ChildConfig['live']>,ctx: { sampler: ReturnType<typeof startRssSampler>; connectMs: number; rssAfterConnect: number; seededPages: number; out: (value: unknown) => void }): Promise<number> {const { performManagedSync } = await import('../../src/core/persistence/sync-run.ts');const { disposePersistenceConsumer } = await import('../../src/core/persistence/service.ts');@@ -161,7 +168,7 @@ async function runLive(engine: import('../../src/core/engine.ts').BrainEngine, clet edits = 0;const commitOne = () => {const path = fixturePath((edits * 7919) % live.files);- writeFileSync(join(live.repo, path), fixtureContent((edits * 7919) % live.files, 1000 + edits));+ writeFileSync(join(live.repo, path), fixtureContent((edits * 7919) % live.files, 1000 + edits, live.large));edits++;git(live.repo, ['add', '--', path]);git(live.repo, ['-c', 'user.name=Bench', '-c', '[email protected]', 'commit', '-q', '-m', 'bench edit ' + edits]);@@ -196,7 +203,8 @@ async function runParent(): Promise<number> {if (!['pglite', 'postgres', 'pgbouncer'].includes(engineKind)) { log('--engine takes pglite, postgres or pgbouncer'); return 2; }const preset = flag('preset', '');if (preset && !PRESETS[preset]) { log(`--preset takes ${Object.keys(PRESETS).join(' or ')}; got ${preset}`); return 2; }- const files = preset ? PRESETS[preset]! : wholeNumber('files', '2000', 1);+ const files = preset ? PRESETS[preset]!.files : wholeNumber('files', '2000', 1);+ const large = preset ? PRESETS[preset]!.large : undefined;const rtt = Number(flag('rtt', '57'));if (!(rtt >= 0)) { log(`--rtt takes milliseconds of at least 0; got ${flag('rtt', '57')}`); return 2; }const idleRounds = wholeNumber('idle-rounds', '20', 1), fullRounds = wholeNumber('full-rounds', '7', 1), warmup = wholeNumber('warmup', '1');@@ -212,7 +220,7 @@ async function runParent(): Promise<number> {const phases: Record<string, unknown> = {};const cleanups: Array<() => Promise<void> | void> = [];try {- const fixture = await ensureFixture(cacheDir, files, log);+ const fixture = await ensureFixture(cacheDir, files, log, large);resetFixture(fixture);phases.fixture = { cached: fixture.cached, generate_ms: Math.round(fixture.generate_ms), generation_timings_ms: fixture.timings_ms, base: fixture.base };log(`fixture: ${fixture.cached ? 'cached' : 'generated'} ${fixture.repo} (${files} files)`);@@ -274,7 +282,7 @@ async function runParent(): Promise<number> {let measured: Record<string, unknown> | null = null;if (!seedOnly) {const configPath = join(workDir, 'child.json');- writeFileSync(configPath, JSON.stringify({ engine: engineKind, database_url: childUrl, database_path: databasePath, source_id: SOURCE_ID, target: rawIdle ? null : head, episode, ...(live ? { live: { repo: fixture.repo, files } } : {}),+ writeFileSync(configPath, JSON.stringify({ engine: engineKind, database_url: childUrl, database_path: databasePath, source_id: SOURCE_ID, target: rawIdle ? null : head, episode, ...(live ? { live: { repo: fixture.repo, files, large } } : {}),idle_rounds: idleRounds, full_rounds: fullRounds, warmup, sample_ms: sampleMs } satisfies ChildConfig));log(`measure: ${warmup} warm-up, ${idleRounds} idle ticks, ${fullRounds} full rounds (${engineKind}${engineKind === 'pglite' ? '' : `, ${rtt} ms RTT`})`);const t = performance.now();diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3581779cea..44e0e8fd91 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap insrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeoutsrc/core/config.ts 1985 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys)-src/core/persistence/sync-run.ts 1616 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; lowered to 1606 #6712 PR 4b lane C: the dead non-company cursor arms retired (cursor adoption and fan-in reports, the retry-held finish arm, the resumable slice stage); the live pass lives in persistence/sync-pass-run.ts; +10 #6712 PR 4b item 7 and lane A rulings: the CLI pass waits out its own held write (whileHeld, awaitWrite whileHeldMs in service.ts), the waiver run hands its admitting screen to the per-entry path, the refresh fence and authority read together, the admission carries the owner epoch, and a failed level read is recorded as that read (onLevelRead; the pass lives in persistence/sync-pass-run.ts)+src/core/persistence/sync-run.ts 1620 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; lowered to 1606 #6712 PR 4b lane C: the dead non-company cursor arms retired (cursor adoption and fan-in reports, the retry-held finish arm, the resumable slice stage); the live pass lives in persistence/sync-pass-run.ts; +10 #6712 PR 4b item 7 and lane A rulings: the CLI pass waits out its own held write (whileHeld, awaitWrite whileHeldMs in service.ts), the waiver run hands its admitting screen to the per-entry path, the refresh fence and authority read together, the admission carries the owner epoch, and a failed level read is recorded as that read (onLevelRead; the pass lives in persistence/sync-pass-run.ts); +4 #6712 PR 4b idle-tick batching: the preflight reads the mode, company profile and source rows in one round trip (readManagedSyncRows in persistence/sync-discovery.ts, activeManagedBrainId in sync-authority.ts) and an idle pass that read no owed tail skips the post-lease tail read (DrainLease.tailClear in sync-lease.ts)src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent blocksrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 710 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts)diff --git a/src/core/company-brain/profile.ts b/src/core/company-brain/profile.tsindex 589593ae5a..f850dd5be2 100644--- a/src/core/company-brain/profile.ts+++ b/src/core/company-brain/profile.ts@@ -26,11 +26,13 @@ function resumeCommand(sourceId: string): string {}export async function getCompanyBrainProfile(engine: BrainEngine, sourceId: string): Promise<CompanyBrainProfile | null> {- const [source] = await engine.executeRaw<{ config: unknown; incarnation: string }>('SELECT config,incarnation FROM sources WHERE id=$1', [sourceId]);+ // The receipt a source without a policy is checked for (of the source's current incarnation) is read beside it.+ const [[source], [receipt]] = await Promise.all([engine.executeRaw<{ config: unknown; incarnation: string }>('SELECT config,incarnation FROM sources WHERE id=$1', [sourceId]),+ engine.executeRaw(`SELECT r.id FROM source_ingestion_receipts r JOIN sources s ON s.id=r.source_id AND s.incarnation=r.source_incarnation+ WHERE r.source_id=$1 AND r.profile='company-brain' LIMIT 1`, [sourceId])]);if (!source) return null;const profile = companyBrainProfile(source.config);if (!profile) {- const [receipt] = await engine.executeRaw("SELECT id FROM source_ingestion_receipts WHERE source_id=$1 AND source_incarnation=$2::uuid AND profile='company-brain' LIMIT 1", [sourceId, source.incarnation]);if (receipt) {throw opError('profile_incompatible', 'The durable company approval has no source policy. Reconnect explicitly; sync cannot fall back to an unrestricted profile.',`Source ${sourceId} has a company-brain receipt but no stored source policy. Check its status; reconnecting means previewing removal with gbrain sources remove ${sourceId} --dry-run and connecting again, a destructive step the user approves. Do not edit stored policy fields.`,diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex bb91af577d..fb76323cb1 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -7,7 +7,7 @@ import { NO_SOURCES } from '../source-id.ts';import { hasScope } from '../scope.ts';import { normalizeTokenScopes } from '../legacy-token-scope.ts';import { authSourcesFromGrant, grantFromTokenRow } from '../grants/model.ts';-import { readLocalWriter, currentVerifiedLocalWriter, verifyLocalWriter, type LocalGrant } from './identity.ts';+import { readLocalWriter, currentVerifiedLocalWriter, takeRegisteredWriterRow, verifyLocalWriter, type LocalGrant } from './identity.ts';import type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model.ts';import { authorizePageVisibility, excludesPrivateWrites } from './page-visibility.ts';import { pipelined, transactionMemo } from '../page-state/transactions.ts';@@ -77,8 +77,13 @@ export async function submissionAuthority(ctx: OperationContext, operation: strireturn a;}-/** #5984: one local-writer read per transaction; a FOR SHARE read also answers a plain one. */-function localWriterRow(engine: SqlEngine, id: string, lock: boolean) {+/**+ * #5984: one local-writer read per transaction; a FOR SHARE read also answers a plain one. #6712 PR 4b: the read the+ * registration check just made answers the authorization that follows it (`withRegisteredLocalWriter`, once).+ */+function localWriterRow(engine: SqlEngine, id: string, lock: boolean): Promise<Array<{ lane: string; revoked_at: unknown; grant_ceiling: LocalGrant }>> {+ const registered = lock ? undefined : takeRegisteredWriterRow(id);+ if (registered) return Promise.resolve([registered]);const key = `local-writer:${id}`;return transactionMemo(engine, lock ? [`${key}:share`] : [key, `${key}:share`],() => engine.executeRaw<{ lane: string; revoked_at: unknown; grant_ceiling: LocalGrant }>(diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.tsindex d758a40ae2..2a807ff08f 100644--- a/src/core/persistence/identity.ts+++ b/src/core/persistence/identity.ts@@ -137,16 +137,40 @@ export async function registerLocalWriter(engine: BrainEngine, lane: 'cli' | 'st}async function ensureLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', grant: LocalGrant, path: string): Promise<LocalRegistration> {+ return (await ensureLocalWriterRow(engine, lane, grant, path)).local;+}+/** `ensureLocalWriter` with the row it read (undefined when it inserted the registration). */+async function ensureLocalWriterRow(engine: BrainEngine, lane: 'cli' | 'stdio', grant: LocalGrant, path: string): Promise<{ local: LocalRegistration; existing?: LocalWriterRow }> {const local = privateJson<LocalRegistration>(path, () => ({ id: randomUUID(), credential: randomBytes(32).toString('hex'), lane }));if (local.lane !== lane || typeof local.credential !== 'string' || typeof local.id !== 'string') throw invalidIdentityFile('Local writer registration is invalid.', path, `${lane} writer registration`);- const [existing] = await engine.executeRaw<{ revoked_at: unknown; credential_hash: string; lane: string }>(- 'SELECT revoked_at,credential_hash,lane FROM persistence_local_writers WHERE id=$1::uuid', [local.id]);+ const [existing] = await engine.executeRaw<LocalWriterRow>(+ 'SELECT revoked_at,credential_hash,lane,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid', [local.id]);if (existing?.revoked_at != null) throw new OperationError('permission_denied', 'This local writer registration was revoked.', 'Explicitly register a new writer to authorize future work.');if (existing && (existing.lane !== lane || existing.credential_hash !== sha256(local.credential))) throw credentialMismatch(path, local.id, lane);// A registered writer is left as it is (the insert would conflict and do nothing).if (!existing) await engine.executeRaw(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)VALUES($1::uuid,$2,$3,$4::text::jsonb) ON CONFLICT(id) DO NOTHING`, [local.id, lane, sha256(local.credential), JSON.stringify(grant)]);- return local;+ return { local, ...(existing ? { existing } : {}) };+}+/**+ * #6712 PR 4b: `registerLocalWriter(engine, lane)` and `withVerifiedLocalRegistration` in one read of the registration:+ * the row the registration check read also verifies it (a row it had to insert is verified by a fresh read). `brainId` is+ * the persistence identity when the caller read it already.+ */+export async function withRegisteredLocalWriter<T>(engine: BrainEngine, lane: 'cli' | 'stdio', run: (writer: VerifiedLocalWriter) => Promise<T>, brainId?: string): Promise<T> {+ const brain = brainId ?? await brainIdentity(engine);+ const { local, existing } = await ensureLocalWriterRow(engine, lane, defaultGrant(), join(persistenceHome(), `${brain}.${lane}.json`));+ const writer = existing ? verifiedFromRow(local, existing) : await verifyLocalWriter(engine, local);+ return verifiedLocalWriter.run(writer, () => registeredRow.run({ id: local.id, row: existing }, () => run(writer)));+}+/** The row `withRegisteredLocalWriter` read: it answers the next plain read of that writer's row inside `run`, once. */+const registeredRow = new AsyncLocalStorage<{ id: string; row?: LocalWriterRow }>();+export function takeRegisteredWriterRow(id: string): LocalWriterRow | undefined {+ const seed = registeredRow.getStore();+ if (seed?.id !== id || !seed.row) return undefined;+ const { row } = seed;+ seed.row = undefined;+ return row;}/** Commit replacement and revocation together, then atomically publish the private credential. */@@ -193,8 +217,12 @@ export async function readLocalWriter(engine: SqlEngine, lane: 'cli' | 'stdio'):return local;}export async function verifyLocalWriter(engine: SqlEngine, local: LocalRegistration, lock = false): Promise<{ principal: Principal; grant: LocalGrant; remote: boolean }> {- const [row] = await engine.executeRaw<{ lane: string; credential_hash: string; grant_ceiling: LocalGrant; revoked_at: unknown }>(+ const [row] = await engine.executeRaw<LocalWriterRow>(`SELECT lane,credential_hash,grant_ceiling,revoked_at FROM persistence_local_writers WHERE id=$1::uuid${lock ? ' FOR SHARE' : ''}`, [local.id]);+ return verifiedFromRow(local, row);+}+export interface LocalWriterRow { lane: string; credential_hash: string; grant_ceiling: LocalGrant; revoked_at: unknown }+function verifiedFromRow(local: LocalRegistration, row: LocalWriterRow | undefined): { principal: Principal; grant: LocalGrant; remote: boolean } {const actual = Buffer.from(sha256(local.credential));const expected = Buffer.from(row?.credential_hash ?? '');if (!row || row.revoked_at != null || row.lane !== local.lane || actual.length !== expected.length || !timingSafeEqual(actual, expected)) {diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.tsindex da4758ba36..ff493e237c 100644--- a/src/core/persistence/sync-authority.ts+++ b/src/core/persistence/sync-authority.ts@@ -10,8 +10,8 @@ import { assertSourceFilesystemActive } from '../minions/source-filesystem.ts';import { throwIfAborted } from '../abort-check.ts';import { authorizePageVisibility } from './page-visibility.ts';import { submissionAuthority, authorizeWrite } from './authority.ts';-import { currentVerifiedLocalWriter, registerLocalWriter } from './identity.ts';-import { readManagedMode } from './managed-mode.ts';+import { currentVerifiedLocalWriter, withRegisteredLocalWriter } from './identity.ts';+import { readManagedMode, readPersistenceBrain } from './managed-mode.ts';import type { WriteAuthority } from './model.ts';import { writerAdminState } from './admin-intent.ts';@@ -67,11 +67,18 @@ async function preActivationClaimRefusal(engine: BrainEngine, sourceId: string):user_message: `Source ${sourceId} was claimed for managed writes, but managed persistence was never turned on, so sync is blocked. Release the claim and go back to classic sync, or turn managed persistence on?`,verify: { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] }, docs: 'docs/architecture/topologies.md#deactivate-runbook' } });}+const inactiveCoordinator = () => new OperationError('writer_coordinator_required', 'Sync cannot publish through an inactive persistence coordinator.',+ 'Stop older writers and review gbrain sources writer status, then explicitly activate persistence before retrying. Claiming a source alone does not exclude running legacy writers.');export async function assertManagedSyncActive(engine: BrainEngine, lock = false): Promise<void> {- if (!await readManagedMode(engine, lock ? { lock: 'share' } : {})) throw new OperationError('writer_coordinator_required', 'Sync cannot publish through an inactive persistence coordinator.',- 'Stop older writers and review gbrain sources writer status, then explicitly activate persistence before retrying. Claiming a source alone does not exclude running legacy writers.');+ if (!await readManagedMode(engine, lock ? { lock: 'share' } : {})) throw inactiveCoordinator();}-export async function managedSyncAuthority(engine: BrainEngine, sourceId: string, incarnation: string, repoPath: string): Promise<SyncAuthority> {+/** #6712 PR 4b: `assertManagedSyncActive` that also returns the persistence identity (`managedSyncAuthority`'s `brainId`), one read. */+export async function activeManagedBrainId(engine: BrainEngine): Promise<string> {+ const brain = await readPersistenceBrain(engine);+ if (!brain.enabled) throw inactiveCoordinator();+ return brain.brain_id;+}+export async function managedSyncAuthority(engine: BrainEngine, sourceId: string, incarnation: string, repoPath: string, brainId?: string): Promise<SyncAuthority> {assertDurableSyncCaller();const current = currentSubmissionAuthority();if (current?.kind === 'remote_agent') throw opError('permission_denied', 'Agent jobs cannot run bulk filesystem sync.',@@ -90,9 +97,10 @@ export async function managedSyncAuthority(engine: BrainEngine, sourceId: stringif (verified?.remote) throw opError('permission_denied', 'Bulk sync requires the local CLI or an authenticated source-scoped admin job.',`This stdio MCP writer cannot run bulk filesystem sync of source ${sourceId}, so nothing was synced. The user runs the command in fix in a terminal on this machine.`,{ fix: hostSyncFix(sourceId, 'user') });- if (!verified) await registerLocalWriter(engine, 'cli');- const writer = await submissionAuthority({ engine, remote: verified?.remote ?? false, sourceId } as OperationContext,+ const authorize = () => submissionAuthority({ engine, remote: verified?.remote ?? false, sourceId } as OperationContext,'submit_job', sourceId, incarnation, '__managed_sync_checkpoint__');+ // An unverified CLI caller registers its writer (if needed) and is verified from the same read.+ const writer = verified ? await authorize() : await withRegisteredLocalWriter(engine, 'cli', authorize, brainId);if (writer.slugPrefixes !== null) throw opError('permission_denied', 'Bulk sync requires a source-wide local grant.',`This CLI writer's grant covers only some slug prefixes of source ${sourceId}, and bulk sync can touch any page, so nothing was synced. Review the grant with the command in fix; widening it (gbrain auth local-writer register cli --replace with the complete intended grant) is the user's decision.`,{ fix: readFix('Lists the local writer registrations with their sources, operations and slug-prefix grants, read-only.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 7f495b67a7..7c1a3de846 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -174,17 +174,24 @@ function managedSyncRefusal(sourceId: string, message: string, suggestion: strinfix: managedSyncFix(sourceId, 'A managed brain syncs its registered checkout through the persistence coordinator: it imports local HEAD without git pull and keeps every ignored-file and failed-receipt guard.'),});}-/** Validate the current owner and source without enumerating a new manifest. */-export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncOpts): Promise<ManagedSyncContext> {- await assertManagedSyncActive(engine);+type ManagedSourceRow = { incarnation: string; archived: boolean; local_path: string | null; last_commit: string | null; config: Record<string, unknown> };+/** The source row and worktree binding `resolveManagedSyncContext` validates, read together. */+export function readManagedSyncRows(engine: BrainEngine, sourceId: string): Promise<[ManagedSourceRow | undefined, WorktreeBinding | null]> {+ return Promise.all([engine.executeRaw<ManagedSourceRow>('SELECT incarnation,archived,local_path,last_commit,config FROM sources WHERE id=$1', [sourceId]).then(rows => rows[0]),+ getWorktreeBinding(engine, sourceId)]);+}+/**+ * Validate the current owner and source without enumerating a new manifest. `rows`: `readManagedSyncRows` started by a+ * caller that has asserted the managed mode itself (and handles the promise's rejection).+ */+export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncOpts, rows?: ReturnType<typeof readManagedSyncRows>): Promise<ManagedSyncContext> {+ if (!rows) await assertManagedSyncActive(engine);const sourceId = opts.sourceId ?? 'default';if (!opts.noPull && !opts.dryRun) throw managedSyncRefusal(sourceId, 'Managed sync requires skipping the Git pull (CLI `--no-pull`, sync_brain `no_pull: true`); Git pull/rebase needs an explicit drained maintenance window.',`Sync without pulling to import the checkout as it is (CLI: gbrain sync --no-pull --source ${sourceId}; MCP: sync_brain with no_pull: true), or fast-forward and sync the checkout with gbrain sources refresh ${sourceId}.`);const forbidden = managedForbiddenFlag(opts);if (forbidden) throw managedSyncFlagRefusal(forbidden, sourceId, ['--source', sourceId, '--no-pull']);- const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; last_commit: string | null; config: Record<string, unknown> }>(- 'SELECT incarnation,archived,local_path,last_commit,config FROM sources WHERE id=$1', [sourceId]);- const binding = await getWorktreeBinding(engine, sourceId);+ const [source, binding] = await (rows ?? readManagedSyncRows(engine, sourceId));if (!source || source.archived || !binding || binding.source_incarnation !== source.incarnation ||binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) {// #6449: a rooted source with no owner at all is the database-only one activation listed; the exit is a deliberate claim.diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.tsindex c936a62f7d..84cd9558f5 100644--- a/src/core/persistence/sync-git-stream.ts+++ b/src/core/persistence/sync-git-stream.ts@@ -63,6 +63,10 @@ function* lines(items: readonly string[], terminator: string): Generator<Buffer>* can mark them unknown.*/export async function readTreeLevel(gitRoot: string, commit: string, scope: string): Promise<Map<string, GitTreeEntry>> {+ // #6712 PR 4b: a commit's tree never changes, so the last one read by commit id is reused (a pass's second round); callers+ // only read the map.+ const key = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit) ? `${gitRoot}\0${commit}\0${scope}` : null;+ if (key !== null && lastTree?.key === key) return lastTree.tree;const tree = new Map<string, GitTreeEntry>();await readRecords(gitRoot, ['ls-tree', '-r', '-z', commit, '--', scope === '' ? '.' : scope], 'ls-tree', record => {const tab = record.indexOf('\t');@@ -70,8 +74,10 @@ export async function readTreeLevel(gitRoot: string, commit: string, scope: striif (!OID.test(oid)) throw malformed('ls-tree', record);if (type === 'blob' || type === 'commit') tree.set(record.slice(tab + 1), { mode, oid });});+ if (key !== null) lastTree = { key, tree };return tree;}+let lastTree: { key: string; tree: Map<string, GitTreeEntry> } | null = null;/** `X`: the index (never the worktree), keyed by Git-root-relative path; a conflicted path keeps its highest stage. */export async function readIndexLevel(gitRoot: string): Promise<Map<string, GitIndexEntry>> {diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 40807f3d8c..630536ef13 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -1080,18 +1080,19 @@ export function fencesNormalizedReport(sourceId: string, tally: FencesTally | un* commands. Remote callers get the counts and a relay instruction only.*/export async function buildHoldReport(engine: Exec, input: { sourceId: string; incarnation: string; runId: string; remote: boolean;- policy: SyncHoldPolicy; screened: number; pendingScreen?: boolean }): Promise<Pick<import('../../commands/sync.ts').SyncResult,+ policy: SyncHoldPolicy | Promise<SyncHoldPolicy>; screened: number; pendingScreen?: boolean }): Promise<Pick<import('../../commands/sync.ts').SyncResult,'held' | 'held_count' | 'holds_outstanding' | 'holds_escalated' | 'holds_truncated' | 'holds_pending_screen' | 'holds_fix'>> {- const [summary] = await engine.executeRaw<{ count: number | string; images: number | string; fences: number | string; stalled: number | string; concurrent: number | string; dirty: number | string; drift: number | string }>(`SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count,+ // #6712 PR 4b: the summary, this run's holds and the policy (a caller may pass its read in flight) in one round trip.+ const [[summary], sourceHolds, policy] = await Promise.all([engine.executeRaw<{ count: number | string; images: number | string; fences: number | string; stalled: number | string; concurrent: number | string; dirty: number | string; drift: number | string }>(`SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count,COALESCE((completed_keys->0->>'drift')::int,0) AS drift,COALESCE((completed_keys->0->>'images')::int,0) AS images, COALESCE((completed_keys->0->>'fences')::int,0) AS fences, COALESCE((completed_keys->0->>'stalled')::int,0) AS stalled,COALESCE((completed_keys->0->>'concurrent')::int,0) AS concurrent, COALESCE((completed_keys->0->>'dirty')::int,0) AS dirtyFROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,- [GIT_HOLD_SUMMARY_OP, summaryFingerprint(input.sourceId, input.incarnation)]);+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(input.sourceId, input.incarnation)]), readGitSourceHolds(engine, { sourceIds: [input.sourceId], runId: input.runId }), input.policy]);const outstanding = Number(summary?.count ?? 0);- const runHolds = (await readGitSourceHolds(engine, { sourceIds: [input.sourceId], runId: input.runId }))[0]?.holds ?? [];+ const runHolds = sourceHolds[0]?.holds ?? [];if (!outstanding && !runHolds.length) return {};- const escalated = holdsEscalated(input.policy, outstanding - Number(summary?.images ?? 0) - Number(summary?.drift ?? 0),+ const escalated = holdsEscalated(policy, outstanding - Number(summary?.images ?? 0) - Number(summary?.drift ?? 0),{ held: runHolds.filter(hold => !imageWeight(hold) && !driftWeight(hold)).length, screened: input.screened });const fences = Math.max(Number(summary?.fences ?? 0), runHolds.filter(hold => fenceWeight(hold)).length);const stalled = Math.max(Number(summary?.stalled ?? 0), runHolds.filter(hold => stalledWeight(hold)).length);@@ -1116,8 +1117,8 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; iwhy: `${runHolds.length} file(s) held this run, ${outstanding} held in source ${input.sourceId}; they do not block sync. Inspect them with 'gbrain sources status ${input.sourceId}'; `+ (fences || stalled || concurrent || dirty || drift || slugConflicts ? `then ${steps.text}.` : 'the repair preview proposes each fix and writes nothing.')+ (escalated ? escalation : '') };- return { held: runHolds.slice(0, input.policy.cap).map(hold => gitHoldItem(hold, auto)), held_count: runHolds.length, holds_outstanding: outstanding,- ...(escalated ? { holds_escalated: true } : {}), ...(runHolds.length > input.policy.cap ? { holds_truncated: true } : {}),+ return { held: runHolds.slice(0, policy.cap).map(hold => gitHoldItem(hold, auto)), held_count: runHolds.length, holds_outstanding: outstanding,+ ...(escalated ? { holds_escalated: true } : {}), ...(runHolds.length > policy.cap ? { holds_truncated: true } : {}),...(input.pendingScreen ? { holds_pending_screen: true } : {}), holds_fix: fix };}diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.tsindex 354da65d96..97e85401e3 100644--- a/src/core/persistence/sync-lease.ts+++ b/src/core/persistence/sync-lease.ts@@ -65,7 +65,8 @@ export interface DrainHolder { kind: DrainHolderKind | 'unknown'; id: string | nversion: string | null; progress: DrainHolderProgress | null }/** `safe_to_loop` and `retry_after_ms` are the `next` fields of the drain's other owner stops (`owner_wedged_here`). */export interface DrainLeaseHeld { code: typeof SYNC_DRAIN_LEASE_HELD; holder: DrainHolder | null; retry_after_ms: number; safe_to_loop: true; lost?: true; fix: Action }-interface DrainLease { lockId: string; sourceId: string; token: string; signal: AbortSignal }+/** `tailClear`: a pass under this lease read that no tail is owed, and nothing under it owed one since (`withSyncTail` reads none). */+interface DrainLease { lockId: string; sourceId: string; token: string; signal: AbortSignal; tailClear?: boolean }const leases = new AsyncLocalStorage<ReadonlyMap<string, DrainLease>>();@@ -202,10 +203,11 @@ export interface DrainLeaseOptions {* `remove_on_fail` drop a dead holder's row instead of queueing it. It is renewed with the lease and deleted on release.*/async function writeHolderRecord(engine: BrainEngine, sourceId: string, lease: DrainLease, holder: DrainHolderRef): Promise<void> {- await engine.executeRaw(`DELETE FROM minion_jobs WHERE queue=$1 AND name='sync' AND data->>'sourceId'=$2`, [LEASE_BEACON_QUEUE, sourceId]);- await engine.executeRaw(`INSERT INTO minion_jobs(name,queue,status,submission_authority,data,max_attempts,max_stalled,lock_token,lock_until,started_at,remove_on_complete,remove_on_fail)- VALUES('sync',$1,'active','{"version":1,"kind":"application"}'::jsonb,$2::text::jsonb,1,0,$3,now()+make_interval(mins => $4),now(),true,true)`,- [LEASE_BEACON_QUEUE, JSON.stringify({ sourceId, drain_lease_beacon: { kind: holder.kind, id: holder.id ?? null, version: VERSION } }), lease.token, DRAIN_LEASE_TTL_MINUTES]);+ // One statement: the insert reads the delete's count, so a former holder's row goes first.+ await engine.executeRaw(`WITH gone AS (DELETE FROM minion_jobs WHERE queue=$1 AND name='sync' AND data->>'sourceId'=$5 RETURNING 1)+ INSERT INTO minion_jobs(name,queue,status,submission_authority,data,max_attempts,max_stalled,lock_token,lock_until,started_at,remove_on_complete,remove_on_fail)+ SELECT 'sync',$1,'active','{"version":1,"kind":"application"}'::jsonb,$2::text::jsonb,1,0,$3,now()+make_interval(mins => $4),now(),true,true FROM (SELECT count(*) FROM gone) g`,+ [LEASE_BEACON_QUEUE, JSON.stringify({ sourceId, drain_lease_beacon: { kind: holder.kind, id: holder.id ?? null, version: VERSION } }), lease.token, DRAIN_LEASE_TTL_MINUTES, sourceId]);}/**@@ -220,6 +222,8 @@ export async function withDrainLease(engine: BrainEngine, sourceId: string, optsconst startedAt = Date.now();let seen: string | undefined, reportedAt = 0;for (;;) {+ // The holder row's delete and the lock's release share a round trip: the delete is awaited once the lock is released.+ let released: Promise<unknown> | undefined;try {return await withRefreshingLock(engine, lockId, async (signal, handle) => {const lease: DrainLease = { lockId, sourceId, token: handle.acquisitionToken, signal };@@ -236,9 +240,9 @@ export async function withDrainLease(engine: BrainEngine, sourceId: string, optsreturn await leases.run(store, () => work(signal));} finally {clearInterval(beacon);- await engine.executeRaw('DELETE FROM minion_jobs WHERE queue=$1 AND lock_token=$2', [LEASE_BEACON_QUEUE, lease.token]).catch(() => undefined);+ released = engine.executeRaw('DELETE FROM minion_jobs WHERE queue=$1 AND lock_token=$2', [LEASE_BEACON_QUEUE, lease.token]).catch(() => undefined);}- }, { ttlMinutes: DRAIN_LEASE_TTL_MINUTES, refreshIntervalMs: DRAIN_LEASE_REFRESH_MS });+ }, { ttlMinutes: DRAIN_LEASE_TTL_MINUTES, refreshIntervalMs: DRAIN_LEASE_REFRESH_MS }).finally(() => released);} catch (error) {if (error instanceof LockStolenError && error.lockId === lockId) {return leaseHeldResult(sourceId, await readDrainHolder(engine, sourceId).catch(() => null), { lost: true, remote: opts.remote, resumeArgv: opts.resumeArgv });diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.tsindex d18fbbc04e..6f18f512f8 100644--- a/src/core/persistence/sync-pass-row.ts+++ b/src/core/persistence/sync-pass-row.ts@@ -142,10 +142,12 @@ export async function readLivePassRows(engine: Exec, sourceIds?: readonly string/*** Writes the pass row inside `tx` (the caller has run `assertDrainLease` in the same transaction). `pin`: the pass that* just took the lease replaces whatever row a former holder left; otherwise the write lands only while the row still- * carries `leaseToken`. Returns false when it did not land (another pass pinned since).+ * carries `leaseToken`. Returns false when it did not land (another pass pinned since). `clock`: `telemetry.started_at` is the+ * transaction's clock (`now()`, as an ISO string), so the write needs no earlier read of it.*/-export async function writePassRow(tx: Exec, value: ManagedSyncPassValue, opts: { pin?: boolean } = {}): Promise<boolean> {- const rows = await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now())+export async function writePassRow(tx: Exec, value: ManagedSyncPassValue, opts: { pin?: boolean; clock?: boolean } = {}): Promise<boolean> {+ const json = opts.clock ? `jsonb_set($3::text::jsonb,'{telemetry,started_at}',to_jsonb(to_char(now() AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')))` : '$3::text::jsonb';+ const rows = await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array(${json}),now())ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now()WHERE $4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5 RETURNING 1`,[MANAGED_SYNC_PASS_OP, passFingerprint(value.source_id, value.incarnation), JSON.stringify(value), opts.pin === true, value.lease_token]);diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 6f95d253d9..07d88469dc 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -44,6 +44,7 @@ import { startPersistenceConsumer } from './service.ts';import { clearManagedSyncFailureAfterSuccess } from './sync-failures.ts';import { managedCursorKey, resolveManagedCursor, retireManagedCursor, retireOrphanSliceRecords } from './sync-cursor-key.ts';import { withCoordinatedWrite } from './context.ts';+import { pipelined } from '../page-state/transactions.ts';import { principalAttribution } from './attribution.ts';import { isCodeFilePath, resolveSlugForPath } from '../sync.ts';import { syncOriginPath } from './sync-origin.ts';@@ -95,11 +96,16 @@ const parserFingerprint = () => digest(['x.md', 'x.ts', 'x.png'].map(path => syn*/async function retireLegacyCursors(engine: BrainEngine, input: { sourceId: string; incarnation: string; remote: boolean; assertActive: () => void }):Promise<{ wait?: RetryWait; hostRequired?: true; episode?: PassEpisode }> {+ const readHeader = (key: string) => engine.executeRaw<{ slices: boolean; header: { runId?: string; done?: boolean; processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions & { exclude?: string[]; includeHidden?: string[]; strategy?: string; srcSubpath?: string; workingTree?: boolean } } | null }>(+ `SELECT (SELECT completed_keys->0 FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1) AS header,+ EXISTS (SELECT 1 FROM op_checkpoints WHERE op=$2 AND left(fingerprint, length($3))=$3) AS slices`, [key, SYNC_SLICE_OP, `${input.sourceId}:${input.incarnation}:`]);+ // #6712 PR 4b: the canonical key's header is read beside the resolution (the key it picks unless it adopts an older one;+ // the resolution never writes the key it picks), and read again only for an adopted key.+ const canonical = managedCursorKey(input.incarnation, undefined), speculative = readHeader(canonical);+ speculative.catch(() => undefined);const resolution = await resolveManagedCursor(engine, { sourceId: input.sourceId, incarnation: input.incarnation, company: undefined, assertActive: input.assertActive, foldIn: !input.remote });if (resolution.waitFor) return { wait: { ...resolution.waitFor, retry_after_ms: 5000 } };- const [row] = await engine.executeRaw<{ slices: boolean; header: { runId?: string; done?: boolean; processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions & { exclude?: string[]; includeHidden?: string[]; strategy?: string; srcSubpath?: string; workingTree?: boolean } } | null }>(- `SELECT (SELECT completed_keys->0 FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1) AS header,- EXISTS (SELECT 1 FROM op_checkpoints WHERE op=$2 AND left(fingerprint, length($3))=$3) AS slices`, [resolution.key, SYNC_SLICE_OP, `${input.sourceId}:${input.incarnation}:`]);+ const [row] = await (resolution.key === canonical ? speculative : readHeader(resolution.key));const header = row?.header;if (!header) {if (row?.slices && !input.remote) await retireOrphanSliceRecords(engine, input.sourceId, input.incarnation);@@ -294,22 +300,29 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prconst remote = authority.writer.remote;const lease = currentDrainLease(sourceId);if (!lease) throw new Error(`The live sync pass of ${sourceId} runs only under the source's drain lease.`);+ lease.tailClear = false;const started = Date.now(), startedAt = new Date(started).toISOString();+ // Pin (design §2.2): the row, sync.admission, HEAD and the mode. The reads the kind needs ride the same round trip: the+ // selection's patterns, the schema pack, the tail, the retry row, the source's holds and the idle probe (which reads the+ // row's watermark and open ids itself). #6712 PR 4b: the legacy cursors' retirement runs beside them; it writes none of+ // what they read, and its outcome is still decided first.+ const pin = Promise.all([readPassRow(engine, sourceId, incarnation),+ readSyncAdmission(engine), engine.getConfig('sync.include_working_tree'), selectionPatterns(engine, opts),+ input.processingOptions.noSchemaPack ? null : loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null),+ readSyncTail(engine, sourceId), readGitHoldRetryPaths(engine, sourceId, incarnation), readGitSourceHolds(engine, { sourceIds: [sourceId] }),+ passIdleProbe(engine, { sourceId, incarnation, worktreeId: context.binding.worktree_id, requestHwm: null, openAtStamp: null }),+ engine.executeRaw(`SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=ANY($1::text[]) LIMIT 1`, [passFailureKeys(sourceId, incarnation)])] as const);+ pin.catch(() => undefined);const handover = await retireLegacyCursors(engine, { sourceId, incarnation, remote, assertActive });const empty = (status: SyncResult['status'], reason?: SyncResult['reason']): SyncResult => ({ status, fromCommit: remote ? null : context.source.last_commit, toCommit: remote ? '' : context.source.last_commit ?? '',added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], filesImported: 0, bankedFiles: 0, ...(reason ? { reason } : {}) });if (handover.wait) return { ...empty('partial', 'writer_pending'), ...(remote ? {} : { retryWait: handover.wait }) };if (handover.hostRequired) return empty('blocked_by_failures', 'reconcile_host_required');-- // Pin (design §2.2): the row, sync.admission, HEAD and the mode. The reads the kind needs ride the same round trip: the- // selection's patterns, the schema pack, the tail, the retry row and the source's holds (only the idle probe needs the row).- const [prior, admission, configuredWorking, patterns, loadedPack, tail, retry, sourceHolds] = await Promise.all([readPassRow(engine, sourceId, incarnation),- readSyncAdmission(engine), engine.getConfig('sync.include_working_tree'), selectionPatterns(engine, opts),- input.processingOptions.noSchemaPack ? null : loadActivePackForEngine(engine, { remote: false, sourceId }).catch(() => null),- readSyncTail(engine, sourceId), readGitHoldRetryPaths(engine, sourceId, incarnation), readGitSourceHolds(engine, { sourceIds: [sourceId] })]);+ const [prior, admission, configuredWorking, patterns, loadedPack, tail, retry, sourceHolds, rowProbe, failed] = await pin;assertActive();- let head = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();- const detached = syncGit(context.gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() === 'HEAD';+ const [headLine, refLine] = syncGit(context.gitRoot, ['rev-parse', 'HEAD', '--abbrev-ref', 'HEAD']).split('\n');+ let head = headLine!.trim();+ const detached = refLine?.trim() === 'HEAD';const mode: SyncSelection['mode'] = detached || (opts.workingTree ?? configuredWorking === 'true') ? 'working' : 'committed';const selection = passSelection(patterns, opts, context, mode);const configured = !remote && !opts.exclude?.length && !opts.includeHidden?.length && opts.srcSubpath === undefined@@ -337,9 +350,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr// The kind (design §2.2), from the real converged state.const converged = obligations.converged;- const probe = converged ? await passIdleProbe(engine, { sourceId, incarnation, worktreeId: context.binding.worktree_id, requestHwm: converged.request_hwm,- openAtStamp: converged.open_at_stamp ?? [] }) : null;- assertActive();+ const probe = converged ? rowProbe : null;const holds = (sourceHolds[0]?.holds ?? []).filter(hold => hold.incarnation === incarnation);// Working mode (design §2.2): the stat cache this process kept from the round its last stamp used; a cold process has none.const cacheKey = passFingerprint(sourceId, incarnation);@@ -371,13 +382,15 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prvalue.telemetry = { ...value.telemetry, outcome: 'up_to_date', ended_at: at, duration_ms: Date.now() - started };await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {assertActive();- await assertDrainLease(tx, sourceId);- // One round trip: the stamp and the transaction's clock read are pipelined.- [, value.telemetry.started_at] = await Promise.all([tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]),- databaseNow(tx)]);- await writePassRow(tx, value, { pin: true });+ // One round trip: the lease check, the stamp and the row (started at the transaction's clock) are pipelined; a lost+ // lease rolls the other two back.+ await pipelined(tx, [() => assertDrainLease(tx, sourceId), () => tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]),+ () => writePassRow(tx, value, { pin: true, clock: true })]);}, principalAttribution(authority.writer.principal)));- await clearPassFailures(engine, sourceId, incarnation);+ // A failure is recorded only under the lease this pass holds, so none recorded at pin means none to clear.+ if (failed.length) await clearPassFailures(engine, sourceId, incarnation);+ // Nor can a tail be owed since the pin read none: the lease's holder reads none after it (sync-run.ts).+ lease.tailClear = !tail;return { ...empty('up_to_date'), toCommit: remote ? '' : head, ...(inherited.length ? { inherited_options: inherited } : {}) };}// Design §7: the cost decision at pin; an unknown or spent envelope defers embeddings for this pass (never inherited).@@ -669,9 +682,9 @@ async function databaseNow(tx: Pick<BrainEngine, 'executeRaw'>): Promise<string>}/** A converged or idle pass clears what earlier stops recorded: the pass row's failure key and the incarnation's cursor key. */+const passFailureKeys = (sourceId: string, incarnation: string) => [passFingerprint(sourceId, incarnation), managedCursorKey(incarnation, undefined)];async function clearPassFailures(engine: BrainEngine, sourceId: string, incarnation: string): Promise<void> {- await Promise.all([clearManagedSyncFailureAfterSuccess(engine, passFingerprint(sourceId, incarnation)),- clearManagedSyncFailureAfterSuccess(engine, managedCursorKey(incarnation, undefined))]);+ await Promise.all(passFailureKeys(sourceId, incarnation).map(key => clearManagedSyncFailureAfterSuccess(engine, key)));}export type { SyncAdmission };diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 1fac77e000..c6d5f5cf29 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -567,21 +567,24 @@ export async function idleTickProbe(engine: BrainEngine, input: { sourceId: stri* #6712 PR 4b (design v3.2 §2.2): the idle tick's database reads in one statement: the pass row, whether a request of the* worktree is newer than the converged watermark (a range on the unique `sequence` index; `requestHwm` overrides the* row's), whether any request is open (`persistence_requests_pending`), and how many of the ids recorded in- * `converged.open_at_stamp` are still open (`r:<request>` requests, `e:<effect>` Git effects).+ * `converged.open_at_stamp` are still open (`r:<request>` requests, `e:<effect>` Git effects; `openAtStamp` null reads the+ * row's, so the probe needs no earlier read of the row).*/export async function passIdleProbe(engine: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; incarnation: string; worktreeId: string;- requestHwm: string | number | null; openAtStamp: readonly string[] }): Promise<{ passRow: Record<string, unknown> | null; newer: boolean; pending: boolean; stillOpen: number }> {+ requestHwm: string | number | null; openAtStamp: readonly string[] | null }): Promise<{ passRow: Record<string, unknown> | null; newer: boolean; pending: boolean; stillOpen: number }> {const [probe] = await engine.executeRaw<{ pass_row: Record<string, unknown> | null; newer: boolean; pending: boolean; still_open: number | string }>(`WITH pass AS (- SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2)+ SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND fingerprint=$2),+ stamp AS (SELECT unnest(COALESCE($5::text[], ARRAY(SELECT jsonb_array_elements_text(CASE WHEN jsonb_typeof(value->'obligations'->'converged'->'open_at_stamp')='array'+ THEN value->'obligations'->'converged'->'open_at_stamp' ELSE '[]'::jsonb END) FROM pass))) AS id)SELECT (SELECT value FROM pass) AS pass_row,EXISTS (SELECT 1 FROM persistence_requests WHERE sequence > COALESCE($3::bigint, ((SELECT value FROM pass)->'obligations'->'converged'->>'request_hwm')::bigint, 0)AND (worktree_id = $4 OR worktree_id IS NULL AND source_id = $6 AND source_incarnation = $7::uuid)) AS newer,EXISTS (SELECT 1 FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id = $4 OR worktree_id IS NULL AND source_id = $6 AND source_incarnation = $7::uuid)) AS pending,(SELECT count(*) FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id = $4 OR worktree_id IS NULL AND source_id = $6 AND source_incarnation = $7::uuid)- AND 'r:'||request_id::text = ANY($5::text[]))+ AND 'r:'||request_id::text IN (SELECT id FROM stamp))+ (SELECT count(*) FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_id- WHERE r.worktree_id = $4 AND e.kind = 'git' AND e.state IN ('queued','running') AND 'e:'||e.id::text = ANY($5::text[])) AS still_open`,- [MANAGED_SYNC_PASS_OP, `${input.sourceId}:${input.incarnation}`, input.requestHwm, input.worktreeId, [...input.openAtStamp], input.sourceId, input.incarnation]);+ WHERE r.worktree_id = $4 AND e.kind = 'git' AND e.state IN ('queued','running') AND 'e:'||e.id::text IN (SELECT id FROM stamp)) AS still_open`,+ [MANAGED_SYNC_PASS_OP, `${input.sourceId}:${input.incarnation}`, input.requestHwm, input.worktreeId, input.openAtStamp ? [...input.openAtStamp] : null, input.sourceId, input.incarnation]);return { passRow: probe?.pass_row ?? null, newer: probe?.newer === true, pending: probe?.pending === true, stillOpen: Number(probe?.still_open ?? 0) };}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex e6c7683bb2..12f9a9a1c6 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -14,12 +14,12 @@ import { preflightSyncCapacity } from './sync-capacity-preflight.ts';import { preparationConfigView } from './config-snapshot.ts';import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';-import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';+import { assertSyncEntryOrigin, discoverManagedSync, readManagedSyncRows, resolveManagedSyncContext, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';import { checkpointRevival } from './sync-slug-mode.ts';import { managedCursorKey, resolveManagedCursor } from './sync-cursor-key.ts';import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';-import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';+import { activeManagedBrainId, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';import { startClaimPhase } from './claim-phase.ts';import { screeningRequest } from './noop-kernel.ts';@@ -1221,10 +1221,12 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slif (opts.dryRun || currentDrainLease(opts.sourceId ?? 'default')) return performManagedPass(engine, opts, slice);const sourceId = opts.sourceId ?? 'default';const remote = currentSubmissionAuthority()?.kind === 'remote_generic';+ let tailClear = false;return withDrainLease(engine, sourceId, { holder: opts.drainHolder ?? { kind: slice ? 'owner_slice' : 'cli', id: null }, remote },- signal => performManagedPass(engine, signal ? { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, signal]) : signal } : opts, slice))- // #6712 PR 2: an owner slice is time-bounded, so its tail gets the slice's budget (pages it leaves stay stale, with the notice).- .then(result => withSyncTail(engine, sourceId, result, { signal: opts.signal, deadlineAtMs: opts.deadlineAtMs, ...(slice ? { budgetMs: slice.maxMs } : {}) }))+ signal => performManagedPass(engine, signal ? { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, signal]) : signal } : opts, slice)+ .finally(() => { tailClear = currentDrainLease(sourceId)?.tailClear === true; }))+ // #6712 PR 2: an owner slice's tail gets the slice's budget. PR 4b: an idle pass that read no owed tail under the lease reads none.+ .then(result => tailClear ? result : withSyncTail(engine, sourceId, result, { signal: opts.signal, deadlineAtMs: opts.deadlineAtMs, ...(slice ? { budgetMs: slice.maxMs } : {}) })).catch(async error => {if (!(error instanceof LockUnavailableError) || error.lockId !== syncLockId(sourceId)) throw error;return leaseHeldResult(sourceId, await readDrainHolder(engine, sourceId).catch(() => null), { remote });@@ -1238,7 +1240,7 @@ async function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: {const cursor = state.cursor?.() ?? null;try {const report = await buildHoldReport(engine, { sourceId: state.sourceId, incarnation: state.incarnation, runId: cursor?.runId ?? '', remote: state.remote === true,- policy: await readSyncHoldPolicy(engine), pendingScreen: synced.reason === 'writer_yield',+ policy: readSyncHoldPolicy(engine), pendingScreen: synced.reason === 'writer_yield',screened: 'entries' in (cursor ?? {}) ? (cursor as Cursor).entries.slice(0, cursor!.index).filter(entry => entry.action === 'import').length : 0 });const recovered = state.remote ? undefined : recoveredReport(state.sourceId, cursor?.counts.recovered);const fences = fencesNormalizedReport(state.sourceId, cursor?.counts.fences, state.remote === true);@@ -1264,16 +1266,18 @@ async function resolvePassCursor(engine: BrainEngine, input: { sourceId: string;return { key: resolution.key, waiting: { ...result(header, 'partial', 'writer_pending'), ...(input.remote ? {} : { retryWait: { ...resolution.waitFor!, retry_after_ms: 5000 } }) } };}async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPages: number; maxMs: number } | undefined, state: HoldRunState): Promise<SyncResult> {- await assertManagedSyncActive(engine);- if (opts.sourceId && !currentCompanyBrainSync(opts.sourceId) && await getCompanyBrainProfile(engine, opts.sourceId)) {- return (await import('../company-brain/runtime.ts')).performCompanyBrainSync(engine, opts);- }+ // #6712 PR 4b: the mode, the company profile and the source's rows in one round trip; each check refuses in its old order.+ const rows = readManagedSyncRows(engine, opts.sourceId ?? 'default'); rows.catch(() => undefined);+ const [active, profile] = await Promise.allSettled([activeManagedBrainId(engine),+ opts.sourceId && !currentCompanyBrainSync(opts.sourceId) ? getCompanyBrainProfile(engine, opts.sourceId) : null]);+ for (const read of [active, profile]) if (read.status === 'rejected') throw read.reason;+ if (profile.status === 'fulfilled' && profile.value) return (await import('../company-brain/runtime.ts')).performCompanyBrainSync(engine, opts);assertPersistenceAccepting(engine);validateManagedSyncOptions(opts);- const context = await resolveManagedSyncContext(engine, opts);+ const context = await resolveManagedSyncContext(engine, opts, rows);// Independent reads, one round trip; a refusal still wins over the authority's own error, as when they ran in turn.const reads = await Promise.allSettled([opts.dryRun ? null : assertManagedSyncAllowed(engine, context.binding.worktree_id, context.sourceId),- managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root)] as const);+ managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root, (active as PromiseFulfilledResult<string>).value)] as const);for (const read of reads) if (read.status === 'rejected') throw read.reason;const authority = (reads[1] as PromiseFulfilledResult<SyncAuthority>).value;const company = currentCompanyBrainSync(context.sourceId);diff --git a/test/sync-pass-live-6712.test.ts b/test/sync-pass-live-6712.test.tsindex 7f506c9d4b..f44d0f5bea 100644--- a/test/sync-pass-live-6712.test.ts+++ b/test/sync-pass-live-6712.test.ts@@ -25,6 +25,9 @@* - a commit during a pass: the next round reads the new HEAD and its batch freezes that commit (no storage_error from an older pin).* - --no-schema-pack: a first pass converges (its parser expects no pack); a cost-gate deferral is no inherited opt-out;* a source configured with a strategy, synced with that strategy named (sync --all), stamps last_commit.+ * - idle-tick batching: a converged tick still clears a recorded failure, writes its pass row at the transaction clock+ * (one pipelined statement set), and with no failure recorded and no tail owed at pin it issues neither the clears nor+ * the post-lease tail read.* - probe 54: a pass intent keeps what the #6862 FIFO guard reads: a `managed_sync_` kind, the slug and page, and `renameFrom.slug`.** Each test fails on capy/6712-pr4b (8cda2764b), where a non-company source still runs the cursor engine: the fences do not@@ -37,6 +40,7 @@ import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { installFaultHook } from '../src/core/persistence/fault-points.ts';import { SYNC_ADMISSION_KEY } from '../src/core/persistence/sync-admission.ts';+import { SYNC_TAIL_OP } from '../src/core/persistence/sync-tail-record.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { RECOVERY_VERSION } from '../src/core/markdown.ts';import { readGitHold, SYNC_IMPORT_PROVENANCE_OP, writeGitHold } from '../src/core/persistence/sync-holds.ts';@@ -169,6 +173,28 @@ describe('#6712 PR 4b live pass fences (pglite)', () => {expect({ status: idle.status, pass: idle.pass }).toEqual({ status: 'up_to_date', pass: undefined });}, { setup }), 180_000);+ test('idle-tick batching: a converged tick clears a recorded failure and stamps the pass row at the transaction clock; with none recorded and no tail owed it issues neither the clears nor the post-lease tail read', () => managedBrain(async ({ engine }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const incarnation = await incarnationOf(engine);+ const failure = "SELECT count(*)::int AS n FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1";+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync-failure',$1,'[{}]'::jsonb)", [`default:${incarnation}`]);+ expect((await performManagedSync(engine, OPTS)).status).toBe('up_to_date');+ expect((await engine.executeRaw<{ n: number }>(failure, [`default:${incarnation}`]))[0]!.n).toBe(0);+ const statements: Array<{ sql: string; params: unknown[] }> = [];+ const executeRaw = engine.executeRaw;+ // A transaction's engine inherits this method: only the engine's own statements are recorded.+ engine.executeRaw = function (this: BrainEngine, sql: string, params?: unknown[], opts?: never) {+ if (this === engine) statements.push({ sql, params: params ?? [] });+ return executeRaw.call(this, sql, params, opts);+ } as typeof engine.executeRaw;+ try { expect((await performManagedSync(engine, OPTS)).status).toBe('up_to_date'); } finally { delete (engine as { executeRaw?: unknown }).executeRaw; }+ expect({ clears: statements.filter(s => /DELETE FROM op_checkpoints WHERE op='managed-sync-failure'/.test(s.sql)).length,+ tailReads: statements.filter(s => s.params[0] === SYNC_TAIL_OP).length }).toEqual({ clears: 0, tailReads: 1 });+ const [row] = await engine.executeRaw<{ started: string; updated: string }>(`SELECT completed_keys->0->'telemetry'->>'started_at' AS started,+ to_char(updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS updated FROM op_checkpoints WHERE op='managed-sync-pass' AND fingerprint=$1`, [`default:${incarnation}`]);+ expect({ started: new Date(row!.started).toISOString(), updated: row!.updated }).toEqual({ started: row!.updated, updated: row!.updated });+ }, { setup }), 180_000);+test('probe 46 (reparse half): a parser change on a fileSame and dbSame page re-imports it as reparse, with no hold', () => managedBrain(async ({ engine }) => {expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');const fingerprint = `default:${await incarnationOf(engine)}:${(await engine.readPageSnapshot('notes/b', { sourceId: 'default' }))!.page.id}`;