Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: #6694 slug-mode checkpoint at the repository root; write-only import provenance (#6712 PR 0)
garrytan73b6f6265159
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3b9a844083..3d8e745694 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 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 1687 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+src/core/persistence/sync-run.ts 1689 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/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent blocksrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 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 ondiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 5b52a20d76..ed4eb50699 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -627,6 +627,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Large pages A3/T44, A4/T32 (Lane 3a).{ since: '0.60.242.0', text: 'Replacing a page\'s chunks now writes them in bounded batches (at most 500 rows and 16 MiB of encoded rows per statement) after one prune, all in the same transaction, instead of one statement carrying every chunk. A page with thousands of chunks no longer builds one giant statement, and a failure in any batch still rolls the whole replacement back.' },{ since: '0.60.242.0', text: 'A chunk vector is now tied to the chunk\'s text and its full embedding input rather than its position. When an edit inserts or removes chunks above it, a projection rebuild moves the unchanged chunk to its new index with its vector instead of dropping it, so only new or changed chunks wait for embedding. An embed that finishes after the page changed now commits the vectors of the chunks that are still the same (same text, source and embedding input) and leaves the rest for the next run, instead of discarding the whole run; the page\'s embedding signature is stamped only when every chunk got its vector. A vector built under an old title or synopsis is still dropped.' },+ // #6712 PR 0 (#6694 + write-only provenance); `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.243.0', text: 'A managed sync of a source rooted at its Git repository root now checkpoints whichever `slug_root_mode` the source pins (both modes give it the same slugs) and keeps that pin; before, a `source-root` pin failed every checkpoint with `revision_conflict`. A plain `gbrain sync --no-pull --source <id>` now finishes a checkpoint that already failed this way. On a source in a subdirectory, a pin that changes while a sync runs is refused as `slug_root_mode_mismatch` (a person chooses the mode) instead of `revision_conflict`; restoring the pin lets the next plain sync finish. After a downgrade, an older gbrain reports these as `revision_conflict` again.' },+ { since: '0.60.243.0', text: 'Managed-sync import provenance now also records the bytes each publish left on disk (`disk_sha256`, `disk_blob_oid`: the canonical writeback when sync rewrote the file), the page revision it produced and what parsed it (import parser version, Markdown chunker, schema pack), and a sync that skips an unchanged file records the same. Nothing reads these yet; a later release uses them to skip unchanged files. Records written before this release lack them and are replaced on the next import of their page; an older gbrain ignores them.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 0a1b4b4541..c25f50c502 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -460,6 +460,13 @@ export const CODES = {fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false,why: 'Read-only: lists the held file with the slug sync files it as and its fix, which names the exact edit and the content-repair preview; nothing is written.',verify: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'] } } },+ // #6694: a managed-sync checkpoint whose run's slug-root mode is not the mode the source pins (a subdirectory source only).+ slug_root_mode_mismatch: { class: 'caller', actor: 'user',+ summary: "A managed sync of a subdirectory source ran under one slug-root mode while the source pins the other (sources.config.slug_root_mode), so its checkpoint did not advance.",+ why: "At a subdirectory the two modes give different slugs (git-root keeps the subdirectory prefix, source-root does not), and the pin exists so a later sync never re-namespaces the source; the pages this run wrote already carry its mode. The pin changed after the run was discovered. A source rooted at its repository root never gets this code: both modes give it identical slugs, and its checkpoint keeps the pin it has. Older releases reported this refusal as revision_conflict.",+ suggestion: 'Ask the user which mode the source keeps. To keep the mode the run used, set sources.config.slug_root_mode back to it and run gbrain sync --no-pull --source <id>; the refused checkpoint is retried by itself. To keep the new pin, run gbrain sync --no-pull --source <id> --retry-failed, which discovers the source again under it; the pages the refused run wrote keep their old slugs beside the new ones.',+ fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Read-only: last_error names the pinned mode and the mode the run used; the choice between them is the user\'s.' } },source_binding_required: { class: 'caller', summary: "A write needs an explicit source binding on this MCP server (--source-guard)." },source_changed: { class: 'caller', summary: "The source changed during the operation; nothing was committed.", why: "Covers a replaced, archived or re-bound source and a canonical file that differs from the page's database copy (detail file_database_drift). A page that records no file of its own reconciles against the file at its slug path only with gbrain sources reconcile <source> <slug> --preview --adopt-slug-path. A canonical file that is gone while its page is live (reason canonical_file_missing, a ghost page) never clears by retrying or syncing: a person restores the file and syncs, or removes the page (docs/guides/write-refusals.md#canonical_file_missing)." },source_id_taken: { class: 'caller', summary: "This source already exists and does not match this exact admitted request." },diff --git a/src/core/persistence/digest.ts b/src/core/persistence/digest.tsindex 56f0219083..38e95c2cec 100644--- a/src/core/persistence/digest.ts+++ b/src/core/persistence/digest.ts@@ -20,6 +20,8 @@ export function stableJson(value: unknown): string {}export function digest(value: unknown): string { return sha256(stableJson(value)); }export function sha256(value: string | Uint8Array): string { return createHash('sha256').update(value).digest('hex'); }+/** Git's blob id of `bytes` (`git hash-object --no-filters`) in the repository's object format. */+export function gitBlobOid(bytes: Uint8Array, format: 'sha1' | 'sha256'): string { return createHash(format).update(`blob ${bytes.length}\0`).update(bytes).digest('hex'); }export function jsonBytes(value: unknown): number { return Buffer.byteLength(stableJson(value), 'utf8'); }export function requireUuid(value: string): string {if (!isWriteRequestId(value)) {diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex 4491e8e43f..43611cb3d2 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -98,6 +98,9 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [{ code: 'write_quota_insufficient', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always',human_reason: 'The run needs more write capacity than is left; the brain host runs the gbrain config set the error prints, then reruns the same sync.' },{ code: 'plan_stale', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The approved company-brain manifest changed; inspect and approve the repository again.' },+ // #6694: the source's pinned slug-root mode changed under a run of a subdirectory source; the checkpoint waits for the choice.+ { code: 'slug_root_mode_mismatch', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: the two modes give different slugs',+ human_reason: 'The source pins one slug-root mode and the sync ran under the other. A person chooses: set sources.config.slug_root_mode back to the mode the run used and rerun gbrain sync --no-pull --source <source> (the checkpoint is retried by itself), or keep the pin and run gbrain sync --no-pull --source <source> --retry-failed (the pages the refused run wrote keep their old slugs beside the new ones).' },{ code: 'invalid_params', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The resume options conflict with the stored cursor; use the resume command the error prints.' },// #6518: bookkeeping of an incarnation the source no longer has; a retry selects a different key, so only the repair clears it.{ code: 'cursor_incarnation_retired', class: 'systemic', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview lists nothing to retire, or the same code returns after the apply' },diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 2f4ddaf0ae..0ddeb1f9e8 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -45,6 +45,8 @@ import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/import type { SyncRename } from './sync-discovery.ts';import { isMultimodalEnabled } from '../sync.ts';import { VERSION } from '../../version.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';+import { gitBlobOid, sha256 } from './digest.ts';export const GIT_HOLD_OP = 'sync-hold';export const GIT_HOLD_SUMMARY_OP = 'sync-hold-summary';@@ -679,6 +681,39 @@ export interface SyncImportProvenance {validated: true;recovery?: Array<{ kind: string; key: string; line: number; recovery_version: number }>;recorded_at: string;+ /**+ * #6712 PR 0 (write-only until a reader lands): the bytes the publish left on disk, the canonical writeback when it+ * wrote one, else the file as admitted; null when no file was on disk. `disk_blob_oid` is their Git blob id, comparable+ * with `git ls-tree` without reading the file. Absent on records written before the stamp, and on records a repair wrote.+ */+ disk_sha256?: string | null;+ disk_blob_oid?: string | null;+ /** The page revision the publish produced. Absent on older records. */+ revision?: string;+ /** What parsed the bytes: the import parser version, the Markdown chunker and the schema pack in effect (null for none). Absent on older records. */+ parser?: SyncImportParser;+}++/**+ * The version of the Markdown import's reading of a file: the frontmatter recovery rules and the fence screen, plus a+ * leading import counter to bump when the import's own parsing or canonical form changes. It deliberately leaves out the+ * release, so a parser fingerprint holds across releases that change no parsing.+ */+export const SYNC_IMPORT_PARSER_VERSION = `import=1;frontmatter=${RECOVERY_VERSION};fence=${FENCE_VERSION}`;++/** The provenance a preparation knows before its page is written; page id, revision and disk bytes come from the publication or the waiver that settles it. */+export type SyncImportProvenanceBase = Omit<SyncImportProvenance, 'page_id' | 'revision' | 'disk_sha256' | 'disk_blob_oid' | 'recorded_at' | 'validated'>;++export interface SyncImportParser { parser_version: string; markdown_chunker: number; schema_pack: string | null }++/** The disk half of an import provenance record for `bytes` (null: no file on disk), in the object format of `target`'s commit id. */+export function syncDiskProvenance(bytes: Uint8Array | null, target: string | null): Pick<SyncImportProvenance, 'disk_sha256' | 'disk_blob_oid'> {+ if (!bytes) return { disk_sha256: null, disk_blob_oid: null };+ return { disk_sha256: sha256(bytes), disk_blob_oid: gitBlobOid(bytes, target?.length === 64 ? 'sha256' : 'sha1') };+}++export function syncImportParser(schemaPack: string | null): SyncImportParser {+ return { parser_version: SYNC_IMPORT_PARSER_VERSION, markdown_chunker: MARKDOWN_CHUNKER_VERSION, schema_pack: schemaPack };}const provenanceFingerprint = (sourceId: string, incarnation: string, pageId: number) => `${sourceId}:${incarnation}:${pageId}`;@@ -690,6 +725,17 @@ export async function recordSyncImportProvenance(tx: Exec, value: Omit<SyncImpor[SYNC_IMPORT_PROVENANCE_OP, provenanceFingerprint(value.source_id, value.incarnation, value.page_id), JSON.stringify([record])]);}+/** Several pages' provenance in one statement (a waiver run); the last value for a page wins. */+export async function recordSyncImportProvenances(tx: Exec, values: ReadonlyArray<Omit<SyncImportProvenance, 'recorded_at' | 'validated'>>): Promise<void> {+ if (!values.length) return;+ const recorded_at = new Date().toISOString();+ const rows = new Map(values.map(value => [provenanceFingerprint(value.source_id, value.incarnation, value.page_id), { ...value, validated: true, recorded_at }]));+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)+ SELECT $1, entry->>'fingerprint', jsonb_build_array(entry->'record') FROM jsonb_array_elements($2::text::jsonb) AS entry+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,+ [SYNC_IMPORT_PROVENANCE_OP, JSON.stringify([...rows].map(([fingerprint, record]) => ({ fingerprint, record })))]);+}+/** The provenance of several pages in one statement, keyed by page id; pages without a record are absent. */export async function readSyncImportProvenances(engine: Exec, sourceId: string, incarnation: string, pageIds: readonly number[]): Promise<Map<number, SyncImportProvenance>> {if (!pageIds.length) return new Map();diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.tsindex d686a4228a..6af9c00976 100644--- a/src/core/persistence/sync-page-fault.ts+++ b/src/core/persistence/sync-page-fault.ts@@ -28,10 +28,9 @@* `needs_human` for a page that keeps moving. Only a systemic failure (the* preparation breaker, authority or binding loss) still ends a run.*/-import { createHash } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import { RECOVERY_VERSION } from '../markdown.ts';-import { sha256 } from './digest.ts';+import { gitBlobOid, sha256 } from './digest.ts';import type { WriteRequest } from './model.ts';import { readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry, type SyncRename } from './sync-discovery.ts';import { readTreeBlobs } from './sync-blobs.ts';@@ -44,11 +43,6 @@ export { HOLD_ATTEMPTS_NEEDS_HUMAN } from './sync-fault-class.ts';type HoldEntry = Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld' | 'action'>;-/** Git's blob id of `bytes` in the object format HEAD uses (sha1, or sha256 when HEAD's ids are 64 hex digits). */-function blobOid(bytes: Buffer, format: 'sha1' | 'sha256'): string {- return createHash(format).update(`blob ${bytes.length}\0`).update(bytes).digest('hex');-}-/*** The working-tree bytes of `path` when they are exactly what HEAD commits for it (their blob id equals* `HEAD:<path>`), with that blob id; null when the file is absent, differs from HEAD, or Git cannot answer.@@ -62,7 +56,7 @@ export function headCommittedBytes(context: Pick<SyncDiscovery, 'root' | 'gitRoolet head: { oid: string } | undefined;try { head = readTreeBlobs(context.gitRoot, 'HEAD', [gitPath]).get(gitPath); } catch { return null; }if (!head) return null;- const oid = blobOid(bytes, head.oid.length === 64 ? 'sha256' : 'sha1');+ const oid = gitBlobOid(bytes, head.oid.length === 64 ? 'sha256' : 'sha1');return oid === head.oid ? { content: bytes.toString('utf8'), oid, rawHash: sha256(bytes) } : null;}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 24e00fb229..b6c0b1077e 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -44,8 +44,9 @@ import { CURSOR_CHANGED_REFUSAL_MESSAGE, EARLIER_PAGE_REFUSAL_MESSAGE, knockOnDeimport { checkpointCursorReplaced } from './sync-checkpoint-replaced.ts';import { frontmatterSlugConflictMessage } from './verb-errors.ts';import { chunkerStamp } from '../chunkers/code.ts';-import { clearGitHold, countGitHolds, recordSyncImportProvenance } from './sync-holds.ts';+import { clearGitHold, countGitHolds, recordSyncImportProvenance, syncDiskProvenance, syncImportParser, type SyncImportProvenanceBase } from './sync-holds.ts';import { clearSyncSlice, writeSyncSlice, type SyncSliceState } from './sync-slices.ts';+import { CHECKPOINT_MOVED_MESSAGE, emptySyncScope, pinnedSlugModeMismatch, slugModeMismatchCause } from './sync-slug-mode.ts';import { readPagePurgeTombstones } from './page-purge.ts';import { fenceWhere } from '../fence-repair/refusal.ts';import { fencesNormalizeEnabled } from '../fence-repair/config.ts';@@ -404,6 +405,52 @@ async function prepareManagedSyncCode(engine: BrainEngine, row: WriteRequest, p:} };}+/** The bytes on disk of an import that writes no file back: its frozen content when that is the file (raw hash), else the file read now (null: absent). */+export function syncDiskBytes(root: string, path: string, content: string, rawHash: string | null): Uint8Array | null {+ return rawHash !== null && rawHash === sha256(content) ? Buffer.from(content) : readSyncFile(root, path);+}++/** The checkpoint request's publication: the whole run committed, so `last_commit` (and the slug-root pin) advance under the guard. */+async function applyManagedSyncCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, releaseHold: (tx: BrainEngine, path: string | null) => Promise<void>): Promise<Record<string, unknown>> {+ const [cursor] = await tx.executeRaw<{ completed_keys: [{ runId: string; index: number; total: number }] }>(+ "SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE", [p.cursorKey]);+ // #6513: validation passed under this run; a replacement that landed since is the same supersession, not an index lag.+ const replaced = checkpointCursorReplaced(p, cursor?.completed_keys[0]?.runId, row.source_id);+ if (replaced) throw syncPublicationRefusal(replaced.code, replaced.message, row, p, replaced.cause);+ if (!cursor || cursor.completed_keys[0].runId !== p.runId || cursor.completed_keys[0].index !== p.total || cursor.completed_keys[0].total !== p.total) {+ throw syncPublicationRefusal('revision_conflict', 'The sync cursor is not fully committed.', row, p,+ `Not every page write of this sync run has committed, so the checkpoint of ${row.source_id} did not advance.`);+ }+ const [manifest] = await tx.executeRaw<{ count: number }>("SELECT jsonb_array_length(completed_keys) AS count FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [p.runId]);+ if (!manifest || Number(manifest.count) !== p.total) throw syncPublicationRefusal('storage_error', 'The immutable sync manifest is incomplete.', row, p,+ `The immutable manifest of this sync run is incomplete, so the checkpoint of ${row.source_id} did not advance.`);+ const incomplete = await findIncompleteSyncReceipt(tx, row.worktree_id!, p.runId, p.supersededRequests ?? [], p.settled ?? null, p.total);+ if (incomplete) throw opError('recovery_required', `An incomplete page receipt (request ${incomplete}) still blocks the sync checkpoint.`,+ `Page request ${incomplete} of this sync run is still open or needs recovery, so checkpoint request ${row.request_id} of ${row.source_id} did not commit. `+ + `Inspect request ${incomplete} and let it finish; do not resubmit it. Then run: ${checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p.processingOptions, syncOptions: p.syncOptions, repoPath: p.repoPath })}`,+ { fix: syncInspectFix(row, incomplete, false) });+ const settled = !p.slice || p.slice.done;+ // #5522: an overtaken run accepts a source another cursor already checkpointed at this exact target.+ // #6694: at the repository root both slug modes give the same slugs, so the checkpoint keeps whichever mode the source pins.+ const emptyScope = emptySyncScope(root, syncGitTopLevel(root, p.runId));+ const changed = await tx.executeRaw(`UPDATE sources SET last_commit=$3,last_sync_at=now(),+ config=jsonb_set(${SOURCE_CONFIG_OBJECT_SQL},'{slug_root_mode}',to_jsonb(CASE WHEN $7::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)),+ newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL)+ WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR ($6::boolean AND last_commit=$3))+ AND ($7::boolean OR config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id`,+ [row.source_id, row.source_incarnation, settled ? p.target : p.from, p.from, p.slugMode, p.overtaken === true, emptyScope]);+ const pinned = !changed.length && !emptyScope ? await pinnedSlugModeMismatch(tx, row.source_id, row.source_incarnation, p.slugMode) : null;+ if (pinned) throw syncPublicationRefusal('slug_root_mode_mismatch', `The source pins slug_root_mode=${pinned}, but this sync ran under ${p.slugMode}.`, row, p, slugModeMismatchCause(row.source_id, pinned, p.slugMode));+ if (!changed.length) throw syncPublicationRefusal('revision_conflict', CHECKPOINT_MOVED_MESSAGE, row, p,+ `Another sync moved the commit checkpoint of ${row.source_id} while this run published.`);+ await recordSliceCursor(tx, row, p, settled);+ // #5566: a full walk re-chunked every stale page, so acknowledge the chunker version as the legacy gate does.+ if (settled && (p.from === null || p.syncOptions?.full === true)) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);+ await tx.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,done}','true'::jsonb),updated_at=now() WHERE op='managed-sync' AND fingerprint=$1", [p.cursorKey]);+ for (const path of p.releasedHolds ?? []) await releaseHold(tx, path);+ return { status: 'synced', source_id: row.source_id, committed_pages: p.total };+}+/*** Whether the import must rewrite its file with `canonicalFile` (its sanitized form). Working-tree bytes that are the* pinned bytes (or differ only by line endings) take the write; bytes that already are the canonical file need none@@ -418,8 +465,11 @@ function canonicalWritebackNeeded(row: WriteRequest, p: SyncIntent, pinned: stri`The canonical correction for ${row.slug} would overwrite newer working-tree bytes; preserve the local edit and commit it.`);}+/** A managed-sync preparation; a Markdown import also carries the provenance its publication records, which a no-op waiver records instead. */+export type SyncPreparedMutation = PreparedMutation & { importProvenance?: SyncImportProvenanceBase };+export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock,- screening?: { unsaved: true }): Promise<PreparedMutation> {+ screening?: { unsaved: true }): Promise<SyncPreparedMutation> {const engine = boundedReads(unbounded, clock);const p = row.intent as SyncIntent | null;if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw syncPublicationRefusal('invalid_params', 'Unsupported internal sync intent.', row, p,@@ -510,39 +560,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrawait checkApprovedSchemaForEngine(tx, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest }, { remote: false, sourceId: row.source_id });}};- if (p.kind === 'managed_sync_checkpoint') return { sourceExclusive: true, observedRevision: null, validate, apply: async tx => {- const [cursor] = await tx.executeRaw<{ completed_keys: [{ runId: string; index: number; total: number }] }>(- "SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE", [p.cursorKey]);- // #6513: validation passed under this run; a replacement that landed since is the same supersession, not an index lag.- const replaced = checkpointCursorReplaced(p, cursor?.completed_keys[0]?.runId, row.source_id);- if (replaced) throw syncPublicationRefusal(replaced.code, replaced.message, row, p, replaced.cause);- if (!cursor || cursor.completed_keys[0].runId !== p.runId || cursor.completed_keys[0].index !== p.total || cursor.completed_keys[0].total !== p.total) {- throw syncPublicationRefusal('revision_conflict', 'The sync cursor is not fully committed.', row, p,- `Not every page write of this sync run has committed, so the checkpoint of ${row.source_id} did not advance.`);- }- const [manifest] = await tx.executeRaw<{ count: number }>("SELECT jsonb_array_length(completed_keys) AS count FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [p.runId]);- if (!manifest || Number(manifest.count) !== p.total) throw syncPublicationRefusal('storage_error', 'The immutable sync manifest is incomplete.', row, p,- `The immutable manifest of this sync run is incomplete, so the checkpoint of ${row.source_id} did not advance.`);- const incomplete = await findIncompleteSyncReceipt(tx, row.worktree_id!, p.runId, p.supersededRequests ?? [], p.settled ?? null, p.total);- if (incomplete) throw opError('recovery_required', `An incomplete page receipt (request ${incomplete}) still blocks the sync checkpoint.`,- `Page request ${incomplete} of this sync run is still open or needs recovery, so checkpoint request ${row.request_id} of ${row.source_id} did not commit. `- + `Inspect request ${incomplete} and let it finish; do not resubmit it. Then run: ${checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p.processingOptions, syncOptions: p.syncOptions, repoPath: p.repoPath })}`,- { fix: syncInspectFix(row, incomplete, false) });- const settled = !p.slice || p.slice.done;- // #5522: an overtaken run accepts a source another cursor already checkpointed at this exact target.- const changed = await tx.executeRaw(`UPDATE sources SET last_commit=$3,last_sync_at=now(),config=jsonb_set(${SOURCE_CONFIG_OBJECT_SQL},'{slug_root_mode}',to_jsonb($5::text)),- newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL)- WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR ($6::boolean AND last_commit=$3))- AND (config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id`, [row.source_id, row.source_incarnation, settled ? p.target : p.from, p.from, p.slugMode, p.overtaken === true]);- if (!changed.length) throw syncPublicationRefusal('revision_conflict', 'The source checkpoint changed during this sync.', row, p,- `Another sync moved the commit checkpoint of ${row.source_id} while this run published.`);- await recordSliceCursor(tx, row, p, settled);- // #5566: a full walk re-chunked every stale page, so acknowledge the chunker version as the legacy gate does.- if (settled && (p.from === null || p.syncOptions?.full === true)) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);- await tx.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,done}','true'::jsonb),updated_at=now() WHERE op='managed-sync' AND fingerprint=$1", [p.cursorKey]);- for (const path of p.releasedHolds ?? []) await releaseHold(tx, path);- return { status: 'synced', source_id: row.source_id, committed_pages: p.total };- } };+ if (p.kind === 'managed_sync_checkpoint') return { sourceExclusive: true, observedRevision: null, validate, apply: tx => applyManagedSyncCheckpoint(tx, row, p, root, releaseHold) };const source = { sourceId: row.source_id };enterClaimStep(clock, 'page_snapshot', undefined, 'db');const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });@@ -581,8 +599,8 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr{ ...p, processingOptions: { ...p.processingOptions!, noSchemaPack: false } },`A company-brain source imports with its pinned schema pack, so ${row.source_id} cannot sync with --no-schema-pack.`);enterClaimStep(clock, 'schema_pack', undefined, 'db');- const activePack = p.processingOptions?.noSchemaPack ? undefined : schema ? (await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },- { remote: false, sourceId: row.source_id })).pack.manifest : (await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null))?.manifest;+ const pack = p.processingOptions?.noSchemaPack ? undefined : schema ? (await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },+ { remote: false, sourceId: row.source_id })).pack : await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null), activePack = pack?.manifest;// A renamed page is prepared where it stands; publication moves it, then re-prepares at the new slug.const renamed = moved && moved.slug !== row.slug ? moved : undefined;if (renamed) enterClaimStep(clock, 'rename_source', undefined, 'db');@@ -656,7 +674,9 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr// A rename projects against the moved page (same id), so its pinned timeline rows carry over.enterClaimStep(clock, 'canonical_projections', undefined, 'db');const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');- const preparedImport: PreparedMutation = { observedRevision: snapshot?.revision ?? null, trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath),+ const importProvenance: SyncImportProvenanceBase = { source_id: row.source_id, incarnation: row.source_incarnation, origin: p.sourcePath!, raw_sha256: sha256(p.content!),+ ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}), parser: syncImportParser(pack?.identity ?? null) };+ const preparedImport: SyncPreparedMutation = { observedRevision: snapshot?.revision ?? null, trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath), importProvenance,// Tells the #5470 screen the content is unchanged; publication still queues its effects.contentUnchanged: ready.noop && !moved && !writeback,...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),@@ -698,8 +718,8 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrelse if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);},() => releaseHold(tx),- async () => { if (final) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(final.page.id), origin: p.sourcePath!,- raw_sha256: sha256(p.content!), ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}) }); },+ async () => { if (final) await recordSyncImportProvenance(tx, { ...importProvenance, page_id: Number(final.page.id), revision: final.revision,+ ...syncDiskProvenance(writeback ? Buffer.from(canonicalFile) : syncDiskBytes(root, p.path!, p.content!, p.rawHash), p.target) }); },]);preparedImport.postimage = final;// #6722: a large or embed_skip page says what this write left its embedding in.diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex e355b0c092..0ce33329a3 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -15,6 +15,7 @@ import { preparationConfigView } from './config-snapshot.ts';import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';+import { slugModeCheckpointRevivable } from './sync-slug-mode.ts';import { selectManagedCursor } from './sync-cursor-key.ts';import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';@@ -798,10 +799,11 @@ const revivableCheckpointRefusal = (done: Pick<WriteRequest, 'state' | 'error_co* knock-on, a receipt at an index the cursor settled), a fresh checkpoint request replaces it by cursor swap, and its* publication validates everything again. The completed manifest and the old receipt stay as they are. Null when it* still blocks, or after `CHECKPOINT_REVIVAL_LIMIT` revivals in this invocation (the next invocation re-assesses).+ * #6694: a checkpoint refused for its slug-root mode is revived the same way once the source admits it (sync-slug-mode.ts).*/async function reviveCheckpoint(engine: BrainEngine, input: SettleInput): Promise<Cursor | null> {const { cursor, key, pending, done } = input;- const refused = revivableCheckpointRefusal(done);+ const refused = revivableCheckpointRefusal(done) || (pending.intent.kind === 'managed_sync_checkpoint' && await slugModeCheckpointRevivable(engine, cursor, pending.intent, done));const revivals = checkpointRevivalsByRun.get(input.run) ?? 0;if (pending.intent.kind !== 'managed_sync_checkpoint' || !refused || done.recovery || cursor.index !== cursor.entries.length || revivals >= CHECKPOINT_REVIVAL_LIMIT) return null;const base: Cursor = { ...cursor }; delete base.pending; delete base.group; delete base.window;diff --git a/src/core/persistence/sync-slug-mode.ts b/src/core/persistence/sync-slug-mode.tsnew file mode 100644index 0000000000..9801cf4560--- /dev/null+++ b/src/core/persistence/sync-slug-mode.ts@@ -0,0 +1,53 @@+/**+ * #6694: the slug-root mode a managed-sync checkpoint publishes under, against the mode the source pins+ * (`sources.config.slug_root_mode`).+ *+ * A source whose root is its repository root (empty scope) gets the same slugs and origins in both modes, so its+ * checkpoint accepts either pin and keeps the one the source has. At a subdirectory the modes give different slugs:+ * a pin that differs from the run's mode is refused as `slug_root_mode_mismatch`, never as a concurrent-writer+ * `revision_conflict`. A checkpoint refused for its slug mode (or, from older releases, as `revision_conflict` with+ * the moved-checkpoint message) is revived by the next plain sync once the source's state admits it.+ */+import { realpathSync } from 'node:fs';+import type { BrainEngine } from '../engine.ts';+import type { WriteRequest } from './model.ts';++type SlugRootMode = 'git-root' | 'source-root';++/** The message of the checkpoint guard's refusal when `last_commit` moved; older releases also used it for a slug-mode pin. */+export const CHECKPOINT_MOVED_MESSAGE = 'The source checkpoint changed during this sync.';++/** Whether the source root is the repository root, where both slug-root modes produce identical slugs. */+export function emptySyncScope(root: string, gitRoot: string): boolean {+ return realpathSync.native(root) === realpathSync.native(gitRoot);+}++/** The source's pinned mode when it differs from `slugMode` (null when unpinned, equal, or the source row is gone). */+export async function pinnedSlugModeMismatch(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, incarnation: string, slugMode: SlugRootMode): Promise<string | null> {+ const [row] = await engine.executeRaw<{ mode: string | null }>("SELECT config->>'slug_root_mode' AS mode FROM sources WHERE id=$1 AND incarnation=$2::uuid", [sourceId, incarnation]);+ return row?.mode != null && row.mode !== slugMode ? row.mode : null;+}++/** The refusal's cause and the decision it leaves to a person (the receipt appends the inspect command). */+export function slugModeMismatchCause(sourceId: string, pinned: string, slugMode: SlugRootMode): string {+ return `Source ${sourceId} pins slug_root_mode=${pinned}, but this sync ran under ${slugMode}; at a subdirectory the two modes give different slugs, so the checkpoint did not advance. `+ + `A person decides which mode the source keeps: set sources.config.slug_root_mode back to ${slugMode} and rerun gbrain sync --no-pull --source ${sourceId}, `+ + `or keep ${pinned} and run gbrain sync --no-pull --source ${sourceId} --retry-failed, which discovers the source again under ${pinned} (pages this run wrote keep their ${slugMode} slugs beside the new ones).`;+}++/**+ * Whether a failed checkpoint was refused for its slug mode and the source now admits it: its `last_commit` is still+ * where the run started, and the pin is unset, equal to the run's mode, or the scope is empty. A legacy+ * `revision_conflict` carrying the moved-checkpoint message qualifies under the same proof; any other refusal does not.+ */+export async function slugModeCheckpointRevivable(engine: Pick<BrainEngine, 'executeRaw'>,+ cursor: { sourceId: string; incarnation: string; root: string; gitRoot: string },+ intent: { slugMode: SlugRootMode; from: string | null },+ done: Pick<WriteRequest, 'state' | 'error_code' | 'error_message' | 'recovery'>): Promise<boolean> {+ if (done.recovery || !['failed', 'conflict'].includes(done.state)) return false;+ if (done.error_code !== 'slug_root_mode_mismatch' && !(done.error_code === 'revision_conflict' && done.error_message === CHECKPOINT_MOVED_MESSAGE)) return false;+ const [row] = await engine.executeRaw<{ mode: string | null; last_commit: string | null }>(+ "SELECT config->>'slug_root_mode' AS mode, last_commit FROM sources WHERE id=$1 AND incarnation=$2::uuid", [cursor.sourceId, cursor.incarnation]);+ if (!row || (row.last_commit ?? null) !== (intent.from ?? null)) return false;+ return row.mode == null || row.mode === intent.slugMode || emptySyncScope(cursor.root, cursor.gitRoot);+}diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.tsindex 6ecbe4e8e3..57bb9c7547 100644--- a/src/core/persistence/sync-waivers.ts+++ b/src/core/persistence/sync-waivers.ts@@ -9,10 +9,12 @@ import { join } from 'node:path';import type { BrainEngine, PageSnapshot } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';+import { recordSyncImportProvenances, syncDiskProvenance, type SyncImportProvenance, type SyncImportProvenanceBase } from './sync-holds.ts';+import { sha256 } from './digest.ts';import { startClaimPhase } from './claim-phase.ts';import { inspectUnchanged, screeningRequest, type NoopKernelWaiver } from './noop-kernel.ts';import { validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';-import { readSyncFile, syncRawHash } from './sync-discovery.ts';+import { readSyncFile } from './sync-discovery.ts';import { isImageFilePath } from '../sync.ts';import { getWorktreeBinding } from './ownership.ts';import { assertSyncPageOrigin, syncOriginScope } from './sync-origin.ts';@@ -26,7 +28,8 @@ import { withBoundedReadSession } from './bounded-reads.ts';export interface WaiverCursor { sourceId: string; incarnation: string; root: string; gitRoot: string; slugMode: 'git-root' | 'source-root';binding: { worktree_id: string }; authority: SyncAuthority; runId: string; index: number }export interface WaiverEntry { requestId: string; slug: string; pageId: number | null; intent: SyncIntent }-export interface NoopWaiver { kind: 'import' | 'delete'; kernel: NoopKernelWaiver[] }+/** `provenance` (a Markdown import): what the waiver records as the page's import provenance, as its publication would have. */+export interface NoopWaiver { kind: 'import' | 'delete'; kernel: NoopKernelWaiver[]; provenance?: SyncImportProvenanceBase }/** `persistence.sync_preparation_ms` (preparation-budget.ts validates it): the budget a managed sync member's preparation gets; default 120 s. */export const SYNC_PREPARATION_MS_KEY = 'persistence.sync_preparation_ms';@@ -122,6 +125,9 @@ export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngine} else if (snapshot?.page.id !== pending.pageId || snapshot.page.deleted_at != null || snapshot.revision !== intent.expected_revision) return null;const unfinished = await tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, unfinishedPageRequestParams(cursor, pending));if (unfinished.length) return null;+ const provenance = waivedProvenance(cursor, pending, waived, snapshot!.revision);+ if (provenance === false) return null;+ await recordSyncImportProvenances(tx, provenance ? [provenance] : []);return advance(tx, waived);});}@@ -151,10 +157,10 @@ async function screenWaiverEntry(engine: BrainEngine, cursor: WaiverCursor, pendif (!frozen) await validateSyncAuthority(engine, cursor.authority, pending.slug);return { kind: 'delete', kernel: [] };}- const kernel = await unchangedSyncImport(engine, cursor, pending, config, signal, frozen?.snapshot);- if (!kernel) return null;+ const unchanged = await unchangedSyncImport(engine, cursor, pending, config, signal, frozen?.snapshot);+ if (!unchanged) return null;if (!frozen) await validateSyncAuthority(engine, cursor.authority, pending.slug);- return { kind: 'import', kernel };+ return { kind: 'import', ...unchanged };}/** #5984: `GBRAIN_SYNC_WAIVE_BATCH=0` (or `sync.waive_batch=false`) waives one entry per transaction, as before. */@@ -199,6 +205,7 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,// #6423: the per-entry checks go out in pipelined chunks of at most WAIVER_PIPELINE_MAX calls, and a chunk is sent only// while every entry before it validated (the prefix stops at the first entry that does not).let valid = 0;+ const provenances: Array<Omit<SyncImportProvenance, 'recorded_at' | 'validated'>> = [];chunks: for (let from = 0; from < run.length; from += WAIVER_PIPELINE_MAX / 2) {const chunk = run.slice(from, from + WAIVER_PIPELINE_MAX / 2);noteDrainSql(UNFINISHED_PAGE_REQUEST_SQL);@@ -214,11 +221,14 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,if (!page || Number(page.id) !== pending.pageId || revision !== pending.intent.expected_revision) break chunks;if (waived.kind === 'delete' ? !page.deleted || readSyncFile(cursor.root, pending.intent.path!) !== null : page.deleted) break chunks;if ((checks[2 * i] as unknown[]).length || checks[2 * i + 1] !== true) break chunks;- if (waived.kind === 'import' && syncRawHash(cursor.root, pending.intent.path!) !== pending.intent.rawHash) break chunks;+ const provenance = waivedProvenance(cursor, pending, waived, revision!);+ if (provenance === false) break chunks;+ if (provenance) provenances.push(provenance);valid++;}}if (!valid) return null;+ await recordSyncImportProvenances(tx, provenances);return { cursor: await advance(tx, run.slice(0, valid)), waived: valid, ...(valid < run.length ? { next: run[valid]!.pending } : {}) };});} catch (error) {@@ -239,6 +249,19 @@ export async function wouldWaiveEntry(engine: BrainEngine, cursor: WaiverCursor,return (await unchangedSyncImport(engine, cursor, pending, config, signal)) !== null;}+/**+ * #6712: the import provenance a waived import records in its waiver transaction, from the file read there: false when+ * the file no longer has the frozen raw hash (the entry is not waived), null for a waiver that records none (a delete,+ * or an import whose preparation carried no provenance, such as a code file).+ */+function waivedProvenance(cursor: WaiverCursor, pending: WaiverEntry, waived: NoopWaiver, revision: string): Omit<SyncImportProvenance, 'recorded_at' | 'validated'> | false | null {+ if (waived.kind !== 'import') return null;+ const bytes = readSyncFile(cursor.root, pending.intent.path!);+ if ((bytes === null ? null : sha256(bytes)) !== pending.intent.rawHash) return false;+ if (!waived.provenance) return null;+ return { ...waived.provenance, page_id: pending.pageId!, revision, ...syncDiskProvenance(bytes, pending.intent.target) };+}+function softDeletedAt(snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, pending: WaiverEntry): boolean {return snapshot?.page.id === pending.pageId && snapshot.page.deleted_at != null && snapshot.revision === pending.intent.expected_revision;}@@ -246,7 +269,7 @@ function softDeletedAt(snapshot: Awaited<ReturnType<BrainEngine['readPageSnapsho/*** #5470 no-op screen for working-tree and company-profile sync: runs the sync* preparer on the frozen, unadmitted entry. A rename or a canonical overlay is- * always admitted. Returns null to admit, or the kernel waivers the skip used.+ * always admitted. Returns null to admit, or the kernel waivers the skip used and the provenance its waiver records.* #5751: a managed working-tree entry waives the two admit reasons its no-op* publication can never resolve (a pending contextual-mode stamp, and file* bytes that differ from the prepared content yet parse to the same page), so@@ -255,7 +278,7 @@ function softDeletedAt(snapshot: Awaited<ReturnType<BrainEngine['readPageSnapsho* nothing is waived, and a cancelled run propagates.*/export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal,- frozenSnapshot?: PageSnapshot | null): Promise<NoopKernelWaiver[] | null> {+ frozenSnapshot?: PageSnapshot | null): Promise<Pick<NoopWaiver, 'kernel' | 'provenance'> | null> {const intent = pending.intent;if (intent.kind !== 'managed_sync_import' || intent.renameFrom || pending.pageId === null || typeof intent.path !== 'string' || typeof intent.content !== 'string') return null;// #6529: an image's preparation is provider work; its hash no-op is decided under the admitted request instead.@@ -276,7 +299,7 @@ export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCurwaive: intent.working === true ? ['contextual_mode', 'canonical_file_differs'] : undefined });if (inspected.admitReason) return null;await prepared.validate?.(engine);- return inspected.waived ?? [];+ return { kernel: inspected.waived ?? [], ...(prepared.importProvenance ? { provenance: prepared.importProvenance } : {}) };} catch (error) {rethrowAbort(error, signal);return null;diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 2957a4fab7..2efdcc4531 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -169,9 +169,11 @@ test/sync-full-cursor-slices-6349.test.tstest/sync-full-untracked-import-5459.test.tstest/sync-group-member-order.test.tstest/sync-handler-drain-6706.test.ts+test/sync-import-provenance-disk.test.tstest/sync-legacy-holds.test.tstest/sync-legacy-retry-actions-6696.test.tstest/sync-origin-live-wins-6517.test.ts+test/sync-slug-root-mode-6694.test.tstest/sync-staged-catchup.test.tstest/sync-status-failure-detail-6513.test.tstest/sync-waiver-budget.test.tsdiff --git a/test/sync-import-provenance-disk.test.ts b/test/sync-import-provenance-disk.test.tsnew file mode 100644index 0000000000..db827ec5e9--- /dev/null+++ b/test/sync-import-provenance-disk.test.ts@@ -0,0 +1,151 @@+/**+ * #6712 PR 0: managed-sync import provenance (`sync-import-provenance` in op_checkpoints) records what the publish+ * left on disk and what it produced: `disk_sha256` and `disk_blob_oid` (the canonical writeback when the publish wrote+ * one, else the file's bytes), `revision` (the page revision of that publish) and `parser` (import parser version, Markdown+ * chunker, schema pack; never the release, so it holds across upgrades that change no parsing). Nothing reads them yet; a later content-addressed resume compares them with `git ls-tree`.+ *+ * Protects: the fields are written, in the publish transaction, for a plain import, an update, a canonical writeback+ * (the written-back file, not the input) and a file whose disk bytes differ from the pinned blob only by line endings;+ * a record without them (older releases, repairs) is read and replaced by the next publish of the page.+ * Regression it catches: a record that hashes the pinned input instead of the bytes on disk, or omits the revision.+ * Code and image pages write no import provenance, so they have no case here. Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { createHash, randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readSyncImportProvenance, SYNC_IMPORT_PARSER_VERSION, SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';+import { loadActivePackForEngine } from '../src/core/schema-pack/engine-resolution.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-provenance-disk-'));+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };+const sha256 = (bytes: Uint8Array | string) => createHash('sha256').update(bytes).digest('hex');+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;+// A facts fence with a fixable kind (`partnership` maps to `fact`): the import rewrites the file canonically.+const FB = '<!--- gbrain:facts:begin -->', FBE = '<!--- gbrain:facts:end -->';+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';+const fixable = `---\ntitle: Fixable\n---\nA synthetic page.\n\n${FB}\n${FH}\n| 1 | Acme-example partners with an example vendor | partnership | 1.0 | private | medium | 2026-01-01 | | chat | |\n${FBE}\n`;++describe('managed-sync import provenance records the bytes on disk, the revision and the parser', () => {+ const engines: BrainEngine[] = [];+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+ });+ const each = (fn: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined },+ async () => { for (const engine of engines) await fn(engine); });++ async function fixture(engine: BrainEngine, files: Record<string, string>) {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = `prov-${randomUUID().slice(0, 12)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ for (const [path, body] of Object.entries(files)) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), body); }+ const head = commit(root, 'seed');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);+ return { id, root, head, incarnation, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };+ }+ type Fixture = Awaited<ReturnType<typeof fixture>>;+ async function provenanceOf(engine: BrainEngine, f: Fixture, slug: string) {+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: f.id }))!;+ return { snapshot, record: (await readSyncImportProvenance(engine, f.id, f.incarnation, Number(snapshot.page.id)))! };+ }+ /** What the record must say about `path` as it is on disk now. */+ async function expectDisk(engine: BrainEngine, f: Fixture, slug: string, path: string) {+ const { snapshot, record } = await provenanceOf(engine, f, slug);+ const disk = readFileSync(join(f.root, path));+ const pack = await loadActivePackForEngine(engine, { remote: false, sourceId: f.id }).catch(() => null);+ expect(record).toMatchObject({ origin: path, disk_sha256: sha256(disk), disk_blob_oid: git(f.root, 'hash-object', '--no-filters', path), revision: snapshot.revision,+ parser: { parser_version: SYNC_IMPORT_PARSER_VERSION, markdown_chunker: MARKDOWN_CHUNKER_VERSION, schema_pack: pack?.identity ?? null } });+ expect(record.parser).not.toHaveProperty('gbrain_version');+ return record;+ }++ test('a plain import and its update record the file bytes, its blob id and each publish revision', async () => each(async engine => {+ const f = await fixture(engine, { 'notes/plain.md': note('A first synthetic observation.') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ const first = await expectDisk(engine, f, 'notes/plain', 'notes/plain.md');+ expect(first.disk_sha256).toBe(first.raw_sha256);+ expect(first.disk_blob_oid).toBe(git(f.root, 'rev-parse', 'HEAD:notes/plain.md'));+ writeFileSync(join(f.root, 'notes/plain.md'), note('A second synthetic observation.')); commit(f.root, 'update');+ expect((await performManagedSync(engine, f.opts)).status).toBe('synced');+ const second = await expectDisk(engine, f, 'notes/plain', 'notes/plain.md');+ expect(second.revision).not.toBe(first.revision);+ expect(second.disk_sha256).not.toBe(first.disk_sha256);+ }), 120_000);++ test('a canonical writeback records the written-back file, not the input it imported', async () => each(async engine => {+ const f = await fixture(engine, { 'people/fixable.md': fixable });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ const written = readFileSync(join(f.root, 'people/fixable.md'), 'utf8');+ expect(written).not.toBe(fixable); expect(written).toContain('| fact |');+ const record = await expectDisk(engine, f, 'people/fixable', 'people/fixable.md');+ expect(record.raw_sha256).toBe(sha256(fixable));+ expect(record.disk_sha256).not.toBe(record.raw_sha256);+ expect(record.disk_blob_oid).not.toBe(git(f.root, 'rev-parse', 'HEAD:people/fixable.md'));+ }), 120_000);++ test('disk bytes that differ from the pinned blob only by line endings are what the record hashes', async () => each(async engine => {+ const f = await fixture(engine, { 'notes/crlf.md': note('A synthetic observation with line endings.') });+ writeFileSync(join(f.root, 'notes/crlf.md'), note('A synthetic observation with line endings.').replace(/\n/g, '\r\n'));+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ const record = await expectDisk(engine, f, 'notes/crlf', 'notes/crlf.md');+ expect(record.raw_sha256).toBe(sha256(note('A synthetic observation with line endings.')));+ expect(record.disk_sha256).not.toBe(record.raw_sha256);+ }), 120_000);++ test.each([['batched'], ['per-entry']] as const)('a %s no-op waiver records the provenance in its waiver transaction without a new revision', async mode => withEnv({ GBRAIN_SYNC_WAIVE_BATCH: mode === 'batched' ? undefined : '0' }, () => each(async engine => {+ const f = await fixture(engine, { 'notes/one.md': note('A first unchanged observation.'), 'notes/two.md': note('A second unchanged observation.'), 'people/fixable.md': fixable });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ commit(f.root, 'commit the canonical writeback');+ const before = new Map<string, string>();+ for (const slug of ['notes/one', 'notes/two', 'people/fixable']) {+ const { snapshot } = await provenanceOf(engine, f, slug);+ before.set(slug, snapshot.revision);+ // A page an older release imported (or whose record was lost) has no provenance.+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, `${f.id}:${f.incarnation}:${snapshot.page.id}`]);+ }+ const full = await performManagedSync(engine, { ...f.opts, full: true });+ expect(full).toMatchObject({ status: 'synced', waived: { imports: 3, deletes: 0 } });+ for (const [slug, path] of [['notes/one', 'notes/one.md'], ['notes/two', 'notes/two.md'], ['people/fixable', 'people/fixable.md']] as const) {+ const record = await expectDisk(engine, f, slug, path);+ expect(record.revision).toBe(before.get(slug)!);+ expect(record.disk_sha256).toBe(record.raw_sha256);+ }+ })), 120_000);++ test('a record without the fields is read as it is, and the next publish of the page stamps them', async () => each(async engine => {+ const f = await fixture(engine, { 'notes/legacy.md': note('A synthetic observation an older release imported.') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ const { snapshot, record } = await provenanceOf(engine, f, 'notes/legacy');+ const { disk_sha256: _a, disk_blob_oid: _b, revision: _c, parser: _d, ...legacy } = record;+ await engine.executeRaw('UPDATE op_checkpoints SET completed_keys=$3::text::jsonb WHERE op=$1 AND fingerprint=$2',+ [SYNC_IMPORT_PROVENANCE_OP, `${f.id}:${f.incarnation}:${snapshot.page.id}`, JSON.stringify([legacy])]);+ const read = await readSyncImportProvenance(engine, f.id, f.incarnation, Number(snapshot.page.id));+ expect(read).toMatchObject({ raw_sha256: record.raw_sha256 });+ expect(read).not.toHaveProperty('disk_sha256'); expect(read).not.toHaveProperty('revision');+ writeFileSync(join(f.root, 'notes/legacy.md'), note('A synthetic observation this release imported.')); commit(f.root, 'update');+ expect((await performManagedSync(engine, f.opts)).status).toBe('synced');+ await expectDisk(engine, f, 'notes/legacy', 'notes/legacy.md');+ }), 120_000);+});diff --git a/test/sync-slug-root-mode-6694.test.ts b/test/sync-slug-root-mode-6694.test.tsnew file mode 100644index 0000000000..eb30458960--- /dev/null+++ b/test/sync-slug-root-mode-6694.test.ts@@ -0,0 +1,152 @@+/**+ * #6694: a managed-sync checkpoint and the source's pinned slug-root mode (`sources.config.slug_root_mode`).+ *+ * Protects: a source rooted at its repository root checkpoints under either pin (both modes give it identical slugs)+ * and keeps the pin it has; a subdirectory source checkpoints under its pin; a pin that changes under a run of a+ * subdirectory source is refused as `slug_root_mode_mismatch`, not as a concurrent-writer `revision_conflict`; and a+ * plain `gbrain sync --no-pull` recovers a checkpoint that already failed that way.+ * Regression it catches: discovery hardcodes `git-root` at an empty scope while the guard compares the pin, so a+ * `source-root` pin on a root source never checkpoints. No existing test syncs a root source with a pin.+ * Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';+import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';+import { CODES } from '../src/core/error-registry.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++type Mode = 'git-root' | 'source-root';+const home = mkdtempSync(join(tmpdir(), 'gbrain-slug-mode-6694-'));+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (repo: string, message: string) => { git(repo, 'add', '-A'); git(repo, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(repo, 'rev-parse', 'HEAD'); };+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation about ${title}.\n`;++describe('#6694 managed-sync checkpoint under a pinned slug_root_mode', () => {+ const engines: BrainEngine[] = [];+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+ });+ const each = (fn: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined },+ async () => { for (const engine of engines) await fn(engine); });++ async function fixture(engine: BrainEngine, scope: string, pin: Mode | null) {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = `slugmode-${randomUUID().slice(0, 12)}`, repo = join(home, id), root = scope ? join(repo, scope) : repo;+ mkdirSync(root, { recursive: true }); git(repo, 'init', '-q');+ if (scope) writeFileSync(join(repo, 'README.md'), 'Repository text outside the source.\n');+ for (const name of ['alpha', 'beta', 'gamma']) { const file = join(root, 'notes', `${name}.md`); mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, note(name)); }+ const head = commit(repo, 'seed');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, root, JSON.stringify(pin ? { slug_root_mode: pin } : {})]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };+ return { id, repo, root, head, opts };+ }+ type Fixture = Awaited<ReturnType<typeof fixture>>;+ const source = async (engine: BrainEngine, f: Fixture) => (await engine.executeRaw<{ last_commit: string | null; mode: string | null }>(+ "SELECT last_commit, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1", [f.id]))[0]!;+ const slugs = async (engine: BrainEngine, f: Fixture) => (await engine.executeRaw<{ slug: string }>(+ 'SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [f.id])).map(row => row.slug);+ /** Runs until every page committed and stops before the checkpoint publishes. */+ async function beforeCheckpoint(engine: BrainEngine, f: Fixture, pages: number) {+ const abort = new AbortController();+ const partial = await performManagedSync(engine, { ...f.opts, signal: abort.signal, onProgress: p => { if (p.bankedFiles === pages) abort.abort(); } });+ expect(partial).toMatchObject({ status: 'partial', filesImported: pages });+ }+ /** A checkpoint column only the owner publishes; the test edits it with managed persistence switched off for the statement. */+ async function unmanaged(engine: BrainEngine, fn: () => Promise<unknown>) {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try { await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ }+ const outcome = (run: Promise<unknown>) => run.then(value => value as Record<string, unknown>, error => ({ thrown: error as { code?: string; message?: string } }));+ const checkpoint = async (engine: BrainEngine, f: Fixture) => (await engine.executeRaw<{ state: string; error_code: string | null; error_message: string | null }>(+ `SELECT state, error_code, error_message FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence DESC LIMIT 1`, [f.id]))[0];++ test.each([['source-root'], ['git-root']] as const)('a source rooted at its repository root, pinned %s, checkpoints and keeps its pin', async pin => each(async engine => {+ const f = await fixture(engine, '', pin);+ expect(await outcome(performManagedSync(engine, f.opts))).toMatchObject({ status: 'first_sync' });+ expect(await source(engine, f)).toEqual({ last_commit: f.head, mode: pin });+ expect(await slugs(engine, f)).toEqual(['notes/alpha', 'notes/beta', 'notes/gamma']);+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ }), 120_000);++ test('an unpinned root source still pins git-root at its first checkpoint', async () => each(async engine => {+ const f = await fixture(engine, '', null);+ expect(await outcome(performManagedSync(engine, f.opts))).toMatchObject({ status: 'first_sync' });+ expect(await source(engine, f)).toEqual({ last_commit: f.head, mode: 'git-root' });+ }), 120_000);++ test.each([['source-root', ['notes/alpha', 'notes/beta', 'notes/gamma']], ['git-root', ['brain/notes/alpha', 'brain/notes/beta', 'brain/notes/gamma']]] as const)(+ 'a subdirectory source pinned %s checkpoints under its pin', async (pin, expected) => each(async engine => {+ const f = await fixture(engine, 'brain', pin);+ expect(await outcome(performManagedSync(engine, f.opts))).toMatchObject({ status: 'first_sync' });+ expect(await source(engine, f)).toEqual({ last_commit: f.head, mode: pin });+ expect(await slugs(engine, f)).toEqual([...expected]);+ }), 120_000);++ test('a pin changed under a run of a subdirectory source is refused as slug_root_mode_mismatch; restoring the pin lets a plain sync finish', async () => each(async engine => {+ const f = await fixture(engine, 'brain', 'source-root');+ await beforeCheckpoint(engine, f, 3);+ await engine.executeRaw(`UPDATE sources SET config=jsonb_set(config,'{slug_root_mode}','"git-root"') WHERE id=$1`, [f.id]);+ const refused = await outcome(performManagedSync(engine, f.opts));+ expect(JSON.stringify(refused)).toContain('slug_root_mode_mismatch');+ expect(await checkpoint(engine, f)).toMatchObject({ error_code: 'slug_root_mode_mismatch' });+ expect((await checkpoint(engine, f))!.error_message).toContain('pins slug_root_mode=git-root, but this sync ran under source-root');+ expect(await source(engine, f)).toEqual({ last_commit: null, mode: 'git-root' });+ expect(classifySyncFault({ code: 'slug_root_mode_mismatch' })).toMatchObject({ class: 'systemic', needs_human: true });+ expect(CODES.slug_root_mode_mismatch.fix?.argv).toEqual(['gbrain', 'sync', 'status', '--source', '{source_id}', '--json']);+ // Still mismatched: a plain rerun stays refused under the named code.+ expect(JSON.stringify(await outcome(performManagedSync(engine, f.opts)))).toContain('slug_root_mode_mismatch');+ await engine.executeRaw(`UPDATE sources SET config=jsonb_set(config,'{slug_root_mode}','"source-root"') WHERE id=$1`, [f.id]);+ expect(await outcome(performManagedSync(engine, f.opts))).toMatchObject({ status: 'first_sync' });+ expect(await source(engine, f)).toEqual({ last_commit: f.head, mode: 'source-root' });+ expect(await slugs(engine, f)).toEqual(['notes/alpha', 'notes/beta', 'notes/gamma']);+ }), 120_000);++ test('keeping a changed pin, --retry-failed discovers the subdirectory source again under it, beside the pages the refused run wrote', async () => each(async engine => {+ const f = await fixture(engine, 'brain', 'source-root');+ await beforeCheckpoint(engine, f, 3);+ await engine.executeRaw(`UPDATE sources SET config=jsonb_set(config,'{slug_root_mode}','"git-root"') WHERE id=$1`, [f.id]);+ expect(JSON.stringify(await outcome(performManagedSync(engine, f.opts)))).toContain('slug_root_mode_mismatch');+ const retried = await outcome(performManagedSync(engine, { ...f.opts, retryFailed: true }));+ expect(retried).not.toHaveProperty('thrown');+ expect(await source(engine, f)).toEqual({ last_commit: f.head, mode: 'git-root' });+ // The pages the refused run wrote under source-root keep their slugs beside the git-root ones; that is the cost the user accepts.+ expect(await slugs(engine, f)).toEqual(['brain/notes/alpha', 'brain/notes/beta', 'brain/notes/gamma', 'notes/alpha', 'notes/beta', 'notes/gamma']);+ }), 120_000);++ test('a plain sync recovers a root source whose checkpoint already failed revision_conflict under a source-root pin', async () => each(async engine => {+ const f = await fixture(engine, '', 'source-root');+ await beforeCheckpoint(engine, f, 3);+ // The receipt older releases left: the checkpoint guard refused with the moved-checkpoint revision_conflict.+ await unmanaged(engine, () => engine.executeRaw("UPDATE sources SET last_commit='0000000000000000000000000000000000000000' WHERE id=$1", [f.id]));+ expect(JSON.stringify(await outcome(performManagedSync(engine, f.opts)))).toContain('revision_conflict');+ expect(await checkpoint(engine, f)).toMatchObject({ error_code: 'revision_conflict', error_message: 'The source checkpoint changed during this sync.' });+ await unmanaged(engine, () => engine.executeRaw('UPDATE sources SET last_commit=NULL WHERE id=$1', [f.id]));+ const recovered = await outcome(performManagedSync(engine, f.opts));+ expect(recovered).toMatchObject({ status: 'first_sync' });+ expect(await source(engine, f)).toEqual({ last_commit: f.head, mode: 'source-root' });+ expect(await checkpoint(engine, f)).toMatchObject({ state: 'committed', error_code: null });+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ }), 120_000);+});