Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sources canonical): typed refusal for --to git without a Git checkout (#7885); #7886 test follow-ups

garrytan931e1c381b18
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a72b56d272..3ef9158c78 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,15 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**`gbrain sources canonical <id> --to git` on a managed source with no Git checkout now refuses with a typed error and a fix.**
+
+When a managed source's folder was a plain directory, or a `git init` with no commit yet, the preview and the apply failed with `internal_error` and a raw git message. They now refuse with `git_checkout_required` or `git_branch_unborn`, read and write nothing, leave the source usable as it is, and carry a fix that asks the user before the folder becomes a Git repository (then `gbrain sources canonical <id> --to git --dry-run --json` previews again).
+
+- The strict-pass receipt-wait test runs in about 6 seconds instead of sleeping past a 30-second wait: the managed sync receipt waits now live in one module with a test seam. It covers both strict passes.
+- A direct test covers the NULL-vector clause of the no-op embedding check.
+
## [0.60.484.0] - 2026-10-28
**Converting a large source to git-canonical no longer re-embeds unchanged pages or stops on its own writes.**
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 229886e5c6..a313fc74b5 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
src/core/config.ts 2012 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured)
-src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)
+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; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts); +1 #7886: the import of persistence/sync-receipt-wait.ts, where the managed sync receipt waits and their test seam live
src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts)
diff --git a/src/core/persistence/git-conversion.ts b/src/core/persistence/git-conversion.ts
index 9b25658e54..df4418d813 100644
--- a/src/core/persistence/git-conversion.ts
+++ b/src/core/persistence/git-conversion.ts
@@ -40,7 +40,7 @@
* remaining categories are reported. `--to mixed` removes the flag and changes nothing else.
*/
import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
-import { dirname, join, relative, sep } from 'node:path';
+import { dirname, join, relative, resolve, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import type { Action } from '../agent-output.ts';
@@ -59,7 +59,8 @@ import { commitThroughDoor } from './git-door.ts';
import { gitRootAhead, pushGitRoot } from './effect-git.ts';
import { DURABILITY_NOT_ENABLED_REASON, gitDurabilityPolicy } from './git-durability-policy.ts';
import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
-import { acquireWorktree, readManagedMode } from './ownership.ts';
+import { acquireWorktree, getWorktreeBinding, readManagedMode } from './ownership.ts';
+import { inspectDurabilityCheckout } from './git-durability-administration.ts';
import { resolveManagedSyncContext, type ManagedSyncContext } from './sync-discovery.ts';
import { readShadowLevel } from './sync-pass.ts';
import { isPrivacyClass, type PrivacyClass } from './git-declared.ts';
@@ -94,6 +95,7 @@ export type ConversionPhase = typeof CONVERSION_PHASES[number];
*/
export interface ConversionProgress { phase: ConversionPhase; groups_committed: number; scanned: number; total: number; round?: number; candidates?: number;
batch?: number; batches?: number; push?: ConversionPush }
+const ROUND_RESET = { round: undefined, candidates: undefined, batch: undefined, batches: undefined } as const;
/**
* Where the push of the apply's door commits stands: `pushed`; `pending` (the commits are local and the next page write's
* push-only effect pushes them; `code` and `notice` say why it did not land); `skipped` (`reason`: durability is off,
@@ -193,11 +195,35 @@ export async function assertConversionCaller(engine: BrainEngine, sourceId: stri
user_message: `Source ${sourceId} can only become git-canonical on a brain with managed writes, and this brain is not managed. Should it move to managed writes first?` } });
}
+/**
+ * #7885: a root with no Git checkout, or one whose branch has no commit yet, has nothing to convert into. The plan refuses
+ * before it reads anything, and the source keeps working as it is (the database is its record).
+ */
+async function assertConversionCheckout(sourceId: string, root: string): Promise<void> {
+ try { await inspectDurabilityCheckout(root); }
+ catch (error) {
+ if (!(error instanceof OperationError) || (error.code !== 'git_checkout_required' && error.code !== 'git_branch_unborn')) {
+ if (error instanceof OperationError && error.code === 'git_detached_head') return;
+ throw error;
+ }
+ const code = error.code === 'git_checkout_required' ? 'git_checkout_required' as const : 'git_branch_unborn' as const;
+ const state = code === 'git_checkout_required' ? 'is not inside a Git checkout' : 'is a Git checkout with no commit yet';
+ const why = 'A git-canonical source commits every page to Git on top of the checkout\'s branch, so its root needs a Git checkout with a first commit.';
+ throw opError(code, `Source ${sourceId}'s root ${root} ${state}, so it has nothing to convert into; nothing was read or written. The source stays usable as it is, with the database as its record.`,
+ 'Keep the source as it is, or make its root a Git repository with a first commit on the brain host (git init, git add -A, git commit), then preview again.',
+ { why, docs: DOCS, fix: { argv: ['gbrain', 'sources', 'canonical', sourceId, '--to', 'git', '--dry-run', '--json'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Previews the conversion again once the root has a first commit; read-only.',
+ user_message: `Source ${sourceId} has no Git history to convert into. It keeps working as it is. Should its folder become a Git repository with a first commit so it can be converted?` } });
+ }
+}
+
/** The context a strict pass reads, for a source whose row does not say so yet. */
const strictContext = (context: ManagedSyncContext): ManagedSyncContext => ({ ...context, source: { ...context.source, config: { ...context.source.config, canonical: 'git' } } });
/** The read-only plan of `--to git`; its preview is what the CLI prints and the apply binds to. */
export async function planGitConversion(engine: BrainEngine, sourceId: string): Promise<GitConversionPlan> {
+ const binding = await getWorktreeBinding(engine, sourceId);
+ if (binding?.local_path) await assertConversionCheckout(sourceId, resolve(binding.local_path, binding.relative_path));
const context = await resolveManagedSyncContext(engine, { sourceId, noPull: true, dryRun: true });
const pages: GitGapPage[] = [];
const equal = new Map<string, PageRevision>();
@@ -516,7 +542,7 @@ export async function applyGitConversion(engine: BrainEngine, sourceId: string,
const processing = { noEmbed: opts.noEmbed, noExtract: opts.noExtract };
const planned = recheck?.paths.length ?? 0;
const pass = (phase: 'strict_pass_1' | 'strict_pass_2') => {
- report({ phase, scanned: 0, total: planned, round: undefined, candidates: undefined, batch: undefined, batches: undefined });
+ report({ phase, scanned: 0, total: planned, ...ROUND_RESET });
return strictPass(engine, sourceId, { sourceId, noPull: true, fullRound: true, ...processing, ...(phase === 'strict_pass_1' ? { canonicalOverride: 'git' as const } : {}),
onProgress: passProgress(report) });
};
@@ -583,7 +609,7 @@ function passProgress(report: ConversionReporter): NonNullable<SyncOpts['onProgr
let base = 0;
return event => {
const round = event.round;
- if (round && event.phase === 'managed_sync.round_level') { base = 0; report({ round: round.round, scanned: 0, candidates: undefined, batch: undefined, batches: undefined }); }
+ if (round && event.phase === 'managed_sync.round_level') { base = 0; report({ ...ROUND_RESET, round: round.round, scanned: 0 }); }
else if (round && event.phase === 'managed_sync.round_admit') report({ round: round.round, scanned: 0, candidates: (round.imports ?? 0) + (round.deletes ?? 0) });
else if (round && event.phase === 'managed_sync.round_batch') { base = round.base ?? 0; report({ round: round.round, scanned: base, batch: round.batch, batches: round.batches }); }
else if (event.bankedFiles !== undefined && event.phase !== 'managed_sync.level_progress' && event.phase !== 'managed_sync.legacy_swept') report({ scanned: base + event.bankedFiles });
diff --git a/src/core/persistence/sync-receipt-wait.ts b/src/core/persistence/sync-receipt-wait.ts
new file mode 100644
index 0000000000..0b36b8e87f
--- /dev/null
+++ b/src/core/persistence/sync-receipt-wait.ts
@@ -0,0 +1,16 @@
+/**
+ * How long a managed sync pass waits on its own admitted write: a single pass stops `writer_pending` after `pass` (`held`
+ * while this process's consumer still holds the write, #6712 item 7), and a drain re-enters after `drain`. One place with a
+ * test seam (#7886), so a test can outlast a wait in milliseconds instead of sleeping past 30 s.
+ */
+const DEFAULTS = { pass: 5000, held: 30_000, drain: 30_000 };
+let waits = DEFAULTS;
+
+export const syncReceiptWait = (): typeof DEFAULTS => waits;
+
+/** Test seam: replace some of the waits (null restores the defaults). Returns a function that restores the previous ones. */
+export function __setSyncReceiptWaitForTests(next: Partial<typeof DEFAULTS> | null): () => void {
+ const previous = waits;
+ waits = next ? { ...DEFAULTS, ...next } : DEFAULTS;
+ return () => { waits = previous; };
+}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 1e59282d75..188ee6a796 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -55,6 +55,7 @@ import { checkpointSuperseded } from './sync-checkpoint-replaced.ts';
import { publicFailureDetail } from './publication-failure.ts';
import { dependentHold, fileDriftHold, sharedOriginSurvivor, fileChangedAfterAdmission, headCommittedBytes, liveRevision, idempotentDeletionProof, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';
import { faultPoint } from './fault-points.ts';
+import { syncReceiptWait } from './sync-receipt-wait.ts';
import { directoryAt, freezeFaultHold, noteFrozen, nullBytesRefusal } from './sync-entry-fault.ts';
import { syncCursorOptions } from './sync-slices.ts';
import { pipelined } from '../page-state/transactions.ts';
@@ -1443,7 +1444,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
let creditedPages = 0, creditStarted = 0, foregroundQueued = false, screenedAdmit: string | null = null;
const sliceStarted = sliceBase?.started ?? performance.now(), sliceFirstIndex = cursor.index - (sliceBase?.pages ?? 0), drainStartedAt = opts.drainStartedAt ?? Date.now();
// #6712 PR 4b: a local pass waits on its own write up to 30 s while this process's consumer still holds it (item 7).
- const whileHeld = !opts.drainStartedAt && !!cursor.passId && !authority.writer.remote ? { whileHeldMs: 30_000 } : {};
+ const whileHeld = !opts.drainStartedAt && !!cursor.passId && !authority.writer.remote ? { whileHeldMs: syncReceiptWait().held } : {};
const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null, foregroundFirst: await foregroundPriority(engine) };
const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(startupConfig), prescreen = { missed: new Set<number>(), limit: Infinity, drainStartedAt, assertActive, signal, onProgress: opts.onProgress,
embeddingRequested: !(cursor.processingOptions ?? processingOptions).noEmbed && !opts.embedDeferred && !config.embedding_disabled && !!config.embedding_model?.trim() };
@@ -1516,7 +1517,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
const freezeAt: FreezeAt = base => async index => { if (base.entries[index]?.prescreened && !prescreen.missed.has(index)) return null; const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun).catch(() => null); return frozen && 'requestId' in frozen ? frozen : null; }; // GBRA-133 S-64: a follower's throw is raised by the single path, naming its own entry
if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && indexOf(cursor, pending) === cursor.index && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);
if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {
- const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000, signal, ...whileHeld }, drainStartedAt, opts.onProgress,
+ const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: syncReceiptWait().drain, signal } : { waitMs: syncReceiptWait().pass, signal, ...whileHeld }, drainStartedAt, opts.onProgress,
opts.drainStartedAt ? next => admitAhead(engine, next, key, bulk, config, freezeAt, assertActive) : undefined);
if ('result' in step) return step.result;
cursor = step.cursor;
@@ -1531,7 +1532,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
// #5762: a checkpoint's validation runs under the coordinator's 5 s statement timeout, so its wait outlasts that
// budget; a timed-out checkpoint then reports its terminal refusal and hint in this run instead of the next.
// #5984: a drain re-enters anyway, so it waits longer per page instead of paying a full re-entry; the stop signal bounds every wait (awaitWrite).
- const waited = await awaitWrite(engine, row, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : 5000, signal, ...whileHeld });
+ const waited = await awaitWrite(engine, row, config, opts.drainStartedAt ? { waitMs: syncReceiptWait().drain, signal } : { waitMs: pending.intent.kind === 'managed_sync_checkpoint' ? 8000 : syncReceiptWait().pass, signal, ...whileHeld });
const done = waited.row;
assertSyncDispatchActive();
if (!isTerminalWriteState(done.state)) {
@@ -1554,7 +1555,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
}
if (done.state !== 'committed') {
const settled = await settleFailedRequest(engine, { cursor, key, pending, done, assertActive, run: frozenRun, syncOptions, processingOptions,
- remote: authority.writer.remote, waitMs: opts.drainStartedAt ? 30_000 : 5000, signal });
+ remote: authority.writer.remote, waitMs: opts.drainStartedAt ? syncReceiptWait().drain : syncReceiptWait().pass, signal });
if ('result' in settled) return settled.result;
cursor = settled.cursor;
opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length });
diff --git a/test/git-canonical-conversion-no-checkout-7885.test.ts b/test/git-canonical-conversion-no-checkout-7885.test.ts
new file mode 100644
index 0000000000..9f59506f89
--- /dev/null
+++ b/test/git-canonical-conversion-no-checkout-7885.test.ts
@@ -0,0 +1,47 @@
+/**
+ * #7885: `sources canonical --to git` on a managed source whose root is not a Git checkout (a repo-less source, or a
+ * fresh `git init` with no commit yet) refuses with a typed host refusal before anything is read, instead of
+ * `internal_error` from a raw `git rev-parse`. The source stays usable as it is: its pages still write.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { operationsByName } from '../src/core/operations.ts';
+import { planGitConversion } from '../src/core/persistence/git-conversion.ts';
+import { runSourcesCanonical } from '../src/commands/sources-canonical.ts';
+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const note = (body: string) => `---\ntype: concept\ntitle: note\n---\n\n${body}\n`;
+const plain = ({ root }: { root: string }) => { mkdirSync(join(root, 'notes'), { recursive: true }); writeFileSync(join(root, 'notes/a.md'), note('A plain file.')); };
+const unborn = ({ root }: { root: string }) => { plain({ root }); execFileSync('git', ['-C', root, 'init', '-q']); };
+
+async function cli(engine: Parameters<typeof runSourcesCanonical>[0], args: string[]): Promise<Record<string, unknown>> {
+ const out: string[] = [];
+ const log = console.log, write = process.stderr.write, priorExitCode = process.exitCode;
+ console.log = (line: unknown) => { out.push(String(line)); };
+ process.stderr.write = (() => true) as typeof process.stderr.write;
+ try { await runSourcesCanonical(engine, args); }
+ finally { console.log = log; process.stderr.write = write; _resetCliExitVerdictForTests(); process.exitCode = priorExitCode ?? 0; }
+ return JSON.parse(out.at(-1)!);
+}
+
+for (const backend of testBackends()) describe(`[${backend}] #7885: --to git on a managed source without a Git checkout`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ for (const [name, setup, code] of [['a plain directory', plain, 'git_checkout_required'], ['a git init with no commit', unborn, 'git_branch_unborn']] as const) {
+ test(`${name}: preview and apply refuse ${code} with a fix, read nothing and write nothing; pages still write`, () => managedBrain(async ({ engine, ctx }) => {
+ await expect(planGitConversion(engine, 'default')).rejects.toMatchObject({ code });
+ for (const args of [['--dry-run', '--json'], ['--apply', '--expect', 'a'.repeat(64), '--json']]) {
+ const refused = await cli(engine, ['default', '--to', 'git', ...args]);
+ expect(refused).toMatchObject({ status: 'refused', code, fix: { argv: ['gbrain', 'sources', 'canonical', 'default', '--to', 'git', '--dry-run', '--json'], actor: 'user' } });
+ expect(String(refused.message)).toContain('stays usable as it is');
+ }
+ expect(await engine.executeRaw("SELECT 1 FROM sources WHERE id='default' AND config->>'canonical'='git'")).toHaveLength(0);
+ const written = await operationsByName.put_page.handler(ctx, { slug: 'notes/after', content: note('Written after the refusal.') }) as { status: string };
+ expect(written.status).toBe('created_or_updated');
+ }, { databaseUrl, setup }), 120_000);
+ }
+});
diff --git a/test/git-canonical-conversion-strict-pass-7866.test.ts b/test/git-canonical-conversion-strict-pass-7866.test.ts
index 124077d5fb..0742a3356b 100644
--- a/test/git-canonical-conversion-strict-pass-7866.test.ts
+++ b/test/git-canonical-conversion-strict-pass-7866.test.ts
@@ -16,6 +16,8 @@ import type { SyncResult } from '../src/commands/sync.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { withDrainLease } from '../src/core/persistence/sync-lease.ts';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { chunksEmbeddedAsIs } from '../src/core/persistence/noop-kernel.ts';
+import { __setSyncReceiptWaitForTests } from '../src/core/persistence/sync-receipt-wait.ts';
import { applyGitConversion, planGitConversion, type ConversionProgress } from '../src/core/persistence/git-conversion.ts';
import { runSourcesCanonical } from '../src/commands/sources-canonical.ts';
import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
@@ -104,6 +106,16 @@ for (const backend of testBackends()) describe(`[${backend}] #7866: the conversi
expect(queued.map(row => Number(row.page_id)).sort((a, b) => a - b)).toEqual([ids['notes/n05']!, ids['notes/n08']!].sort((a, b) => a - b));
}, { databaseUrl, setup }), 300_000);
+ // Value: protects=chunksEmbeddedAsIs reads a chunk with no vector in the active column as owing embedding work; fails_when=the predicate drops its NULL-vector clause; why_new=the conversion round never re-imports such a page, so only a direct call reaches the clause (#7886); seam=none; no_claim=which effect a sync queues (covered above)
+ test('chunksEmbeddedAsIs: a page whose chunk has no vector in the active column still owes embedding work', () => managedBrain(async ({ engine }) => {
+ await firstSync(engine);
+ await legacyEmbedded(engine);
+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug='notes/n06'");
+ expect(await chunksEmbeddedAsIs(engine, Number(page!.id))).toBe(true);
+ await engine.executeRaw('UPDATE content_chunks SET embedding=NULL WHERE id=(SELECT min(id) FROM content_chunks WHERE page_id=$1)', [page!.id]);
+ expect(await chunksEmbeddedAsIs(engine, Number(page!.id))).toBe(false);
+ }, { databaseUrl, setup }), 300_000);
+
// Value: protects=the human-mode refusal prints the Next: command from fix and strict-pass stderr progress names the planned paths; fails_when=the Next: line or the strict-pass progress text is dropped; why_new=the drainer test reads --json only; seam=none; no_claim=JSON contract (covered by the drainer test)
test('a refused apply in text mode prints the refusal with the fix command as Next, and strict-pass progress on stderr', () => managedBrain(async ({ engine, root }) => {
await firstSync(engine);
@@ -125,33 +137,36 @@ for (const backend of testBackends()) describe(`[${backend}] #7866: the conversi
expect(err.join('')).toContain(`[sources canonical] strict_pass_1: ${N} planned path(s), 0 group(s) committed`);
}, { databaseUrl, setup }), 300_000);
- test('a strict pass whose own write outlives the single pass\'s receipt wait drains on instead of refusing writer_pending', () => managedBrain(async ({ engine, root }) => {
+ for (const phase of ['strict_pass_1', 'strict_pass_2'] as const) test(`${phase}: a strict pass whose own write outlives the single pass's receipt wait drains on instead of refusing writer_pending`, () => managedBrain(async ({ engine, root }) => {
await firstSync(engine);
- writeFileSync(join(root, 'notes/n03.md'), note(3, 'Edited in Git after the last sync.'));
- git(root, 'commit', '-qam', 'edit n03');
+ const slug = phase === 'strict_pass_1' ? 'n03' : 'n04';
+ const edit = () => { writeFileSync(join(root, `notes/${slug}.md`), note(3, 'Edited in Git after the last sync.')); git(root, 'commit', '-qam', `edit ${slug}`); };
+ if (phase === 'strict_pass_1') edit();
const seen: ConversionProgress[] = [];
- let stalled = false;
- // Once the strict pass froze its import, the consumer stops claiming for 33 s: the admitted request waits queued past
- // the single pass's receipt wait (5 s, held to 30 s while queued here), as it does behind a busy owner on a production host.
- let armed = false;
+ let stalled = false, armed = false;
+ // The waits are scaled down (#7886): once the pass froze its import, the consumer stops claiming for longer than the
+ // single pass's receipt wait (held while queued here), as it does behind a busy owner on a production host. Pass 2 gets
+ // its import from a Git commit landed between the passes.
+ const restore = __setSyncReceiptWaitForTests({ pass: 200, held: 600, drain: 600 });
installFaultHook(async point => {
- if (point === 'sync:after_freeze' && seen.at(-1)?.phase === 'strict_pass_1') armed = true;
+ if (point === 'conversion:before_flip' && phase === 'strict_pass_2') edit();
+ if (point === 'sync:after_freeze' && seen.at(-1)?.phase === phase) armed = true;
if (point !== 'consumer:claiming' || !armed || stalled) return;
stalled = true;
- // gstack-timing-ok: the stall must outlast the 30 s receipt wait; the assertions read the outcome, not the elapsed time
- await Bun.sleep(33_000);
+ // gstack-timing-ok: the stall must outlast the injected 600 ms receipt wait; the assertions read the outcome, not the elapsed time
+ await Bun.sleep(1500);
});
try {
expect(await convert(engine, seen)).toMatchObject({ status: 'converted' });
- } finally { installFaultHook(undefined); }
+ } finally { installFaultHook(undefined); restore(); }
expect(stalled).toBe(true);
- const [page] = await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE slug='notes/n03'");
+ const [page] = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE slug='notes/${slug}'`);
expect(page!.compiled_truth).toContain('Edited in Git after the last sync.');
// The round names its candidate and its one import batch; the total stays the planned paths.
- const pass1 = seen.filter(progress => progress.phase === 'strict_pass_1');
- expect(pass1.every(progress => progress.total === N)).toBe(true);
- expect(pass1.some(progress => progress.round === 1 && progress.candidates === 1 && progress.batch === 1 && progress.batches === 1)).toBe(true);
- expect(pass1.every(progress => progress.scanned <= (progress.candidates ?? 0))).toBe(true);
+ const pass = seen.filter(progress => progress.phase === phase);
+ expect(pass.every(progress => progress.total === N)).toBe(true);
+ expect(pass.some(progress => progress.round === 1 && progress.candidates === 1 && progress.batch === 1 && progress.batches === 1)).toBe(true);
+ expect(pass.every(progress => progress.scanned <= (progress.candidates ?? 0))).toBe(true);
}, { databaseUrl, setup }), 300_000);
test('a concurrent drainer of the source refuses the apply with the operator contract and counts, before anything is flipped', () => managedBrain(async ({ engine, root }) => {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 3ddc103718..290eadc3f2 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -84,6 +84,7 @@ test/forecast-journal.test.ts
test/frontmatter-reserved-keys-6454.test.ts
test/get-chunks-paging.test.ts
test/git-canonical-conversion-g8a.test.ts
+test/git-canonical-conversion-no-checkout-7885.test.ts
test/git-canonical-conversion-progress.test.ts
test/git-canonical-conversion-strict-pass-7866.test.ts
test/git-canonical-declared-g7a.test.ts