Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

WIP #6712 lane C: peel cursor transitions into sync-cursor-moves.ts, freezeNext, holdBasisMoved; fix size gates and stale tests

garrytan860fba50215e
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index 05e2937538..012ccc2e70 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -27,6 +27,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/sync-slug-mode.ts` — #6694: the checkpoint's slug-root mode against the source's pinned `slug_root_mode`. `emptySyncScope` (source root is the repository root, both realpathed) lets `sync-prepare.ts`'s checkpoint `UPDATE` accept either pin and keep the pinned one; at a subdirectory a differing pin is diagnosed by `pinnedSlugModeMismatch` after the guarded `UPDATE` matched nothing and refused `slug_root_mode_mismatch` (cause and the person's two choices from `slugModeMismatchCause`); anything else stays `revision_conflict` (`CHECKPOINT_MOVED_MESSAGE`). `slugModeCheckpointRevivable` is the second revival predicate of `sync-run.ts` `reviveCheckpoint`: a checkpoint refused `slug_root_mode_mismatch`, or an older release's moved-checkpoint `revision_conflict`, is revived when `last_commit` still equals the run's `from` and the pin is unset, equal to the run's mode or the scope is empty; `retryFailedStart` does not consult it, so `--retry-failed` keeps its rediscovery. Test: `test/sync-slug-root-mode-6694.test.ts` (both engines).
+- `src/core/persistence/sync-cursor-moves.ts` — #6712 (L2, one page, one fate): the managed-sync cursor's pure transitions, peeled out of `sync-run.ts`; each returns the next cursor and writes nothing (sync-run.ts saves it with one compare-and-swap). `advanceHeld`/`settledPast` pass an entry without a commit (held, waived via `waivedCursor`, an idempotent deletion via `deletionSettled`) and add its index to the settled ranges the checkpoint skips; a deferred entry (`Cursor.deferred`, a `source_changed` file retried after the manifest end) leaves the deferred list instead of moving the index. `promoteWindow` makes the window's first group the cursor's group once the cursor reaches it, so requests admitted after a failed or held entry are read by their own receipts, never frozen again; `committedPast` does the same after a commit. `withHeldKeys` records a held entry's page keys (`dependencyKeys`) so a later entry of the run that shares one is held behind it (`blocked_on`).
- `src/core/persistence/sync-knock-on.ts` — #6643, shrunk by #6712 (one page, one fate): no producer is left. It keeps the legacy predicate over receipts older builds wrote (`error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }`, or the pre-#6643 producers' exact messages, never an operator cancel): `isSyncKnockOn`/`syncKnockOnSql` (one predicate, never NULL) feed the terminal classifier, which renders such a receipt superseded, and `sync-run.ts` `refreezeInPlace`, which re-freezes the entry when a resumed cursor meets one (bounded by `STOPS_PER_ENTRY`, no config key). `cursorFenceCause` reads the two live causes of "cursor changed" (`run_replaced`, `outside_fence`; an older `window_dropped` still parses). `checkpoint-validation.ts` clause 3 skips converted receipts and the cursor's settled index ranges only; #6712 removed the knock-on exemption. `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`, each with `knock_on`).
- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.
- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4f42cdd6ce..f575164c39 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 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 1978 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)
-src/core/persistence/sync-run.ts 1690 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)
+src/core/persistence/sync-run.ts 1671 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); lowered to 1671 by #6712 PR 1 lane C (L2 one page, one fate): the cursor's pure transitions (advanceHeld, settledPast, promoteWindow, committedPast, waivedCursor and the deferral/dependency-edge helpers) peeled into persistence/sync-cursor-moves.ts, with L2's class-routed settle, source_changed deferral and dependency edges composed under it
src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block
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
src/core/ops/pages.ts 705 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
diff --git a/src/core/persistence/sync-cursor-moves.ts b/src/core/persistence/sync-cursor-moves.ts
new file mode 100644
index 0000000000..c24aa5823e
--- /dev/null
+++ b/src/core/persistence/sync-cursor-moves.ts
@@ -0,0 +1,80 @@
+/**
+ * #6712 (L2, one page, one fate): the managed-sync cursor's pure transitions, peeled out of sync-run.ts. Each returns
+ * the next cursor and writes nothing; sync-run.ts saves it with one compare-and-swap. An entry the cursor passes without
+ * a commit (waived, held, settled) joins the settled index ranges the checkpoint skips; a deferred entry (retried past
+ * the manifest end) leaves the deferred list instead of moving the index; the window of requests admitted after a
+ * passed entry becomes the cursor's group, so those requests are read, never frozen again.
+ */
+import { addSettledRange, type SyncSettledIndexes } from './checkpoint-validation.ts';
+import { dependencyKeys } from './sync-group.ts';
+import type { Cursor, Pending } from './sync-run.ts';
+import type { HeldEntry } from './sync-screen.ts';
+import type { NoopWaiver } from './sync-waivers.ts';
+
+/** The cursor after a waived entry: counted under `waived`, plus the #5751 kernel breakdown kept for `legacySkips`. */
+export function waivedCursor(cursor: Cursor, waived: NoopWaiver, index = cursor.index): Cursor {
+ const prior = cursor.counts.waived ?? { imports: 0, deletes: 0 };
+ const passed: Cursor = { ...cursor }; delete passed.pending; delete passed.group;
+ const next: Cursor = { ...settledPast(passed, index), counts: { ...cursor.counts,
+ waived: { imports: prior.imports + (waived.kind === 'import' ? 1 : 0), deletes: prior.deletes + (waived.kind === 'delete' ? 1 : 0) } } };
+ if (waived.kernel.includes('contextual_mode')) next.counts.skippedContextualMode = (next.counts.skippedContextualMode ?? 0) + 1;
+ if (waived.kernel.includes('canonical_file_differs')) next.counts.skippedCanonicalBytes = (next.counts.skippedCanonicalBytes ?? 0) + 1;
+ return next;
+}
+/** #6643: the cursor's settled indexes with its current entry added (it passes that entry without a commit). */
+export function settleIndex(cursor: Cursor): SyncSettledIndexes {
+ return addSettledRange(cursor.settled ?? { from: cursor.index, ranges: [] }, cursor.index, cursor.index);
+}
+/** #5988: the cursor past a held entry (no request admitted for it, or none committed); #6712: `index` may name a deferred entry. */
+export function advanceHeld(held: Cursor, converted?: string[], index = held.index): Cursor {
+ const next: Cursor = { ...held, counts: { ...held.counts, held: (held.counts.held ?? 0) + 1 }, ...(converted ? { convertedFromFailed: converted } : {}) };
+ delete next.pending; delete next.group;
+ return settledPast(next, index);
+}
+/**
+ * #6712: the cursor with entry `index` settled without a commit: the cursor's own entry advances the cursor, a deferred
+ * entry leaves the deferred list. Either way the index joins the settled ranges the checkpoint skips.
+ */
+export function settledPast(cursor: Cursor, index: number): Cursor {
+ if (index === cursor.index) return promoteWindow({ ...cursor, index: cursor.index + 1, settled: settleIndex(cursor) });
+ const next: Cursor = { ...cursor, deferred: (cursor.deferred ?? []).filter(entry => entry.index !== index),
+ settled: addSettledRange(cursor.settled ?? { from: cursor.index, ranges: [] }, index, index) };
+ if (!next.deferred!.length) delete next.deferred;
+ return next;
+}
+/**
+ * #6712: a cursor with no pending entry whose window starts at its index takes the window's first group as its group:
+ * those requests were admitted after an entry the cursor has now passed, and are read, never frozen again.
+ */
+export function promoteWindow(cursor: Cursor): Cursor {
+ const [first, ...rest] = cursor.window ?? [];
+ if (cursor.pending || !first?.length || first[0]!.intent.index !== cursor.index) return cursor;
+ const next: Cursor = { ...cursor, pending: first[0], group: first };
+ if (rest.length) next.window = rest; else delete next.window;
+ return next;
+}
+/** #6712: the cursor past its committed pending entry: its own entry advances it, a deferred one leaves the deferred list (its receipt is its record). */
+export function committedPast(cursor: Cursor, pending: Pending): Cursor {
+ const index = indexOf(cursor, pending);
+ const next: Cursor = { ...cursor }; delete next.pending; delete next.group;
+ if (index === cursor.index) return promoteWindow({ ...next, index: cursor.index + 1 });
+ next.deferred = (cursor.deferred ?? []).filter(entry => entry.index !== index);
+ if (!next.deferred.length) delete next.deferred;
+ return next;
+}
+/** #6712: the entry a pending request was frozen for: the cursor's own, or a deferred one past the manifest end. */
+export const indexOf = (cursor: Cursor, pending: Pending) => typeof pending.intent.index === 'number' ? pending.intent.index : cursor.index;
+export const entryOf = (cursor: Cursor, pending: Pending) => cursor.entries[indexOf(cursor, pending)];
+/** #6712: the cursor without `pending` and the group it heads; the window (later admitted requests) stays. */
+export function withoutPending(cursor: Cursor): Cursor {
+ const base: Cursor = { ...cursor }; delete base.pending; delete base.group;
+ return base;
+}
+/** #6600: the cursor past an idempotent deletion: counted as a waived delete, its index settled. */
+export const deletionSettled = (cursor: Cursor, index: number) => waivedCursor(withoutPending(cursor), { kind: 'delete', kernel: [] }, index);
+/** #6712: the cursor with `hold`'s page keys recorded, so a later entry of the run that shares one is held behind it. */
+export function withHeldKeys(cursor: Cursor, hold: HeldEntry): Cursor {
+ if (!hold.slug) return cursor;
+ const keys = dependencyKeys({ slug: hold.slug, pageId: hold.page_id ?? null });
+ return { ...cursor, heldKeys: { ...cursor.heldKeys, ...Object.fromEntries(keys.map(key => [key, { path: hold.path, code: hold.code }])) } };
+}
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 6ae2051f58..f4c1f49ee8 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -23,7 +23,7 @@ import type { CompanyBrainPlan } from '../company-brain/types.ts';
import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, selectOriginClaimant, sharedOriginExit, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive } from './sync-authority.ts';
import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
-import { holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances } from './sync-holds.ts';
+import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHolds, readSyncImportProvenances } from './sync-holds.ts';
import { readBlobContents, readTreeBlobs, SYNC_READ_BOUND } from './sync-blobs.ts';
import { gitChildEnv } from '../git-env.ts';
import { readSyncSlice, sliceEntries, syncCursorOptions, type SyncSliceCursor, type SyncSliceState } from './sync-slices.ts';
@@ -384,16 +384,11 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
return hold && !hold.meta.blob_oid && !hold.meta.working && blob ? [blob] : [];
});
const contents = readBlobContents(gitRoot, unversioned);
- // #6712: a deterministic `concurrent_write` hold re-screens when its page's revision moves (a reconcile, an authorized delete).
- const watched = checked.flatMap(path => { const hold = holdByPath.get(path); return hold?.code === 'concurrent_write' && hold.page_id != null && hold.meta.page_revision ? [Number(hold.page_id)] : []; });
- const revisions = new Map(watched.length ? (await engine.executeRaw<{ id: number; revision: string }>('SELECT id, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[])',
- [sourceId, watched])).map(row => [Number(row.id), row.revision]) : []);
+ const moved = await holdBasisMoved(engine, sourceId, holdByPath, checked);
for (const path of checked) {
const hold = holdByPath.get(path), gitPath = toGitPath(path), blob = blobs.get(gitPath);
const workingHold = working && (hold?.meta.working === true || !blob);
- // #6712 dependency edge: a hold that waits on an earlier entry's hold re-screens once that hold is gone.
- let changed = !hold || holdRescreenDue(hold, retry.has(path)) || (!!hold.meta.blocked_on && !holdByPath.has(hold.meta.blocked_on))
- || (hold.code === 'concurrent_write' && hold.page_id != null && !!hold.meta.page_revision && revisions.get(Number(hold.page_id)) !== hold.meta.page_revision);
+ let changed = !hold || holdRescreenDue(hold, retry.has(path)) || moved.has(path);
let present = !!blob;
if (workingHold) {
let bytes: Buffer | null = null;
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 1830052d8e..385fa0c718 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -387,6 +387,24 @@ export async function readGitHoldListing(engine: Exec, sourceIds: string[], limi
return [...out.values()];
}
+/**
+ * #6712: the held paths whose verdict rests on something that has since moved: a dependency-edge hold (`blocked_on`)
+ * whose predecessor's hold is gone, and a deterministic `concurrent_write` hold whose page's revision moved (a
+ * reconcile, an authorized delete). Discovery re-screens them like a changed file.
+ */
+export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, holds: ReadonlyMap<string, Pick<GitHoldRecord, 'code' | 'page_id' | 'meta'>>,
+ paths: readonly string[]): Promise<Set<string>> {
+ const watched = paths.flatMap(path => { const hold = holds.get(path); return hold?.code === 'concurrent_write' && hold.page_id != null && hold.meta.page_revision ? [Number(hold.page_id)] : []; });
+ const revisions = new Map(watched.length ? (await engine.executeRaw<{ id: number; revision: string }>('SELECT id, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[])',
+ [sourceId, watched])).map(row => [Number(row.id), row.revision]) : []);
+ return new Set(paths.filter(path => {
+ const hold = holds.get(path);
+ if (!hold) return false;
+ if (hold.meta.blocked_on && !holds.has(hold.meta.blocked_on)) return true;
+ return hold.code === 'concurrent_write' && hold.page_id != null && !!hold.meta.page_revision && revisions.get(Number(hold.page_id)) !== hold.meta.page_revision;
+ }));
+}
+
/**
* #6188 (E23): the one re-screen predicate managed discovery and legacy sync
* share, apart from the byte comparison each makes its own way. A hold is
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index bd4868a642..d69616d0c5 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -24,7 +24,7 @@ import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } f
import { startClaimPhase } from './claim-phase.ts';
import { screeningRequest } from './noop-kernel.ts';
import { FINISH_BUDGET_MS, stampDrainStep } from './drain-step.ts';
-import { noopWaiversEnabled, raceSyncBudget, screenWaiver, syncPreparationBudgetMs, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';
+import { noopWaiversEnabled, raceSyncBudget, screenWaiver, syncPreparationBudgetMs, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type WaiverRunEntry } from './sync-waivers.ts';
import { existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';
@@ -34,7 +34,7 @@ import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../planner-st
import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, managedSyncRetryCommand, type ManagedSyncFailure, type ManagedSyncRootCause } from './sync-failures.ts';
import { writeFailureDiagnostic } from './verb-errors.ts';
import { extractManagedStaleLinks } from './links-maintenance.ts';
-import { addSettledRange, CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint, findIncompleteSyncReceipt, type SyncSettledIndexes } from './checkpoint-validation.ts';
+import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint, findIncompleteSyncReceipt, type SyncSettledIndexes } from './checkpoint-validation.ts';
import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';
import { principalKey, type WriteRequest } from './model.ts';
import { readJournalLimits } from './limits.ts';
@@ -63,6 +63,7 @@ import { recordSyncRunTrend } from '../fence-repair/census-store.ts';
import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type GitHoldCode, type SyncHoldPolicy } from './sync-holds.ts';
import { withScreeningPaths } from './screening-paths.ts';
import { withBoundedReadSession } from './bounded-reads.ts';
+import { advanceHeld, committedPast, deletionSettled, entryOf, indexOf, promoteWindow, waivedCursor, withHeldKeys, withoutPending } from './sync-cursor-moves.ts';
export interface ManagedSyncWriteDiagnostic {
source_id: string;
@@ -79,16 +80,16 @@ export interface ManagedSyncWriteDiagnostic {
docs?: string;
}
-interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; rebound?: true;
+export interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; rebound?: true;
/** #5988: re-frozen in place from a failed content refusal; a second refusal of the same bytes stays blocked. */
converted?: true;
/** #6712: re-frozen in place after the run stopped on this entry (a transport or systemic fault, a legacy knock-on); the re-freezes in a row here. */
stops?: number; }
/** #5988: the frozen entry is held instead of admitted. #6340 `overtaken`: another cursor of the source imported the entry's page meanwhile (#5522), so the checkpoint accepts a source already at this target. */
-interface Held { hold: HeldEntry; overtaken?: true }
+export interface Held { hold: HeldEntry; overtaken?: true }
/** #6600: the frozen deletion was already carried out by a committed, authorized delete of its exact page (`idempotentDeletionProof`); it settles with no admission and clears its hold. */
-interface Settled { settled: { path: string; request_id: string } }
-interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean; companyReceiptId?: string;
+export interface Settled { settled: { path: string; request_id: string } }
+export interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean; companyReceiptId?: string;
processingOptions?: SyncProcessingOptions; syncOptions?: SyncCursorOptions; overtaken?: true;
counts: { added: number; modified: number; deleted: number; chunks: number; renamed?: number;
/** #5751: unchanged working-tree files skipped only because a no-op publication could never resolve their admit reason. */
@@ -267,20 +268,6 @@ async function currentCursor(engine: BrainEngine, key: string, cached: Cursor):
`The durable sync cursor of source ${cached.sourceId} vanished (another run of the source finished or replaced it), so this run stopped.`);
return current;
}
-/** The cursor after a waived entry: counted under `waived`, plus the #5751 kernel breakdown kept for `legacySkips`. */
-function waivedCursor(cursor: Cursor, waived: NoopWaiver, index = cursor.index): Cursor {
- const prior = cursor.counts.waived ?? { imports: 0, deletes: 0 };
- const passed: Cursor = { ...cursor }; delete passed.pending; delete passed.group;
- const next: Cursor = { ...settledPast(passed, index), counts: { ...cursor.counts,
- waived: { imports: prior.imports + (waived.kind === 'import' ? 1 : 0), deletes: prior.deletes + (waived.kind === 'delete' ? 1 : 0) } } };
- if (waived.kernel.includes('contextual_mode')) next.counts.skippedContextualMode = (next.counts.skippedContextualMode ?? 0) + 1;
- if (waived.kernel.includes('canonical_file_differs')) next.counts.skippedCanonicalBytes = (next.counts.skippedCanonicalBytes ?? 0) + 1;
- return next;
-}
-/** #6643: the cursor's settled indexes with its current entry added (it passes that entry without a commit). */
-function settleIndex(cursor: Cursor): SyncSettledIndexes {
- return addSettledRange(cursor.settled ?? { from: cursor.index, ranges: [] }, cursor.index, cursor.index);
-}
/** The rollback signal of an admission whose cursor no longer holds the frozen entry (ENG-A7). */
class CursorMoved extends Error {}
async function replaceCursor(engine: BrainEngine, key: string, before: CursorHeader, next: Cursor, assertActive: () => void): Promise<Cursor | { wait: RetryWait }> {
@@ -467,6 +454,27 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
}
/** A resume adopts the cursor's stored processing options unless the caller set a conflicting one explicitly. */
+/**
+ * #6712: the cursor's next freeze. Past the manifest's last entry it is the first entry deferred because its file
+ * changed after admission. A settled deletion (#6600) and a hold, the entry's own or a dependency edge's (an entry that
+ * shares a slug or page id with one this run held waits on that hold), are saved in one cursor step (`saved`); anything
+ * else is the frozen entry to admit.
+ */
+async function freezeNext(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void, run: Parameters<typeof freezeEntry>[4],
+ observedAt: string): Promise<{ saved: Cursor; held: boolean } | { frozen: Pending; deferredAt?: number }> {
+ const deferredAt: number | undefined = cursor.index >= cursor.entries.length ? cursor.deferred?.[0]?.index : undefined;
+ const index = deferredAt ?? cursor.index;
+ let frozen = await freezeEntry(engine, { ...cursor, index }, key, assertActive, run);
+ if ('settled' in frozen) return { held: false, saved: await saveCursor(engine, key, cursor, deletionSettled(cursor, index), false, assertActive, holdClear(cursor, frozen.settled.path, observedAt)) };
+ const blockedOn = 'requestId' in frozen ? dependencyKeys(frozen).map(page => cursor.heldKeys?.[page]).find(Boolean) : undefined;
+ if (blockedOn && 'requestId' in frozen && cursor.entries[index]) frozen = { hold: dependentHold(cursor.entries[index]!, frozen.slug, frozen.pageId, frozen.intent, blockedOn) };
+ if ('hold' in frozen) {
+ return { held: true, saved: await saveCursor(engine, key, cursor, { ...withHeldKeys(advanceHeld(cursor, undefined, index), frozen.hold), ...(frozen.overtaken ? { overtaken: true as const } : {}) },
+ false, assertActive, heldWrite(cursor, frozen.hold, observedAt)) };
+ }
+ return { frozen, ...(deferredAt !== undefined ? { deferredAt } : {}) };
+}
+
function assertCursorProcessingOptions(cursor: Cursor, processingOptions: SyncProcessingOptions, explicitProcessing: SyncOpts['explicitProcessing']): void {
const stored = cursor.processingOptions;
if (stored ? digest(stored) !== digest(processingOptions) : !cursor.pending) {
@@ -500,60 +508,6 @@ const holdClear = (cursor: Cursor, path: string | null | undefined, observedAt:
const heldWrite = (held: Cursor, hold: HeldEntry, observedAt: string) => (tx: BrainEngine) => writeGitHold(tx, { source_id: held.sourceId, incarnation: held.incarnation, ...hold,
observed_at: observedAt, run_id: held.runId, mode: 'managed' });
-/** #5988: the cursor past a held entry (no request admitted for it, or none committed); #6712: `index` may name a deferred entry. */
-function advanceHeld(held: Cursor, converted?: string[], index = held.index): Cursor {
- const next: Cursor = { ...held, counts: { ...held.counts, held: (held.counts.held ?? 0) + 1 }, ...(converted ? { convertedFromFailed: converted } : {}) };
- delete next.pending; delete next.group;
- return settledPast(next, index);
-}
-/**
- * #6712: the cursor with entry `index` settled without a commit: the cursor's own entry advances the cursor, a deferred
- * entry leaves the deferred list. Either way the index joins the settled ranges the checkpoint skips.
- */
-function settledPast(cursor: Cursor, index: number): Cursor {
- if (index === cursor.index) return promoteWindow({ ...cursor, index: cursor.index + 1, settled: settleIndex(cursor) });
- const next: Cursor = { ...cursor, deferred: (cursor.deferred ?? []).filter(entry => entry.index !== index),
- settled: addSettledRange(cursor.settled ?? { from: cursor.index, ranges: [] }, index, index) };
- if (!next.deferred!.length) delete next.deferred;
- return next;
-}
-/**
- * #6712: a cursor with no pending entry whose window starts at its index takes the window's first group as its group:
- * those requests were admitted after an entry the cursor has now passed, and are read, never frozen again.
- */
-function promoteWindow(cursor: Cursor): Cursor {
- const [first, ...rest] = cursor.window ?? [];
- if (cursor.pending || !first?.length || first[0]!.intent.index !== cursor.index) return cursor;
- const next: Cursor = { ...cursor, pending: first[0], group: first };
- if (rest.length) next.window = rest; else delete next.window;
- return next;
-}
-/** #6712: the cursor past its committed pending entry: its own entry advances it, a deferred one leaves the deferred list (its receipt is its record). */
-function committedPast(cursor: Cursor, pending: Pending): Cursor {
- const index = indexOf(cursor, pending);
- const next: Cursor = { ...cursor }; delete next.pending; delete next.group;
- if (index === cursor.index) return promoteWindow({ ...next, index: cursor.index + 1 });
- next.deferred = (cursor.deferred ?? []).filter(entry => entry.index !== index);
- if (!next.deferred.length) delete next.deferred;
- return next;
-}
-/** #6712: the entry a pending request was frozen for: the cursor's own, or a deferred one past the manifest end. */
-const indexOf = (cursor: Cursor, pending: Pending) => typeof pending.intent.index === 'number' ? pending.intent.index : cursor.index;
-const entryOf = (cursor: Cursor, pending: Pending) => cursor.entries[indexOf(cursor, pending)];
-/** #6712: the cursor without `pending` and the group it heads; the window (later admitted requests) stays. */
-function withoutPending(cursor: Cursor): Cursor {
- const base: Cursor = { ...cursor }; delete base.pending; delete base.group;
- return base;
-}
-/** #6600: the cursor past an idempotent deletion: counted as a waived delete, its index settled. */
-const deletionSettled = (cursor: Cursor, index: number) => waivedCursor(withoutPending(cursor), { kind: 'delete', kernel: [] }, index);
-/** #6712: the cursor with `hold`'s page keys recorded, so a later entry of the run that shares one is held behind it. */
-function withHeldKeys(cursor: Cursor, hold: HeldEntry): Cursor {
- if (!hold.slug) return cursor;
- const keys = dependencyKeys({ slug: hold.slug, pageId: hold.page_id ?? null });
- return { ...cursor, heldKeys: { ...cursor.heldKeys, ...Object.fromEntries(keys.map(key => [key, { path: hold.path, code: hold.code }])) } };
-}
-
/** #6278: the terminal code an owner stamps on a request whose preparation never settled within its attempts (Lane A, consumer.ts). */
export const PREPARATION_STALLED = 'preparation_stalled';
const preparationStalled = (row: Pick<WriteRequest, 'state' | 'error_code'>) => row.state === 'failed' && row.error_code === PREPARATION_STALLED;
@@ -1581,24 +1535,14 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
}
foregroundWaitStart = 0;
phase = 'freeze'; stampDrainStep('freeze', signal);
- // #6712: past the manifest's last entry, entries deferred because their file changed after admission are retried before the checkpoint.
- const deferredAt: number | undefined = cursor.index >= cursor.entries.length ? cursor.deferred?.[0]?.index : undefined;
- let frozen = await freezeEntry(engine, deferredAt === undefined ? cursor : { ...cursor, index: deferredAt }, key, assertActive, frozenRun);
- if ('settled' in frozen) {
- cursor = await saveCursor(engine, key, cursor, deletionSettled(cursor, deferredAt ?? cursor.index), false, assertActive, holdClear(cursor, frozen.settled.path, observedAt));
- opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length, waived: true }); assertActive();
- continue;
- }
- // #6712 dependency edge: an entry sharing a slug or page id with one this run held waits on that hold.
- const blockedOn = 'requestId' in frozen ? dependencyKeys(frozen).map(page => cursor!.heldKeys?.[page]).find(Boolean) : undefined;
- const entryAt: SyncDiscovery['entries'][number] | undefined = cursor.entries[deferredAt ?? cursor.index];
- if (blockedOn && entryAt && 'requestId' in frozen) frozen = { hold: dependentHold(entryAt, frozen.slug, frozen.pageId, frozen.intent, blockedOn) };
- if ('hold' in frozen) {
- cursor = await saveCursor(engine, key, cursor, { ...withHeldKeys(advanceHeld(cursor, undefined, deferredAt ?? cursor.index), frozen.hold), ...(frozen.overtaken ? { overtaken: true as const } : {}) }, false, assertActive, heldWrite(cursor, frozen.hold, observedAt));
- opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index }); assertActive();
- if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
+ const next = await freezeNext(engine, cursor, key, assertActive, frozenRun, observedAt);
+ if ('saved' in next) {
+ cursor = next.saved;
+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, ...(next.held ? {} : { total: cursor.entries.length, waived: true }) }); assertActive();
+ if (next.held && slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
continue;
}
+ const { frozen, deferredAt } = next;
const waived: Cursor | null = waiveBatch && !frozen.rebound && deferredAt === undefined ? await waiveRun(engine, cursor, frozen, key, config, assertActive, frozenRun, drainStartedAt,
slice ? slice.maxPages - (cursor.index - sliceFirstIndex) : WAIVER_RUN_MAX, opts.onProgress) : null;
if (waived && slice && (waived.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(waived, 'partial', 'writer_yield');
diff --git a/test/e2e/persistence-preparation-deadline.e2e.test.ts b/test/e2e/persistence-preparation-deadline.e2e.test.ts
index 4cfeddeca2..c5bd1850e8 100644
--- a/test/e2e/persistence-preparation-deadline.e2e.test.ts
+++ b/test/e2e/persistence-preparation-deadline.e2e.test.ts
@@ -125,14 +125,15 @@ describe.skipIf(!hasDatabase())('managed catch-up preparation deadlines (Postgre
expect(hold.holds()).toBe(2);
// Time from the first cut-off attempt to the terminal receipt stays inside budget x attempts plus slack.
expect(ended - held[0]!).toBeLessThan(BUDGET_MS * 2 + 20_000);
- // The root kept publishing: every page before the stuck one committed; nothing after it published; the late result never did.
+ // The root kept publishing: every page before the stuck one committed; the late result never did. #6712 (one page, one
+ // fate): the pages admitted after it are never cancelled for it; each publishes on its own.
const stuckAt = rows.findIndex(row => row.slug === stuckSlug);
expect(stuckAt).toBeGreaterThan(0);
expect(rows.slice(0, stuckAt).every(row => row.state === 'committed')).toBe(true);
expect(rows.slice(0, stuckAt).every(row => row.preparation_attempts === 0)).toBe(true);
expect(await engine.getPage(stuckSlug, { sourceId: f.id })).toBeNull();
- for (const row of rows.slice(stuckAt + 1)) expect(await engine.getPage(row.slug, { sourceId: f.id })).toBeNull();
- expect(rows.slice(stuckAt + 1).every(row => ['cancelled', 'queued'].includes(row.state))).toBe(true);
+ expect(rows.slice(stuckAt + 1).filter(row => !['committed', 'queued', 'running'].includes(row.state)).map(row => `${row.slug} ${row.state}`)).toEqual([]);
+ for (const row of rows.slice(stuckAt + 1).filter(row => row.state === 'committed')) expect(await engine.getPage(row.slug, { sourceId: f.id })).not.toBeNull();
// The members behind it in its own group were released uncharged, never claim_lost.
expect(rows.filter(row => row.blocked_reason === 'claim_lost')).toEqual([]);
expect(rows.filter(row => row.preparation_attempts > 0).map(row => row.slug)).toEqual([stuckSlug]);
diff --git a/test/e2e/persistence-request-indexes-postgres.test.ts b/test/e2e/persistence-request-indexes-postgres.test.ts
index ae356a13f3..15f30ac115 100644
--- a/test/e2e/persistence-request-indexes-postgres.test.ts
+++ b/test/e2e/persistence-request-indexes-postgres.test.ts
@@ -74,7 +74,7 @@ test('#5762 on a 512k-row request table every probe is an index scan, and the fo
await engine.executeRaw('ANALYZE persistence_requests');
const runId = randomUUID();
const [{ 'QUERY PLAN': [probe] }] = await engine.executeRaw<{ 'QUERY PLAN': Array<{ Plan: Record<string, unknown> }> }>(
- `EXPLAIN (FORMAT JSON) ${INCOMPLETE_SYNC_RECEIPT_SQL}`, [binding.worktree_id, runId, [], [], [], 0]);
+ `EXPLAIN (FORMAT JSON) ${INCOMPLETE_SYNC_RECEIPT_SQL}`, [binding.worktree_id, runId, [], [], []]);
const nodes = planNodes(probe.Plan);
expect(nodes.filter(node => node['Node Type'] === 'Seq Scan' && node['Relation Name'] === 'persistence_requests')).toEqual([]);
const used = new Set(nodes.map(node => node['Index Name']).filter(Boolean));
diff --git a/test/error-registry-retired.test.ts b/test/error-registry-retired.test.ts
index bd789edbb4..4d531babd7 100644
--- a/test/error-registry-retired.test.ts
+++ b/test/error-registry-retired.test.ts
@@ -19,7 +19,7 @@ import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
const RETIRED_KEYS = ['sync.knock_on_refreeze_limit', 'sync.knock_on_run_limit'];
const entries = (registry: Record<string, unknown>) => Object.entries(registry) as Array<[string, CodeEntry]>;
-const fixText = (entry: CodeEntry) => [entry.suggestion, entry.why, ...(entry.fix ? [entry.fix.argv.join(' '), entry.fix.why] : [])].filter(Boolean).join('\n');
+const fixText = (entry: CodeEntry) => [entry.suggestion, entry.why, ...(entry.fix ? [(entry.fix.argv ?? []).join(' '), entry.fix.why] : [])].filter(Boolean).join('\n');
test('no registered fix, suggestion or reason names a retired config key', () => {
const texts: Array<[string, string]> = [
@@ -59,7 +59,7 @@ test('a retired code renders superseded: its fix is read-only, needs no consent,
for (const [, entry] of retired) {
expect(entry.summary).toMatch(/^Retired:/);
expect(entry.fix).toMatchObject({ consent: [], requires_exclusive: false });
- expect(entry.fix!.argv.join(' ')).not.toMatch(/config set|--retry-failed|--reset-checkpoint/);
+ expect((entry.fix?.argv ?? []).join(' ')).not.toMatch(/config set|--retry-failed|--reset-checkpoint/);
}
expect(CODES.knock_on_exhausted.suggestion).toContain('gbrain sync --source <id> --no-pull');
});