Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: reuse the T listing across passes with git diff-tree (sync.level_reuse, default on)

garrytana3cb8174cbfc
diff --git a/.github/workflows/sync-freshness-gate.yml b/.github/workflows/sync-freshness-gate.yml
index 81e9126d20..63ccafe567 100644
--- a/.github/workflows/sync-freshness-gate.yml
+++ b/.github/workflows/sync-freshness-gate.yml
@@ -6,7 +6,8 @@ name: Sync freshness gate
# 10k synthetic pages, on Postgres managed, PGLite managed and Postgres classic. The gate
# value is the p50 of 10 reps after one discarded warm-up; a cell fails above the committed
# baseline (scripts/bench/sync-freshness-baseline.json) + 25%. The baseline is valid only
-# on this runner class (Ubicloud standard-4). Nightly and on dispatch; never in the PR tier.
+# on this runner class (Ubicloud standard-4). Then the untimed level-reuse oracle (--oracle):
+# the managed cells with GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1. Nightly and on dispatch; never in the PR tier.
on:
schedule:
@@ -41,6 +42,12 @@ jobs:
git config --global user.email [email protected]
bun scripts/bench/sync-freshness-gate.ts --work-dir .context/bench/sync-freshness-gate --out .context/bench/sync-freshness-gate/run.json \
| tee -a "$GITHUB_STEP_SUMMARY"
+ - name: Level-reuse oracle (every reused level read compared with a whole read; untimed)
+ if: always()
+ timeout-minutes: 30
+ run: |
+ set -o pipefail
+ bun scripts/bench/sync-freshness-gate.ts --oracle --work-dir .context/bench/sync-freshness-gate | tee -a "$GITHUB_STEP_SUMMARY"
- name: Stop harness containers and processes
if: always()
run: |
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 648ac579d8..c1faebfe18 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -136,6 +136,21 @@ Timing knobs the drain uses:
| `GBRAIN_SYNC_BULK_MAX_TXN_MS` (was `sync.bulk_max_txn_ms`, retired in 0.60.266.0) | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. |
| `sync.bulk_size` / `GBRAIN_SYNC_BULK_SIZE` | Largest bulk group. | 16 | — |
+### Level reuse
+
+A pass in a long-running process (the serve, or `gbrain sync --watch`) keeps
+the tree listing of the commit it read. The next pass at a new commit lists
+only what changed between the two commits (`git diff-tree`) and patches that
+listing instead of listing the whole tree; it still judges every path. Any
+doubt reads the tree whole: a new process, another source or incarnation, a
+pass that failed before it walked the listing, a listing unused for 10
+minutes, a diff larger than a quarter of the tree (and over 2,000 paths), a
+scope with pathspec characters, or a Git error. `gbrain config set
+sync.level_reuse false` turns reuse off and every pass reads the whole tree;
+`true` or unset keeps it on. `GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1` also reads
+every reused listing whole and fails the pass on any difference (tests and the
+nightly freshness cell use it).
+
### Sync config keys
`gbrain config` keeps three kinds of `sync.*` keys (`src/core/sync-config-keys.ts`):
@@ -143,7 +158,7 @@ Timing knobs the drain uses:
- **Tunables** you set and keep: `sync.bulk_size`, `sync.lanes`, `sync.exclude`, `sync.include_hidden`,
`sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`, `sync.on_commit`,
`sync.freshness_target_seconds` ([on-commit sync](on-commit-sync.md)), `sync.metafile_pages`
- ([what gets synced](#what-gets-synced)).
+ ([what gets synced](#what-gets-synced)), `sync.level_reuse` ([level reuse](#level-reuse)).
- **Rollback keys**, the way back a notice or migration promised: `sync.job_drain`, `sync.foreground_priority`,
`sync.federated_v2`, `sync.waive_batch`, `sync.bulk`. Each one set to `false` restores the earlier behavior, and
stays honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`). They are not
diff --git a/llms-full.txt b/llms-full.txt
index 6b8a4a24a7..bd25ecbff0 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6984,6 +6984,21 @@ Timing knobs the drain uses:
| `GBRAIN_SYNC_BULK_MAX_TXN_MS` (was `sync.bulk_max_txn_ms`, retired in 0.60.266.0) | Target time per bulk group; sizes the next group from the last one's time per page. | 15000 | A smaller next group. |
| `sync.bulk_size` / `GBRAIN_SYNC_BULK_SIZE` | Largest bulk group. | 16 | — |
+### Level reuse
+
+A pass in a long-running process (the serve, or `gbrain sync --watch`) keeps
+the tree listing of the commit it read. The next pass at a new commit lists
+only what changed between the two commits (`git diff-tree`) and patches that
+listing instead of listing the whole tree; it still judges every path. Any
+doubt reads the tree whole: a new process, another source or incarnation, a
+pass that failed before it walked the listing, a listing unused for 10
+minutes, a diff larger than a quarter of the tree (and over 2,000 paths), a
+scope with pathspec characters, or a Git error. `gbrain config set
+sync.level_reuse false` turns reuse off and every pass reads the whole tree;
+`true` or unset keeps it on. `GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1` also reads
+every reused listing whole and fails the pass on any difference (tests and the
+nightly freshness cell use it).
+
### Sync config keys
`gbrain config` keeps three kinds of `sync.*` keys (`src/core/sync-config-keys.ts`):
@@ -6991,7 +7006,7 @@ Timing knobs the drain uses:
- **Tunables** you set and keep: `sync.bulk_size`, `sync.lanes`, `sync.exclude`, `sync.include_hidden`,
`sync.include_working_tree`, `sync.holds`, `sync.write_through`, `sync.cost_gate_min_usd`, `sync.on_commit`,
`sync.freshness_target_seconds` ([on-commit sync](on-commit-sync.md)), `sync.metafile_pages`
- ([what gets synced](#what-gets-synced)).
+ ([what gets synced](#what-gets-synced)), `sync.level_reuse` ([level reuse](#level-reuse)).
- **Rollback keys**, the way back a notice or migration promised: `sync.job_drain`, `sync.foreground_priority`,
`sync.federated_v2`, `sync.waive_batch`, `sync.bulk`. Each one set to `false` restores the earlier behavior, and
stays honored until at least 2027-01-14 (`CONFIG_ROLLBACK_WINDOWS` in `src/core/wire-skew.ts`). They are not
diff --git a/scripts/bench/sync-freshness-gate.ts b/scripts/bench/sync-freshness-gate.ts
index 5596937a8f..7da56fe6b3 100644
--- a/scripts/bench/sync-freshness-gate.ts
+++ b/scripts/bench/sync-freshness-gate.ts
@@ -4,6 +4,7 @@
*
* bun scripts/bench/sync-freshness-gate.ts [--cells a,b] [--baseline scripts/bench/sync-freshness-baseline.json]
* [--work-dir DIR] [--out run.json] [--write-baseline FILE --machine-class NAME]
+ * bun scripts/bench/sync-freshness-gate.ts --oracle [--work-dir DIR]
*
* Procedure per cell: one sync-freshness.ts run of 11 reps with a 50 ms probe; rep 0 is a discarded warm-up and the
* gate value is the p50 of commit -> keyword-visible over reps 1..10. A cell fails when that p50 exceeds the committed
@@ -13,9 +14,14 @@
* Only cells measured stable are gated: 25 runs on 5 fresh Ubicloud standard-4 VMs (the CI runner class) put every
* serve-watch cell's p50 within a max/min ratio of 1.18, with no false failure in any of 600 baseline/candidate run
* pairs at +25%. A manual managed sync was left out: its p50 moves with the VM (852 to 1254 ms, 52 of 600 pairs failed).
+ *
+ * --oracle (GBRA-133 wave 4, untimed): the two managed cells once more with GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1, so the
+ * serve compares every level read it reused across passes with a whole read (persistence/sync-tree-reuse.ts) and logs
+ * one `[level_reuse]` line per check. A cell fails when a rep never became visible, the serve logged a mismatch, or it
+ * verified no reuse at all (the oracle checked nothing).
*/
import { join, resolve } from 'node:path';
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { machineInfo, pct } from './sync-freshness-lib.ts';
const REPO = resolve(import.meta.dir, '../..');
@@ -37,6 +43,33 @@ const WRITE = argv.includes('--write-baseline') ? resolve(flag('write-baseline',
mkdirSync(WORK, { recursive: true });
interface CellResult { cell: string; p50_ms: number | null; counted: Array<number | null>; warmup_ms: number | null; limit_ms?: number; baseline_ms?: number; pass?: boolean; reason?: string }
+if (argv.includes('--oracle')) process.exit(await levelReuseOracle());
+
+/** --oracle: see the header. 6 reps per managed cell, 120 s each at most; the verdict comes from the serve logs. */
+async function levelReuseOracle(): Promise<number> {
+ const rows: string[] = [];
+ let ok = true;
+ for (const engine of ['pglite', 'postgres']) {
+ const started = Date.now();
+ const p = Bun.spawn([process.execPath, join(REPO, 'scripts/bench/sync-freshness.ts'), '--engine', engine, '--mode', 'managed', '--commit', 'single', '--trigger', 'serve',
+ '--detection', 'watch', '--pages', '10000', '--reps', '6', '--probe-ms', '50', '--timeout', '120', '--work-dir', WORK, '--label', 'oracle', '--json'],
+ { cwd: REPO, stdout: 'pipe', stderr: 'inherit', env: { ...process.env, GBRAIN_SYNC_LEVEL_REUSE_VERIFY: '1' } });
+ const [out, code] = await Promise.all([new Response(p.stdout).text(), p.exited]);
+ const line = out.trim().split('\n').reverse().find(l => l.startsWith('{'));
+ const reps = line ? (JSON.parse(line).reps as Array<{ search_ms: number | null }>).map(r => r.search_ms) : [];
+ const logs = join(WORK, 'results', 'logs');
+ const text = existsSync(logs) ? readdirSync(logs).filter(f => f.startsWith(`${engine}-managed-10000-single-serve-oracle-`) && statSync(join(logs, f)).mtimeMs >= started)
+ .map(f => readFileSync(join(logs, f), 'utf8')).join('\n') : '';
+ const verified = text.match(/level_reuse_verified/g)?.length ?? 0, mismatches = text.match(/level_reuse_mismatch/g)?.length ?? 0;
+ const reason = code !== 0 || !line ? 'bench exited ' + code : reps.some(r => r === null) ? 'a rep never became visible'
+ : mismatches ? mismatches + ' mismatch(es) in the serve log' : verified === 0 ? 'no reused level read was verified' : null;
+ if (reason) ok = false;
+ rows.push('| ' + [engine + '-managed', reps.length, verified, mismatches, reason ? 'FAIL: ' + reason : 'pass'].join(' | ') + ' |');
+ }
+ console.log('| oracle cell | reps | reused reads verified | mismatches | verdict |\n|---|---|---|---|---|\n' + rows.join('\n'));
+ return ok ? 0 : 1;
+}
+
const results: CellResult[] = [];
for (const name of names) {
const p = Bun.spawn([process.execPath, join(REPO, 'scripts/bench/sync-freshness.ts'), ...CELLS[name]!, '--pages', '10000', '--reps', String(REPS), '--probe-ms', '50',
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 78b790c914..9279c85a9b 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/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 parseWithTimeout
-src/core/config.ts 2005 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); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts)
+src/core/config.ts 2006 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); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts)
src/core/persistence/sync-run.ts 1682 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; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives)
src/core/bootstrap/harness.ts 2592 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 block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/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 option
diff --git a/src/core/config.ts b/src/core/config.ts
index f0e6c86956..8a1820dd0b 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1740,6 +1740,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'sync.federated_v2',
'sync.include_working_tree',
'sync.metafile_pages', // GBRA-150: typed (default) | off, whether a nested folder-scaffolding file with type:/title: frontmatter is a page (core/sync.ts)
+ 'sync.level_reuse', // GBRA-133 wave 4: true (default) | false, whether a resident pass patches the tree listing its last pass read (persistence/sync-tree-reuse.ts)
// #5984: managed Postgres sync publishes pages in bulk groups (on by default; each page keeps its own request).
'sync.bulk',
'sync.bulk_size',
diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.ts
index f328469d47..72d0a61033 100644
--- a/src/core/persistence/sync-git-stream.ts
+++ b/src/core/persistence/sync-git-stream.ts
@@ -134,6 +134,35 @@ export async function walkTreeLevel(gitRoot: string, commit: string, scope: stri
}, shared);
}
+/** One `diff-tree -r` change of a `T` path: its entry at the new commit, or null where the new commit has none. */
+export interface GitTreeChange { path: string; entry: GitTreeEntry | null }
+/** The modes `readTreeLevel` keeps (blob and gitlink entries); a change to anything else is not a `T` change it can apply. */
+const TREE_ENTRY_MODE = /^(?:10[0-7]{4}|120000|160000)$/;
+
+/**
+ * The changes of `T` under `scope` from commit `from` to `to` (one `diff-tree -r -z --no-renames`, raw: full OIDs),
+ * or null when a record names an entry `readTreeLevel` would not list the same way: the caller reads `T` whole then.
+ */
+export async function readTreeChanges(gitRoot: string, from: string, to: string, scope: string, shared?: LoopYield): Promise<GitTreeChange[] | null> {
+ const changes: GitTreeChange[] = [];
+ let meta: string | null = null, foreign = false;
+ await readRecords(gitRoot, ['diff-tree', '-r', '-z', '--no-renames', from, to, ...(scope ? ['--', scope] : [])], 'diff-tree', bytes => {
+ if (meta === null) {
+ meta = bytes.toString('latin1');
+ if (!meta.startsWith(':')) throw malformed('diff-tree', meta);
+ return;
+ }
+ const [, dstMode = '', , dstOid = '', status = ''] = meta.slice(1).split(' ');
+ meta = null;
+ const path = bytes.toString('utf8');
+ if (status === 'D') changes.push({ path, entry: null });
+ else if ((status === 'A' || status === 'M' || status === 'T') && TREE_ENTRY_MODE.test(dstMode) && OID.test(dstOid)) changes.push({ path, entry: { mode: dstMode, oid: dstOid } });
+ else foreign = true;
+ }, shared);
+ if (meta !== null) throw new SyncTreeReadIncomplete('diff-tree', 'a status record had no path');
+ return foreign ? null : changes;
+}
+
/** `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, shared?: LoopYield): Promise<Map<string, GitIndexEntry>> {
const index = new Map<string, GitIndexEntry>();
diff --git a/src/core/persistence/sync-held-deletions.ts b/src/core/persistence/sync-held-deletions.ts
index 394bc84992..7816fa9068 100644
--- a/src/core/persistence/sync-held-deletions.ts
+++ b/src/core/persistence/sync-held-deletions.ts
@@ -28,6 +28,7 @@ import type { ManagedSyncContext } from './sync-discovery.ts';
import { readBlobs } from './sync-git-stream.ts';
import { readGitSourceHolds } from './sync-holds.ts';
import { readDeletionProvenance } from './sync-origin-evidence.ts';
+import { levelReuseAllowed, SYNC_LEVEL_REUSE_KEY } from './sync-tree-reuse.ts';
import type { ShadowLevel, ShadowPath } from './sync-pass.ts';
const execFileAsync = promisify(execFile);
@@ -46,18 +47,21 @@ const TRANSIENT: ReadonlySet<HeldDeletionRefusal> = new Set(['provenance_unknown
export interface HeldDeletionState { screened: Set<string>; applied: number; refused: number }
export const newHeldDeletionState = (): HeldDeletionState => ({ screened: new Set(), applied: 0, refused: 0 });
-/** Whether the switch is on for `sourceId` (the per-source key wins over the brain-wide one; only `true` turns it on): one read, once per pass. */
-export async function heldDeletionsEnabled(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<boolean> {
+/**
+ * The pass's config switches in one statement, read once per pass: `sync.apply_held_deletions` (the per-source key wins over
+ * the brain-wide one; only `true` turns it on) and `sync.level_reuse` (sync-tree-reuse.ts; on unless turned off).
+ */
+export async function readPassSwitches(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<{ heldDeletions: boolean; levelReuse: boolean }> {
const own = `${SYNC_APPLY_HELD_DELETIONS_KEY}.source.${sourceId}`;
- const rows = await engine.executeRaw<{ key: string; value: string | null }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[own, SYNC_APPLY_HELD_DELETIONS_KEY]]);
- const value = rows.find(row => row.key === own)?.value ?? rows.find(row => row.key === SYNC_APPLY_HELD_DELETIONS_KEY)?.value;
- return value?.trim().toLowerCase() === 'true';
+ const rows = await engine.executeRaw<{ key: string; value: string | null }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[own, SYNC_APPLY_HELD_DELETIONS_KEY, SYNC_LEVEL_REUSE_KEY]]);
+ const value = (key: string) => rows.find(row => row.key === key)?.value;
+ return { heldDeletions: (value(own) ?? value(SYNC_APPLY_HELD_DELETIONS_KEY))?.trim().toLowerCase() === 'true', levelReuse: levelReuseAllowed(value(SYNC_LEVEL_REUSE_KEY)) };
}
/**
* Settles the round's held committed deletions the proof accepts as deletes (`heldDeletion` on the result) and marks
* the ones it refuses (`heldDeletionRefused`), turning a settled hold back into a `delete_drift` so the pass records the
- * refusal on it. The pass reads the switch once (`heldDeletionsEnabled`) and calls this only while it is on.
+ * refusal on it. The pass reads the switch once (`readPassSwitches`) and calls this only while it is on.
*/
export async function applyHeldDeletions(engine: BrainEngine, level: ShadowLevel, context: ManagedSyncContext, state: HeldDeletionState): Promise<void> {
const holdPath = (entry: ShadowPath) => level.scope ? entry.path.slice(level.scope.length + 1) : entry.path;
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 76079e25a3..24ec8f1281 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -52,7 +52,7 @@ import { withCoordinatedWrite } from './context.ts';
import { pipelined } from '../page-state/transactions.ts';
import { principalAttribution } from './attribution.ts';
import { isCodeFilePath, readMetafilePagesMode, resolveSlugForPath } from '../sync.ts';
-import { heldDeletionsEnabled } from './sync-held-deletions.ts';
+import { readPassSwitches } from './sync-held-deletions.ts';
import { syncOriginPath } from './sync-origin.ts';
import { databaseOnlyPageSql } from './unbound-pages.ts';
import { originMarkerFingerprint } from './sync-markers.ts';
@@ -387,7 +387,8 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNull
// the fingerprint an older pass stamped): the first pass after the upgrade or a flip reads the whole level once.
const metafilePages = await readMetafilePagesMode(engine);
// GBRA-133: so does `sync.apply_held_deletions` when on (sync-held-deletions.ts): turning it on reads the level, and its held deletions, once.
- const heldDeletions = await heldDeletionsEnabled(engine, sourceId);
+ // `sync.level_reuse` rides the same read (sync-tree-reuse.ts); it changes how the level is read, not what it is.
+ const { heldDeletions, levelReuse } = await readPassSwitches(engine, sourceId);
const selectionFp = digest({ ...selection, ...(metafilePages === 'off' ? {} : { metafile_pages: metafilePages }), ...(heldDeletions ? { apply_held_deletions: true } : {}) }), parserFp = parserFingerprint();
const obligations: ManagedSyncPassValue['obligations'] = prior ? structuredClone(prior.value.obligations)
: { baseline_commit: context.source.last_commit, mismatch: {}, not_converged_streak: 0, faults: {} };
@@ -440,7 +441,7 @@ async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNull
// The incarnation's legacy markers (§2.7 b1) are owed until a local pass wrote them, not only by its first row.
const markersOwed = () => remote ? !prior : !value.obligations.legacy_markers_at;
return { prior, admission, tail, retry, failed, holds, idleFacts, head, mode, selection, configured, selectionFp, parserFp, obligations, passId, optOutEpisode, episode,
- processingOptions, inherited, pack, converged, cacheKey, kindStarted, working, kind, value, markersOwed, heldDeletions };
+ processingOptions, inherited, pack, converged, cacheKey, kindStarted, working, kind, value, markersOwed, heldDeletions, levelReuse };
}
/**
@@ -686,7 +687,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const pinned = await pinPass(engine, input, lease, started);
if (pinned.ended) return pinned.ended;
const { prior, admission, tail, retry, failed, mode, selection, configured, selectionFp, parserFp, obligations, passId, optOutEpisode,
- processingOptions, inherited, pack, converged, cacheKey, working, kind, value, markersOwed, heldDeletions } = pinned;
+ processingOptions, inherited, pack, converged, cacheKey, working, kind, value, markersOwed, heldDeletions, levelReuse } = pinned;
let { head, episode } = pinned;
if (kind === 'idle' && working.cache) rememberWorkingStatCache(cacheKey, working.cache);
@@ -838,7 +839,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
writeIds: value.obligations.converged?.writeback ?? [] })) return synced(true);
const levelInput = { sourceId, context, workingTree: mode === 'working',
pass: { noSchemaPack: processingOptions.noSchemaPack, episodeFullId: episode?.full_id ?? null, retryConsumed: round > 1 ? retryConsumed : undefined, exclude: opts.exclude, includeHidden: opts.includeHidden, strategy: opts.strategy, bootstrap: markersOwed(),
- slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded, onProgress: beat.report, assertActive } };
+ slugMode: value.obligations.slug_mode, cache: levelCache, levelReuse, passId, recorded: applied.recorded, onProgress: beat.report, assertActive } };
const level = await readShadowLevel(engine, levelInput);
await faultPoint('sync:level_read', { sourceId, round, level: level ? { statements: level.statements, confirm: level.confirm ?? null, reused: level.reused ?? 0, shadow: level, input: levelInput } : undefined });
assertActive();
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 832cae5644..b7c2b71aaf 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -38,6 +38,7 @@ import { movedDriftHolds, sameParser } from './sync-prescreen.ts';
import { sameSyncOrigin, selectOriginClaimant, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';
import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexDelta, readIndexLevel, readTreeLevel, workingChanged, type GitIndexEntry, type GitTreeEntry, type WorkingStatCache } from './sync-git-stream.ts';
import { readOriginEvidence } from './sync-origin-evidence.ts';
+import { readTreeLevelReusing, type TreeReuse } from './sync-tree-reuse.ts';
import { classifySyncPath, syncPassKind, type SyncClassified, type SyncIdleBlocker, type SyncPathState } from './sync-classify.ts';
import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceReceipt, type ConvergenceScreen } from './sync-convergence.ts';
import { readManagedMode } from './ownership.ts';
@@ -70,6 +71,8 @@ export interface PassLevelInput {
slugMode?: 'git-root' | 'source-root';
/** The pass's own cache (it dies with the pass): the eligible tree of the commit and selection its last round read. */
cache?: PassLevelCache;
+ /** `sync.level_reuse` (read once per pass): the round may patch the `T` listing the last pass of this process kept (sync-tree-reuse.ts). */
+ levelReuse?: boolean;
/** The pass's id: a round after the first reuses the cached `I⋈P` when its writes are all the database changed (sync-pass-confirm.ts). */
passId?: string;
/** The pages whose import record the pass's previous round wrote (sync-pass-apply.ts `recorded`). */
@@ -276,6 +279,8 @@ export interface ShadowLevel {
narrow?: string };
/** A taken confirm round: the paths whose previous-round classification it kept (`reusableMatched`). */
reused?: number;
+ /** How a round that listed `T` got it (sync-tree-reuse.ts): read whole, the last pass's listing at the same commit, or that listing patched. */
+ treeReuse?: TreeReuse;
}
/** A page of the source with the import-record fields the classifier reads; `arm1` / `attested_hash` (`A`) are filled for the pages that need a proof. */
@@ -643,16 +648,14 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
let priorClassified = cache?.classified?.treeKey === treeKey ? cache.classified : undefined;
const priorDomain = cache?.domain;
if (cache) { cache.classified = undefined; cache.domain = undefined; }
+ let treeReuse: TreeReuse | undefined;
// The tree's ':' paths (#5032) are kept apart: they are refused, never part of the level.
const eligibleTree = async (): Promise<{ tree: Map<string, GitTreeEntry>; colon: string[] }> => {
if (cache?.tree?.key === treeKey) return cache.tree;
if (cache) cache.tree = undefined;
- const tree = new Map<string, GitTreeEntry>(), colon: string[] = [];
- for (const [path, entry] of levelMetafiles.primeTree(await readTreeLevel(gitRoot, head, scope, step))) {
- if (isWindowsColonTarget(path)) colon.push(path);
- else if (eligible(path)) tree.set(path, entry);
- if (step.due()) await step.pause();
- }
+ const { tree, colon, reuse } = await eligibleListing(gitRoot, head, scope, { key: [sourceId, incarnation], allowed: input.pass?.levelReuse === true, step, eligible,
+ prime: listing => levelMetafiles.primeTree(listing) });
+ treeReuse = reuse;
if (cache) cache.tree = { key: treeKey, tree, colon };
return { tree, colon };
};
@@ -889,7 +892,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
heldRenames: holds.flatMap(hold => hold.meta.rename_from ? [{ path: toGit(hold.path), rename: hold.meta.rename_from }] : []),
releasableHolds: holds.filter(hold => !domain.has(toGit(hold.path))).map(hold => hold.path),
paths, reconcilable, ...(colon.refusals.size ? { fileRefusals: [...colon.refusals.values()] } : {}), timings_ms: timings, statements: statements + attestationStatements + 3,
- ...(confirm ? { confirm: narrow ? { ...confirm, narrow: narrow === 'taken' && !reuse ? 'classified' : narrow } : confirm } : {}), ...(reuse ? { reused } : {}), pack: pack?.identity ?? null,
+ ...(confirm ? { confirm: narrow ? { ...confirm, narrow: narrow === 'taken' && !reuse ? 'classified' : narrow } : confirm } : {}), ...(reuse ? { reused } : {}), ...(treeReuse ? { treeReuse } : {}), pack: pack?.identity ?? null,
selection: { exclude: [...exclude].sort(), includeHidden: [...includeHidden].sort(), strategy, srcSubpath: scope || null, mode },
rescreenDue: holds.filter(hold => holdRescreenDue(hold, retry.has(hold.path))).map(hold => toGit(hold.path)), workingCache: hashed?.cache ?? null };
}
@@ -903,6 +906,20 @@ function scopedPageOrigin(recorded: string, slug: string, originScope: SyncOrigi
}
/** The level's settings, one round trip each and all in flight together; null for a company-brain source. */
+/** `T`'s eligible entries and its ':' paths (#5032: refused, never part of the level), walked from the listing the last pass may have kept (sync-tree-reuse.ts). */
+async function eligibleListing(gitRoot: string, head: string, scope: string, opts: { key: string[]; allowed: boolean; step: LoopYield; eligible: (path: string) => boolean;
+ prime: (listing: Map<string, GitTreeEntry>) => Map<string, GitTreeEntry> }): Promise<{ tree: Map<string, GitTreeEntry>; colon: string[]; reuse: TreeReuse }> {
+ const listed = await readTreeLevelReusing(gitRoot, head, scope, { key: opts.key, allowed: opts.allowed, shared: opts.step });
+ const tree = new Map<string, GitTreeEntry>(), colon: string[] = [];
+ for (const [path, entry] of opts.prime(listed.tree)) {
+ if (isWindowsColonTarget(path)) colon.push(path);
+ else if (opts.eligible(path)) tree.set(path, entry);
+ if (opts.step.due()) await opts.step.pause();
+ }
+ listed.keep();
+ return { tree, colon, reuse: listed.reuse };
+}
+
async function readLevelSettings(engine: BrainEngine, context: ManagedSyncContext, scope: string, input: { workingTree?: boolean; pass?: PassLevelInput }) {
const { sourceId, root } = context;
const [company, slugModeRead, excludeRead, includeHiddenRead, workingRead, packRead, mirrorRead, metafilePagesRead] = await Promise.allSettled([
diff --git a/src/core/persistence/sync-tree-reuse.ts b/src/core/persistence/sync-tree-reuse.ts
new file mode 100644
index 0000000000..3562504000
--- /dev/null
+++ b/src/core/persistence/sync-tree-reuse.ts
@@ -0,0 +1,77 @@
+/**
+ * GBRA-133 wave 4: `T` across the passes of one resident process. A pass at a new commit patches the listing of the
+ * commit the last pass read (`readTreeChanges`: one `diff-tree` between the two commits) instead of listing the whole
+ * tree again. Only the listing is reused: the pass still judges every path's eligibility, so a selection change needs no
+ * key. A commit's tree never changes (Git runs with GIT_NO_REPLACE_OBJECTS), so a listing of `from` patched with the
+ * changes from `from` to `to` is the listing of `to`.
+ *
+ * Fails closed to a whole read: another process starts empty; an entry leaves the cache while a pass uses it and comes
+ * back only after that pass walked it whole (a failed or concurrent pass finds none); an entry idle for
+ * TREE_REUSE_MAX_AGE_MS is dropped; the key is the source, its incarnation, the Git root and the scope; a scope with
+ * pathspec magic, a diff larger than a quarter of the tree, a change `readTreeLevel` would not list, and any Git
+ * failure read whole. `sync.level_reuse false` turns reuse off (docs/guides/live-sync.md). With
+ * GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1 (tests and the nightly freshness cell) every reused listing is compared with a whole
+ * read, each check prints one `[level_reuse]` stderr line, and any difference throws.
+ */
+import { readTreeChanges, readTreeLevel, type GitTreeEntry } from './sync-git-stream.ts';
+import type { LoopYield } from './sync-yield.ts';
+
+export const SYNC_LEVEL_REUSE_KEY = 'sync.level_reuse';
+/** An entry unused this long is dropped (its tree is the largest thing a resident serve keeps between passes). */
+export const TREE_REUSE_MAX_AGE_MS = 10 * 60_000;
+/** A diff of more paths than this (and a quarter of the tree) reads the tree whole. */
+const TREE_REUSE_MIN_DIFF_BOUND = 2_000;
+
+interface TreeReuseEntry { head: string; tree: Map<string, GitTreeEntry>; at: number; expiry: ReturnType<typeof setTimeout> }
+const entries = new Map<string, TreeReuseEntry>();
+
+export class LevelReuseMismatch extends Error {
+ readonly code = 'level_reuse_mismatch';
+ constructor(read: string, detail: string) { super(`sync level reuse: the reused ${read} differs from a whole read (${detail})`); this.name = 'LevelReuseMismatch'; }
+}
+
+/** Whether `sync.level_reuse` allows reuse: only `false` (or off/0/no) turns it off. */
+export const levelReuseAllowed = (value: string | null | undefined): boolean => !/^(?:false|off|0|no)$/i.test(value?.trim() ?? '');
+
+export type TreeReuse = 'read' | 'same' | 'patched';
+
+/**
+ * `T` at `head` under `scope`, from the last listing this process kept for `key` when `allowed`; `keep` stores it for the
+ * next pass once the caller has walked it (until then the next pass reads whole), and the caller must not change it.
+ */
+export async function readTreeLevelReusing(gitRoot: string, head: string, scope: string, opts: { key: readonly string[]; allowed: boolean; shared?: LoopYield }):
+ Promise<{ tree: Map<string, GitTreeEntry>; reuse: TreeReuse; keep: () => void }> {
+ const key = JSON.stringify([...opts.key, gitRoot, scope]);
+ const prior = opts.allowed ? entries.get(key) : undefined;
+ if (prior) { clearTimeout(prior.expiry); entries.delete(key); }
+ const keep = (tree: Map<string, GitTreeEntry>) => () => {
+ const expiry = setTimeout(() => { if (entries.get(key)?.tree === tree) entries.delete(key); }, TREE_REUSE_MAX_AGE_MS);
+ expiry.unref?.();
+ entries.set(key, { head, tree, at: Date.now(), expiry });
+ };
+ const whole = async () => { const tree = await readTreeLevel(gitRoot, head, scope, opts.shared); return { tree, reuse: 'read' as const, keep: opts.allowed ? keep(tree) : () => {} }; };
+ if (!opts.allowed || !prior || Date.now() - prior.at > TREE_REUSE_MAX_AGE_MS || /[\\[*?]|^:/.test(scope)) return whole();
+ let reuse: TreeReuse = 'same';
+ if (prior.head !== head) {
+ const changes = await readTreeChanges(gitRoot, prior.head, head, scope, opts.shared).catch(() => null);
+ if (!changes || changes.length > Math.max(TREE_REUSE_MIN_DIFF_BOUND, prior.tree.size / 4)) return whole();
+ for (const { path, entry } of changes) { if (entry) prior.tree.set(path, entry); else prior.tree.delete(path); }
+ reuse = 'patched';
+ }
+ if (process.env.GBRAIN_SYNC_LEVEL_REUSE_VERIFY === '1') {
+ const fresh = await readTreeLevel(gitRoot, head, scope, opts.shared);
+ const differs = fresh.size !== prior.tree.size ? `${prior.tree.size} paths, whole read ${fresh.size}`
+ : [...fresh].find(([path, entry]) => { const own = prior.tree.get(path); return own?.oid !== entry.oid || own.mode !== entry.mode; })?.[0];
+ // One stderr line per check, so the nightly oracle cell can count them in the serve's log.
+ const verdict = differs ? new LevelReuseMismatch('T', `${reuse} from ${prior.head} to ${head}: ${differs}`) : null;
+ console.error(verdict ? `[level_reuse] level_reuse_mismatch ${verdict.message}` : `[level_reuse] level_reuse_verified T ${reuse} at ${head}`);
+ if (verdict) throw verdict;
+ }
+ return { tree: prior.tree, reuse, keep: keep(prior.tree) };
+}
+
+/** Drops every kept listing (tests). */
+export function __resetTreeReuseForTests(): void {
+ for (const entry of entries.values()) clearTimeout(entry.expiry);
+ entries.clear();
+}
diff --git a/src/core/sync-config-keys.ts b/src/core/sync-config-keys.ts
index 88d412ca48..3fa4ee7e7b 100644
--- a/src/core/sync-config-keys.ts
+++ b/src/core/sync-config-keys.ts
@@ -15,7 +15,7 @@ import type { BrainEngine } from './engine.ts';
export const SYNC_TUNABLE_KEYS = ['sync.bulk_size', 'sync.lanes', 'sync.exclude', 'sync.include_hidden', 'sync.include_working_tree', 'sync.holds',
'sync.write_through', 'sync.cost_gate_min_usd', 'sync.on_commit', 'sync.freshness_target_seconds', 'sync.admission',
- 'sync.metafile_pages'] as const;
+ 'sync.metafile_pages', 'sync.level_reuse'] as const;
/**
* #6858 ask 6, option C (Garry's "rec", via GBRA-108): a resident serve starts a managed source's sync when its
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index ee458afa72..7c8c5b31f4 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -464,6 +464,7 @@ test/sync-prescreen-drift-6712.test.ts
test/sync-slug-root-mode-6694.test.ts
test/sync-staged-catchup.test.ts
test/sync-status-failure-detail-6513.test.ts
+test/sync-tree-reuse-gbra133.test.ts
test/sync-unblock-repair-error-gbra130.test.ts
test/sync-uncommitted-origin-7130.test.ts
test/sync-unreadable-file-gbra130.test.ts
diff --git a/test/sync-tree-reuse-gbra133.test.ts b/test/sync-tree-reuse-gbra133.test.ts
new file mode 100644
index 0000000000..9fe8a6ade7
--- /dev/null
+++ b/test/sync-tree-reuse-gbra133.test.ts
@@ -0,0 +1,188 @@
+/**
+ * GBRA-133 wave 4: `T` across passes (sync-tree-reuse.ts). A resident process keeps the tree listing its last pass read,
+ * and the next pass at a new commit patches it with `git diff-tree` between the two commits instead of listing the whole
+ * tree again.
+ * - Equivalence oracle: every reused listing equals a whole `readTreeLevel` of the same commit, across adds, edits,
+ * deletions, a mode change, a symlink, a gitlink, odd path names, a scope, unrelated history and a commit no longer
+ * in the repository; with GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1 a listing that differs throws (forced probe: a corrupted
+ * kept listing).
+ * - Fail closed: switched off, another key, an entry a pass did not finish walking, an entry past its age, a diff
+ * larger than the bound, a scope with pathspec magic and a missing commit all read whole.
+ * - A managed pass on PGLite (and Postgres when DATABASE_URL is set) patches the listing on its next commit, imports
+ * the same pages, and reads whole under `sync.level_reuse false`.
+ * Before: every pass listed the whole tree.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, setSystemTime, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { readTreeLevel, type GitTreeEntry } from '../src/core/persistence/sync-git-stream.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { __resetTreeReuseForTests, LevelReuseMismatch, readTreeLevelReusing, TREE_REUSE_MAX_AGE_MS } from '../src/core/persistence/sync-tree-reuse.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',
+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message, '--allow-empty'); return git(root, 'rev-parse', 'HEAD'); };
+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;
+const KEY = ['source-a', 'incarnation-1'];
+const sorted = (tree: Map<string, GitTreeEntry>) => [...tree].sort(([a], [b]) => (a < b ? -1 : 1));
+
+describe('readTreeLevelReusing: T across passes', () => {
+ let root: string;
+ beforeAll(() => {
+ root = mkdtempSync(join(tmpdir(), 'gbra133-tree-reuse-'));
+ git(root, 'init', '-q');
+ mkdirSync(join(root, 'brain/notes'), { recursive: true });
+ for (let i = 0; i < 40; i++) writeFileSync(join(root, `brain/notes/n${i}.md`), note(`n${i}`, `body ${i}`));
+ writeFileSync(join(root, 'brain/notes/with space.md'), 'a');
+ writeFileSync(join(root, 'brain/notes/ünïcødé.md'), 'b');
+ writeFileSync(join(root, 'outside.md'), 'c');
+ commit(root, 'first');
+ });
+ afterAll(() => { rmSync(root, { recursive: true, force: true }); });
+ afterEach(() => { __resetTreeReuseForTests(); setSystemTime(); });
+
+ /** One pass's read of `T`: the reused listing, checked against a whole read, then kept as a finished pass keeps it. */
+ async function pass(scope: string, opts: { allowed?: boolean; key?: string[]; keep?: boolean } = {}) {
+ const head = git(root, 'rev-parse', 'HEAD');
+ const got = await readTreeLevelReusing(root, head, scope, { key: opts.key ?? KEY, allowed: opts.allowed ?? true });
+ expect(sorted(got.tree)).toEqual(sorted(await readTreeLevel(root, head, scope)));
+ if (opts.keep !== false) got.keep();
+ return got;
+ }
+
+ test('patches adds, edits, deletions, mode changes, a symlink, a gitlink and odd names; equal to a whole read every time', async () => {
+ for (const scope of ['', 'brain']) {
+ __resetTreeReuseForTests();
+ expect((await pass(scope)).reuse).toBe('read');
+ expect((await pass(scope)).reuse).toBe('same');
+ writeFileSync(join(root, 'brain/notes/n1.md'), 'edited');
+ unlinkSync(join(root, 'brain/notes/n2.md'));
+ writeFileSync(join(root, 'brain/notes/added.md'), 'new');
+ chmodSync(join(root, 'brain/notes/n3.md'), 0o755);
+ unlinkSync(join(root, 'brain/notes/n4.md'));
+ symlinkSync('n5.md', join(root, 'brain/notes/n4.md'));
+ writeFileSync(join(root, 'brain/notes/new\nline.md'), 'nl');
+ writeFileSync(join(root, 'outside.md'), 'changed outside the scope');
+ git(root, 'add', '-A');
+ git(root, 'update-index', '--add', '--cacheinfo', `160000,${git(root, 'rev-parse', 'HEAD')},brain/vendored`);
+ git(root, 'commit', '-qm', `edits under ${scope || 'the root'}`);
+ expect(git(root, 'ls-tree', 'HEAD', 'brain/vendored')).toStartWith('160000 commit');
+ expect((await pass(scope)).reuse).toBe('patched');
+ // Back to the first commit's contents: every change undone, the gitlink and the symlink removed.
+ git(root, 'revert', '--no-edit', 'HEAD');
+ expect((await pass(scope)).reuse).toBe('patched');
+ }
+ }, 60_000);
+
+ test('unrelated history and a commit Git no longer has', async () => {
+ expect((await pass('brain')).reuse).toBe('read');
+ const branch = git(root, 'rev-parse', '--abbrev-ref', 'HEAD');
+ git(root, 'checkout', '-q', '--orphan', 'unrelated');
+ git(root, 'rm', '-rq', '--cached', '.');
+ for (const f of ['brain/notes/n0.md', 'brain/notes/n7.md']) git(root, 'add', f);
+ git(root, 'commit', '-qm', 'orphan');
+ expect((await pass('brain')).reuse).toBe('patched');
+ // The kept commit leaves the repository: the diff fails and the tree is read whole.
+ const orphan = git(root, 'rev-parse', 'HEAD');
+ git(root, 'checkout', '-qf', branch);
+ git(root, 'branch', '-qD', 'unrelated');
+ git(root, 'reflog', 'expire', '--expire=now', '--all');
+ git(root, 'gc', '-q', '--prune=now');
+ expect(() => git(root, 'cat-file', '-e', orphan)).toThrow();
+ expect((await pass('brain')).reuse).toBe('read');
+ }, 60_000);
+
+ test('fails closed: off, another key, an unfinished walk, past its age, a large diff, pathspec magic', async () => {
+ expect((await pass('brain', { allowed: false })).reuse).toBe('read');
+ expect((await pass('brain')).reuse).toBe('read');
+ // A read with reuse off neither uses nor drops the kept listing.
+ expect((await pass('brain', { allowed: false })).reuse).toBe('read');
+ expect((await pass('brain')).reuse).toBe('same');
+ expect((await pass('brain', { key: ['source-b', 'incarnation-1'] })).reuse).toBe('read');
+ expect((await pass('brain', { key: ['source-a', 'incarnation-2'] })).reuse).toBe('read');
+ // A pass that took the listing and did not walk it to the end keeps nothing.
+ expect((await pass('brain', { keep: false })).reuse).toBe('same');
+ expect((await pass('brain')).reuse).toBe('read');
+ setSystemTime(new Date(Date.now() + TREE_REUSE_MAX_AGE_MS + 1_000));
+ expect((await pass('brain')).reuse).toBe('read');
+ setSystemTime();
+ mkdirSync(join(root, 'brain/bulk'), { recursive: true });
+ for (let i = 0; i < 2_100; i++) writeFileSync(join(root, `brain/bulk/b${i}.md`), String(i));
+ commit(root, 'bulk');
+ expect((await pass('brain')).reuse).toBe('read');
+ expect((await pass('brain/bulk/b1*')).reuse).toBe('read');
+ expect((await pass('brain/bulk/b1*')).reuse).toBe('read');
+ }, 120_000);
+
+ test('the oracle: GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1 throws when a kept listing differs from a whole read (forced probe)', async () => {
+ await withEnv({ GBRAIN_SYNC_LEVEL_REUSE_VERIFY: '1' }, async () => {
+ const first = await pass('brain');
+ writeFileSync(join(root, 'brain/notes/n9.md'), 'edited for the oracle');
+ commit(root, 'oracle edit');
+ expect((await pass('brain')).reuse).toBe('patched');
+ // Corrupt the kept listing (what a wrong patch would leave): the next reuse must not hand it out.
+ const kept = await readTreeLevelReusing(root, git(root, 'rev-parse', 'HEAD'), 'brain', { key: KEY, allowed: true });
+ kept.tree.delete('brain/notes/n10.md');
+ kept.keep();
+ writeFileSync(join(root, 'brain/notes/n11.md'), 'edited again');
+ commit(root, 'oracle edit 2');
+ const error = await readTreeLevelReusing(root, git(root, 'rev-parse', 'HEAD'), 'brain', { key: KEY, allowed: true }).then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(LevelReuseMismatch);
+ expect((error as LevelReuseMismatch).code).toBe('level_reuse_mismatch');
+ // The corrupt listing is gone: the next read is whole.
+ expect((await pass('brain')).reuse).toBe('read');
+ expect(first.reuse).toBe('read');
+ });
+ }, 60_000);
+});
+
+for (const backend of testBackends()) describe(`[${backend}] GBRA-133: a managed pass reuses T across passes`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+ const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const name of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${name}.md`), note(name, `The body of ${name}.`));
+ commit(root, 'notes');
+ };
+ afterEach(() => { installFaultHook(undefined); __resetTreeReuseForTests(); });
+ const live = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string; body: string }>(
+ "SELECT slug, compiled_truth AS body FROM pages WHERE source_id='default' AND deleted_at IS NULL AND slug LIKE 'notes/%' ORDER BY slug")).map(row => [row.slug, row.body.trim()]);
+
+ test('the next commit patches the last pass\'s listing; sync.level_reuse false reads it whole; pages match either way', () => withEnv({ GBRAIN_SYNC_LEVEL_REUSE_VERIFY: '1' }, () => managedBrain(async ({ engine, root }) => {
+ const reuse: string[] = [];
+ installFaultHook((point, detail) => {
+ if (point !== 'sync:level_read' || detail.round !== 1) return;
+ const shadow = detail.level?.shadow as { treeReuse?: string } | undefined;
+ reuse.push(shadow?.treeReuse ?? 'none');
+ });
+ await performManagedSync(engine, OPTS);
+ writeFileSync(join(root, 'notes/a.md'), note('a', 'The edited body of a.'));
+ unlinkSync(join(root, 'notes/b.md'));
+ writeFileSync(join(root, 'notes/d.md'), note('d', 'The body of d.'));
+ commit(root, 'edit a, drop b, add d');
+ await performManagedSync(engine, OPTS);
+ expect(reuse.at(-1)).toBe('patched');
+ expect(await live(engine)).toEqual([['notes/a', 'The edited body of a.'], ['notes/c', 'The body of c.'], ['notes/d', 'The body of d.']]);
+
+ await engine.setConfig('sync.level_reuse', 'false');
+ writeFileSync(join(root, 'notes/c.md'), note('c', 'The edited body of c.'));
+ commit(root, 'edit c');
+ await performManagedSync(engine, OPTS);
+ expect(reuse.at(-1)).toBe('read');
+ expect(await live(engine)).toEqual([['notes/a', 'The edited body of a.'], ['notes/c', 'The edited body of c.'], ['notes/d', 'The body of d.']]);
+
+ await engine.setConfig('sync.level_reuse', 'true');
+ writeFileSync(join(root, 'notes/e.md'), note('e', 'The body of e.'));
+ commit(root, 'add e');
+ await performManagedSync(engine, OPTS);
+ expect(reuse.at(-1)).toBe('patched');
+ expect((await live(engine)).map(([slug]) => slug)).toEqual(['notes/a', 'notes/c', 'notes/d', 'notes/e']);
+ }, { databaseUrl, setup })), 300_000);
+});