Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): #6712 PR 4b gate: one profile read per import batch, pass and managed-sync phases under the function-size limit
garrytan136766a970c7
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 9c12499c21..bccfbf680c 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap insrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeoutsrc/core/config.ts 1986 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6712 PR 4b: sync.admission KNOWN_CONFIG_KEYS row (value logic in persistence/sync-admission.ts)-src/core/persistence/sync-run.ts 1621 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; lowered to 1606 #6712 PR 4b lane C: the dead non-company cursor arms retired (cursor adoption and fan-in reports, the retry-held finish arm, the resumable slice stage); the live pass lives in persistence/sync-pass-run.ts; +10 #6712 PR 4b item 7 and lane A rulings: the CLI pass waits out its own held write (whileHeld, awaitWrite whileHeldMs in service.ts), the waiver run hands its admitting screen to the per-entry path, the refresh fence and authority read together, the admission carries the owner epoch, and a failed level read is recorded as that read (onLevelRead; the pass lives in persistence/sync-pass-run.ts); +4 #6712 PR 4b idle-tick batching: the preflight reads the mode, company profile and source rows in one round trip (readManagedSyncRows in persistence/sync-discovery.ts, activeManagedBrainId in sync-authority.ts) and an idle pass that read no owed tail skips the post-lease tail read (DrainLease.tailClear in sync-lease.ts); +1 #6712 PR 4b lane C gate: Cursor.passLegacyWaived interface field (a pass batch reports the #5751 waivers the pass settles at their level; the settle lives in persistence/sync-pass-run.ts)+src/core/persistence/sync-run.ts 1650 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; lowered to 1606 #6712 PR 4b lane C: the dead non-company cursor arms retired (cursor adoption and fan-in reports, the retry-held finish arm, the resumable slice stage); the live pass lives in persistence/sync-pass-run.ts; +10 #6712 PR 4b item 7 and lane A rulings: the CLI pass waits out its own held write (whileHeld, awaitWrite whileHeldMs in service.ts), the waiver run hands its admitting screen to the per-entry path, the refresh fence and authority read together, the admission carries the owner epoch, and a failed level read is recorded as that read (onLevelRead; the pass lives in persistence/sync-pass-run.ts); +4 #6712 PR 4b idle-tick batching: the preflight reads the mode, company profile and source rows in one round trip (readManagedSyncRows in persistence/sync-discovery.ts, activeManagedBrainId in sync-authority.ts) and an idle pass that read no owed tail skips the post-lease tail read (DrainLease.tailClear in sync-lease.ts); +1 #6712 PR 4b lane C gate: Cursor.passLegacyWaived interface field (a pass batch reports the #5751 waivers the pass settles at their level; the settle lives in persistence/sync-pass-run.ts); +29 #6712 PR 4b gate: runManagedSync (353 lines, no baseline row) split into named helpers in this module (admitPendingWrite, foldPassTotals, companyRetryOwed, assertCursorBinding, recordRunFailure); they close over the private cursor machinery (CursorMoved, syncRunRefusal, OP), so a sibling would import this module at runtime, and their signatures are the growthsrc/core/bootstrap/harness.ts 2584 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.tssrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 710 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts)diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 6f7ec00ab6..27840277f8 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -72,7 +72,7 @@ const BATCH_SHARED_READS = new Set(['SELECT brain_id FROM persistence_brain WHERE singleton=1','SELECT value FROM config WHERE key=$1',"SELECT config,incarnation FROM sources WHERE id=$1",- "SELECT id FROM source_ingestion_receipts WHERE source_id=$1 AND source_incarnation=$2::uuid AND profile='company-brain' LIMIT 1",+ "SELECT r.id FROM source_ingestion_receipts r JOIN sources s ON s.id=r.source_id AND s.incarnation=r.source_incarnation WHERE r.source_id=$1 AND r.profile='company-brain' LIMIT 1",'SELECT s.id,s.local_path,h.local_path AS worktree_path,b.relative_path FROM sources s LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid WHERE NOT s.archived',]);/**diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 747d87b230..3672e4aa59 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -313,15 +313,15 @@ async function writeLegacyMarkers(engine: BrainEngine, level: ShadowLevel): Promreturn rows.length;}-/** The pass of one managed, non-company source (module header). */-export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Promise<SyncResult> {+/**+ * The pass's pin (design §2.2): its reads, mode, selection, options, kind and the row it opens; `ended` when the legacy+ * cursors' retirement ends the pass before it pins.+ */+async function pinPass(engine: BrainEngine, input: SyncPassInput, lease: NonNullable<ReturnType<typeof currentDrainLease>>, started: number) {const { opts, context, authority, assertActive } = input;const { sourceId, incarnation } = context;const remote = authority.writer.remote;- const lease = currentDrainLease(sourceId);- if (!lease) throw new Error(`The live sync pass of ${sourceId} runs only under the source's drain lease.`);- lease.tailClear = false;- const started = Date.now(), startedAt = new Date(started).toISOString();+ const startedAt = new Date(started).toISOString();// Pin (design §2.2): the row, sync.admission, HEAD and the mode. The reads the kind needs ride the same round trip: the// selection's patterns, the schema pack, the tail, the retry row, the source's holds and the idle probe (which reads the// row's watermark and open ids itself). #6712 PR 4b: the legacy cursors' retirement runs beside them; it writes none of@@ -334,14 +334,13 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prengine.executeRaw(`SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=ANY($1::text[]) LIMIT 1`, [passFailureKeys(sourceId, incarnation)])] as const);pin.catch(() => undefined);const handover = await retireLegacyCursors(engine, { sourceId, incarnation, remote, assertActive });- const empty = (status: SyncResult['status'], reason?: SyncResult['reason']): SyncResult => ({ status, fromCommit: remote ? null : context.source.last_commit, toCommit: remote ? '' : context.source.last_commit ?? '',- added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], filesImported: 0, bankedFiles: 0, ...(reason ? { reason } : {}) });- if (handover.wait) return { ...empty('partial', 'writer_pending'), ...(remote ? {} : { retryWait: handover.wait }) };- if (handover.hostRequired) return empty('blocked_by_failures', 'reconcile_host_required');+ const empty = (status: SyncResult['status'], reason?: SyncResult['reason']) => emptyPassResult(context, remote, status, reason);+ if (handover.wait) return { ended: { ...empty('partial', 'writer_pending'), ...(remote ? {} : { retryWait: handover.wait }) } };+ if (handover.hostRequired) return { ended: empty('blocked_by_failures', 'reconcile_host_required') };const [prior, admission, configuredWorking, patterns, loadedPack, tail, retry, sourceHolds, rowProbe, failed] = await pin;assertActive();const [headLine, refLine] = syncGit(context.gitRoot, ['rev-parse', 'HEAD', '--abbrev-ref', 'HEAD']).split('\n');- let head = headLine!.trim();+ const head = headLine!.trim();const detached = refLine?.trim() === 'HEAD';const mode: SyncSelection['mode'] = detached || (opts.workingTree ?? configuredWorking === 'true') ? 'working' : 'committed';const selection = passSelection(patterns, opts, context, mode);@@ -361,7 +360,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr// A pass that admits under an opt-out opens an episode carrying it (design §6), when it admits its first batch.const optOutEpisode: PassEpisode | null = !obligations.episode && (requested.noEmbed || requested.noExtract || requested.noSchemaPack) ? { opened_at: startedAt, selection,inherited: { noEmbed: requested.noEmbed, noExtract: requested.noExtract, noSchemaPack: requested.noSchemaPack, from: 'flag' } } : null;- let episode = obligations.episode;+ const episode = obligations.episode;// A flagless pass keeps the open episode's opt-outs (#6712 PR 1's inherited_options contract).const processingOptions: SyncProcessingOptions = { noEmbed: requested.noEmbed || !!episode?.inherited.noEmbed, noExtract: requested.noExtract || !!episode?.inherited.noExtract,noSchemaPack: requested.noSchemaPack || !!episode?.inherited.noSchemaPack };@@ -397,30 +396,135 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prcounts: {}, duration_ms: null, timings_ms: {} } };// The incarnation's legacy markers (§2.7 b1) are owed until a local pass wrote them, not only by its first row.const markersOwed = () => remote ? !prior : !value.obligations.legacy_markers_at;+ return { prior, admission, tail, retry, failed, head, mode, selection, configured, selectionFp, parserFp, obligations, passId, optOutEpisode, episode,+ processingOptions, inherited, pack, converged, cacheKey, kindStarted, working, kind, value, markersOwed };+}- if (kind === 'idle' && working.cache) rememberWorkingStatCache(cacheKey, working.cache);- if (kind === 'idle') {- // Master's up_to_date (a complete check that found nothing): only last_sync_at, plus the pass row's count.- const at = new Date().toISOString();- value.obligations.converged = { ...converged!, passes_since_full: converged!.passes_since_full + 1 };- value.obligations.stuck_since = null;- // Design §7: an owner approval (--yes) on an idle tick still makes an unknown cost known again.- if (opts.costApproved && value.obligations.cost?.approved_usd === null) value.obligations.cost = (await passCostDecision(engine, { sourceId, incarnation,- scope: episode?.full_id ?? passId, priorRow: true, prior: value.obligations.cost, approved: true })).cost;- value.telemetry = { ...value.telemetry, outcome: 'up_to_date', ended_at: at, duration_ms: Date.now() - started, timings_ms: { setup: kindStarted - started, kind: Date.now() - kindStarted } };- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {- assertActive();- // One round trip: the lease check, the stamp and the row (started at the transaction's clock) are pipelined; a lost- // lease rolls the other two back.- await pipelined(tx, [() => assertDrainLease(tx, sourceId), () => tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]),- () => writePassRow(tx, value, { pin: true, clock: true })]);- }, principalAttribution(authority.writer.principal)));- // A failure is recorded only under the lease this pass holds, so none recorded at pin means none to clear.- if (failed.length) await clearPassFailures(engine, sourceId, incarnation);- // Nor can a tail be owed since the pin read none: the lease's holder reads none after it (sync-run.ts).- lease.tailClear = !tail;- return { ...empty('up_to_date'), toCommit: remote ? '' : head, ...(inherited.length ? { inherited_options: inherited } : {}) };+/** A pass result that imported nothing, at the source's last commit. */+function emptyPassResult(context: ManagedSyncContext, remote: boolean, status: SyncResult['status'], reason?: SyncResult['reason']): SyncResult {+ return { status, fromCommit: remote ? null : context.source.last_commit, toCommit: remote ? '' : context.source.last_commit ?? '',+ added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], filesImported: 0, bankedFiles: 0, ...(reason ? { reason } : {}) };+}++/** Master's up_to_date for an idle tick (a complete check that found nothing): only last_sync_at, plus the pass row's count. */+async function stampIdlePass(engine: BrainEngine, input: SyncPassInput, lease: NonNullable<ReturnType<typeof currentDrainLease>>, started: number, pinned: Exclude<Awaited<ReturnType<typeof pinPass>>, { ended: SyncResult }>): Promise<SyncResult> {+ const { opts, context, authority, assertActive } = input;+ const { sourceId, incarnation } = context;+ const remote = authority.writer.remote;+ const { value, converged, episode, passId, kindStarted, failed, tail, head, inherited } = pinned;+ const at = new Date().toISOString();+ value.obligations.converged = { ...converged!, passes_since_full: converged!.passes_since_full + 1 };+ value.obligations.stuck_since = null;+ // Design §7: an owner approval (--yes) on an idle tick still makes an unknown cost known again.+ if (opts.costApproved && value.obligations.cost?.approved_usd === null) value.obligations.cost = (await passCostDecision(engine, { sourceId, incarnation,+ scope: episode?.full_id ?? passId, priorRow: true, prior: value.obligations.cost, approved: true })).cost;+ value.telemetry = { ...value.telemetry, outcome: 'up_to_date', ended_at: at, duration_ms: Date.now() - started, timings_ms: { setup: kindStarted - started, kind: Date.now() - kindStarted } };+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {+ assertActive();+ // One round trip: the lease check, the stamp and the row (started at the transaction's clock) are pipelined; a lost+ // lease rolls the other two back.+ await pipelined(tx, [() => assertDrainLease(tx, sourceId), () => tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]),+ () => writePassRow(tx, value, { pin: true, clock: true })]);+ }, principalAttribution(authority.writer.principal)));+ // A failure is recorded only under the lease this pass holds, so none recorded at pin means none to clear.+ if (failed.length) await clearPassFailures(engine, sourceId, incarnation);+ // Nor can a tail be owed since the pin read none: the lease's holder reads none after it (sync-run.ts).+ lease.tailClear = !tail;+ return { ...emptyPassResult(context, remote, 'up_to_date'), toCommit: remote ? '' : head, ...(inherited.length ? { inherited_options: inherited } : {}) };+}++/**+ * A round's unsettled paths by what the pass does with them: deletes and imports to batch, in-flight writes to wait for,+ * settle mismatches, and owed paths it cannot settle. A path settled earlier in this pass is admitted at most once more.+ */+async function triageRound(level: ShadowLevel, input: { S: Map<string, string>; legacyWaived: Set<string>; readmitted: Set<string>; admission: string; remote: boolean;+ counts: { pausedDeletes: number } }) {+ const { S, legacyWaived, readmitted, admission, remote, counts } = input;+ const settledKey = (path: string, levelOid: string | null) => `${path}\0${levelOid ?? ''}`;+ const deletes: ShadowPath[] = [], imports: ShadowPath[] = [], inFlight: ShadowPath[] = [], mismatch: ShadowPath[] = [], owed: ShadowPath[] = [];+ const heldRenameOrigins = new Set(level.heldRenames.map(held => syncOriginPath(held.rename.sourcePath)));+ const step = loopYield();+ for (const entry of level.paths) {+ if (step.due()) await step.pause();+ const r = entry.result;+ if (r.settled) continue;+ if (r.inFlight) { inFlight.push(entry); continue; }+ if (S.has(settledKey(entry.path, entry.state.level))) {+ // A hold this pass wrote or re-screened at L, or a slug collision it skipped, is that path's fate here, even when+ // its code re-screens every pass or the skipped twin still classifies as an import.+ if (entry.state.hold?.atLevel || S.get(settledKey(entry.path, entry.state.level)) === 'collision'+ || legacyWaived.has(settledKey(entryPaths(level, entry.path).path, entry.state.level))) continue;+ // Design §3.1: admitted at most once more per (path, level) in this pass, then counted as a settle mismatch.+ const again = settledKey(entry.path, entry.state.level);+ if (readmitted.has(again)) { mismatch.push(entry); continue; }+ readmitted.add(again);+ }+ if (r.action === 'delete') {+ if (heldRenameOrigins.has(syncOriginPath(entryPaths(level, entry.path).sourcePath))) { S.set(settledKey(entry.path, entry.state.level), 'rename_held'); continue; }+ if (admission !== 'normal') { S.set(settledKey(entry.path, entry.state.level), 'paused_deletes'); counts.pausedDeletes++; continue; }+ deletes.push(entry);+ } else if (r.action === 'import' || r.action === 'reparse' || (!remote && (r.cls === 'drift' || r.cls === 'dirty'))) imports.push(entry);+ else owed.push(entry);}+ return { deletes, imports, inFlight, mismatch, owed };+}++/**+ * v3 §3.3: a pass that finds nothing at last_commit = T admits no checkpoint; it keeps master's up_to_date (only+ * last_sync_at), and its full round refreshes the converged watermark so the next tick can be idle.+ */+async function stampUnchangedPass(engine: BrainEngine, input: SyncPassInput, round: { value: ManagedSyncPassValue; level: ShadowLevel; head: string; kind: PassKind;+ converged: ManagedSyncPassValue['obligations']['converged']; parserFp: string; pack: string | null; selectionFp: string; passId: string; startedAt: string; started: number;+ counts: Record<string, number>; applied: ReturnType<typeof newPassApplyState> }): Promise<void> {+ const { context, authority, assertActive } = input;+ const { sourceId, incarnation } = context;+ const { value, level, head, kind, converged, parserFp, pack, selectionFp, passId, startedAt, started, counts, applied } = round;+ const at = new Date().toISOString();+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {+ assertActive();+ await assertDrainLease(tx, sourceId);+ await tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]);+ // Holds on paths that left the level go with it here too, as a stamp releases them.+ for (const path of level.releasableHolds) await clearGitHold(tx, { sourceId, incarnation, path, observedAt: startedAt });+ await recordPassFenceTrend(tx, { worktreeId: context.binding.worktree_id, sourceId, passId, since: converged?.request_hwm ?? null });+ const watermark = await readConvergedWatermark(tx, { worktreeId: context.binding.worktree_id, sourceId, incarnation }, null, OPEN_AT_STAMP_CAP);+ value.obligations.converged = { target: head, at, ...watermark, parser_fp: parserFp, pack, selection_fp: selectionFp,+ last_full_at: kind === 'full' || !converged ? at : converged.last_full_at, passes_since_full: kind === 'full' || !converged ? 0 : converged.passes_since_full + 1 };+ Object.assign(value.obligations, { not_converged_streak: 0, mismatch: {}, stuck_since: null });+ value.telemetry = { ...value.telemetry, outcome: 'up_to_date', ended_at: at, remaining: 0, duration_ms: Date.now() - started, counts: { ...counts, ...passApplyCounts(applied) },+ classes: applied.classes, ...(applied.summary ? { summary: applied.summary } : {}) };+ await writePassRow(tx, value);+ }, principalAttribution(authority.writer.principal)));+}++/**+ * Design §3.1: a path settled in this pass that does not classify settled is a settle mismatch, counted per (path, level)+ * across passes (lane B turns a streak of SETTLE_MISMATCH_STREAK into a settle_mismatch hold).+ */+function mismatchStreaks(before: ManagedSyncPassValue['obligations']['mismatch'], mismatched: ShadowPath[]): ManagedSyncPassValue['obligations']['mismatch'] {+ return Object.fromEntries(mismatched.map(entry => {+ const seen = before?.[entry.path];+ return [entry.path, { level: entry.state.level, streak: seen && seen.level === entry.state.level ? seen.streak + 1 : 1 }];+ }));+}++/** The pass of one managed, non-company source (module header). */+export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Promise<SyncResult> {+ const { opts, context, authority, assertActive } = input;+ const { sourceId, incarnation } = context;+ const remote = authority.writer.remote;+ const lease = currentDrainLease(sourceId);+ if (!lease) throw new Error(`The live sync pass of ${sourceId} runs only under the source's drain lease.`);+ lease.tailClear = false;+ const started = Date.now(), startedAt = new Date(started).toISOString();+ const pinned = await pinPass(engine, input, lease, started);+ if (pinned.ended) return pinned.ended;+ const { prior, admission, tail, retry, failed, mode, selection, configured, selectionFp, parserFp, obligations, passId, optOutEpisode,+ processingOptions, inherited, pack, converged, cacheKey, working, kind, value, markersOwed } = pinned;+ let { head, episode } = pinned;++ if (kind === 'idle' && working.cache) rememberWorkingStatCache(cacheKey, working.cache);+ if (kind === 'idle') return stampIdlePass(engine, input, lease, started, pinned);// Design §7: the cost decision at pin; an unknown or spent envelope defers embeddings for this pass (never inherited).const costScope = episode?.full_id ?? passId;const costDecision = await passCostDecision(engine, { sourceId, incarnation, scope: costScope, priorRow: !!prior, prior: obligations.cost, approved: opts.costApproved === true });@@ -589,32 +693,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrassertActive();if (applied.sweptAll && !value.obligations.legacy_sweep) value.obligations.legacy_sweep = { first_full_at: new Date().toISOString() };if (!remote) value.obligations.deletes_withheld = applied.withheld?.set_hash ?? null;- const deletes: ShadowPath[] = [], imports: ShadowPath[] = [], inFlight: ShadowPath[] = [], mismatch: ShadowPath[] = [], owed: ShadowPath[] = [];+ const { deletes, imports, inFlight, mismatch, owed } = await triageRound(level, { S, legacyWaived, readmitted, admission, remote, counts });lastMismatch = mismatch;- const heldRenameOrigins = new Set(level.heldRenames.map(held => syncOriginPath(held.rename.sourcePath)));- const step = loopYield();- for (const entry of level.paths) {- if (step.due()) await step.pause();- const r = entry.result;- if (r.settled) continue;- if (r.inFlight) { inFlight.push(entry); continue; }- if (S.has(settledKey(entry.path, entry.state.level))) {- // A hold this pass wrote or re-screened at L, or a slug collision it skipped, is that path's fate here, even when- // its code re-screens every pass or the skipped twin still classifies as an import.- if (entry.state.hold?.atLevel || S.get(settledKey(entry.path, entry.state.level)) === 'collision'- || legacyWaived.has(settledKey(entryPaths(level, entry.path).path, entry.state.level))) continue;- // Design §3.1: admitted at most once more per (path, level) in this pass, then counted as a settle mismatch.- const again = settledKey(entry.path, entry.state.level);- if (readmitted.has(again)) { mismatch.push(entry); continue; }- readmitted.add(again);- }- if (r.action === 'delete') {- if (heldRenameOrigins.has(syncOriginPath(entryPaths(level, entry.path).sourcePath))) { S.set(settledKey(entry.path, entry.state.level), 'rename_held'); continue; }- if (admission !== 'normal') { S.set(settledKey(entry.path, entry.state.level), 'paused_deletes'); counts.pausedDeletes++; continue; }- deletes.push(entry);- } else if (r.action === 'import' || r.action === 'reparse' || (!remote && (r.cls === 'drift' || r.cls === 'dirty'))) imports.push(entry);- else owed.push(entry);- }// Origins that differ only by case or separator spelling may be one file on another platform: refuse rather than guess, as discovery does.const spelled = owed.filter(entry => entry.result.cls === 'spelling').map(entry => entryPaths(level, entry.path).sourcePath);if (spelled.length) {@@ -651,24 +731,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr}if (mismatch.length || owed.length) break;if (round === 1 && configured && context.source.last_commit === head && !episode && !retry.length && !tail && !value.obligations.slug_mode) {- // v3 §3.3: a pass that finds nothing at last_commit = T admits no checkpoint; it keeps master's up_to_date (only- // last_sync_at), and its full round refreshes the converged watermark so the next tick can be idle.- const at = new Date().toISOString();- await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {- assertActive();- await assertDrainLease(tx, sourceId);- await tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [sourceId, incarnation]);- // Holds on paths that left the level go with it here too, as a stamp releases them.- for (const path of level.releasableHolds) await clearGitHold(tx, { sourceId, incarnation, path, observedAt: startedAt });- await recordPassFenceTrend(tx, { worktreeId: context.binding.worktree_id, sourceId, passId, since: converged?.request_hwm ?? null });- const watermark = await readConvergedWatermark(tx, { worktreeId: context.binding.worktree_id, sourceId, incarnation }, null, OPEN_AT_STAMP_CAP);- value.obligations.converged = { target: head, at, ...watermark, parser_fp: parserFp, pack, selection_fp: selectionFp,- last_full_at: kind === 'full' || !converged ? at : converged.last_full_at, passes_since_full: kind === 'full' || !converged ? 0 : converged.passes_since_full + 1 };- Object.assign(value.obligations, { not_converged_streak: 0, mismatch: {}, stuck_since: null });- value.telemetry = { ...value.telemetry, outcome: 'up_to_date', ended_at: at, remaining: 0, duration_ms: Date.now() - started, counts: { ...counts, ...passApplyCounts(applied) },- classes: applied.classes, ...(applied.summary ? { summary: applied.summary } : {}) };- await writePassRow(tx, value);- }, principalAttribution(authority.writer.principal)));+ // v3 §3.3: a pass that finds nothing at last_commit = T admits no checkpoint (`stampUnchangedPass`).+ await stampUnchangedPass(engine, input, { value, level, head, kind, converged, parserFp, pack, selectionFp, passId, startedAt, started, counts, applied });rememberLevel();await clearPassFailures(engine, sourceId, incarnation);await finishPassApply(engine, sourceId, applied);@@ -726,11 +790,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr// Not converged (design §3.1): four rounds, or a settle mismatch or a path this release cannot settle.// A path settled in this pass that does not classify settled is a settle mismatch: counted per (path, level) across// passes; lane B turns a streak of SETTLE_MISMATCH_STREAK into a settle_mismatch hold.- const before = value.obligations.mismatch;- value.obligations.mismatch = Object.fromEntries(lastMismatch.map(entry => {- const seen = before[entry.path];- return [entry.path, { level: entry.state.level, streak: seen && seen.level === entry.state.level ? seen.streak + 1 : 1 }];- }));+ value.obligations.mismatch = mismatchStreaks(value.obligations.mismatch, lastMismatch);value.obligations.not_converged_streak = (value.obligations.not_converged_streak ?? 0) + 1;await finishPassApply(engine, sourceId, applied);await save('resumable', 'not_converged');diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 05c51f795e..f312903a74 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -14,7 +14,7 @@ import { preflightSyncCapacity } from './sync-capacity-preflight.ts';import { preparationConfigView } from './config-snapshot.ts';import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';-import { assertSyncEntryOrigin, discoverManagedSync, readManagedSyncRows, resolveManagedSyncContext, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.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';import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';@@ -1252,6 +1252,97 @@ async function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: {}}+/** ENG-A7: admits the cursor's frozen head while the cursor (or the pass batch) still holds it, under the drain lease; null when the cursor moved. */+function admitPendingWrite(engine: BrainEngine, key: string, admitting: Cursor, pending: Pending, assertActive: () => void) {+ return retryWriteAdmission(pending.requestId, remaining => engine.transaction(async tx => {+ assertActive();+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",+ [`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);+ const accepted = await admitWriteInTransaction(tx, { requestId: pending.requestId, operation: 'submit_job',+ sourceId: admitting.sourceId, sourceIncarnation: admitting.incarnation, slug: pending.slug, pageId: pending.pageId,+ worktreeId: admitting.binding.worktree_id, topologyGeneration: admitting.binding.topology_generation, ownerEpoch: admitting.binding.owner_epoch,+ principal: admitting.authority.writer.principal, authority: admitting.authority.writer, callerIntent: pending.intent, intent: pending.intent });+ // ENG-A7: after the counter locks (the publication lock order), admit only while the cursor still holds this entry+ // with this intent (#6075: a bulk pass may have grouped the head since this pass read it).+ if (isPassBatchKey(key)) {+ // #6712 PR 4b: a pass batch has no cursor row; the lease (below) fences it, and the batch must still hold this entry.+ const head = readPassBatch<Cursor>(key)?.pending;+ if (head?.requestId !== pending.requestId || digest(head.intent) !== digest(pending.intent)) throw new CursorMoved();+ } else {+ const [held] = await tx.executeRaw<{ request_id: string | null; same: boolean | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id,+ completed_keys->0->'pending'->'intent' = $3::text::jsonb AS same FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, JSON.stringify(pending.intent)]);+ if (held?.request_id !== pending.requestId || held.same !== true) throw new CursorMoved();+ }+ await assertDrainLease(tx, admitting.sourceId);+ await assertPassAdmission(tx, [pending.intent]);+ assertActive();+ return accepted;+ }), undefined, error => engine.reconnect({ error })).catch(error => cursorMovedAdmission(engine, key, admitting, pending, error));+}++/** A pass's recovered, normalized and converted totals, summed over its batches. */+type PassTotals = { recovered?: Cursor['counts']['recovered']; fences?: FencesTally; converted: string[] };+function foldPassTotals(totals: PassTotals, done: Cursor): void {+ const sum = (a: Record<string, number> = {}, b: Record<string, number> = {}) => Object.fromEntries([...new Set([...Object.keys(a), ...Object.keys(b)])].map(k => [k, (a[k] ?? 0) + (b[k] ?? 0)]));+ const { recovered, fences } = done.counts;+ if (recovered) totals.recovered = { count: (totals.recovered?.count ?? 0) + recovered.count, sample_paths: [...totals.recovered?.sample_paths ?? [], ...recovered.sample_paths].slice(0, 5),+ ...((totals.recovered?.comment_values ?? 0) + (recovered.comment_values ?? 0) ? { comment_values: (totals.recovered?.comment_values ?? 0) + (recovered.comment_values ?? 0) } : {}) };+ if (fences) totals.fences = { count: (totals.fences?.count ?? 0) + fences.count, by_class: sum(totals.fences?.by_class, fences.by_class),+ sample_paths: [...totals.fences?.sample_paths ?? [], ...fences.sample_paths].slice(0, 5), dirs: sum(totals.fences?.dirs, fences.dirs) };+ totals.converted = [...new Set([...totals.converted, ...done.convertedFromFailed ?? []])];+}++/** #6712: whether a stopped company-brain run re-freezes its head with this run's processing options (an approved run keeps its own). */+async function companyRetryOwed(engine: BrainEngine, cursor: Cursor, companyStop: NonNullable<Awaited<ReturnType<typeof recordedStop>>>,+ run: { processingOptions: NonNullable<Cursor['processingOptions']>; syncOptions: Cursor['syncOptions']; repoPath: string | undefined; assertActive: () => void }): Promise<boolean> {+ const { processingOptions, syncOptions, assertActive } = run;+ const failed = cursor.pending ? await getWriteRequest(engine, admittedBy(cursor.pending, cursor), cursor.pending.requestId) : null;+ const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [cursor.sourceId]);+ assertActive();+ // #6712: a legacy knock-on is re-frozen in place by the drain (refreezeInPlace), within its stop bound.+ // The approved manifest pins the content, so a content refusal this version recorded replays until the approval changes.+ if (!(!unfinished.length && (failed && ['failed', 'conflict', 'cancelled'].includes(failed.state) && !isSyncKnockOn(failed) && !replaysContentRefusal(failed, companyStop, () => true)+ || !cursor.pending && !cursor.processingOptions))) return false;+ if (cursor.processingOptions && digest(cursor.processingOptions) !== digest(processingOptions)) {+ throw syncRunRefusal('invalid_params', 'The approved company sync must retain its original processing options.',+ { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath: run.repoPath },+ `The unfinished company-brain sync of source ${cursor.sourceId} was approved with ${SYNC_PROCESSING_KEYS.map(key => `${key}=${cursor!.processingOptions![key]}`).join(', ')}, and its retry must keep exactly those processing options; nothing was retried.`);+ }+ return true;+}++/** A cursor written under an older source binding (incarnation, worktree, topology, owner epoch or root) never drains. */+function assertCursorBinding(cursor: Cursor, context: ManagedSyncContext, syncOptions: Cursor['syncOptions'], repoPath: string | undefined): void {+ if (cursor.incarnation !== context.incarnation || cursor.binding.worktree_id !== context.binding.worktree_id ||+ String(cursor.binding.topology_generation) !== String(context.binding.topology_generation) ||+ String(cursor.binding.owner_epoch) !== String(context.binding.owner_epoch) || cursor.root !== context.root) {+ throw syncRunRefusal('source_changed', 'The unfinished sync cursor belongs to an older source binding.',+ { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath },+ `The unfinished sync cursor of source ${cursor.sourceId} was written under an older binding (its owner epoch, topology generation, worktree or root changed since), so this run stopped without importing; the retry rediscovers against the current binding.`);+ }+}++/** Records a run's failure (not transient back-pressure, a lost connection or a statement timeout) and points its message at the retry. */+async function recordRunFailure(engine: BrainEngine, error: unknown, run: { cursor: Cursor | null; key: string; phase: ManagedSyncFailure['phase']; discoveryTarget: string | null;+ discoveryRun: string; context: ManagedSyncContext; remote: boolean; syncOptions: Cursor['syncOptions']; processingOptions: NonNullable<Cursor['processingOptions']>; repoPath: string | undefined }): Promise<void> {+ const { cursor, key, phase, discoveryTarget, discoveryRun, context, syncOptions, processingOptions } = run;+ const code = error instanceof OperationError ? error.code : 'storage_error';+ // A refresh fence, or an admission refused while other requests hold the writer's outstanding cap (#6278: the drain+ // waits for them), is transient admission back-pressure, not a sync failure to record. #6340: neither is a lost+ // database connection or a statement timeout: the cursor and its frozen manifest stay, and the next pass resumes them.+ if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code) && !isWriteCapacityWait(error) && !(error instanceof LockStolenError)+ && !isRetryableConnError(error) && !isStatementTimeoutError(error)) {+ const [stored] = cursor ? [] : await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]);+ const failedCursor = cursor ?? stored?.completed_keys?.[0];+ const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,+ message: error instanceof Error ? error.message : String(error), request_id: failedCursor?.pending?.requestId ?? null,+ run_id: failedCursor?.runId ?? discoveryRun, target: failedCursor?.target ?? discoveryTarget, cursor_key: cursor?.failureKey ?? key,+ syncOptions: failedCursor?.syncOptions ?? syncOptions, processingOptions: failedCursor?.processingOptions ?? processingOptions, phase, state: 'failed',+ observation_id: failedCursor ? `${failedCursor.runId}:${failedCursor.index}:${phase}:${code}` : `${key}:discovery:${discoveryTarget}:${code}` });+ if (error instanceof Error) error.message = run.remote ? 'Managed sync is blocked; ask the host operator to inspect doctor.' : `${formatManagedSyncFailure(failure)} Fix the cause, then run: ${managedSyncRetryCommand(failure, run.repoPath)}`;+ }+}+/*** #6712 PR 1: the key this pass reads and the older keys folded in (`resolveManagedCursor`). A remote caller folds nothing* in: the cursors it would cancel or retire may belong to another principal (it adopts only its own). A superseded run's@@ -1397,30 +1488,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPcontinue;}const admitting = cursor;- const row = prior ?? await retryWriteAdmission(pending.requestId, remaining => engine.transaction(async tx => {- assertActive();- await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",- [`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);- const accepted = await admitWriteInTransaction(tx, { requestId: pending.requestId, operation: 'submit_job',- sourceId: admitting.sourceId, sourceIncarnation: admitting.incarnation, slug: pending.slug, pageId: pending.pageId,- worktreeId: admitting.binding.worktree_id, topologyGeneration: admitting.binding.topology_generation, ownerEpoch: admitting.binding.owner_epoch,- principal: admitting.authority.writer.principal, authority: admitting.authority.writer, callerIntent: pending.intent, intent: pending.intent });- // ENG-A7: after the counter locks (the publication lock order), admit only while the cursor still holds this entry- // with this intent (#6075: a bulk pass may have grouped the head since this pass read it).- if (isPassBatchKey(key)) {- // #6712 PR 4b: a pass batch has no cursor row; the lease (below) fences it, and the batch must still hold this entry.- const head = readPassBatch<Cursor>(key)?.pending;- if (head?.requestId !== pending.requestId || digest(head.intent) !== digest(pending.intent)) throw new CursorMoved();- } else {- const [held] = await tx.executeRaw<{ request_id: string | null; same: boolean | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id,- completed_keys->0->'pending'->'intent' = $3::text::jsonb AS same FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, JSON.stringify(pending.intent)]);- if (held?.request_id !== pending.requestId || held.same !== true) throw new CursorMoved();- }- await assertDrainLease(tx, admitting.sourceId);- await assertPassAdmission(tx, [pending.intent]);- assertActive();- return accepted;- }), undefined, error => engine.reconnect({ error })).catch(error => cursorMovedAdmission(engine, key, admitting, pending, error));+ const row = prior ?? await admitPendingWrite(engine, key, admitting, pending, assertActive);if (!row) { cursor = await currentCursor(engine, key, cursor); continue; }await validateSyncAuthority(engine, cursor.authority, pending.slug);assertSyncDispatchActive(); stampDrainStep('await_receipt', signal);@@ -1490,8 +1558,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP// runs keep the frozen manifest and its cursor.if (!company && !opts.dryRun) {// The run's report reads the recovered, normalized and converted totals of every batch of the pass, not its last (stamp) batch.- const totals: { recovered?: Cursor['counts']['recovered']; fences?: FencesTally; converted: string[] } = { converted: [] };- const sum = (a: Record<string, number> = {}, b: Record<string, number> = {}) => Object.fromEntries([...new Set([...Object.keys(a), ...Object.keys(b)])].map(k => [k, (a[k] ?? 0) + (b[k] ?? 0)]));+ const totals: PassTotals = { converted: [] };let folded: Cursor | null = null;state.cursor = () => live.cursor ? { ...live.cursor, counts: { ...live.cursor.counts, recovered: totals.recovered, fences: totals.fences }, convertedFromFailed: totals.converted } : null;return await runSyncPass(engine, { opts, slice, context, authority, processingOptions, syncOptions, assertActive, signal, state, runStartedAt,@@ -1511,12 +1578,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst done = live.cursor;if (done?.passId && done !== folded) {folded = done;- const { recovered, fences } = done.counts;- if (recovered) totals.recovered = { count: (totals.recovered?.count ?? 0) + recovered.count, sample_paths: [...totals.recovered?.sample_paths ?? [], ...recovered.sample_paths].slice(0, 5),- ...((totals.recovered?.comment_values ?? 0) + (recovered.comment_values ?? 0) ? { comment_values: (totals.recovered?.comment_values ?? 0) + (recovered.comment_values ?? 0) } : {}) };- if (fences) totals.fences = { count: (totals.fences?.count ?? 0) + fences.count, by_class: sum(totals.fences?.by_class, fences.by_class),- sample_paths: [...totals.fences?.sample_paths ?? [], ...fences.sample_paths].slice(0, 5), dirs: sum(totals.fences?.dirs, fences.dirs) };- totals.converted = [...new Set([...totals.converted, ...done.convertedFromFailed ?? []])];+ foldPassTotals(totals, done);}}} });@@ -1529,23 +1591,10 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPif (cursor && !cursor.done && !opts.dryRun) cursor = await adoptCursor(engine, key, cursor, { authority, processingOptions, embedDeferred: opts.embedDeferred, assertActive });assertActive();const companyStop = company && cursor && !cursor.done && !opts.dryRun ? await recordedStop(engine, key, cursor.runId) : null;- if (companyStop && cursor) {- const failed = cursor.pending ? await getWriteRequest(engine, admittedBy(cursor.pending, cursor), cursor.pending.requestId) : null;- const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [cursor.sourceId]);- assertActive();- // #6712: a legacy knock-on is re-frozen in place by the drain (refreezeInPlace), within its stop bound.- // The approved manifest pins the content, so a content refusal this version recorded replays until the approval changes.- if (!unfinished.length && (failed && ['failed', 'conflict', 'cancelled'].includes(failed.state) && !isSyncKnockOn(failed) && !replaysContentRefusal(failed, companyStop, () => true)- || !cursor.pending && !cursor.processingOptions)) {- if (cursor.processingOptions && digest(cursor.processingOptions) !== digest(processingOptions)) {- throw syncRunRefusal('invalid_params', 'The approved company sync must retain its original processing options.',- { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath: frozenRun.repoPath },- `The unfinished company-brain sync of source ${cursor.sourceId} was approved with ${SYNC_PROCESSING_KEYS.map(key => `${key}=${cursor!.processingOptions![key]}`).join(', ')}, and its retry must keep exactly those processing options; nothing was retried.`);- }- phase = 'freeze';- const retry = { ...cursor, processingOptions };- cursor = await saveCursor(engine, key, cursor, { ...retry, pending: await freezeEntry(engine, retry, key, assertActive, frozenRun) as Pending }, true, assertActive);- }+ if (companyStop && cursor && await companyRetryOwed(engine, cursor, companyStop, { processingOptions, syncOptions, repoPath: frozenRun.repoPath, assertActive })) {+ phase = 'freeze';+ const retry = { ...cursor, processingOptions };+ cursor = await saveCursor(engine, key, cursor, { ...retry, pending: await freezeEntry(engine, retry, key, assertActive, frozenRun) as Pending }, true, assertActive);}const startupConfig = await preparationConfigView(engine); // #5984 G3: one config read answers the startup's config readsassertActive();@@ -1581,13 +1630,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPfresh.retryTaken?.length ? tx => clearGitHoldRetryPaths(tx, fresh.sourceId, fresh.incarnation, fresh.retryTaken!) : undefined);}assertActive();- if (cursor.incarnation !== context.incarnation || cursor.binding.worktree_id !== context.binding.worktree_id ||- String(cursor.binding.topology_generation) !== String(context.binding.topology_generation) ||- String(cursor.binding.owner_epoch) !== String(context.binding.owner_epoch) || cursor.root !== context.root) {- throw syncRunRefusal('source_changed', 'The unfinished sync cursor belongs to an older source binding.',- { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath: frozenRun.repoPath },- `The unfinished sync cursor of source ${cursor.sourceId} was written under an older binding (its owner epoch, topology generation, worktree or root changed since), so this run stopped without importing; the retry rediscovers against the current binding.`);- }+ assertCursorBinding(cursor, context, syncOptions, frozenRun.repoPath);if (opts.dryRun) return dryRun(cursor);return await drainCursor(cursor, startupConfig) as SyncResult;} catch (error) {@@ -1600,21 +1643,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPadded: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], filesImported: 0, bankedFiles: 0 };}if (!opts.dryRun) {- const code = error instanceof OperationError ? error.code : 'storage_error';- // A refresh fence, or an admission refused while other requests hold the writer's outstanding cap (#6278: the drain- // waits for them), is transient admission back-pressure, not a sync failure to record. #6340: neither is a lost- // database connection or a statement timeout: the cursor and its frozen manifest stay, and the next pass resumes them.- if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code) && !isWriteCapacityWait(error) && !(error instanceof LockStolenError)- && !isRetryableConnError(error) && !isStatementTimeoutError(error)) {- const [stored] = cursor ? [] : await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]);- const failedCursor = cursor ?? stored?.completed_keys?.[0];- const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,- message: error instanceof Error ? error.message : String(error), request_id: failedCursor?.pending?.requestId ?? null,- run_id: failedCursor?.runId ?? discoveryRun, target: failedCursor?.target ?? discoveryTarget, cursor_key: cursor?.failureKey ?? key,- syncOptions: failedCursor?.syncOptions ?? syncOptions, processingOptions: failedCursor?.processingOptions ?? processingOptions, phase, state: 'failed',- observation_id: failedCursor ? `${failedCursor.runId}:${failedCursor.index}:${phase}:${code}` : `${key}:discovery:${discoveryTarget}:${code}` });- if (error instanceof Error) error.message = authority.writer.remote ? 'Managed sync is blocked; ask the host operator to inspect doctor.' : `${formatManagedSyncFailure(failure)} Fix the cause, then run: ${managedSyncRetryCommand(failure, frozenRun.repoPath)}`;- }+ await recordRunFailure(engine, error, { cursor, key, phase, discoveryTarget, discoveryRun, context, remote: authority.writer.remote, syncOptions, processingOptions, repoPath: frozenRun.repoPath });}throw error;}