Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Let a managed sync's file freeze take timer turns between its Git reads (GBRA-133)

garrytane0d3e9a797e9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e0726a1c8c..dc2644d548 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,16 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+### A managed sync's file freeze no longer holds timers through its Git reads
+
+**While a managed sync freezes a file, it now lets timers and other work run between its Git reads once it has run about 30 ms, so searches, lease renewals and heartbeats are no longer held behind them.** Before, the freeze ran its reads of the file, its pinned blob, its content, its filter driver and HEAD one after another with no break. On a slow machine the first freeze of a large sync held timers past the 100 ms bound that `test/sync-pass-batch-entries-6712.test.ts` sets.
+
+- What a freeze records is unchanged. The reads of a committed file are of the pinned commit, or of HEAD checked by hash against the file's first read, so a write that lands during a break keeps the pinned content instead of importing the new bytes. A working-tree file is still read twice with no break between. The run is checked again after each break, so a cancelled run stops there.
+- `test/sync-freeze-turn-write-gbra133.test.ts` commits new bytes for the file during a break, between the file's first read and its HEAD read, on PGLite and Postgres. The frozen request keeps the pinned content and is not published, and a later freeze imports the new bytes under their own hash.
+- A fourth test in `test/sync-pass-batch-entries-6712.test.ts` adds 40 ms of CPU to each of the first freeze's reads. Before this change the longest stretch was 205 to 211 ms; it now stays under 100 ms.
+
## [0.60.669.0] - 2026-11-11
### Five flaky tests fixed at their cause
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ea67837951..c0971dbf24 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 in
src/commands/hook.ts 1997 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); +13 GBRA-188 per-turn brain-first rule: user-prompt emission and its HookIo seam (rule and ledger read in core/setup/brain-first.ts); +3 GBRA-188 plugin lane: GBRAIN_HOOK_LANE=plugin yields to another gbrain lane wiring the event (import, comment and guard; detection in bootstrap/plugin-lanes.ts otherLaneWiresHook); +5 GBRA-243 turn-rule lane: GBRAIN_HOOK_LANE=turn-rule yields to every other lane and answers rule-only (import, two guards and comments; logic in core/setup/turn-hook.ts), user-prompt passes cwd to the scope-aware rule; +34 #8064/#8016/#8028: the session-speaker banking decision at compact, stop and session-end (logic in context/session-speaker.ts), the harness-prompt skip and the lane-scoped parser_drift clear; +1 #8424: hookSessionCwd import (the session directory the hook launcher records; logic in core/setup/hook-launcher.ts); +1 #8424 review: runHook captures the launcher-recorded session directory first (logic in setup/hook-launcher.ts captureHookSessionCwd); +7 #8427: the hook git probes skip core.fsmonitor and run only in the workspace the install receipt names; +1 GBRA-377 PR B: the GBRAIN_HOOK_LANE=skill-resolver dispatch line (logic in core/skills/resolver/hook-lane.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 2026 ratchet +1 GBRA-154 #7175: search.keyword_phrase KNOWN_CONFIG_KEYS row; +1 search.saved_facts_supersede KNOWN_CONFIG_KEYS row (read in search/saved-facts-match.ts; re-summed at the #7703 merge: 2014 + 1); +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); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +2 GBRA-205: search.evidence_titles / query_budget_unit / query_facts_block / fact_source_pages KNOWN_CONFIG_KEYS rows (read in search/evidence-date.ts, evidence-packing.ts, facts-arm.ts); +1 GBRA-156: search.remote_page_cap KNOWN_CONFIG_KEYS row (read in search/remote-page-cap.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (2021 measured); +2 GBRA-377 PR B: loadConfig reads a config.json of file-plane settings alone (skills.resolver) as no brain, plus its comment; +3 #8776: self_upgrade.autopilot_launcher (GBrainConfig field with its doc line, and the KNOWN_CONFIG_KEYS row; parsed in core/self-upgrade.ts); re-summed at the #8797 merge (2026 measured)
-src/core/persistence/sync-run.ts 1700 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); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move); +3 GST-2312 #9024: freezeEntry refuses a committed blob a Git filter owns with sync.holds=fail before the NUL check (filterOwnedRefusal and pinnedFilterDriver live in sync-entry-fault.ts and sync-screen.ts; the check reads freezeEntry locals)
+src/core/persistence/sync-run.ts 1710 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); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live; +3 #7931: the freeze drift screen also accepts a file that holds the page as prepareFileTarget reads it (fileMatchesSnapshot import, comment, the split condition line); +5 GBRA-218: performManagedSync wraps every managed pass (sync, drain, sources refresh, git conversion, owner slice) in withCommittedPolicy (logic in access/policy-git.ts) and keeps the lease path in performLeasedPass; re-summed at the memory train #8481 merge with v0.60.576.0 (1696 measured); +1 convergence nightly fix: the sync:passed_over fault point after the pass-over cursor save (a kill seam sits where its cursor commits, so it cannot move); +3 GST-2312 #9024: freezeEntry refuses a committed blob a Git filter owns with sync.holds=fail before the NUL check (filterOwnedRefusal and pinnedFilterDriver live in sync-entry-fault.ts and sync-screen.ts; the check reads freezeEntry locals); +10 GBRA-133: freezeEntry takes a timer turn between its synchronous Git reads and re-checks the run there (loopYield lives in sync-yield.ts; the turns sit between reads of freezeEntry locals)
src/core/bootstrap/harness.ts 2630 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); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +7 GBRA-243 per-turn rule hook: consent-block interface field, step-10c call site, turn_hooks JSON field, exit code and the remove arm (writer, host list and consent text live in harness-brain-first.ts); +2 #8428: the harness lane Claude Code and Codex SessionEnd hooks start gbrain through the hook launcher; +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)
src/core/oauth-provider.ts 1237 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; +1 GST-1113 transactional token mint
src/core/ops/pages.ts 743 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; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +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); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +1 GST-687: get_page include_timeline_entries quotes rows for remote readers (import only; logic in ops/timeline-quote.ts); +2 #8384: the quoted_unverified_origin notice call in get_page and fetch (logic lives in get-page-projection.ts); +1 GBRA-218: put_page checks a remote readable_by before admission (logic in persistence/page-visibility.ts assertSubmittedReaders) (re-summed at the train M merge of master v0.60.539.0: 732 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (739 measured); +4 GBRA-449: an empty list_pages names the page types present when no visible page has the requested type (logic in ops/list-pages-pagination.ts unusedTypeNotice)
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 67bc0835c8..81c2ff3d3d 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -14,6 +14,7 @@ import { preflightSyncCapacity } from './sync-capacity-preflight.ts';
import { preparationConfigView } from './config-snapshot.ts';
import { retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';
+import { loopYield } from './sync-yield.ts';
import { assertSyncEntryOrigin, discoverManagedSync, readManagedSyncRows, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';
import { checkpointRevival } from './sync-slug-mode.ts';
import { managedCursorKey, resolveManagedCursor } from './sync-cursor-key.ts';
@@ -369,6 +370,10 @@ async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string,
return { originFault: error };
}), engine.readPageSnapshot(entry.slug!, { sourceId: cursor.sourceId, includeDeleted: true })]);
assertActive();
+ // GBRA-133: once a stretch has run its budget, the freeze takes a timer turn between its synchronous Git reads. A committed entry
+ // reads the pinned commit, or HEAD checked by hash against its first read (`headCommittedBytes`); a working-tree entry reads its
+ // file twice with no turn between. So work that runs at a turn changes nothing frozen, and the run is re-checked there.
+ const step = loopYield(), turn = async () => { if (!step.over()) return; await step.pause(); assertActive(); };
if (occupant && 'originFault' in occupant) {
if (entry.action === 'delete' && snapshot?.page.deleted_at != null && !existsSync(join(cursor.root, entry.path))) {
const done = await idempotentDeletionProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId: entry.pageId ?? null, revision: entry.revision ?? null, sourcePath: entry.sourcePath });
@@ -393,14 +398,16 @@ async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string,
if (!bodyRef && !screening) throw error;
if (!bodyRef) oversize = { size: null };
}
+ if (!entry.working) await turn();
if ((screening || image) && !entry.working && !bodyRef) {
// #5988: an over-bound pinned blob is held by its size before its content is loaded.
blob = pinnedBlob(cursor, entry.path);
if (blob && blob.size > SYNC_READ_BOUND) oversize = { size: blob.size };
+ await turn();
}
rawHash = bodyRef ? bodyRef.sha256 : bytes === null ? null : sha256(bytes);
if (image && oversize) return { hold: oversizeHold(entry, entry.slug!, entry.pageId ?? null, oversize.size, blob) };
- if (image) imageBytes = pinnedImageBytes(cursor, entry);
+ if (image) { imageBytes = pinnedImageBytes(cursor, entry); await turn(); }
if (entry.action === 'import' && cursor.companyPlan) {
const company = currentCompanyBrainSync(cursor.sourceId);
const blob = company?.entries.get(entry.path);
@@ -410,9 +417,11 @@ async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string,
content = (await readCommittedBlob(cursor.companyPlan.revision!, blob, cursor.companyPlan.limits)).toString('utf8');
assertActive();
} else content = imageBytes ? frozenImageIntent(imageBytes).content : entry.action === 'import' && !oversize && !bodyRef ? pinnedContent(cursor, entry) : null;
+ await turn();
const filtered = !screening && content !== null && !image // GST-2312 (#9024) with sync.holds=fail
? filterOwnedRefusal(entry.path, content, entry.working ? null : pinnedFilterDriver(cursor, entry.path), cursor.sourceId, false) : null;
if (filtered) throw syncRunRefusal('content_filter_owned', 'A synced file is stored through a Git filter.', retry, filtered.message);
+ await turn();
const nul = !screening && content !== null && !image ? nullBytesRefusal(entry.path, content) : null; // GBRA-133 S-39 with sync.holds=fail
if (nul) throw syncRunRefusal('content_null_bytes', 'A synced Markdown file holds NUL bytes.', retry, nul.message);
// #6340: working-tree bytes that differ from the pinned blob but are committed at HEAD (a commit past the pin on a
@@ -421,6 +430,7 @@ async function freezeEntryOnce(engine: BrainEngine, cursor: Cursor, key: string,
if (entry.action === 'import' && !cursor.companyPlan && !image && !entry.working && content !== null && rawHash !== null && rawHash !== sha256(content)) {
const head = headCommittedBytes(cursor, entry.path);
if (head && head.rawHash === rawHash) { content = head.content; blob = { oid: head.oid, size: bytes!.length }; }
+ await turn();
}
lineEndingOnly = !image && bytes !== null && content !== null && bytes.equals(Buffer.from(bytes.toString('utf8'))) &&
bytes.toString('utf8').replace(/\r\n/g, '\n') === content.replace(/\r\n/g, '\n');
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 22b3c05f94..e35afa2b91 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -581,6 +581,7 @@ test/sync-fenced-slices-gbra133.test.ts
test/sync-file-drift-agrees-7931.test.ts
test/sync-filter-owned-9024.test.ts
test/sync-filter-owned-company-9024.test.ts
+test/sync-freeze-turn-write-gbra133.test.ts
test/sync-freshness-6858.test.ts
test/sync-frontmatter-recovery.test.ts
test/sync-frontmatter-slug-conflict.test.ts
diff --git a/test/sync-freeze-turn-write-gbra133.test.ts b/test/sync-freeze-turn-write-gbra133.test.ts
new file mode 100644
index 0000000000..dc1be0b7e0
--- /dev/null
+++ b/test/sync-freeze-turn-write-gbra133.test.ts
@@ -0,0 +1,94 @@
+/**
+ * GBRA-133: a managed sync's freeze runs its Git reads one synchronous child after another, and takes a timer turn between
+ * them once a stretch has run its budget (sync-run.ts `freezeEntryOnce`). At such a turn other code in the same process
+ * runs: here, a write that commits new bytes for the entry's own path, landing after the freeze read the working-tree
+ * bytes and before it re-reads them against HEAD (`headCommittedBytes`). The freeze must keep the pinned content or hold
+ * the entry; it never pairs one read's hash with another read's bytes, so it never imports the bytes of the write.
+ *
+ * The fixture pins a first sync at the commit holding version one, then commits version two at the batch build, before
+ * the freeze: the working tree holds a commit past the pin, which the freeze imports as HEAD has it (#6340). Every timer
+ * turn the freeze asks for is forced, and at the first one after the working-tree read the test commits version three.
+ */
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import * as syncDiscovery from '../src/core/persistence/sync-discovery.ts';
+import * as syncPageFault from '../src/core/persistence/sync-page-fault.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import * as syncYield from '../src/core/persistence/sync-yield.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (version: string) => `---\ntitle: Example\n---\n\nAlpha note, version ${version}.\n`;
+const sha256 = (text: string) => createHash('sha256').update(text).digest('hex');
+
+afterEach(() => installFaultHook(undefined));
+
+const engines = [{ name: 'pglite', databaseUrl: undefined as string | undefined }, ...(process.env.DATABASE_URL ? [{ name: 'postgres', databaseUrl: process.env.DATABASE_URL }] : [])];
+
+for (const { name, databaseUrl } of engines) describe(`GBRA-133: a write at a freeze's timer turn (${name})`, () => {
+ /** Runs the first sync with every freeze turn forced; `interfere` commits version three at the first turn after the working-tree read. */
+ const run = async (interfere: boolean) => {
+ let result: { events: string[]; requests: { content: string | null; raw_hash: string | null; state: string }[]; page: string | null } | undefined;
+ await managedBrain(async ({ engine, root }) => {
+ const events: string[] = [];
+ let readWorking = false, wrote = false;
+ installFaultHook(async point => {
+ if (point === 'sync:batch_entries' && !events.includes('v2')) { writeFileSync(join(root, 'a.md'), note('two')); commit(root, 'version two, past the pin'); events.push('v2'); }
+ });
+ const { readSyncFile } = syncDiscovery, { headCommittedBytes } = syncPageFault, { loopYield } = syncYield;
+ const spies = [
+ spyOn(syncDiscovery, 'readSyncFile').mockImplementation(((root: string, path: string) => {
+ const bytes = readSyncFile(root, path);
+ if (path === 'a.md' && events.includes('v2')) { readWorking = true; events.push('read'); }
+ return bytes;
+ }) as typeof readSyncFile),
+ spyOn(syncPageFault, 'headCommittedBytes').mockImplementation(((...args: Parameters<typeof headCommittedBytes>) => {
+ if (args[1] === 'a.md') events.push('head');
+ return headCommittedBytes(...args);
+ }) as typeof headCommittedBytes),
+ spyOn(syncYield, 'loopYield').mockImplementation(() => {
+ const step = loopYield();
+ return { ...step, over: () => true, pause: async () => {
+ if (readWorking && !wrote) { events.push('pause'); if (interfere) { writeFileSync(join(root, 'a.md'), note('three')); commit(root, 'version three, at the freeze turn'); events.push('v3'); } wrote = true; }
+ await step.pause();
+ } };
+ }),
+ ];
+ try {
+ await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true }).catch(error => { events.push(`error:${error?.code ?? error}`); });
+ } finally { for (const spy of spies) spy.mockRestore(); installFaultHook(undefined); }
+ const requests = await engine.executeRaw<{ content: string | null; raw_hash: string | null; state: string }>(
+ "SELECT intent->>'content' AS content, intent->>'rawHash' AS raw_hash, state FROM persistence_requests WHERE source_id='default' AND intent->>'path'='a.md' ORDER BY sequence");
+ const page = await engine.getPage('a', { sourceId: 'default' });
+ result = { events, requests, page: page?.compiled_truth ?? null };
+ }, { databaseUrl, setup: ({ root }) => { git(root, 'init', '-q'); writeFileSync(join(root, 'a.md'), note('one')); commit(root, 'version one'); } });
+ return result!;
+ };
+
+ test('with no write at the turn, the freeze imports the commit past the pin as HEAD has it', async () => {
+ const { events, requests, page } = await run(false);
+ expect(events.slice(0, 4)).toEqual(['v2', 'read', 'pause', 'head']);
+ expect(requests).toEqual([{ content: note('two'), raw_hash: sha256(note('two')), state: 'committed' }]);
+ expect(page).toContain('version two');
+ }, 120_000);
+
+ test('a commit of the same path at the turn keeps the pinned content, and only a later freeze imports the new bytes', async () => {
+ const { events, requests, page } = await run(true);
+ expect(events.slice(0, 5)).toEqual(['v2', 'read', 'pause', 'v3', 'head']);
+ // The entry frozen across the turn carries the pinned version, never the bytes committed at the turn, and is not published.
+ expect(requests[0]).toMatchObject({ content: note('one'), raw_hash: sha256(note('two')) });
+ expect(requests[0]!.state).not.toBe('committed');
+ // Whatever was published carries the hash of its own bytes.
+ const committed = requests.filter(request => request.state === 'committed');
+ expect(committed.length).toBeGreaterThan(0);
+ for (const request of committed) expect(request.raw_hash).toBe(sha256(request.content!));
+ expect(committed.at(-1)!.content).toBe(note('three'));
+ expect(page).toContain('version three');
+ }, 120_000);
+});
diff --git a/test/sync-pass-batch-entries-6712.test.ts b/test/sync-pass-batch-entries-6712.test.ts
index 904e618f82..c98c8d9fef 100644
--- a/test/sync-pass-batch-entries-6712.test.ts
+++ b/test/sync-pass-batch-entries-6712.test.ts
@@ -24,15 +24,18 @@ import { execFileSync } from 'node:child_process';
import type { BrainEngine } from '../src/core/engine.ts';
import * as syncCore from '../src/core/sync.ts';
import * as syncDiscovery from '../src/core/persistence/sync-discovery.ts';
+import * as syncPageFault from '../src/core/persistence/sync-page-fault.ts';
+import * as syncScreen from '../src/core/persistence/sync-screen.ts';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
-import { watchLoopLag } from './helpers/cpu-time.ts';
+import { spinCpuMs, watchLoopLag } from './helpers/cpu-time.ts';
import { isolatedTest } from './helpers/isolated-test.ts';
import { managedBrain } from './helpers/managed-brain.ts';
const PATHS = 8_000;
const MAX_LAG_MS = 100;
const SLUG_CPU_MS = 0.05;
+const FREEZE_READ_CPU_MS = 40;
const git = (root: string, args: string[], input?: string) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', input, maxBuffer: 1 << 26 }).trim();
const setup = ({ root }: { root: string }) => {
@@ -121,4 +124,35 @@ describe('GBRA-133 PR 2b: a first sync builds its batch in linear time', () => {
expect(turned).toEqual({ 'legacy-identity read': true, 'slug-holder read': true, 'first freeze': true });
} finally { clearInterval(ticker); engine.executeRaw = raw; slugSpy.mockRestore(); adoptSpy.mockRestore(); compareSpy.mockRestore(); }
}, { setup }), 300_000);
+
+ isolatedTest(import.meta.path, `with ${FREEZE_READ_CPU_MS} ms of CPU per Git read, the first freeze still yields within ${MAX_LAG_MS} ms`, () => managedBrain(async ({ engine }) => {
+ // GBRA-133: the first freeze reads the file, its pinned blob and its pinned content one synchronous call after another
+ // (Git children for the pinned reads). Each read here costs FREEZE_READ_CPU_MS more of this thread's CPU, so a freeze
+ // that runs its reads as one stretch holds timers past the bound on any machine, and one that yields between them never
+ // does. The filter driver and HEAD reads are wrapped too; this fixture (holds on, a clean checkout) reaches neither.
+ const resolve = syncCore.resolveSlugForPath;
+ let slugs = 0, reads = 0;
+ const slugSpy = spyOn(syncCore, 'resolveSlugForPath').mockImplementation(((...args: Parameters<typeof resolve>) => {
+ if (window.open) slugs++;
+ return resolve(...args);
+ }) as typeof resolve);
+ const slow = <T extends (...args: never[]) => unknown>(fn: T) => ((...args: Parameters<T>) => {
+ if (window.open && slugs >= PATHS) { reads++; spinCpuMs(FREEZE_READ_CPU_MS); }
+ return fn(...args);
+ }) as unknown as T;
+ const { pinnedBlob, pinnedContent, pinnedFilterDriver } = syncScreen, { readSyncFile } = syncDiscovery, { headCommittedBytes } = syncPageFault;
+ const spies = [
+ spyOn(syncScreen, 'pinnedBlob').mockImplementation(slow(pinnedBlob)),
+ spyOn(syncScreen, 'pinnedContent').mockImplementation(slow(pinnedContent)),
+ spyOn(syncScreen, 'pinnedFilterDriver').mockImplementation(slow(pinnedFilterDriver)),
+ spyOn(syncDiscovery, 'readSyncFile').mockImplementation(slow(readSyncFile)),
+ spyOn(syncPageFault, 'headCommittedBytes').mockImplementation(slow(headCommittedBytes)),
+ ];
+ try {
+ const maxLag = await batchBuildLag(engine, () => true);
+ expect(reads).toBeGreaterThanOrEqual(3);
+ expect(maxLag).toBeDefined();
+ expect(Math.round(maxLag!)).toBeLessThan(MAX_LAG_MS);
+ } finally { slugSpy.mockRestore(); for (const spy of spies) spy.mockRestore(); }
+ }, { setup }), 300_000);
});