Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(convergence): the #6712 L0 gate harness, per-mode brains and one fault preload
garrytan84b3e9ed0449
diff --git a/docs/architecture/key-files/core-persistence-request-indexes.md b/docs/architecture/key-files/core-persistence-request-indexes.mdindex 2f7e2009d5..036adb54a9 100644--- a/docs/architecture/key-files/core-persistence-request-indexes.md+++ b/docs/architecture/key-files/core-persistence-request-indexes.md@@ -5,5 +5,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELThe online-built request-table indexes (the managed sync checkpoint pair, the page purge's slug index), the checkpoint validation they serve, the named fault seams the persistence gate and the purge tests inject at, and the stuck-recovery resolution (`gbrain repair stuck-recovery`) that uses them.- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index of `PERSISTENCE_REQUEST_ONLINE_INDEXES` (or the list passed) as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.-- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`) `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload.+- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`), `sync:after_freeze` (#6712 PR 0: at the end of `freezeEntry` for an import entry, after its bytes are read and before the request is admitted; detail carries `slug` and `path`), `consumer:prepared` (between preparing a claimed request and publishing it), `stuck_recovery:*` (between the steps of `recovery-resolve.ts`) and the purge lookups `purge:*` (page-purge.ts, intent-redaction.ts, facts/purge.ts; a hook throwing a 57014 models a statement timeout). Used by `scripts/persistence/crash-robot.ts`, the #6511 tests and `test/sync-convergence.serial.test.ts`, which installs it in real `serve`/`sync` processes through the `test/fixtures/convergence-fault-kill.ts` preload (one action registry: kill, uncommitted edit, stall until released, or throw a given SQLSTATE, at the nth hit).- `src/core/persistence/recovery-resolve.ts` + `src/core/repair/stuck-recovery.ts` — `gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]` (#6650 §1.10), explicit-only, preview-bound and destructive (registry `consentText`; `--apply --expect <hash> --keep prior|disk --yes`, a non-interactive apply without `--yes` exits 3). `scanStuckRecoveries` (owner host only, else `owner_unavailable` for a named source) reads the source's queued head blocker (`readHeadBlockers`; its `request_recovery` ids select the records) and every non-terminal recovery record on the worktree blocked on `unexpected_file_bytes` or whose file matches neither recorded version; a v2 shared-skill bundle record refuses `recovery_bundle_unsupported` (catalogue entry, `docs/guides/repair.md#recovery-bundle-unsupported`), a withdrawal-mirror effect recovery on the worktree is listed in `refused` (residual `effect_recovery`; named with `--request-id` it refuses `recovery_effect_unsupported`), a blocked terminal request is listed in `refused` (residual `terminal_refused`; named with `--request-id` it refuses `recovery_choice_refused`, as does a choice the record cannot support), and unblocked terminal cleanups, staging-byte blocks and self-recovering records are residuals. Each item lists every file's prior (or absent) and disk (or deleted) fingerprints and what recovery sees; a local preview writes the prior, disk and unified-diff files 0600 under `~/.gbrain/backups/stuck-recovery/<request>/<digest>/` (a private directory outside every checkout) and prints the `diff -u` command. The item digest binds the recovery identity (attempt, owner epoch, path and published hash per file), the recorded prior hashes, each file's disk view and the page's `knowledge_revision`. `resolveStuckRecovery` runs under `acquireWorktree` with a bounded wait (10 s, then `writer_lock_unavailable`; so the resident recovery pass returns unchanged), re-verifies the digest (`preview_changed`) and journals in `op_checkpoints` op `stuck-recovery-resolution` keyed `<request row id>:<preview hash>` (exempt from the checkpoint purge; the finished row is the audit entry): `backed_up` (disk and prior bytes durable, always), then `written` (`--keep prior`: `upgradeRecoveryStaging` reserves an older record's restoration stage within the recovery budget, `queue_capacity` otherwise, then the prior bytes are published through `publishPersistenceFile` at that stage after `cleanupRecoveryStaging`, an absent prior unlinked) or `abandoned` (`--keep disk`, #6640's drop: `completeWrite` ends the live request `conflict` `source_changed`, or `finishUnpublishedFailure` with its recorded failure; the record is never rewritten, so its reserved bytes are released by the terminal path's `clearResolvedRecovery`), then `recoverPublication(…, alreadyLocked)` finishes by its unchanged rule and the journal records `done` with the result. A step refuses `unexpected_file_bytes` when the file changed again; a different `--keep` for the same hash refuses `idempotency_conflict`; an identical apply after `done` replays the result (also after the approved set aged out). A record the resident consumer (any version) or an earlier killed run already finished reports `finished_by: another_pass`. `--keep prior` on a request with no recorded failure requeues it (the accepted write publishes again). `--keep disk` hands off to `gbrain sources reconcile <source> <slug> --brain host --preview` and never reports the page repaired. Fault seams `stuck_recovery:{backed_up,written,abandoned,recovered}`. Tests: `test/repair-stuck-recovery.test.ts`, `test/e2e/repair-stuck-recovery-postgres.test.ts`.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3b9a844083..bda9054a4c 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 1688 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; +1 #6712 PR 0: the test-only sync:after_freeze fault seam at the end of freezeEntry (no-op without an installed hook), where the gate edits an entry after it is frozensrc/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/scripts/persistence/README.md b/scripts/persistence/README.mdindex 953176bdfc..ec2bfc8733 100644--- a/scripts/persistence/README.md+++ b/scripts/persistence/README.md@@ -537,30 +537,78 @@ The CLI without `--informational` still enforces the threshold. The originalheavy shell entry invokes this harness; its optional `STRICT_LATENCY=1`flag affects only the latency threshold, never validity requirements.-### Managed-sync convergence harness (quarantined)--`test/sync-convergence.serial.test.ts` (#6650) is a real-process profile of-this gate. It uses the same fault seam (`src/core/persistence/fault-points.ts`,-preloaded into real `gbrain serve` and `gbrain sync` processes by-`test/fixtures/convergence-fault-kill.ts`, since production never installs a-hook) against one isolated Postgres brain behind transaction-mode PgBouncer,-through an in-test TCP proxy that adds 50 ms of round-trip latency to the-pooled and the direct URL. It SIGKILLs the resident serve and a sync client at-seeded publication fault points while a writer rewrites 5% of the pages with-`gbrain put`, then allows at most three plain `gbrain sync --no-pull` runs-under a fresh serve (only exit 0 with outcome `synced` counts) and checks the-oracle: disk == database, no blocking request, every non-committed terminal-request superseded or carrying a registered code, the cursor at HEAD, and no-lost fact or timeline row on the large page (timeline duplicates are printed,-not asserted), the next sync delegating to the live serve whatever heartbeat a-killed client left, and no sync after an owner kill stalling longer than the-consumer liveness window plus one renewal and 30 s of slack. Each check is its own test, named by this gate's violation-class; elapsed times and the longest stall each sync printed are-`[convergence]` lines.--It skips unless `GBRAIN_TEST_CONVERGENCE=1`, no CI lane sets that, and a run-takes about 18 minutes at 50 ms (under 2 at 0 ms). Run it against the E2E-Postgres plus a PgBouncer in front of it:+### Managed-sync convergence gate++`test/sync-convergence.serial.test.ts` (#6650, the #6712 L0 gate) is a+real-process profile of this gate. It uses the same fault seam+(`src/core/persistence/fault-points.ts`, preloaded into real `gbrain serve` and+`gbrain sync` processes by `test/fixtures/convergence-fault-kill.ts`, since+production never installs a hook). The preload acts once, at the nth hit of+one point, through a registry of actions: `kill` (SIGKILL), `stall` (until the+harness releases it), `edit` (an uncommitted worktree edit) and `throw` (an+error carrying a given SQLSTATE, as the driver reports a database error). Each+scenario builds its own Postgres database behind transaction-mode PgBouncer,+reached through an in-test TCP proxy that adds the configured round-trip+latency to the pooled and the direct URL.++The chaos modes, each named in failures and selectable with+`GBRAIN_TEST_CONVERGENCE_MODES`:++| Mode | What happens | Expected end state | On master |+| --- | --- | --- | --- |+| (a) client kills, (b) serve kills | A kill loop of `GBRAIN_TEST_CONVERGENCE_KILLS` change rounds, each ending in one `kill -9` at a point of the curated list (`publication:before_commit`, `publication:after_commit`, `consumer:preparing`, `lane:applied`, `sync:before_group_admission`, `sync:mid_checkpoint`), cycling a `--no-delegate` client, a serve running a delegated catch-up, and a serve with its delegating client | strict convergence | runs |+| (c) concurrent writers | During the kill loop: `gbrain put` rewrites of 5% of the notes, `remember` facts on an entity page, `gbrain extract timeline --source db` (a managed maintenance job) | strict convergence; every acknowledged write in the ledger | runs |+| (c-db) DB-only competitor | With `sync.write_through=false`, a DB-only `put` lands while the run is stalled on that page's frozen entry, and another on a page whose file did not change | the raced page is held `concurrent_write` (needs a person), its file keeps the committed bytes and its page the DB write; both pages are left out of disk == DB | runs |+| (d) out-of-band Git | While a run is stalled mid-manifest: `git mv` and `git rm` of 1% of the files, committed, and deletion of 1% uncommitted | moves and removals converge strictly; each uncommitted deletion is listed by `gbrain pages ghosts` with the `gbrain repair ghost-pages` exit and left out of disk == DB | runs |+| (e) mid-run edit | The `sync:after_freeze` hook writes an uncommitted edit to a seeded entry after it was frozen | the run's receipt and `sync status` name `worktree_dirty`; after the editor commits, strict convergence | skipped until PR 1 of #6712: no `worktree_dirty` hold is named, and the run churns through `source_changed` conflicts and cancellations (5 of 20 entries after 150 s) |+| (f) pooler drop | Every pooled connection drops at the proxy after 20 committed pages of a bulk run (`GBRAIN_TEST_CONVERGENCE_PGBOUNCER_CONTAINER=<name>` restarts that container instead) | no new hold; the drain resumes within the owner-kill stall bound; strict convergence | skipped until PR 1 of #6712: it converges with no hold, but publication stalls 356 s (a publication lease) after the drop |+| (g) two drainers | `sync --all --no-delegate` beside a serve draining a delegated sync of the same source | strict convergence | runs |+| (knock-on) | One page's publication throws P0001 once inside a bulk group, then a trigger refuses one page with P0001 for a whole run | no other page of the run is cancelled; strict convergence once the trigger is gone | skipped until PR 1 of #6712: the one-shot throw is retried and cancels nothing, but the refused page cancels the run's other 74 requests, and both plain syncs after the trigger is dropped stop `blocked_by_failures` on the frozen `storage_error` request until `--retry-failed` |+| (systemic) | A trigger on `pages` raises an unregistered P0001 (one scenario) or 55000 (another) on every page write for one run, then is dropped | the refused run does not report success and its receipt names the SQLSTATE; strict convergence once the trigger is gone | skipped until PR 1 of #6712: the refused run stops `blocked` naming the SQLSTATE, but both plain syncs after the trigger is dropped stay `blocked_by_failures` until `--retry-failed` |++A skipped mode stays written; naming it in `GBRAIN_TEST_CONVERGENCE_MODES` runs it+anyway, which is how the PR that fixes it turns it on.++After the chaos every scenario gets a fresh serve (what a supervisor restarts)+and at most two plain `gbrain sync --no-pull` runs, with no operator step; only+exit 0 with outcome `synced` counts. Then the oracle, each check its own test+named by this gate's violation class: disk == database both ways (except the+pages the mode's end state names), no request queued, running, recovering or+holding a recovery record, every non-committed terminal request superseded or+carrying a registered code, the cursor at HEAD, no lost fact or timeline row on+the large page (timeline duplicates are printed, not asserted), the next sync+delegating to the live serve whatever heartbeat a killed client left, no sync+after an owner kill stalling longer than the consumer liveness window plus one+renewal and 30 s of slack, and two oracles independent of the brain's own+bookkeeping:++- **The acknowledged-write ledger.** Every writer operation that returned+ success (a harness commit, a `put`, a `remember`, a maintenance run, a DB-only+ write, a `git mv`/`git rm`, an uncommitted deletion) is recorded by the harness+ with the time it started and the time it was acknowledged, and where it+ landed (the page, its file, or an additive fact). For every page and location+ the final state must show a write that no later acknowledged write causally+ supersedes (none started after it was acknowledged); a remembered fact must+ survive unless a page write on its entity may have been ordered after it.+- **The status oracle.** `gbrain sync status --source <id> --json` must carry+ every field the operator loop reads (`checkpoint_blockers` and `cursors`+ arrays, `checkpoint_blockers` empty, `terminal_failures` `ok` with no active+ blocker, `needs_human`, `holds` exactly the end state's, `last_error` and+ `next` null) and a finished cursor (done, or retired to `null`).+ `checkpoint_blockers` is present on every status, empty when no checkpoint is+ pending (`test/sync-status-checkpoint-blockers-shape.test.ts` pins the four+ cursor states); PR 2 of #6712 moves the heavy reads behind `sync status+ --detail` and the oracle then reads that. An always-on calibration test proves+ the oracle fails when any required field is missing.++Every random choice (victims, fault points and their nth hit, writer targets)+comes from `GBRAIN_TEST_CONVERGENCE_SEED`, and every failure prints the seed,+the scenario's modes, the fault plan, which faults fired, and a one-line repro+command. `[convergence <scenario>]` lines print elapsed times and the longest+stall each sync printed.++It skips unless `GBRAIN_TEST_CONVERGENCE=1`. Run it against the E2E Postgres+plus a PgBouncer in front of it:```bashdocker network create gbtest@@ -570,20 +618,38 @@ docker run -d --name gbrain-test-pgbouncer --network gbtest -e DB_HOST=gbrain-te-e DB_USER=postgres -e DB_PASSWORD=postgres -e POOL_MODE=transaction -e AUTH_TYPE=plain \-e IGNORE_STARTUP_PARAMETERS=extra_float_digits,statement_timeout,idle_in_transaction_session_timeout,search_path \-p 6543:5432 edoburu/pgbouncer:latest-GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@localhost:6543/gbrain_test \-GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@localhost:5434/gbrain_test \- bun run test:convergence+export GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@localhost:6543/gbrain_test+export GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@localhost:5434/gbrain_test+GBRAIN_TEST_CONVERGENCE_LATENCY_MS=10 bun run test:convergence # the PR cell+GBRAIN_TEST_CONVERGENCE_MODES=e bun run test:convergence # one mode, skipped or notdocker rm -f gbrain-test-pgbouncer gbrain-test-pg && docker network rm gbtest```-Knobs: `GBRAIN_TEST_CONVERGENCE_SEED` (default 6650) fixes the fault plan and-the writer's targets, so a failure reproduces; `GBRAIN_TEST_CONVERGENCE_LATENCY_MS`-(default 50; 0 for a fast local loop); `GBRAIN_TEST_CONVERGENCE_LOG_DIR` keeps-every client, serve and writer log. `GBRAIN_TEST_CONVERGENCE_PGBOUNCER_CONTAINER=<name>`-adds a round that runs `docker restart -t 0 <name>` once the drain has-committed 20 pages. That round restarts the pooler, not the database, and-cannot place the restart between a COMMIT and its reply, so a database or-pooler restart with an uncertain commit stays an uncovered case.+Knobs (`GBRAIN_TEST_CONVERGENCE_*`): `SEED` (default 6650), `MODES` (default:+every mode not skipped), `NOTES` (default 200; the large page is always there),+`KILLS` (default 6), `LATENCY_MS` (default 50; 0 for a fast local loop),+`SYNC_TIMEOUT_MS` (per child process, default 900000), `SCENARIO_TIMEOUT_MS`+(per scenario, default 3600000), `LOG_DIR` (keeps `convergence.log` and every+client, serve and writer log per scenario) and `PGBOUNCER_CONTAINER` (mode (f)).++CI: the `convergence` job of `.github/workflows/persistence-validation.yml`, on+both supported Bun versions with the deployment matrix's pgvector and+transaction-mode PgBouncer services. Pull requests run it when+`scripts/ci-convergence-scope.sh` selects their diff (persistence, sync,+projections, storage, the harness and its workflow; never `package.json`+alone; `bun.lock` and `vendor/postgres/` select it, since a driver change is a+persistence change); merge-queue runs and pushes always run it. Those run the+PR cell: 200 notes at 10 ms, 6 kills, seed 6650.++The nightly cell is its own scheduled workflow,+`.github/workflows/convergence-nightly.yml` ("Convergence nightly", its own+concurrency group, outside `test.yml` and its `test-status` gate): 2,000 notes+at 50 ms, 20 kills, the run id as the seed (`workflow_dispatch` takes a seed to+replay one), with a 300-minute step timeout inside a 330-minute job, so the+cleanup step (it kills any harness process a timed-out step left), the failure+summary (every failing test with its seed, fault plan, fired faults and repro+line) and the upload of `LOG_DIR` still run. The nightly watcher+(`nightly-watch.yml`) files its failures like every other scheduled workflow.## Engine graduation testsdiff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex b62bee1d4d..9337707400 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -371,7 +371,7 @@ test/sources-push-cli.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_HOtest/spawn-seam-batch1-4992.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GIT_DIR) and spies on node:child_processtest/stdio-stderr-redirect.serial.test.ts global-state global-state: patches process stdout/stderr/consoletest/subagent-put-page-rejection.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gateway; spyOn putPage.handler-test/sync-convergence.serial.test.ts global-state global-state: binds local servers/ports (two latency proxies) and spawns serve/sync/put processes against one shared brain; its oracle tests read the single chaos scenario that beforeAll ran, across it() boundaries+test/sync-convergence.serial.test.ts global-state global-state: binds local servers/ports (two latency proxies per scenario) and spawns serve/sync/put/call processes against each scenario's brain; its oracle tests read the chaos scenario their describe's beforeAll ran, across it() boundariestest/sync-cost-gate.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/consoletest/sync-default-write-guard.serial.test.ts global-state global-state: spyOn console.error, console.log, process.exittest/sync-delegated-options-6696.serial.test.ts global-state global-state: process-wide test seams __resetDelegatedSyncForTests and the embedding transport; binds local servers/ports; patches process stdout/stderr/consolediff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 2c13cb8c86..a11a6aa6d3 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -290,7 +290,7 @@ test/scripts/ci-local-rendering.test.ts ci-local execution coverage 5 readFileSytest/scripts/ci-local-rendering.test.ts local test configuration through run-e2e 2 readFileSynctest/scripts/ci-local-rendering.test.ts required PgBouncer execution through run-e2e 1 readFileSynctest/scripts/ci-manifest-diff.test.ts test.yml dependency-audit scope 2 readFileSync-test/scripts/ci-pr-scope.test.ts pull-request CI scope 11 readFileSync+test/scripts/ci-pr-scope.test.ts pull-request CI scope 14 readFileSynctest/scripts/ci-runner-routing.test.ts CI runner routing 7 readFileSynctest/scripts/classify-tests.test.ts classify-tests detectors 23 bun-file,doctor-source-helper,exec-scan,readFileSync,source-surface-helpertest/scripts/classify-tests.test.ts structural-suites manifest 1 readFileSyncdiff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex df0f15d25d..e2cdf876d2 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -4,7 +4,7 @@* recovery path must finish: publication boundaries, after an effect's side* effect but before its completion is recorded, before a recovery record is* cleared, between sync checkpoints, after the consumer prepared a- * claimed request, (`lane:applied`) when a lane group has applied its pages and waits for its commit turn, and (`stuck_recovery:*`) between the steps of a stuck-recovery resolution. Production never installs a hook, so every call is a+ * claimed request, (`sync:after_freeze`) after a managed sync import entry is frozen and before it is admitted, (`lane:applied`) when a lane group has applied its pages and waits for its commit turn, and (`stuck_recovery:*`) between the steps of a stuck-recovery resolution. Production never installs a hook, so every call is a* no-op there; the gate's workers install one that SIGKILLs or stalls the* process at a chosen point.*/@@ -16,6 +16,8 @@ export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundexport type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid` | 'effect:embedding:settle'| 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'consumer:prepared'| 'consumer:preparing' | 'lane:applied'+ // #6712 PR 0: after `freezeEntry` froze an import entry (its bytes are read) and before the request is admitted or published.+ | 'sync:after_freeze'// #6511: the page purge's in-transaction journal lookups (page-purge.ts `journalLookup`); a hook that throws a 57014 models a statement timeout there.| 'purge:slug_lookup' | 'purge:tail_recheck' | 'purge:pending_recheck' | 'purge:redaction_read'// #6511: before each keyset chunk of the preparation-time journal sweep (a stalling hook models a slow chunk), and the fact purge's planning read.@@ -28,7 +30,7 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect* a stalling hook can model both the reporter's cases: a preparer that honours* cancellation (settle on abort) and one that ignores it (hang on).*/-export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null; signal?: AbortSignal }+export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null; signal?: AbortSignal; slug?: string; path?: string }type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;/** The mid-effect seam of every effect kind; a new kind without one fails typecheck. */diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex e355b0c092..75794de731 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -446,6 +446,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass}await validateSyncAuthority(engine, cursor.authority, slug);assertActive();+ if (entry?.action === 'import') await faultPoint('sync:after_freeze', { sourceId: cursor.sourceId, slug, path: entry.path });return remember(frozenSnapshot, { requestId: randomUUID(), slug, pageId, ...(occupantRebound ? { rebound: true as const } : {}), intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly,...(entry?.unownedDeletion ? { unownedDeletion: true } : {}),diff --git a/test/fixtures/convergence-fault-kill.ts b/test/fixtures/convergence-fault-kill.tsindex b74d4fa058..23371dc79c 100644--- a/test/fixtures/convergence-fault-kill.ts+++ b/test/fixtures/convergence-fault-kill.ts@@ -1,19 +1,45 @@/**- * Preload for test/sync-convergence.serial.test.ts: SIGKILLs this process at- * the nth hit of one named persistence fault point (`fault-points.ts`), after- * writing a marker that records where it died. Configured by- * GBRAIN_TEST_CONVERGENCE_FAULT = {"point","nth","marker"[,"operation"]}.+ * The one preload for test/sync-convergence.serial.test.ts: acts once, at the+ * nth hit of one named persistence fault point (`fault-points.ts`), after+ * writing a marker that records where. Configured by GBRAIN_TEST_CONVERGENCE_FAULT =+ * {"point","nth","marker"[,"operation"][,"path"][,"action"][,...action fields]}.+ * `operation` and `path` filter the hits counted (a hit without that detail+ * never matches). The actions (ACTIONS):+ *+ * kill (default) SIGKILL this process;+ * edit write `edit.content` to `edit.file` (an uncommitted worktree edit), then continue;+ * stall wait until the harness creates the `release` file, or for `ms` (at most 600 s), then continue;+ * throw throw an error carrying SQLSTATE `sqlstate` (default P0001), as the driver reports a database error.*/-import { writeFileSync } from 'node:fs';+import { existsSync, writeFileSync } from 'node:fs';import { installFaultHook, type FaultPoint } from '../../src/core/persistence/fault-points.ts';+interface Fault { point: FaultPoint; nth: number; marker: string; operation?: string; path?: string; action?: keyof typeof ACTIONS;+ edit?: { file: string; content: string }; release?: string; ms?: number; sqlstate?: string }++const ACTIONS = {+ kill: () => { process.kill(process.pid, 'SIGKILL'); },+ edit: (fault: Fault) => { writeFileSync(fault.edit!.file, fault.edit!.content); },+ stall: async (fault: Fault) => {+ const deadline = Date.now() + Math.min(fault.ms ?? 600_000, 600_000);+ while (Date.now() < deadline && !(fault.release && existsSync(fault.release))) await Bun.sleep(50);+ },+ throw: (fault: Fault, point: FaultPoint, nth: number) => {+ const sqlstate = fault.sqlstate ?? 'P0001';+ throw Object.assign(new Error(`convergence harness: injected ${sqlstate} at ${point} #${nth}`), { name: 'PostgresError', code: sqlstate, severity: 'ERROR' });+ },+} satisfies Record<string, (fault: Fault, point: FaultPoint, nth: number) => unknown>;+const raw = process.env.GBRAIN_TEST_CONVERGENCE_FAULT;if (!raw) throw new Error('convergence-fault-kill needs GBRAIN_TEST_CONVERGENCE_FAULT.');-const fault = JSON.parse(raw) as { point: FaultPoint; nth: number; marker: string; operation?: string };+const fault = JSON.parse(raw) as Fault;+const action = fault.action ?? 'kill';+if (!(action in ACTIONS)) throw new Error(`convergence-fault-kill: unknown action '${action}' (known: ${Object.keys(ACTIONS).join(', ')}).`);let seen = 0;-installFaultHook((point, detail) => {- if (point !== fault.point || (fault.operation && detail.operation !== fault.operation)) return;+installFaultHook(async (point, detail) => {+ if (point !== fault.point || (fault.operation && detail.operation !== fault.operation) || (fault.path && detail.path !== fault.path)) return;if (++seen !== fault.nth) return;- writeFileSync(fault.marker, JSON.stringify({ point, nth: seen, pid: process.pid, requestId: detail.requestId, operation: detail.operation ?? null }), { mode: 0o600 });- process.kill(process.pid, 'SIGKILL');+ writeFileSync(fault.marker, JSON.stringify({ point, nth: seen, pid: process.pid, requestId: detail.requestId, operation: detail.operation ?? null,+ path: detail.path ?? null, action }), { mode: 0o600 });+ await ACTIONS[action](fault, point, seen);});diff --git a/test/sync-convergence.serial.test.ts b/test/sync-convergence.serial.test.tsindex 17e09ecd05..26b7067d91 100644--- a/test/sync-convergence.serial.test.ts+++ b/test/sync-convergence.serial.test.ts@@ -1,55 +1,67 @@/**- * #6650 L0: the managed-sync convergence harness, quarantined.+ * #6650 L0 / #6712 PR 0: the managed-sync convergence gate.*- * One isolated Postgres brain behind PgBouncer in transaction mode, reached by- * every child process through a TCP proxy in this file that adds- * GBRAIN_TEST_CONVERGENCE_LATENCY_MS (default 50) of round-trip latency to the- * pooled URL and to the direct URL (GBRAIN_DIRECT_DATABASE_URL). The managed- * fixture is 200 notes plus one large, child-heavy page (a facts fence and a- * long timeline). Three chaos rounds, each on a new commit, while a writer- * rewrites 5% of the notes through the coordinator (`gbrain put`):- *- * 1. the resident `gbrain serve` owner is SIGKILLed at a publication fault- * point while it runs a delegated catch-up;- * 2. a `--no-delegate` sync client is SIGKILLed at a publication fault point- * in its own consumer;- * 3. a new serve is SIGKILLed at a publication fault point and the- * delegating client is SIGKILLed with it.- *- * Production never installs a fault hook, so the killed processes are the real+ * Each scenario builds one isolated Postgres brain behind PgBouncer in+ * transaction mode, reached by every child process through a TCP proxy in this+ * file that adds GBRAIN_TEST_CONVERGENCE_LATENCY_MS (default 50) of round-trip+ * latency to the pooled URL and to the direct URL (GBRAIN_DIRECT_DATABASE_URL).+ * The managed fixture is GBRAIN_TEST_CONVERGENCE_NOTES notes (default 200) plus+ * one large, child-heavy page (a facts fence and a long timeline). Production+ * never installs a fault hook, so the faulted processes are the real* `src/cli.ts serve` / `sync` entry points started with the hook-installing* preload test/fixtures/convergence-fault-kill.ts (the persistence gate's seam,- * `fault-points.ts`). With GBRAIN_TEST_CONVERGENCE_PGBOUNCER_CONTAINER set, a- * fourth round restarts that PgBouncer container under a running drain.+ * `fault-points.ts`), which kills, stalls, edits or throws a given SQLSTATE at a named point.*- * Recovery is a fresh serve (what a supervisor restarts) and at most three- * `gbrain sync --no-pull` runs, with no operator step; only exit 0 with outcome- * `synced` counts. The oracle tests then assert, each as its own test named by- * the persistence gate's violation class so a run names exactly which ones- * fail: disk == database for every page; no request blocks the checkpoint or a- * root; every non-committed terminal request is superseded (the page's current- * content hash equals the file's) or carries a registered error code; the- * cursor reached HEAD; the large page loses no fence fact or timeline entry and- * duplicates no fact; a killed client's heartbeat never keeps the next sync- * from delegating to the live serve; no sync after an owner kill stalls past- * `OWNER_KILL_STALL_BOUND_S`. Timeline duplicates and elapsed times (with the- * longest stall each sync printed) are measured and printed as `[convergence]`- * lines.+ * Chaos modes (MODES below; a mode master fails is skipped with the PR that turns it on):+ * (a) client kills and (b) serve kills mid-publish: a kill loop of+ * GBRAIN_TEST_CONVERGENCE_KILLS (default 6) seeded `kill -9`s at fault points+ * from the curated sync-reachable list KILL_POINTS, one per change round,+ * cycling a `--no-delegate` client, a resident serve running a delegated+ * catch-up, and a serve together with the client delegating to it;+ * (c) concurrent writers through the coordinator during the kill loop:+ * `gbrain put` rewrites, `remember` facts on an entity page and a managed+ * maintenance job (`gbrain extract timeline --source db`);+ * (c-db) a DB-only competitor: a DB-only write racing a file change of the+ * same page ends as a named `concurrent_write` hold with both versions+ * kept; a DB-only write to a page whose file did not change converges;+ * (d) out-of-band `git mv` / `git rm` of 1% of committed files and deletion+ * of uncommitted worktree files while a run is stalled mid-manifest;+ * (e) a deterministic mid-run edit: the `sync:after_freeze` hook edits a+ * seeded entry after it was frozen and before it is published;+ * (f) a pooler drop mid-bulk (no new holds);+ * (g) two concurrent drainers: a `--all` run beside a serve;+ * (knock-on) one page's failure inside a bulk group cancels none of the others;+ * (systemic) a trigger raising an unregistered P0001, then a 55000, on every+ * page write for one run: the run stops with one named blocker, and a+ * plain sync converges once the trigger is gone.*- * Every random choice (fault points, their nth hit, which notes the writer- * rewrites) comes from GBRAIN_TEST_CONVERGENCE_SEED (default 6650), so a- * failure reproduces. Run it with `bun run test:convergence` and- * GBRAIN_PGBOUNCER_URL / GBRAIN_PGBOUNCER_DIRECT_URL; scripts/persistence/README.md- * ("Managed-sync convergence harness") has the setup. It is skipped unless- * GBRAIN_TEST_CONVERGENCE=1.+ * Every scenario then gets a fresh serve (what a supervisor restarts) and at+ * most MAX_RECOVERY_RUNS plain `gbrain sync --no-pull` runs, with no operator+ * step; only exit 0 with outcome `synced` counts. The oracle tests are named by+ * the persistence gate's violation class: disk == database for every page+ * (except the pages a mode's end state names: a ghost, a held page); no request+ * blocks the checkpoint or a root; every non-committed terminal request is+ * superseded or carries a registered code; the cursor reached HEAD; the large+ * page keeps every fence fact; the acknowledged-write ledger (every writer+ * operation that returned success, recorded here independently of the brain)+ * survives or is causally superseded by a later acknowledged write; and+ * `gbrain sync status --json` reports the converged state with every field the+ * operator loop reads present.+ *+ * Every random choice comes from GBRAIN_TEST_CONVERGENCE_SEED (default 6650), and+ * every failure prints the seed, the scenario's modes, its fault plan and a+ * one-line local repro command. GBRAIN_TEST_CONVERGENCE_MODES=a,d,... runs+ * exactly those modes (a skipped mode named there runs anyway). Setup:+ * scripts/persistence/README.md ("Managed-sync convergence gate"). It is+ * skipped unless GBRAIN_TEST_CONVERGENCE=1.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { execFileSync, spawn, type ChildProcess } from 'node:child_process';import { randomUUID } from 'node:crypto';-import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { createConnection, createServer, type Server, type Socket } from 'node:net';import { tmpdir } from 'node:os';-import { join, relative, resolve } from 'node:path';+import { dirname, join, relative, resolve } from 'node:path';import postgres from '#postgres';import { PostgresEngine } from '../src/core/postgres-engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';@@ -67,27 +79,63 @@ import type { ViolationClass } from '../scripts/persistence/model.ts';const REPO_ROOT = resolve(import.meta.dir, '..');const FAULT_PRELOAD = join(REPO_ROOT, 'test/fixtures/convergence-fault-kill.ts');-const SEED = Number(process.env.GBRAIN_TEST_CONVERGENCE_SEED ?? '6650');-const LATENCY_MS = Number(process.env.GBRAIN_TEST_CONVERGENCE_LATENCY_MS ?? '50');+const knob = (name: string, fallback: number): number => {+ const raw = process.env[`GBRAIN_TEST_CONVERGENCE_${name}`];+ const value = raw === undefined || raw === '' ? fallback : Number(raw);+ if (!Number.isInteger(value) || value < 0) throw new Error(`GBRAIN_TEST_CONVERGENCE_${name} must be a non-negative integer, got '${raw}'.`);+ return value;+};+const SEED = knob('SEED', 6650);+const LATENCY_MS = knob('LATENCY_MS', 50);+const NOTES = Math.max(20, knob('NOTES', 200));+const KILLS = knob('KILLS', 6);+/** Per child process (a sync or a writer call) and per scenario setup; the nightly cell raises both. */+const SYNC_TIMEOUT_MS = knob('SYNC_TIMEOUT_MS', 900_000);+const SCENARIO_TIMEOUT_MS = knob('SCENARIO_TIMEOUT_MS', 3_600_000);const pooledTarget = process.env.GBRAIN_PGBOUNCER_URL;const directTarget = process.env.GBRAIN_PGBOUNCER_DIRECT_URL;const enabled = process.env.GBRAIN_TEST_CONVERGENCE === '1';if (enabled && !(pooledTarget && directTarget)) {throw new Error('GBRAIN_TEST_CONVERGENCE=1 needs GBRAIN_PGBOUNCER_URL (transaction-mode PgBouncer) and GBRAIN_PGBOUNCER_DIRECT_URL (the Postgres behind it).');}-const describeConvergence = enabled ? describe : describe.skip;+const PGBOUNCER_CONTAINER = process.env.GBRAIN_TEST_CONVERGENCE_PGBOUNCER_CONTAINER;+const LOG_DIR = process.env.GBRAIN_TEST_CONVERGENCE_LOG_DIR;++/** The chaos modes. `skip` names the PR that turns a mode master fails on; the mode stays written and runs when named in GBRAIN_TEST_CONVERGENCE_MODES. */+const PR1 = 'PR 1 of #6712 (L1 content-addressed resume + L2 one page, one fate + the drain lease)';+const MODES = {+ a: { title: 'client kills', skip: null },+ b: { title: 'serve kills mid-publish', skip: null },+ c: { title: 'concurrent writers: put, remember and a managed maintenance job', skip: null },+ 'c-db': { title: 'a DB-only competitor', skip: null },+ d: { title: 'out-of-band git mv/git rm of committed files and deletion of uncommitted files', skip: null },+ e: { title: 'a deterministic mid-run edit after freezeEntry', skip: PR1 },+ f: { title: 'a pooler drop mid-bulk', skip: PR1 },+ g: { title: 'two concurrent drainers: a --all run beside a serve', skip: null },+ 'knock-on': { title: 'one page failure inside a bulk group', skip: PR1 },+ systemic: { title: 'a systemic database refusal: an unknown P0001 or a 55000 from a trigger on every page write', skip: PR1 },+} as const satisfies Record<string, { title: string; skip: string | null }>;+type Mode = keyof typeof MODES;+const requestedModes = process.env.GBRAIN_TEST_CONVERGENCE_MODES?.split(',').map(mode => mode.trim()).filter(Boolean);+for (const mode of requestedModes ?? []) if (!(mode in MODES)) throw new Error(`GBRAIN_TEST_CONVERGENCE_MODES names unknown mode '${mode}' (known: ${Object.keys(MODES).join(', ')}).`);+const runs = (mode: Mode): boolean => requestedModes ? requestedModes.includes(mode) : MODES[mode].skip === null;const SOURCE = 'workspace';-const NOTES = 200;const BIG = 'companies/acme-example';+const ENTITY = 'people/alice-example';/**- * The publication seams a managed sync import crosses. Its pages are already in- * Git, so the file-publication pair (`before_publication`/`after_publication`)- * never fires for it; `lane:applied` is the bulk group's applied-but-not-- * committed point, once per group.+ * The kill loop's fault points: the seams a managed sync import crosses. Its pages are already in Git, so the+ * file-publication pair (`before_publication`/`after_publication`) never fires for it. Per-page seams are counted+ * per submit_job request (nth inside the first 60% of a round); `lane:applied` and `sync:before_group_admission`+ * fire once per bulk group, and a small round may form one group, so they kill at the first; `sync:mid_checkpoint`+ * fires on every cursor save (the first or second).*/-const FAULT_POINTS = ['publication:before_commit', 'publication:after_commit', 'lane:applied'] as const satisfies readonly FaultPoint[];-const MAX_RECOVERY_RUNS = 3;+const KILL_POINTS = [+ { point: 'publication:before_commit', per: 'page' }, { point: 'publication:after_commit', per: 'page' },+ { point: 'consumer:preparing', per: 'page' }, { point: 'lane:applied', per: 'group' },+ { point: 'sync:before_group_admission', per: 'group' }, { point: 'sync:mid_checkpoint', per: 'save' },+] as const satisfies ReadonlyArray<{ point: FaultPoint; per: 'page' | 'group' | 'save' }>;+const MAX_RECOVERY_RUNS = 2;/** Oracle tests are named by the persistence gate's violation class (scripts/persistence/model.ts) they would report. */const as = (violation: ViolationClass, title: string): string => `[${violation}] ${title}`;/**@@ -109,13 +157,104 @@ function prng(seed: number): () => number {return ((t ^ (t >>> 14)) >>> 0) / 4294967296;};}-const rand = prng(SEED);-const pick = <T>(items: readonly T[]): T => items[Math.floor(rand() * items.length)];-const between = (lo: number, hi: number): number => lo + Math.floor(rand() * (hi - lo + 1));-/** A seeded fault inside a round that imports about `pages` pages: per-page seams land in its first 60%, the group seam in its first three groups. */-const planFault = (pages: number) => { const point = pick(FAULT_POINTS); return { point, nth: point === 'lane:applied' ? between(1, 3) : between(8, Math.floor(pages * 0.6)) }; };-const LOG_DIR = process.env.GBRAIN_TEST_CONVERGENCE_LOG_DIR;-function keepLog(name: string, text: string): void { if (LOG_DIR) { mkdirSync(LOG_DIR, { recursive: true }); writeFileSync(join(LOG_DIR, name), text); } }++// ---------------------------------------------------------------- the status oracle++/** Every `gbrain sync status --json` field the operator loop reads (sync-status.ts `SyncStatus`). */+const STATUS_FIELDS = ['source_id', 'run_id', 'cursor', 'committed_last_10m', 'live_job_id', 'holds', 'last_error', 'needs_human',+ 'resume_argv', 'checkpoint_blockers', 'cursors', 'terminal_failures', 'next'] as const;+interface StatusExpectation { holds?: Array<{ code: string; path: string }>; needsHuman?: boolean }+/**+ * What a converged source's status must say. Field-present assertions first: a renderer that drops a field fails+ * here, not in an agent's loop. `checkpoint_blockers` and `cursors` are arrays on every status (#6712 PR 0 made+ * `checkpoint_blockers` always present). TODO(PR 2 of #6712): read `sync status --json --detail` once it exists,+ * with the heavy reads it moves behind the flag.+ */+function statusProblems(status: Record<string, unknown> | null, expected: StatusExpectation = {}): string[] {+ if (!status) return ['sync status --json printed no JSON document'];+ const out = STATUS_FIELDS.filter(field => !(field in status)).map(field => `sync status --json: field ${field} missing`);+ if (out.length) return out;+ const cursor = status.cursor as { done?: boolean } | null;+ if (!Array.isArray(status.cursors)) out.push('sync status --json: cursors is not an array');+ if (!Array.isArray(status.checkpoint_blockers)) out.push('sync status --json: checkpoint_blockers is not an array');+ else if (status.checkpoint_blockers.length) out.push(`sync status --json: ${status.checkpoint_blockers.length} checkpoint blocker(s)`);+ // A finished run's cursor is retired, so a converged source shows none (null) or a done one.+ if (cursor && cursor.done !== true) out.push(`sync status --json: cursor not done (${JSON.stringify(cursor)})`);+ const terminal = status.terminal_failures as { status?: string; active_blockers?: unknown[] } | null;+ if (terminal?.status !== 'ok') out.push(`sync status --json: terminal_failures.status is ${terminal?.status}`);+ else if (!Array.isArray(terminal.active_blockers)) out.push('sync status --json: terminal_failures.active_blockers is not an array');+ else if (terminal.active_blockers.length) out.push(`sync status --json: ${terminal.active_blockers.length} active terminal blocker(s)`);+ if (status.needs_human !== (expected.needsHuman ?? false)) out.push(`sync status --json: needs_human is ${status.needs_human}, expected ${expected.needsHuman ?? false}`);+ const holds = Array.isArray(status.holds) ? (status.holds as Array<{ code: string; path: string }>).map(h => `${h.code}:${h.path}`).sort() : ['holds is not an array'];+ const want = (expected.holds ?? []).map(h => `${h.code}:${h.path}`).sort();+ if (JSON.stringify(holds) !== JSON.stringify(want)) out.push(`sync status --json: holds [${holds.join(', ')}], expected [${want.join(', ')}]`);+ if (status.last_error !== null) out.push(`sync status --json: last_error ${JSON.stringify(status.last_error)}`);+ if (!expected.holds?.length && status.next !== null) out.push(`sync status --json: next ${JSON.stringify(status.next)}`);+ return out;+}++// ---------------------------------------------------------------- the acknowledged-write ledger++/**+ * One writer operation that returned success, recorded by the harness at the moment it saw the success (never read+ * back from the brain). `touches` is where the write landed: the page in the database, its file, or (for `remember`)+ * an additive fact row. `marker` is text that only this write put there; `null` on a page location is a deletion.+ */+interface Ack { kind: 'commit' | 'put' | 'remember' | 'maintenance' | 'db_only' | 'git_mv' | 'git_rm' | 'unlink'; slug: string;+ marker: string | null; touches: Array<'db' | 'file'> | 'fact'; start: number; ack: number }+class Ledger {+ acks: Ack[] = [];+ record(ack: Ack): void { this.acks.push(ack); }+ /**+ * For every slug and location, the writes no later acknowledged write causally supersedes (none started after it+ * was acknowledged); the final state must show one of them. An additive fact survives unless a page write on its+ * slug may have been ordered after it.+ */+ problems(disk: Map<string, string>, db: Map<string, { body: string } | null>, facts: Set<string>): string[] {+ const out: string[] = [];+ const pageWrites = this.acks.filter(a => a.touches !== 'fact' && a.kind !== 'maintenance');+ for (const slug of new Set(pageWrites.map(a => a.slug))) {+ for (const where of ['db', 'file'] as const) {+ const writes = pageWrites.filter(a => a.slug === slug && (a.touches as string[]).includes(where));+ if (!writes.length) continue;+ const maximal = writes.filter(w => !writes.some(later => later.start > w.ack));+ const seen = where === 'file' ? disk.get(slug) ?? null : db.get(slug)?.body ?? null;+ if (maximal.some(w => w.marker === null ? seen === null : seen?.includes(w.marker))) continue;+ out.push(`${where} ${slug}: lost acknowledged write; has ${seen === null ? 'nothing' : JSON.stringify(seen.slice(0, 80))}, expected one of ${maximal.map(w => `${w.kind}@${Math.round(w.ack)}:${w.marker === null ? '(absent)' : JSON.stringify(w.marker)}`).join(' | ')}`);+ }+ }+ for (const fact of this.acks.filter(a => a.touches === 'fact')) {+ const excused = pageWrites.some(w => w.slug === fact.slug && (w.touches as string[]).includes('db') && w.ack > fact.start);+ if (!excused && !facts.has(fact.marker!)) out.push(`fact on ${fact.slug}: lost acknowledged remember ${JSON.stringify(fact.marker)}`);+ }+ return out;+ }+}++// ---------------------------------------------------------------- the fixture++function noteText(i: number, version: string): string {+ return `---\ntype: concept\ntitle: Note ${i} Example\n---\n\n${version} body for note ${i}, an observation about widget-co and acme-example.\n\n${'Supporting detail sentence. '.repeat(8 + (i % 5))}\n`;+}+const noteMarker = (i: number, version: string) => `${version} body for note ${i},`;+const noteSlug = (i: number) => `notes/note-${String(i).padStart(4, '0')}`;+function bigPage(facts: number, timeline: number, version: string): string {+ const day = (n: number) => new Date(Date.UTC(2018, 0, 1) + n * 86_400_000).toISOString().slice(0, 10);+ const paragraphs = Array.from({ length: 30 }, (_, i) => `Section ${i} (${version}): acme-example ${'expanded with a steady stream of synthetic operating detail. '.repeat(6)}`);+ const rows = Array.from({ length: facts }, (_, i) =>+ `| ${i + 1} | Synthetic claim ${i + 1} about acme-example | fact | 0.9 | world | medium | ${day(i)} | | fixture | |`);+ const bullets = Array.from({ length: timeline }, (_, i) => `- **${day(i)}** | Synthetic event ${i + 1} at acme-example`);+ return [+ '---', 'type: company', 'title: Acme Example', '---', '', '# Acme Example', '', ...paragraphs.flatMap(p => [p, '']),+ '## Facts', '', '<!--- gbrain:facts:begin -->',+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',+ ...rows, '<!--- gbrain:facts:end -->', '', '<!-- timeline -->', '', ...bullets, '',+ ].join('\n');+}+const entityText = '---\ntype: person\ntitle: Alice Example\n---\n\nAlice Example works with acme-example.\n';++// ---------------------------------------------------------------- the latency proxy/** A TCP proxy that delays every chunk by half the configured round trip in each direction, preserving order. */class LatencyProxy {@@ -156,50 +295,313 @@ class LatencyProxy {this.delayed(client, upstream);this.delayed(upstream, client);}+ /** Mode (f): every live connection through the pooler drops at once, as a pooler restart looks to its clients. */+ drop(): number { const n = this.sockets.size; for (const socket of this.sockets) socket.destroy(); return n; }async close(): Promise<void> {for (const socket of this.sockets) socket.destroy();await new Promise<void>(done => this.server.close(() => done()));}}-let home: string, repo: string, database: string;-let admin: ReturnType<typeof postgres> | undefined;-let engine: PostgresEngine | undefined;-let pooledProxy: LatencyProxy | undefined, directProxy: LatencyProxy | undefined;-let pooledUrl: string, directUrl: string;-const serves: StdioServe[] = [];-const log: string[] = [];-const elapsed: Record<string, number> = {};-let recoveryRuns: { code: number; ms: number; envelope: Record<string, unknown> | null; err: string }[] = [];-let writerResults: { slug: string; attempts: number; code: number }[] = [];-let calibration: string[] = [];-/** Longest stall each sync that ran after an owner kill printed, by round. */-const ownerKillStalls: Record<string, number> = {};-/** Every sync client's stderr, and the PIDs this run SIGKILLed. */-const syncErrs: Record<string, string> = {};-const killedPids = new Set<number>();-let round3Err = '';-const fired: Record<string, string | null> = {};-const PGBOUNCER_CONTAINER = process.env.GBRAIN_TEST_CONVERGENCE_PGBOUNCER_CONTAINER;+// ---------------------------------------------------------------- one brain-function note(line: string): void { log.push(line); console.error(`[convergence] ${line}`); }-function git(...args: string[]): string { return execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }-function commitAll(message: string): string { git('add', '-A'); git('commit', '-qm', message); return git('rev-parse', 'HEAD'); }--function childEnv(extra: Record<string, string | undefined> = {}): Record<string, string> {- return keylessBrainEnv(process.env, home, {- DATABASE_URL: pooledUrl, GBRAIN_DATABASE_URL: undefined, GBRAIN_DIRECT_DATABASE_URL: directUrl,- GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: SOURCE, GBRAIN_SWEEP: '0', GBRAIN_HOOKS: undefined,- GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_SKILL_NAG: '1', GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS: '300',- GBRAIN_SYNC_NO_DELEGATE: undefined, GBRAIN_TEST_CONVERGENCE_FAULT: undefined,- ...extra,- });+interface Fault { point: FaultPoint; nth: number; marker: string; operation?: string; path?: string; action?: 'kill' | 'edit' | 'stall' | 'throw';+ edit?: { file: string; content: string }; release?: string; ms?: number; sqlstate?: string }+interface Run { code: number; out: string; err: string; ms: number }+interface SyncRun { proc: ReturnType<typeof Bun.spawn>; result: Promise<Run> }++async function until(check: () => boolean | Promise<boolean>, label: string, timeoutMs = 300_000): Promise<void> {+ const deadline = performance.now() + timeoutMs;+ while (performance.now() < deadline) {+ if (await check()) return;+ await Bun.sleep(100);+ }+ throw new Error(`timed out waiting for ${label}`);+}+function lastJson(out: string): Record<string, unknown> | null {+ try { return JSON.parse(out) as Record<string, unknown>; } catch { /* several documents */ }+ for (const line of out.trim().split('\n').reverse()) { try { return JSON.parse(line) as Record<string, unknown>; } catch { /* not the envelope */ } }+ return null;+}+/** The longest `stalled Ns` progress line a sync printed: how long it waited on a predecessor's leftovers. */+function worstStall(err: string): number { return Math.max(0, ...[...err.matchAll(/stalled (\d+)s/g)].map(m => Number(m[1]))); }++/**+ * One scenario's brain: its database, home, Git worktree, proxies, child processes, ledger and log. `context()` is+ * what every failure prints: seed, modes, the fault plan and the one-line repro.+ */+class Brain {+ home = ''; repo = ''; database = '';+ admin: ReturnType<typeof postgres> | undefined;+ engine: PostgresEngine | undefined;+ pooledProxy: LatencyProxy | undefined; directProxy: LatencyProxy | undefined;+ pooledUrl = ''; directUrl = '';+ serves: StdioServe[] = [];+ ledger = new Ledger();+ plan: string[] = [];+ fired: Record<string, string | null> = {};+ killedPids = new Set<number>();+ recoveryRuns: Array<Run & { envelope: Record<string, unknown> | null }> = [];+ elapsed: Record<string, number> = {};+ calibration: string[] = [];+ readonly rand: () => number;+ constructor(readonly name: string, readonly modes: Mode[]) { this.rand = prng(SEED ^ [...name].reduce((h, c) => Math.imul(h, 31) + c.charCodeAt(0), 7)); }++ between(lo: number, hi: number): number { return lo + Math.floor(this.rand() * (hi - lo + 1)); }+ note(line: string): void {+ console.error(`[convergence ${this.name}] ${line}`);+ if (LOG_DIR) { mkdirSync(LOG_DIR, { recursive: true }); appendFileSync(join(LOG_DIR, 'convergence.log'), `[${this.name}] ${line}\n`); }+ }+ keepLog(name: string, text: string): void { if (LOG_DIR) { mkdirSync(join(LOG_DIR, this.name), { recursive: true }); writeFileSync(join(LOG_DIR, this.name, name), text); } }+ context(): string {+ const env = [`GBRAIN_TEST_CONVERGENCE_SEED=${SEED}`, `GBRAIN_TEST_CONVERGENCE_MODES=${this.modes.join(',')}`, `GBRAIN_TEST_CONVERGENCE_NOTES=${NOTES}`,+ `GBRAIN_TEST_CONVERGENCE_KILLS=${KILLS}`, `GBRAIN_TEST_CONVERGENCE_LATENCY_MS=${LATENCY_MS}`];+ return [`seed ${SEED}; modes ${this.modes.join(',')}; notes ${NOTES}; latency ${LATENCY_MS} ms`,+ `fault plan: ${this.plan.join('; ') || 'none'}`,+ `fired: ${Object.entries(this.fired).map(([k, v]) => `${k} => ${v ?? 'did not fire'}`).join('; ') || 'none'}`,+ `repro (Postgres + PgBouncer from scripts/persistence/README.md): ${env.join(' ')} GBRAIN_PGBOUNCER_URL="$GBRAIN_PGBOUNCER_URL" GBRAIN_PGBOUNCER_DIRECT_URL="$GBRAIN_PGBOUNCER_DIRECT_URL" bun run test:convergence`].join('\n');+ }+ /** Throws with the problems and the failure context; a passing check prints nothing. */+ verdict(problems: string[]): void {+ if (problems.length) throw new Error(`${problems.length} problem(s):\n ${problems.slice(0, 40).join('\n ')}\n${this.context()}`);+ }+ marker(tag: string): string { return join(this.home, `fault-${tag}.json`); }+ recordFault(tag: string, label: string): string | null {+ const at = existsSync(this.marker(tag)) ? readFileSync(this.marker(tag), 'utf8') : null;+ this.fired[label] = at;+ if (at) { const fired = JSON.parse(at) as { pid: number; action: string }; if (fired.action === 'kill') this.killedPids.add(fired.pid); }+ return at;+ }++ git(...args: string[]): string { return execFileSync('git', ['-C', this.repo, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+ /**+ * Writes files and commits exactly those paths, as the shared-checkout rules require of every committer; each write+ * is acknowledged when the commit returns. Sweeping the worktree (`git add -A`) would commit a writer's in-flight+ * write-through bytes as an out-of-band Git change of a page that writer is still writing.+ */+ commit(message: string, files: Array<{ slug: string; content: string; marker: string }>): void {+ const start = performance.now();+ for (const f of files) { mkdirSync(dirname(join(this.repo, `${f.slug}.md`)), { recursive: true }); writeFileSync(join(this.repo, `${f.slug}.md`), f.content); }+ const paths = files.map(f => `${f.slug}.md`);+ this.git('add', '--', ...paths); this.git('commit', '-qm', message, '--', ...paths);+ const ack = performance.now();+ for (const f of files) this.ledger.record({ kind: 'commit', slug: f.slug, marker: f.marker, touches: ['db', 'file'], start, ack });+ }+ writeNotes(indexes: number[], version: string, message: string, extra: Array<{ slug: string; content: string; marker: string }> = []): void {+ this.commit(message, [...indexes.map(i => ({ slug: noteSlug(i), content: noteText(i, version), marker: noteMarker(i, version) })), ...extra]);+ }+ bigFile(facts: number, timeline: number, version: string) { return { slug: BIG, content: bigPage(facts, timeline, version), marker: `Section 0 (${version})` }; }++ childEnv(extra: Record<string, string | undefined> = {}): Record<string, string> {+ return keylessBrainEnv(process.env, this.home, {+ DATABASE_URL: this.pooledUrl, GBRAIN_DATABASE_URL: undefined, GBRAIN_DIRECT_DATABASE_URL: this.directUrl,+ GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: SOURCE, GBRAIN_SWEEP: '0', GBRAIN_HOOKS: undefined,+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_SKILL_NAG: '1', GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS: '300',+ GBRAIN_SYNC_NO_DELEGATE: undefined, GBRAIN_TEST_CONVERGENCE_FAULT: undefined,+ ...extra,+ });+ }+ faultArgs(fault?: Fault): { preload: string[]; env: Record<string, string | undefined> } {+ if (!fault) return { preload: [], env: {} };+ return { preload: ['--preload', FAULT_PRELOAD], env: { GBRAIN_TEST_CONVERGENCE_FAULT: JSON.stringify(fault) } };+ }+ spawnCli(args: string[], opts: { fault?: Fault; stdin?: string; timeoutMs?: number } = {}): SyncRun {+ const { preload, env } = this.faultArgs(opts.fault);+ const started = performance.now();+ const proc = Bun.spawn([process.execPath, '--no-env-file', ...preload, join(REPO_ROOT, 'src/cli.ts'), ...args], {+ cwd: REPO_ROOT, env: this.childEnv(env), stdin: opts.stdin === undefined ? 'ignore' : new Blob([opts.stdin]), stdout: 'pipe', stderr: 'pipe',+ });+ const timer = setTimeout(() => proc.kill('SIGKILL'), opts.timeoutMs ?? SYNC_TIMEOUT_MS);+ const result = Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited])+ .then(([out, err, code]) => ({ code, out, err, ms: performance.now() - started }))+ .finally(() => clearTimeout(timer));+ return { proc, result };+ }+ sync(args: string[], fault?: Fault): SyncRun { return this.spawnCli(['sync', '--source', SOURCE, ...args], { fault }); }+ async committedSince(at: string): Promise<number> {+ return (await this.engine!.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests WHERE state='committed' AND completed_at > $1::timestamptz AND operation='submit_job'`, [at]))[0].n;+ }+ async now(): Promise<string> { return (await this.engine!.executeRaw<{ at: string }>('SELECT now()::text AS at'))[0].at; }++ async setup(seed: (b: Brain) => void, config: Record<string, string> = {}): Promise<void> {+ assertSafeE2eDatabaseUrl(directTarget!);+ this.home = mkdtempSync(join(tmpdir(), 'gb-conv-'));+ mkdirSync(join(this.home, '.gbrain'));+ this.database = `gbrain_test_convergence_${randomUUID().replaceAll('-', '')}`;+ this.admin = postgres(directTarget!, { max: 1, prepare: false });+ await this.admin.unsafe(`CREATE DATABASE ${this.database}`);+ const direct = new URL(directTarget!); direct.pathname = `/${this.database}`;+ const pooled = new URL(pooledTarget!); pooled.pathname = `/${this.database}`;+ this.pooledProxy = new LatencyProxy({ host: pooled.hostname, port: Number(pooled.port) || 5432 }, LATENCY_MS / 2);+ this.directProxy = new LatencyProxy({ host: direct.hostname, port: Number(direct.port) || 5432 }, LATENCY_MS / 2);+ await Promise.all([this.pooledProxy.listen(), this.directProxy.listen()]);+ const viaPooled = new URL(pooled); viaPooled.hostname = '127.0.0.1'; viaPooled.port = String(this.pooledProxy.port); viaPooled.searchParams.set('prepare', 'false');+ const viaDirect = new URL(direct); viaDirect.hostname = '127.0.0.1'; viaDirect.port = String(this.directProxy.port);+ this.pooledUrl = viaPooled.toString(); this.directUrl = viaDirect.toString();+ this.engine = new PostgresEngine();+ await withEnv({ GBRAIN_HOME: this.home, GBRAIN_DIRECT_DATABASE_URL: undefined }, async () => {+ await this.engine!.connect({ database_url: direct.toString(), poolSize: 4 });+ await this.engine!.initSchema();+ });+ writeFileSync(join(this.home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: this.pooledUrl, embedding_disabled: true }));+ this.repo = mkdtempSync(join(tmpdir(), 'gb-conv-repo-'));+ this.git('init', '-q'); this.git('config', 'user.email', '[email protected]'); this.git('config', 'user.name', 'Example');+ seed(this);+ await withEnv({ GBRAIN_HOME: this.home }, async () => {+ await this.engine!.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await this.engine!.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [SOURCE, this.repo]);+ await claimWorktree(this.engine!, SOURCE, this.repo);+ for (const [key, value] of Object.entries(config)) await this.engine!.setConfig(key, value);+ await this.engine!.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ });+ this.note(`seed=${SEED} latency=${LATENCY_MS}ms round trip via proxies (pooled -> ${pooled.host}, direct -> ${direct.host}); modes ${this.modes.join(',')}`);+ // Phase 0: a fault-free import, so the oracle is calibrated before any chaos.+ const started = performance.now();+ const baseline = await this.sync(['--no-pull', '--no-delegate', '--json']).result;+ this.elapsed.baseline_import_ms = performance.now() - started;+ if (baseline.code !== 0) throw new Error(`baseline sync exited ${baseline.code}\n${baseline.out}\n${baseline.err}\n${this.context()}`);+ this.calibration = await this.diskDbMismatches(new Set());+ if (existsSync(join(this.repo, `${BIG}.md`))) {+ const rows = await this.childRowProblems();+ this.calibration.push(...rows.problems, ...(rows.timelineDuplicates || rows.timelineStrays ? [`timeline: ${rows.timelineDuplicates} duplicate and ${rows.timelineStrays} stray rows after a fault-free import`] : []));+ }+ this.note(`phase 0: fault-free import in ${(this.elapsed.baseline_import_ms / 1000).toFixed(1)}s; oracle calibration problems: ${this.calibration.length}`);+ }++ /** A fresh resident serve and at most MAX_RECOVERY_RUNS plain syncs, no operator step. */+ async recover(): Promise<void> {+ const started = performance.now();+ const serve = new StdioServe(this);+ await serve.start();+ for (let run = 1; run <= MAX_RECOVERY_RUNS; run++) {+ const r = await this.sync(['--no-pull', '--json']).result;+ const envelope = lastJson(r.out);+ this.recoveryRuns.push({ ...r, envelope });+ this.keepLog(`recovery-${run}-client.log`, `${r.out}\n${r.err}`);+ this.note(`recovery run ${run}: exit ${r.code} in ${(r.ms / 1000).toFixed(1)}s outcome=${String(envelope?.outcome ?? envelope?.sync_status ?? envelope?.error ?? 'none')}`);+ if (r.code === 0 && envelope?.outcome === 'synced') break;+ }+ this.elapsed.recovery_ms = performance.now() - started;+ this.keepLog('recovery-serve.log', serve.stderr);+ this.note(`elapsed: ${Object.entries(this.elapsed).map(([k, ms]) => `${k.replace(/_ms$/, '')} ${(ms / 1000).toFixed(1)}s`).join(', ')}; recovery took ${this.recoveryRuns.length} sync run(s)`);+ }++ async teardown(): Promise<void> {+ for (const serve of this.serves) await serve.stop().catch(() => {});+ try { await this.engine?.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); } catch { /* best effort */ }+ await this.engine?.disconnect().catch(() => {});+ await this.pooledProxy?.close().catch(() => {});+ await this.directProxy?.close().catch(() => {});+ if (this.admin) {+ try { if (this.database) await this.admin.unsafe(`DROP DATABASE IF EXISTS ${this.database} WITH (FORCE)`); } finally { await this.admin.end(); }+ }+ for (const dir of [this.home, this.repo]) if (dir) rmSync(dir, { recursive: true, force: true });+ }++ // ------------------------------------------------------------ oracle reads++ diskPages(): Map<string, string> {+ const out = new Map<string, string>();+ const walk = (dir: string) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ if (entry.name.startsWith('.')) continue;+ const full = join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else if (entry.name.endsWith('.md')) out.set(relative(this.repo, full).replace(/\.md$/, ''), readFileSync(full, 'utf8'));+ }+ };+ walk(this.repo);+ return out;+ }+ async dbPages(): Promise<Map<string, { hash: string | null; body: string }>> {+ const rows = await this.engine!.executeRaw<{ slug: string; content_hash: string | null; body: string }>(+ `SELECT slug, content_hash, coalesce(compiled_truth,'') || E'\\n' || coalesce(timeline,'') AS body FROM pages WHERE source_id=$1 AND deleted_at IS NULL`, [SOURCE]);+ return new Map(rows.map(r => [r.slug, { hash: r.content_hash, body: r.body }]));+ }+ async diskDbMismatches(exclude: Set<string>): Promise<string[]> {+ const disk = this.diskPages(), db = await this.dbPages(), out: string[] = [];+ for (const [slug, content] of disk) {+ if (exclude.has(slug)) continue;+ if (!db.has(slug)) out.push(`${slug}: file exists, no live page`);+ else if (db.get(slug)!.hash !== fileHash(slug, content)) out.push(`${slug}: page content_hash differs from the file`);+ }+ for (const slug of db.keys()) if (!disk.has(slug) && !exclude.has(slug)) out.push(`${slug}: live page, no file`);+ return out;+ }+ async ledgerProblems(): Promise<string[]> {+ const facts = new Set((await this.engine!.executeRaw<{ fact: string }>('SELECT fact FROM facts WHERE source_id=$1 AND expired_at IS NULL', [SOURCE])).map(r => r.fact));+ return this.ledger.problems(this.diskPages(), await this.dbPages(), facts);+ }+ async openRequests(): Promise<unknown[]> {+ const open = await this.engine!.executeRaw<{ request_id: string; slug: string; state: string; recovery: boolean; blocked_reason: string | null }>(+ `SELECT request_id::text, slug, state, recovery IS NOT NULL AS recovery, blocked_reason FROM persistence_requests+ WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL ORDER BY sequence`);+ const worktrees = await this.engine!.executeRaw<{ id: string; state: string }>(`SELECT id::text, state FROM persistence_worktrees WHERE state<>'active'`);+ return [...open.map(r => `open request ${JSON.stringify(r)}`), ...worktrees.map(w => `worktree ${w.id} is ${w.state}`)];+ }+ async unexplainedTerminal(exclude: Set<string>): Promise<string[]> {+ const rows = await this.engine!.executeRaw<{ request_id: string; slug: string; state: string; error_code: string | null; operation: string }>(+ `SELECT request_id::text, slug, state, error_code, operation FROM persistence_requests WHERE state IN ('conflict','failed','cancelled') ORDER BY sequence`);+ const disk = this.diskPages(), db = await this.dbPages();+ this.note(`terminal non-committed requests: ${rows.length} (${[...new Set(rows.map(r => `${r.state}:${r.error_code}`))].join(', ') || 'none'})`);+ return rows.filter(row => {+ const content = disk.get(row.slug);+ const superseded = exclude.has(row.slug) || (content !== undefined && db.get(row.slug)?.hash === fileHash(row.slug, content));+ return !superseded && !(row.error_code && row.error_code in CODES);+ }).map(row => `unexplained ${row.state} request ${row.request_id} (${row.slug}, ${row.error_code ?? 'no code'})`);+ }+ async cursorProblems(): Promise<string[]> {+ const [source] = await this.engine!.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [SOURCE]);+ const head = this.git('rev-parse', 'HEAD');+ return source.last_commit === head ? [] : [`sources.last_commit ${source.last_commit} is not HEAD ${head}`];+ }+ async status(): Promise<Record<string, unknown> | null> {+ const r = await this.spawnCli(['sync', 'status', '--source', SOURCE, '--json']).result;+ this.keepLog('status.json', `${r.out}\n${r.err}`);+ return lastJson(r.out);+ }+ recoveryProblems(): string[] {+ const last = this.recoveryRuns.at(-1);+ return last?.code === 0 && last.envelope?.outcome === 'synced' ? []+ : [`no plain sync succeeded within ${MAX_RECOVERY_RUNS} runs: ${this.recoveryRuns.map(r => `exit ${r.code} outcome ${String(r.envelope?.outcome ?? r.envelope?.error ?? 'none')}`).join('; ')}`];+ }+ /**+ * The large page's child rows against its file. Facts are keyed by fence row, so+ * loss, duplication and strays are all problems. Timeline rows are judged for+ * loss only; duplicate and stray timeline rows come back as a measured count,+ * because derived timeline rows are never pruned (a known defect outside #6650).+ */+ async childRowProblems(): Promise<{ problems: string[]; timelineDuplicates: number; timelineStrays: number }> {+ const content = this.diskPages().get(BIG);+ if (!content) return { problems: [`${BIG}: no file`], timelineDuplicates: 0, timelineStrays: 0 };+ const out: string[] = [];+ const expectedTimeline = [...content.matchAll(/^- \*\*(\d{4}-\d{2}-\d{2})\*\* \| (.+)$/gm)].map(m => `${m[1]}|${m[2]}`);+ const timeline = await this.engine!.executeRaw<{ key: string; n: number }>(+ `SELECT t.date::text || '|' || t.summary AS key, count(*)::int AS n FROM timeline_entries t JOIN pages p ON p.id=t.page_id+ WHERE p.source_id=$1 AND p.slug=$2 AND p.deleted_at IS NULL AND t.event_page_id IS NULL GROUP BY 1`, [SOURCE, BIG]);+ const have = new Map(timeline.map(r => [r.key, r.n]));+ const lostTimeline = expectedTimeline.filter(k => !have.has(k));+ const dupTimeline = timeline.filter(r => r.n > 1);+ const extraTimeline = timeline.filter(r => !expectedTimeline.includes(r.key));+ if (lostTimeline.length) out.push(`timeline: ${lostTimeline.length} of ${expectedTimeline.length} file entries missing (first: ${lostTimeline[0]})`);+ const expectedFacts = parseFactsFence(content).facts.map(f => `${f.rowNum}|${f.claim}`);+ const facts = await this.engine!.executeRaw<{ key: string; n: number }>(+ `SELECT row_num::text || '|' || fact AS key, count(*)::int AS n FROM facts+ WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL GROUP BY 1`, [SOURCE, BIG]);+ const haveFacts = new Map(facts.map(r => [r.key, r.n]));+ const lostFacts = expectedFacts.filter(k => !haveFacts.has(k));+ const dupFacts = facts.filter(r => r.n > 1);+ const extraFacts = facts.filter(r => !expectedFacts.includes(r.key));+ if (lostFacts.length) out.push(`facts: ${lostFacts.length} of ${expectedFacts.length} fence rows missing (first: ${lostFacts[0]})`);+ if (dupFacts.length) out.push(`facts: ${dupFacts.length} rows duplicated (first: ${dupFacts[0].key} x${dupFacts[0].n})`);+ if (extraFacts.length) out.push(`facts: ${extraFacts.length} rows not in the fence (first: ${extraFacts[0].key})`);+ return { problems: out, timelineDuplicates: dupTimeline.reduce((n, r) => n + r.n - 1, 0), timelineStrays: extraTimeline.length };+ }}-interface Fault { point: string; nth: number; marker: string; operation: string }-function faultArgs(fault?: Fault): { preload: string[]; env: Record<string, string | undefined> } {- if (!fault) return { preload: [], env: {} };- return { preload: ['--preload', FAULT_PRELOAD], env: { GBRAIN_TEST_CONVERGENCE_FAULT: JSON.stringify(fault) } };+function fileHash(slug: string, content: string): string {+ const parsed = parseMarkdown(content, `${slug}.md`);+ return contentHash({ title: parsed.title, type: parsed.type, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: [...parsed.tags].sort() });}/** One stdio MCP session against a spawned `gbrain serve`; the serve is the host's resident persistence owner. */@@ -210,9 +612,9 @@ class StdioServe {private nextId = 1;private pending = new Map<number, (msg: Record<string, unknown>) => void>();private buf = '';- constructor(fault?: Fault) {- const { preload, env } = faultArgs(fault);- this.child = spawn(process.execPath, ['--no-env-file', ...preload, join(REPO_ROOT, 'src/cli.ts'), 'serve'], { cwd: REPO_ROOT, env: childEnv(env), stdio: ['pipe', 'pipe', 'pipe'] });+ constructor(private brain: Brain, fault?: Fault) {+ const { preload, env } = brain.faultArgs(fault);+ this.child = spawn(process.execPath, ['--no-env-file', ...preload, join(REPO_ROOT, 'src/cli.ts'), 'serve'], { cwd: REPO_ROOT, env: brain.childEnv(env), stdio: ['pipe', 'pipe', 'pipe'] });this.exited = new Promise(done => this.child.once('exit', code => done(code)));this.child.stderr!.on('data', (d: Buffer) => { this.stderr += d.toString('utf8'); });this.child.stdin!.on('error', () => {});@@ -229,7 +631,7 @@ class StdioServe {} catch { /* serve chatter */ }}});- serves.push(this);+ brain.serves.push(this);}get pid(): number { return this.child.pid!; }get alive(): boolean { return this.child.exitCode === null && this.child.signalCode === null; }@@ -244,7 +646,7 @@ class StdioServe {async start(): Promise<void> {await this.request('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'convergence', version: '1' } });this.child.stdin!.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');- await until(async () => (await engine!.executeRaw<{ n: number }>(+ await until(async () => (await this.brain.engine!.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_consumers WHERE pid=$1 AND kind='serve' AND renewed_at > now() - interval '30 seconds'`, [this.pid]))[0].n > 0,`serve ${this.pid} heartbeat`, 120_000);}@@ -256,161 +658,99 @@ class StdioServe {}}-interface SyncRun { proc: ReturnType<typeof Bun.spawn>; result: Promise<{ code: number; out: string; err: string; ms: number }> }-function startSync(args: string[], fault?: Fault, timeoutMs = 900_000): SyncRun {- const { preload, env } = faultArgs(fault);- const started = performance.now();- const proc = Bun.spawn([process.execPath, '--no-env-file', ...preload, join(REPO_ROOT, 'src/cli.ts'), 'sync', '--source', SOURCE, ...args], {- cwd: REPO_ROOT, env: childEnv(env), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',- });- const timer = setTimeout(() => proc.kill('SIGKILL'), timeoutMs);- const result = Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited])- .then(([out, err, code]) => ({ code, out, err, ms: performance.now() - started }))- .finally(() => clearTimeout(timer));- return { proc, result };-}-/** The longest `stalled Ns` progress line a sync printed: how long it waited on a predecessor's leftovers. */-function worstStall(err: string): number { return Math.max(0, ...[...err.matchAll(/stalled (\d+)s/g)].map(m => Number(m[1]))); }-function lastJson(out: string): Record<string, unknown> | null {- for (const line of out.trim().split('\n').reverse()) { try { return JSON.parse(line) as Record<string, unknown>; } catch { /* not the envelope */ } }- return null;-}+// ---------------------------------------------------------------- the writers of mode (c)-async function until(check: () => boolean | Promise<boolean>, label: string, timeoutMs = 300_000): Promise<void> {- const deadline = performance.now() + timeoutMs;- while (performance.now() < deadline) {- if (await check()) return;- await Bun.sleep(100);+/** A writer call that retries an unsettled attempt (exit 10, a lost owner) with the same request id and a terminal refusal with a new one. */+async function acknowledged(b: Brain, label: string, call: (requestId: string) => SyncRun, stop: () => boolean): Promise<{ start: number; ack: number } | null> {+ let requestId = randomUUID();+ for (let attempt = 1; attempt <= 20 && !stop(); attempt++) {+ const start = performance.now();+ const r = await call(requestId).result;+ b.keepLog(`writer-${label.replaceAll('/', '_')}-${attempt}.log`, `exit ${r.code}\n${r.out}\n${r.err}`);+ if (r.code === 0) return { start, ack: performance.now() };+ const terminal = /\((conflict|failed|cancelled)\)/.test(r.err);+ b.note(`writer ${label} attempt ${attempt} exit ${r.code}${terminal ? ' (terminal; next attempt uses a new request id)' : ''}: ${r.err.trim().split('\n').slice(-1)[0] ?? ''}`);+ if (terminal) requestId = randomUUID();+ await Bun.sleep(3000);}- throw new Error(`timed out waiting for ${label}`);-}--// ---------------------------------------------------------------- fixture--function noteText(i: number, version: string): string {- return `---\ntype: concept\ntitle: Note ${i} Example\n---\n\n${version} body for note ${i}, an observation about widget-co and acme-example.\n\n${'Supporting detail sentence. '.repeat(8 + (i % 5))}\n`;-}-function writeNote(i: number, version: string): void { writeFileSync(join(repo, 'notes', `note-${String(i).padStart(4, '0')}.md`), noteText(i, version)); }--function bigPage(facts: number, timeline: number, version: string): string {- const day = (n: number) => new Date(Date.UTC(2018, 0, 1) + n * 86_400_000).toISOString().slice(0, 10);- const paragraphs = Array.from({ length: 30 }, (_, i) => `Section ${i} (${version}): acme-example ${'expanded with a steady stream of synthetic operating detail. '.repeat(6)}`);- const rows = Array.from({ length: facts }, (_, i) =>- `| ${i + 1} | Synthetic claim ${i + 1} about acme-example | fact | 0.9 | world | medium | ${day(i)} | | fixture | |`);- const bullets = Array.from({ length: timeline }, (_, i) => `- **${day(i)}** | Synthetic event ${i + 1} at acme-example`);- return [- '---', 'type: company', 'title: Acme Example', '---', '', '# Acme Example', '', ...paragraphs.flatMap(p => [p, '']),- '## Facts', '', '<!--- gbrain:facts:begin -->',- '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',- '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',- ...rows, '<!--- gbrain:facts:end -->', '', '<!-- timeline -->', '', ...bullets, '',- ].join('\n');+ return null;}-function writeBig(facts: number, timeline: number, version: string): void { writeFileSync(join(repo, `${BIG}.md`), bigPage(facts, timeline, version)); }--// ---------------------------------------------------------------- oracle reads--function diskPages(): Map<string, string> {- const out = new Map<string, string>();- const walk = (dir: string) => {- for (const entry of readdirSync(dir, { withFileTypes: true })) {- if (entry.name.startsWith('.')) continue;- const full = join(dir, entry.name);- if (entry.isDirectory()) walk(full);- else if (entry.name.endsWith('.md')) out.set(relative(repo, full).replace(/\.md$/, ''), readFileSync(full, 'utf8'));+/** Rewrites notes through the coordinator (`gbrain put`), remembers facts on the entity page and runs the managed timeline maintenance job until `stop`. */+async function runWriters(b: Brain, putTargets: string[], stop: () => boolean): Promise<string[]> {+ const results: string[] = [];+ const put = async () => {+ for (const [k, slug] of putTargets.entries()) {+ if (stop()) break;+ const marker = `Writer rewrite ${k} of ${slug} (${randomUUID().slice(0, 8)})`;+ const content = `---\ntype: concept\ntitle: ${slug.split('/')[1]} rewritten\n---\n\n${marker} through the coordinator.\n`;+ // The start is taken before the first attempt: a retried put may have committed on an earlier attempt.+ const start = performance.now();+ const ok = await acknowledged(b, slug, requestId => b.spawnCli(['put', slug, '--source-id', SOURCE, '--force', '--request-id', requestId, '--wait-ms', '10000'], { stdin: content }), stop);+ if (ok) b.ledger.record({ kind: 'put', slug, marker, touches: ['db', 'file'], start, ack: ok.ack });+ results.push(`put ${slug}=${ok ? 'ok' : 'unacknowledged'}`);+ await Bun.sleep(b.between(200, 1500));}};- walk(repo);- return out;-}-function fileHash(slug: string, content: string): string {- const parsed = parseMarkdown(content, `${slug}.md`);- return contentHash({ title: parsed.title, type: parsed.type, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter, tags: [...parsed.tags].sort() });-}-async function dbPages(): Promise<Map<string, string | null>> {- const rows = await engine!.executeRaw<{ slug: string; content_hash: string | null }>(- 'SELECT slug, content_hash FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [SOURCE]);- return new Map(rows.map(r => [r.slug, r.content_hash]));-}-async function diskDbMismatches(): Promise<string[]> {- const disk = diskPages(), db = await dbPages(), out: string[] = [];- for (const [slug, content] of disk) {- if (!db.has(slug)) out.push(`${slug}: file exists, no live page`);- else if (db.get(slug) !== fileHash(slug, content)) out.push(`${slug}: page content_hash differs from the file`);- }- for (const slug of db.keys()) if (!disk.has(slug)) out.push(`${slug}: live page, no file`);- return out;-}-/**- * The large page's child rows against its file. Facts are keyed by fence row, so- * loss, duplication and strays are all problems. Timeline rows are judged for- * loss only; duplicate and stray timeline rows come back as a measured count,- * because derived timeline rows are never pruned (a known defect outside #6650).- */-async function childRowProblems(): Promise<{ problems: string[]; timelineDuplicates: number; timelineStrays: number }> {- const content = diskPages().get(BIG);- if (!content) return { problems: [`${BIG}: no file`], timelineDuplicates: 0, timelineStrays: 0 };- const out: string[] = [];- const expectedTimeline = [...content.matchAll(/^- \*\*(\d{4}-\d{2}-\d{2})\*\* \| (.+)$/gm)].map(m => `${m[1]}|${m[2]}`);- const timeline = await engine!.executeRaw<{ key: string; n: number }>(- `SELECT t.date::text || '|' || t.summary AS key, count(*)::int AS n FROM timeline_entries t JOIN pages p ON p.id=t.page_id- WHERE p.source_id=$1 AND p.slug=$2 AND p.deleted_at IS NULL AND t.event_page_id IS NULL GROUP BY 1`, [SOURCE, BIG]);- const have = new Map(timeline.map(r => [r.key, r.n]));- const lostTimeline = expectedTimeline.filter(k => !have.has(k));- const dupTimeline = timeline.filter(r => r.n > 1);- const extraTimeline = timeline.filter(r => !expectedTimeline.includes(r.key));- if (lostTimeline.length) out.push(`timeline: ${lostTimeline.length} of ${expectedTimeline.length} file entries missing (first: ${lostTimeline[0]})`);- const expectedFacts = parseFactsFence(content).facts.map(f => `${f.rowNum}|${f.claim}`);- const facts = await engine!.executeRaw<{ key: string; n: number }>(- `SELECT row_num::text || '|' || fact AS key, count(*)::int AS n FROM facts- WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL GROUP BY 1`, [SOURCE, BIG]);- const haveFacts = new Map(facts.map(r => [r.key, r.n]));- const lostFacts = expectedFacts.filter(k => !haveFacts.has(k));- const dupFacts = facts.filter(r => r.n > 1);- const extraFacts = facts.filter(r => !expectedFacts.includes(r.key));- if (lostFacts.length) out.push(`facts: ${lostFacts.length} of ${expectedFacts.length} fence rows missing (first: ${lostFacts[0]})`);- if (dupFacts.length) out.push(`facts: ${dupFacts.length} rows duplicated (first: ${dupFacts[0].key} x${dupFacts[0].n})`);- if (extraFacts.length) out.push(`facts: ${extraFacts.length} rows not in the fence (first: ${extraFacts[0].key})`);- return { problems: out, timelineDuplicates: dupTimeline.reduce((n, r) => n + r.n - 1, 0), timelineStrays: extraTimeline.length };+ const remember = async () => {+ for (let k = 0; !stop(); k++) {+ const fact = `Alice Example noted item ${k} (${randomUUID().slice(0, 8)}) with acme-example.`;+ const start = performance.now();+ const ok = await acknowledged(b, `remember-${k}`, requestId => b.spawnCli(['call', '--source', SOURCE, 'remember',+ JSON.stringify({ fact, entity: ENTITY, infer_entity: false, provenance: 'convergence harness', request_id: requestId })]), stop);+ if (ok) b.ledger.record({ kind: 'remember', slug: ENTITY, marker: fact, touches: 'fact', start, ack: ok.ack });+ results.push(`remember ${k}=${ok ? 'ok' : 'unacknowledged'}`);+ await Bun.sleep(b.between(1000, 4000));+ }+ };+ const maintenance = async () => {+ for (let k = 0; !stop(); k++) {+ const start = performance.now();+ const r = await b.spawnCli(['extract', 'timeline', '--source', 'db']).result;+ b.keepLog(`maintenance-${k}.log`, `exit ${r.code}\n${r.out}\n${r.err}`);+ if (r.code === 0) b.ledger.record({ kind: 'maintenance', slug: '*', marker: null, touches: ['db'], start, ack: performance.now() });+ results.push(`maintenance ${k}=exit ${r.code}`);+ await Bun.sleep(b.between(5000, 10000));+ }+ };+ await Promise.all([put(), remember(), maintenance()]);+ return results;}-// ---------------------------------------------------------------- the concurrent writer+// ---------------------------------------------------------------- the shared oracle-/**- * Rewrites each target note once through the coordinator (`gbrain put`) as a- * correct client does: an unsettled attempt (exit 10, a lost owner) retries- * with the same request id; a terminal refusal (a page the pending catch-up- * has not imported yet refuses `source_changed`) retries with a new one.- */-async function runWriter(slugs: string[], stop: () => boolean): Promise<void> {- for (const [k, slug] of slugs.entries()) {- let requestId = randomUUID();- const content = `---\ntype: concept\ntitle: ${slug.split('/')[1]} rewritten\n---\n\nWriter rewrite ${k} of ${slug} through the coordinator.\n`;- let attempts = 0, code = -1;- while (attempts < 20) {- attempts++;- const proc = Bun.spawn([process.execPath, '--no-env-file', join(REPO_ROOT, 'src/cli.ts'), 'put', slug, '--source-id', SOURCE, '--force', '--request-id', requestId, '--wait-ms', '10000'], {- cwd: REPO_ROOT, env: childEnv(), stdin: new Blob([content]), stdout: 'pipe', stderr: 'pipe',- });- const [out, err, exit] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);- code = exit;- keepLog(`writer-${slug.replace('/', '_')}-${attempts}.log`, `exit ${exit}\n${out}\n${err}`);- if (exit === 0) break;- const terminal = /\((conflict|failed|cancelled)\)/.test(err);- note(`writer ${slug} attempt ${attempts} exit ${exit}${terminal ? ' (terminal; next attempt uses a new request id)' : ''}: ${err.trim().split('\n').slice(-1)[0] ?? ''}`);- if (terminal) requestId = randomUUID();- await Bun.sleep(3000);- }- writerResults.push({ slug, attempts, code });- if (stop()) break;- await Bun.sleep(between(200, 1500));- }+interface EndState { exclude?: Set<string>; status?: StatusExpectation; bigPage?: boolean }+/** The oracle tests every scenario ends with; `end()` is read when the tests run (after the scenario's beforeAll). */+function oracleTests(b: Brain, end: () => EndState): void {+ test('the oracle is calibrated: a fault-free import satisfies it', () => b.verdict(b.calibration));+ test('every planned fault fired, so the chaos actually happened', () => b.verdict(Object.entries(b.fired).filter(([, at]) => at === null).map(([fault]) => `${fault} did not fire`)));+ test(as('wedge', `a plain sync succeeds within ${MAX_RECOVERY_RUNS} runs after the chaos, with no operator step`), () => b.verdict(b.recoveryProblems()));+ test(as('projection_drift', 'disk == database for every page the end state does not name'), async () => b.verdict(await b.diskDbMismatches(end().exclude ?? new Set())));+ test(as('wedge', 'no request blocks the checkpoint or a root'), async () => b.verdict((await b.openRequests()).map(String)));+ test(as('untyped_error', 'every non-committed terminal request is superseded or carries a registered error code'), async () => b.verdict(await b.unexplainedTerminal(end().exclude ?? new Set())));+ test(as('wedge', 'the cursor reached HEAD'), async () => b.verdict(await b.cursorProblems()));+ test(as('lost_write', 'every acknowledged write survives or is causally superseded by a later acknowledged write'), async () => {+ b.note(`ledger: ${b.ledger.acks.length} acknowledged writes (${[...new Set(b.ledger.acks.map(a => a.kind))].map(kind => `${kind} ${b.ledger.acks.filter(a => a.kind === kind).length}`).join(', ')})`);+ b.verdict(await b.ledgerProblems());+ });+ test(as('wedge', 'sync status --json reports the converged state with every field present'), async () => b.verdict(statusProblems(await b.status(), end().status)));+ if (end().bigPage !== false) test(as('lost_write', 'the large page keeps every fence fact exactly once and loses no timeline entry'), async () => {+ const { problems, timelineDuplicates, timelineStrays } = await b.childRowProblems();+ b.note(`large page timeline (measured, not asserted): ${timelineDuplicates} duplicate rows, ${timelineStrays} rows not in the file`);+ b.verdict(problems);+ });+}++/** A describe that runs when any of its modes runs; skipped (with every skip reason in its title) otherwise. */+function scenario(modes: Mode[], title: string, body: () => void): void {+ const active = enabled && modes.some(runs);+ const reasons = [...new Set(modes.map(m => MODES[m].skip).filter(Boolean))];+ (active ? describe : describe.skip)(`${title} [${modes.map(m => `(${m})`).join(' ')}]${!active && reasons.length ? ` (skipped until ${reasons.join('; ')})` : ''}`, body);}-// ---------------------------------------------------------------- scenario+// ---------------------------------------------------------------- always-on calibration// Runs on every invocation, harness enabled or not: the calibration the chaos run's verdicts rest on.-describe('convergence harness calibration (#6650 L0)', () => {+describe('convergence harness calibration (#6650 L0, #6712 PR 0)', () => {test('the owner-kill stall bound is below the default publication lease it exists to catch', () => {expect(OWNER_KILL_STALL_BOUND_S * 1000).toBeLessThan(publicationLeaseMs(PUBLICATION_CEILING_DEFAULT_MS));});@@ -419,228 +759,395 @@ describe('convergence harness calibration (#6650 L0)', () => {expect(draw(SEED)).toEqual(draw(SEED));expect(draw(SEED)).not.toEqual(draw(SEED + 1));});+ const converged = (): Record<string, unknown> => ({ source_id: SOURCE, run_id: 'r', cursor: { index: 3, total: 3, pinned_target: 'abc', last_advance_at: null, done: true },+ committed_last_10m: 3, live_job_id: null, rate_pages_per_min: null, eta_seconds: null, holds: [], last_error: null, needs_human: false, resume_argv: ['--source', SOURCE],+ checkpoint_blockers: [], cursors: [], terminal_failures: { status: 'ok', window_days: 7, active_blockers: [], unresolved: { rows: 0 } }, next: null });+ test('the status oracle accepts a converged status, with the finished cursor done or retired', () => {+ expect(statusProblems(converged())).toEqual([]);+ expect(statusProblems({ ...converged(), cursor: null, run_id: null })).toEqual([]);+ });+ // Forced probe: every field the oracle requires fails it when missing, so a renderer that drops one cannot pass.+ test('the status oracle fails when any required field is missing or not an array', () => {+ for (const field of STATUS_FIELDS) {+ const status = converged(); delete status[field];+ expect(statusProblems(status)).toEqual([`sync status --json: field ${field} missing`]);+ }+ expect(statusProblems({ ...converged(), cursor: { index: 2, total: 3, done: false } })).toContain('sync status --json: cursor not done ({"index":2,"total":3,"done":false})');+ expect(statusProblems({ ...converged(), cursors: {} })).toContain('sync status --json: cursors is not an array');+ expect(statusProblems({ ...converged(), checkpoint_blockers: null })).toContain('sync status --json: checkpoint_blockers is not an array');+ expect(statusProblems({ ...converged(), checkpoint_blockers: [{ request_id: 'x' }] })).toContain('sync status --json: 1 checkpoint blocker(s)');+ expect(statusProblems({ ...converged(), terminal_failures: { status: 'unknown', reason: 'timeout' } })).toContain('sync status --json: terminal_failures.status is unknown');+ });+ test('the ledger accepts the latest acknowledged write and any of two concurrent ones, and flags a lost one', () => {+ const ledger = new Ledger();+ ledger.record({ kind: 'commit', slug: 'n', marker: 'v1', touches: ['db', 'file'], start: 0, ack: 1 });+ ledger.record({ kind: 'put', slug: 'n', marker: 'v2', touches: ['db', 'file'], start: 2, ack: 5 });+ ledger.record({ kind: 'commit', slug: 'n', marker: 'v3', touches: ['db', 'file'], start: 4, ack: 6 });+ ledger.record({ kind: 'remember', slug: 'e', marker: 'fact-1', touches: 'fact', start: 0, ack: 1 });+ const page = (body: string) => new Map([['n', { body }]]);+ expect(ledger.problems(new Map([['n', 'v2']]), page('v3'), new Set(['fact-1']))).toEqual([]);+ expect(ledger.problems(new Map([['n', 'v1']]), page('v1'), new Set(['fact-1']))).toHaveLength(2);+ expect(ledger.problems(new Map([['n', 'v2']]), page('v2'), new Set())).toEqual(['fact on e: lost acknowledged remember "fact-1"']);+ });+ // Forced probe: a harness commit leaves another writer's uncommitted bytes alone (a swept commit raced `remember`'s write-through into a concurrent_write hold).+ test('a harness commit commits only the files it wrote', () => {+ const b = new Brain('commit-probe', ['a']);+ b.repo = mkdtempSync(join(tmpdir(), 'gb-conv-probe-'));+ try {+ b.git('init', '-q'); b.git('config', 'user.email', '[email protected]'); b.git('config', 'user.name', 'Example');+ b.commit('fixture', [{ slug: noteSlug(0), content: 'v0\n', marker: 'v0' }, { slug: ENTITY, content: 'e0\n', marker: 'e0' }]);+ writeFileSync(join(b.repo, `${ENTITY}.md`), 'in-flight write-through\n');+ writeFileSync(join(b.repo, 'stray.md'), 'untracked\n');+ b.commit('round one', [{ slug: noteSlug(0), content: 'v1\n', marker: 'v1' }]);+ expect(b.git('show', '--name-only', '--format=', 'HEAD').split('\n')).toEqual([`${noteSlug(0)}.md`]);+ expect(b.git('diff', '--name-only')).toBe(`${ENTITY}.md`);+ expect(b.git('ls-files', '--others', '--exclude-standard')).toBe('stray.md');+ } finally { rmSync(b.repo, { recursive: true, force: true }); }+ });+ test('modes master fails stay written and name the PR that turns them on', () => {+ for (const mode of ['e', 'f', 'knock-on', 'systemic'] as const) expect(MODES[mode].skip).toContain('PR 1 of #6712');+ for (const mode of ['a', 'b', 'c', 'c-db', 'd', 'g'] as const) expect(MODES[mode].skip).toBeNull();+ });});-describeConvergence('managed sync converges after owner, client and writer chaos (#6650 L0)', () => {+// ---------------------------------------------------------------- (a) (b) (c): the kill loop under concurrent writers++scenario(['a', 'b', 'c'], 'managed sync converges after a seeded kill loop of clients and serves under concurrent writers', () => {+ const b = new Brain('kill-loop', (['a', 'b', 'c'] as Mode[]).filter(runs));+ const syncErrs: Record<string, string> = {};+ const ownerKillStalls: Record<string, number> = {};+ const afterClientKill: string[] = [];beforeAll(async () => {- assertSafeE2eDatabaseUrl(directTarget!);- home = mkdtempSync(join(tmpdir(), 'gb-conv-'));- mkdirSync(join(home, '.gbrain'));- database = `gbrain_test_convergence_${randomUUID().replaceAll('-', '')}`;- admin = postgres(directTarget!, { max: 1, prepare: false });- await admin.unsafe(`CREATE DATABASE ${database}`);- const direct = new URL(directTarget!); direct.pathname = `/${database}`;- const pooled = new URL(pooledTarget!); pooled.pathname = `/${database}`;- pooledProxy = new LatencyProxy({ host: pooled.hostname, port: Number(pooled.port) || 5432 }, LATENCY_MS / 2);- directProxy = new LatencyProxy({ host: direct.hostname, port: Number(direct.port) || 5432 }, LATENCY_MS / 2);- await Promise.all([pooledProxy.listen(), directProxy.listen()]);- const viaPooled = new URL(pooled); viaPooled.hostname = '127.0.0.1'; viaPooled.port = String(pooledProxy.port); viaPooled.searchParams.set('prepare', 'false');- const viaDirect = new URL(direct); viaDirect.hostname = '127.0.0.1'; viaDirect.port = String(directProxy.port);- pooledUrl = viaPooled.toString(); directUrl = viaDirect.toString();- engine = new PostgresEngine();- await withEnv({ GBRAIN_HOME: home, GBRAIN_DIRECT_DATABASE_URL: undefined }, async () => {- await engine!.connect({ database_url: direct.toString(), poolSize: 4 });- await engine!.initSchema();+ await b.setup(brain => brain.commit('fixture', [+ ...Array.from({ length: NOTES }, (_, i) => ({ slug: noteSlug(i), content: noteText(i, 'Initial'), marker: noteMarker(i, 'Initial') })),+ brain.bigFile(120, 400, 'v0'), { slug: ENTITY, content: entityText, marker: 'Alice Example works with acme-example.' },+ ]));+ // The fault plan, drawn from the seed before anything runs: one kill per round.+ const kinds = [runs('a') && 'client', runs('b') && 'serve', runs('a') && runs('b') && 'serve+client'].filter(Boolean) as Array<'client' | 'serve' | 'serve+client'>;+ const perRound = Math.min(100, Math.max(10, Math.round(NOTES * 0.1)));+ // Victims and fault points cycle from seeded offsets, so six kills reach every point and each victim kind twice.+ const offset = b.between(0, 2), pointOffset = b.between(0, KILL_POINTS.length - 1);+ const plan = Array.from({ length: kinds.length ? KILLS : 0 }, (_, k) => {+ const kind = kinds[(k + offset) % kinds.length];+ const { point, per } = KILL_POINTS[(k + pointOffset) % KILL_POINTS.length];+ const nth = per === 'page' ? b.between(2, Math.floor(perRound * 0.6)) : per === 'group' ? 1 : b.between(1, 2);+ return { round: k + 1, kind, point, nth, operation: per === 'page' || point === 'lane:applied' ? 'submit_job' : undefined };});- writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: pooledUrl, embedding_disabled: true }));-- repo = mkdtempSync(join(tmpdir(), 'gb-conv-repo-'));- git('init', '-q'); git('config', 'user.email', '[email protected]'); git('config', 'user.name', 'Example');- mkdirSync(join(repo, 'notes')); mkdirSync(join(repo, 'companies'));- for (let i = 0; i < NOTES; i++) writeNote(i, 'Initial');- writeBig(120, 400, 'v0');- commitAll('fixture');- await withEnv({ GBRAIN_HOME: home }, async () => {- await engine!.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');- await engine!.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [SOURCE, repo]);- await claimWorktree(engine!, SOURCE, repo);- await engine!.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');- });- note(`seed=${SEED} latency=${LATENCY_MS}ms round trip via proxies (pooled -> ${pooled.host}, direct -> ${direct.host})`);-- // Phase 0: a fault-free import, so the oracle is calibrated before any chaos.- let started = performance.now();- const baseline = await startSync(['--no-pull', '--no-delegate', '--json']).result;- elapsed.baseline_import_ms = performance.now() - started;- if (baseline.code !== 0) throw new Error(`baseline sync exited ${baseline.code}\n${baseline.out}\n${baseline.err}`);- const baselineRows = await childRowProblems();- calibration = [...await diskDbMismatches(), ...baselineRows.problems,- ...(baselineRows.timelineDuplicates || baselineRows.timelineStrays ? [`timeline: ${baselineRows.timelineDuplicates} duplicate and ${baselineRows.timelineStrays} stray rows after a fault-free import`] : [])];- note(`phase 0: fault-free import of ${NOTES + 1} pages in ${(elapsed.baseline_import_ms / 1000).toFixed(1)}s; oracle calibration problems: ${calibration.length}`);-- // The chaos plan, drawn from the seed before anything runs.- const plan = [NOTES + 41, NOTES / 2 + 1, Math.ceil((NOTES + 40) / 3) + 1].map((pages, i) => ({ round: i + 1, ...planFault(pages) }));- const writerTargets = [...new Set(Array.from({ length: 40 }, () => between(0, NOTES - 1)))].slice(0, Math.round((NOTES + 40) * 0.05))- .map(i => `notes/note-${String(i).padStart(4, '0')}`);- note(`plan: ${plan.map(p => `round ${p.round} ${p.point} #${p.nth}`).join('; ')}; writer rewrites ${writerTargets.length} notes`);+ b.plan = plan.map(p => `round ${p.round} ${p.kind} ${p.point} #${p.nth}`);+ const putTargets = runs('c') ? [...new Set(Array.from({ length: 40 }, () => b.between(0, NOTES - 1)))].slice(0, Math.round(NOTES * 0.05)).map(noteSlug) : [];+ b.note(`plan: ${b.plan.join('; ') || 'no kills'}; ${perRound} notes per round; writers ${runs('c') ? `put ${putTargets.length} notes, remember, maintenance` : 'off'}`);let chaosDone = false;- const writer = runWriter(writerTargets, () => chaosDone);- const marker = (round: number) => join(home, `fault-${round}.json`);- const record = (round: number) => {- const at = existsSync(marker(round)) ? readFileSync(marker(round), 'utf8') : null;- fired[`round ${round} ${plan[round - 1].point} #${plan[round - 1].nth}`] = at;- if (at) killedPids.add((JSON.parse(at) as { pid: number }).pid);- };+ const writers: Promise<string[]> = runs('c') ? runWriters(b, putTargets, () => chaosDone) : Promise.resolve([]);const chaosStarted = performance.now();-- // Round 1: rewrite every note, add 40, grow the large page; the resident serve dies mid-catch-up.- for (let i = 0; i < NOTES; i++) writeNote(i, 'Round one');- for (let i = NOTES; i < NOTES + 40; i++) writeNote(i, 'Added');- writeBig(160, 500, 'v1');- commitAll('round one');- started = performance.now();- const s1 = new StdioServe({ ...plan[0], marker: marker(1), operation: 'submit_job' });- await s1.start();- const c1 = startSync(['--no-pull', '--json']);- await Promise.race([s1.exited, c1.result]);- const r1 = await c1.result;- syncErrs.round1 = r1.err; ownerKillStalls['round 1 (serve killed mid-catch-up)'] = worstStall(r1.err);- keepLog('round1-client.log', `${r1.out}\n${r1.err}`); keepLog('round1-serve.log', s1.stderr);- record(1);- note(`round 1: serve ${s1.alive ? 'survived' : `killed (${existsSync(marker(1)) ? readFileSync(marker(1), 'utf8') : 'no marker'})`}; client exit ${r1.code} in ${(r1.ms / 1000).toFixed(1)}s, worst stall ${worstStall(r1.err)}s: ${r1.err.trim().split('\n').slice(-2).join(' / ')}`);- await s1.stop();- elapsed.round1_ms = performance.now() - started;-- // Round 2: rewrite half the notes and the large page; a --no-delegate client dies in its own consumer.- for (let i = 0; i < NOTES; i += 2) writeNote(i, 'Round two');- writeBig(180, 560, 'v2');- commitAll('round two');- started = performance.now();- const r2 = await startSync(['--no-pull', '--no-delegate', '--json'], { ...plan[1], marker: marker(2), operation: 'submit_job' }).result;- keepLog('round2-client.log', `${r2.out}\n${r2.err}`); syncErrs.round2 = r2.err;- record(2);- note(`round 2: client exit ${r2.code} (${existsSync(marker(2)) ? `killed ${readFileSync(marker(2), 'utf8')}` : 'no fault fired'}) in ${(r2.ms / 1000).toFixed(1)}s, worst stall ${worstStall(r2.err)}s`);- elapsed.round2_ms = performance.now() - started;-- // Round 3: rewrite a third and the large page; a new serve dies at its fault point and the delegating client dies with it.- for (let i = 1; i < NOTES + 40; i += 3) writeNote(i, 'Round three');- writeBig(200, 620, 'v3');- commitAll('round three');- started = performance.now();- const s2 = new StdioServe({ ...plan[2], marker: marker(3), operation: 'submit_job' });- await s2.start();- const c3 = startSync(['--no-pull', '--json']);- await Promise.race([s2.exited, c3.result]);- if (!s2.alive) { c3.proc.kill('SIGKILL'); killedPids.add(c3.proc.pid); }- const r3 = await c3.result;- syncErrs.round3 = round3Err = r3.err; ownerKillStalls['round 3 (after the round-2 client kill)'] = worstStall(r3.err);- keepLog('round3-client.log', `${r3.out}\n${r3.err}`); keepLog('round3-serve.log', s2.stderr);- record(3);- note(`round 3: serve ${s2.alive ? 'survived' : `killed (${existsSync(marker(3)) ? readFileSync(marker(3), 'utf8') : 'no marker'})`}; client exit ${r3.code}${c3.proc.signalCode ? ` (${c3.proc.signalCode})` : ''} in ${(r3.ms / 1000).toFixed(1)}s, worst stall ${worstStall(r3.err)}s; ${r3.err.split('\n').find(l => /live write owner|owns this host's writes/.test(l))?.trim() ?? 'no delegation line'}`);- await s2.stop();- elapsed.round3_ms = performance.now() - started;-- // Round 4, only with a named PgBouncer container: restart the pooler under a running drain once it has committed 20 pages.- if (PGBOUNCER_CONTAINER) {- for (let i = 2; i < NOTES; i += 4) writeNote(i, 'Round four');- commitAll('round four');- started = performance.now();- const [{ at }] = await engine!.executeRaw<{ at: string }>('SELECT now()::text AS at');- const c4 = startSync(['--no-pull', '--no-delegate', '--json']);- let restarted = false;- const restart = until(async () => (await engine!.executeRaw<{ n: number }>(- `SELECT count(*)::int AS n FROM persistence_requests WHERE state='committed' AND completed_at > $1::timestamptz AND operation='submit_job'`, [at]))[0].n >= 20, 'twenty committed round-four pages', 600_000)- .then(() => { execFileSync('docker', ['restart', '-t', '0', PGBOUNCER_CONTAINER], { stdio: 'ignore' }); restarted = true; });- const r4 = await c4.result;- await restart.catch(error => note(`round 4: no restart (${(error as Error).message})`));- keepLog('round4-client.log', `${r4.out}\n${r4.err}`); syncErrs.round4 = r4.err;- fired[`round 4 docker restart ${PGBOUNCER_CONTAINER} after 20 commits`] = restarted ? 'restarted' : null;- note(`round 4: pooler ${restarted ? 'restarted mid-drain' : 'not restarted'}; client exit ${r4.code} in ${(r4.ms / 1000).toFixed(1)}s, worst stall ${worstStall(r4.err)}s: ${r4.err.trim().split('\n').slice(-1)[0] ?? ''}`);- elapsed.round4_ms = performance.now() - started;+ for (const p of plan) {+ const started = performance.now();+ const tag = `round-${p.round}`;+ const fault: Fault = { point: p.point, nth: p.nth, marker: b.marker(tag), operation: p.operation };+ const first = (p.round * perRound) % NOTES;+ const indexes = Array.from({ length: perRound }, (_, i) => (first + i) % NOTES);+ b.writeNotes(indexes, `Round ${p.round}`, `round ${p.round}`, p.round % 3 === 1 ? [b.bigFile(120 + 20 * p.round, 400 + 40 * p.round, `v${p.round}`)] : []);+ let line: string;+ if (p.kind === 'client') {+ const r = await b.sync(['--no-pull', '--no-delegate', '--json'], fault).result;+ syncErrs[tag] = r.err; b.keepLog(`${tag}-client.log`, `${r.out}\n${r.err}`);+ line = `client exit ${r.code} in ${(r.ms / 1000).toFixed(1)}s`;+ } else {+ const serve = new StdioServe(b, fault);+ await serve.start();+ const client = b.sync(['--no-pull', '--json']);+ await Promise.race([serve.exited, client.result]);+ if (p.kind === 'serve+client' && !serve.alive) { client.proc.kill('SIGKILL'); b.killedPids.add(client.proc.pid); }+ const r = await client.result;+ syncErrs[tag] = r.err; ownerKillStalls[`${tag} (${p.kind})`] = worstStall(r.err);+ b.keepLog(`${tag}-client.log`, `${r.out}\n${r.err}`); b.keepLog(`${tag}-serve.log`, serve.stderr);+ line = `serve ${serve.alive ? 'survived' : 'killed'}; client exit ${r.code}${client.proc.signalCode ? ` (${client.proc.signalCode})` : ''} in ${(r.ms / 1000).toFixed(1)}s, worst stall ${worstStall(r.err)}s`;+ if (plan[p.round - 2]?.kind === 'client') afterClientKill.push(tag);+ await serve.stop();+ }+ const fired = b.recordFault(tag, `round ${p.round} ${p.kind} ${p.point} #${p.nth}`);+ b.note(`round ${p.round} (${p.kind}): ${fired ? `fault fired ${fired}` : 'no fault fired'}; ${line}`);+ b.elapsed[`${tag}_ms`] = performance.now() - started;}chaosDone = true;- await writer;- elapsed.chaos_ms = performance.now() - chaosStarted;- note(`writer: ${writerResults.map(w => `${w.slug}=${w.code}${w.attempts > 1 ? `/${w.attempts}` : ''}`).join(' ')}`);-- // Recovery: a fresh resident serve and at most three plain syncs, no operator step.- const recoveryStarted = performance.now();- const s3 = new StdioServe();- await s3.start();- for (let run = 1; run <= MAX_RECOVERY_RUNS; run++) {- const r = await startSync(['--no-pull', '--json']).result;- const envelope = lastJson(r.out);- recoveryRuns.push({ code: r.code, ms: r.ms, envelope, err: r.err });- keepLog(`recovery-${run}-client.log`, `${r.out}\n${r.err}`); syncErrs[`recovery ${run}`] = r.err;- ownerKillStalls[`recovery run ${run}`] = worstStall(r.err);- note(`recovery run ${run}: exit ${r.code} in ${(r.ms / 1000).toFixed(1)}s outcome=${String(envelope?.outcome ?? envelope?.sync_status ?? envelope?.error ?? 'none')}`);- if (r.code === 0 && envelope?.outcome === 'synced') break;- }- elapsed.recovery_ms = performance.now() - recoveryStarted;- keepLog('recovery-serve.log', s3.stderr);- note(`elapsed: ${Object.entries(elapsed).map(([k, ms]) => `${k.replace(/_ms$/, '')} ${(ms / 1000).toFixed(1)}s`).join(', ')}; recovery took ${recoveryRuns.length} sync run(s)`);- }, 3_600_000);-- afterAll(async () => {- for (const serve of serves) await serve.stop().catch(() => {});- try { await engine?.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); } catch { /* best effort */ }- await engine?.disconnect().catch(() => {});- await pooledProxy?.close().catch(() => {});- await directProxy?.close().catch(() => {});- if (admin) {- try { if (database) await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`); } finally { await admin.end(); }- }- for (const dir of [home, repo]) if (dir) rmSync(dir, { recursive: true, force: true });- });-- test('the oracle is calibrated: a fault-free import satisfies it', () => {- expect(calibration).toEqual([]);- });+ const results = await writers;+ b.elapsed.chaos_ms = performance.now() - chaosStarted;+ b.note(`writers: ${results.join(' ')}`);+ await b.recover();+ for (const [i, run] of b.recoveryRuns.entries()) { syncErrs[`recovery ${i + 1}`] = run.err; ownerKillStalls[`recovery run ${i + 1}`] = worstStall(run.err); }+ }, SCENARIO_TIMEOUT_MS);+ afterAll(() => b.teardown(), 120_000);+ oracleTests(b, () => ({}));test(as('wedge', "a killed client's stale heartbeat never keeps ownership from a live serve"), () => {const deadOwners = Object.entries(syncErrs).flatMap(([run, err]) => [...err.matchAll(/the live write owner on this host is a (\w+) process \(PID (\d+)\)/g)]- .filter(m => killedPids.has(Number(m[2]))).map(m => `${run}: ${m[0]}`));- expect({ delegatedToLiveServe: /running the managed catch-up inside it as this CLI's writer/.test(round3Err), deadOwners })- .toEqual({ delegatedToLiveServe: true, deadOwners: [] });+ .filter(m => b.killedPids.has(Number(m[2]))).map(m => `${run}: ${m[0]}`));+ const notDelegated = afterClientKill.filter(tag => !/running the managed catch-up inside it as this CLI's writer/.test(syncErrs[tag] ?? ''))+ .map(tag => `${tag}: the client after a client kill did not delegate to the live serve`);+ b.verdict([...deadOwners, ...notDelegated]);});-test(as('wedge', 'recovery after an owner kill does not wait out the publication lease'), () => {- note(`worst stall after an owner kill (bound ${OWNER_KILL_STALL_BOUND_S}s): ${Object.entries(ownerKillStalls).map(([k, v]) => `${k} ${v}s`).join(', ')}`);- expect(Object.entries(ownerKillStalls).filter(([, stall]) => stall > OWNER_KILL_STALL_BOUND_S)).toEqual([]);+ b.note(`worst stall after an owner kill (bound ${OWNER_KILL_STALL_BOUND_S}s): ${Object.entries(ownerKillStalls).map(([k, v]) => `${k} ${v}s`).join(', ')}`);+ b.verdict(Object.entries(ownerKillStalls).filter(([, stall]) => stall > OWNER_KILL_STALL_BOUND_S).map(([k, v]) => `${k} stalled ${v}s`));});+});- test('every planned fault fired, so the chaos actually happened', () => {- expect(Object.entries(fired).filter(([, at]) => at === null).map(([fault]) => fault)).toEqual([]);- });+// ---------------------------------------------------------------- (c-db): a DB-only competitor- test(as('wedge', `a plain sync succeeds within ${MAX_RECOVERY_RUNS} runs after the chaos, with no operator step`), () => {- const last = recoveryRuns.at(-1);- expect({ code: last?.code, outcome: last?.envelope?.outcome }).toEqual({ code: 0, outcome: 'synced' });+scenario(['c-db'], 'a DB-only write racing a file change ends as a named hold with both versions kept', () => {+ const b = new Brain('db-only', ['c-db']);+ const notes = 20;+ const raced = noteSlug(3), quiet = noteSlug(11);+ beforeAll(async () => {+ // A DB-only write needs write-through off (the #6194 contract): the coordinator then publishes page writes to the database only.+ await b.setup(brain => brain.writeNotes(Array.from({ length: notes }, (_, i) => i), 'Initial', 'fixture'), { 'sync.write_through': 'false' });+ const indexes = Array.from({ length: 8 }, (_, i) => i);+ b.writeNotes(indexes, 'Git edit', 'git edit');+ const tag = 'stall', release = join(b.home, 'release-stall');+ b.plan = [`stall at sync:after_freeze for ${raced}.md; DB-only put of ${raced} and ${quiet}`];+ const run = b.sync(['--no-pull', '--no-delegate', '--json'], { point: 'sync:after_freeze', nth: 1, path: `${raced}.md`, marker: b.marker(tag), action: 'stall', release });+ await until(() => existsSync(b.marker(tag)), 'the run to freeze the raced entry', SYNC_TIMEOUT_MS);+ for (const slug of [raced, quiet]) {+ const marker = `Database-only edit of ${slug} (${randomUUID().slice(0, 8)})`;+ const start = performance.now();+ const r = await b.spawnCli(['put', slug, '--source-id', SOURCE, '--force', '--wait-ms', '30000'], { stdin: `---\ntype: concept\ntitle: ${slug} database edit\n---\n\n${marker}.\n` }).result;+ b.keepLog(`db-only-${slug.replace('/', '_')}.log`, `exit ${r.code}\n${r.out}\n${r.err}`);+ if (r.code !== 0) throw new Error(`the DB-only put of ${slug} exited ${r.code}: ${r.err}\n${b.context()}`);+ b.ledger.record({ kind: 'db_only', slug, marker, touches: ['db'], start, ack: performance.now() });+ }+ writeFileSync(release, '');+ const r = await run.result;+ b.keepLog('raced-run.log', `${r.out}\n${r.err}`);+ b.recordFault(tag, b.plan[0]);+ b.note(`raced run: exit ${r.code} in ${(r.ms / 1000).toFixed(1)}s`);+ await b.recover();+ }, SCENARIO_TIMEOUT_MS);+ afterAll(() => b.teardown(), 120_000);+ oracleTests(b, () => ({ exclude: new Set([raced, quiet]), bigPage: false,+ status: { holds: [{ code: 'concurrent_write', path: `${raced}.md` }], needsHuman: true } }));+ test(as('lost_write', 'the held file keeps its committed bytes and the page keeps the DB-only write'), () => {+ const disk = b.diskPages();+ b.verdict([+ ...(disk.get(raced)?.includes(noteMarker(3, 'Git edit')) ? [] : [`${raced}: the file lost its committed Git edit`]),+ ...(disk.get(quiet)?.includes(noteMarker(11, 'Initial')) ? [] : [`${quiet}: the file changed although only the database was written`]),+ ]);});+});++// ---------------------------------------------------------------- (d): out-of-band git mv / git rm and uncommitted deletions- test(as('projection_drift', 'disk == database for every page'), async () => {- expect(await diskDbMismatches()).toEqual([]);+scenario(['d'], 'committed git mv/git rm mid-run converge; an uncommitted deletion is a ghost with the repair ghost-pages exit', () => {+ const b = new Brain('git-moves', ['d']);+ const notes = Math.min(NOTES, 200);+ const share = Math.max(2, Math.round(notes * 0.01));+ const moved: string[] = [], removed: string[] = [], ghosts: string[] = [];+ let ghostScan: Record<string, unknown> | null = null;+ beforeAll(async () => {+ await b.setup(brain => brain.writeNotes(Array.from({ length: notes }, (_, i) => i), 'Initial', 'fixture'));+ const indexes = Array.from({ length: 40 }, (_, i) => i);+ b.writeNotes(indexes, 'Round one', 'round one');+ const others = Array.from({ length: notes - 40 }, (_, i) => i + 40).sort(() => b.rand() - 0.5);+ moved.push(...others.slice(0, share).map(noteSlug)); removed.push(...others.slice(share, 2 * share).map(noteSlug)); ghosts.push(...others.slice(2 * share, 3 * share).map(noteSlug));+ const tag = 'stall', release = join(b.home, 'release-stall');+ b.plan = [`stall at sync:after_freeze #5; git mv ${moved.join(',')}; git rm ${removed.join(',')}; unlink (uncommitted) ${ghosts.join(',')}`];+ const run = b.sync(['--no-pull', '--no-delegate', '--json'], { point: 'sync:after_freeze', nth: 5, marker: b.marker(tag), action: 'stall', release });+ await until(() => existsSync(b.marker(tag)), 'the run to freeze its fifth entry', SYNC_TIMEOUT_MS);+ const start = performance.now();+ mkdirSync(join(b.repo, 'moved'), { recursive: true });+ for (const slug of moved) b.git('mv', `${slug}.md`, `moved/${slug.split('/')[1]}.md`);+ for (const slug of removed) b.git('rm', '-q', `${slug}.md`);+ b.git('commit', '-qm', 'out-of-band moves and removals');+ for (const slug of ghosts) rmSync(join(b.repo, `${slug}.md`));+ const ack = performance.now();+ for (const slug of moved) {+ const i = Number(slug.split('-')[1]);+ b.ledger.record({ kind: 'git_mv', slug, marker: null, touches: ['db', 'file'], start, ack });+ b.ledger.record({ kind: 'git_mv', slug: `moved/${slug.split('/')[1]}`, marker: noteMarker(i, 'Initial'), touches: ['db', 'file'], start, ack });+ }+ for (const slug of removed) b.ledger.record({ kind: 'git_rm', slug, marker: null, touches: ['db', 'file'], start, ack });+ for (const slug of ghosts) b.ledger.record({ kind: 'unlink', slug, marker: null, touches: ['file'], start, ack });+ writeFileSync(release, '');+ const r = await run.result;+ b.keepLog('stalled-run.log', `${r.out}\n${r.err}`);+ b.recordFault(tag, b.plan[0]);+ b.note(`stalled run: exit ${r.code} in ${(r.ms / 1000).toFixed(1)}s`);+ await b.recover();+ const scan = await b.spawnCli(['pages', 'ghosts', '--source', SOURCE, '--json']).result;+ b.keepLog('ghosts.json', `${scan.out}\n${scan.err}`);+ ghostScan = lastJson(scan.out);+ }, SCENARIO_TIMEOUT_MS);+ afterAll(() => b.teardown(), 120_000);+ oracleTests(b, () => ({ exclude: new Set(ghosts), bigPage: false }));+ test(as('projection_drift', 'each uncommitted deletion is reported as a ghost page whose exit is repair ghost-pages'), () => {+ const listed = ((ghostScan?.ghosts ?? []) as Array<{ slug: string }>).map(g => g.slug).sort();+ const next = JSON.stringify(ghostScan?.next ?? []);+ b.verdict([+ ...(JSON.stringify(listed) === JSON.stringify([...ghosts].sort()) ? [] : [`pages ghosts lists [${listed.join(', ')}], expected [${[...ghosts].sort().join(', ')}]`]),+ ...(next.includes(`gbrain repair ghost-pages --source ${SOURCE}`) ? [] : [`pages ghosts next does not name gbrain repair ghost-pages: ${next}`]),+ ]);});+});- test(as('wedge', 'no request blocks the checkpoint or a root'), async () => {- const open = await engine!.executeRaw<{ request_id: string; slug: string; state: string; recovery: boolean; blocked_reason: string | null }>(- `SELECT request_id::text, slug, state, recovery IS NOT NULL AS recovery, blocked_reason FROM persistence_requests- WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL ORDER BY sequence`);- const worktrees = await engine!.executeRaw<{ id: string; state: string }>(`SELECT id::text, state FROM persistence_worktrees WHERE state<>'active'`);- expect({ open, worktrees }).toEqual({ open: [], worktrees: [] });+// ---------------------------------------------------------------- (e): a deterministic mid-run edit++scenario(['e'], 'an edit after freezeEntry is held worktree_dirty, then converges strictly once committed', () => {+ const b = new Brain('mid-run-edit', ['e']);+ const notes = Math.min(NOTES, 60);+ const target = 7;+ let raced: Record<string, unknown> | null = null;+ let heldAfterRun: Array<{ code: string; path: string }> = [];+ beforeAll(async () => {+ await b.setup(brain => brain.writeNotes(Array.from({ length: notes }, (_, i) => i), 'Initial', 'fixture'));+ b.writeNotes(Array.from({ length: 20 }, (_, i) => i), 'Round one', 'round one');+ const tag = 'edit', file = join(b.repo, `${noteSlug(target)}.md`);+ b.plan = [`edit ${noteSlug(target)}.md at sync:after_freeze #1 (uncommitted)`];+ const start = performance.now();+ const r = await b.sync(['--no-pull', '--no-delegate', '--json'], { point: 'sync:after_freeze', nth: 1, path: `${noteSlug(target)}.md`, marker: b.marker(tag), action: 'edit',+ edit: { file, content: noteText(target, 'Uncommitted edit') } }).result;+ b.keepLog('edited-run.log', `${r.out}\n${r.err}`);+ b.recordFault(tag, b.plan[0]);+ raced = lastJson(r.out);+ heldAfterRun = ((await b.status())?.holds ?? []) as Array<{ code: string; path: string }>;+ b.note(`edited run: exit ${r.code}; holds ${JSON.stringify(heldAfterRun.map(h => `${h.code}:${h.path}`))}`);+ b.git('add', '--', `${noteSlug(target)}.md`); b.git('commit', '-qm', 'the editor commits', '--', `${noteSlug(target)}.md`);+ b.ledger.record({ kind: 'commit', slug: noteSlug(target), marker: noteMarker(target, 'Uncommitted edit'), touches: ['db', 'file'], start, ack: performance.now() });+ await b.recover();+ }, SCENARIO_TIMEOUT_MS);+ afterAll(() => b.teardown(), 120_000);+ test(as('lost_write', 'the run that met the uncommitted edit names worktree_dirty for it'), () => {+ const path = `${noteSlug(target)}.md`;+ const envelopeNames = JSON.stringify(raced ?? {}).includes('worktree_dirty');+ b.verdict(heldAfterRun.some(h => h.code === 'worktree_dirty' && h.path === path) && envelopeNames ? []+ : [`expected a worktree_dirty hold on ${path} in the run's receipt and status; status holds ${JSON.stringify(heldAfterRun)}, receipt ${JSON.stringify(raced).slice(0, 400)}`]);});+ oracleTests(b, () => ({ bigPage: false }));+});- test(as('untyped_error', 'every non-committed terminal request is superseded or carries a registered error code'), async () => {- const rows = await engine!.executeRaw<{ request_id: string; slug: string; state: string; error_code: string | null; operation: string }>(- `SELECT request_id::text, slug, state, error_code, operation FROM persistence_requests WHERE state IN ('conflict','failed','cancelled') ORDER BY sequence`);- const disk = diskPages(), db = await dbPages();- const unexplained = rows.filter(row => {- const content = disk.get(row.slug);- const superseded = content !== undefined && db.get(row.slug) === fileHash(row.slug, content);- return !superseded && !(row.error_code && row.error_code in CODES);+// ---------------------------------------------------------------- (f): a pooler drop mid-bulk++scenario(['f'], 'a pooler drop mid-bulk leaves no new hold and converges', () => {+ const b = new Brain('pooler-drop', ['f']);+ const notes = Math.min(NOTES, 200);+ let holdsBefore = 0, holdsAfter = 0, stall = 0;+ beforeAll(async () => {+ await b.setup(brain => brain.writeNotes(Array.from({ length: notes }, (_, i) => i), 'Initial', 'fixture'));+ b.writeNotes(Array.from({ length: Math.min(notes, 120) }, (_, i) => i), 'Round one', 'round one');+ holdsBefore = ((await b.status())?.holds as unknown[] | undefined)?.length ?? 0;+ const at = await b.now();+ const how = PGBOUNCER_CONTAINER ? `docker restart -t 0 ${PGBOUNCER_CONTAINER}` : 'drop every pooled connection at the proxy';+ b.plan = [`${how} after 20 committed pages`];+ const run = b.sync(['--no-pull', '--no-delegate', '--json']);+ const dropped = until(async () => (await b.committedSince(at)) >= 20, 'twenty committed pages', SYNC_TIMEOUT_MS).then(() => {+ if (PGBOUNCER_CONTAINER) execFileSync('docker', ['restart', '-t', '0', PGBOUNCER_CONTAINER], { stdio: 'ignore' });+ else b.note(`dropped ${b.pooledProxy!.drop()} pooled connections`);+ return 'dropped';});- note(`terminal non-committed requests: ${rows.length} (${[...new Set(rows.map(r => `${r.state}:${r.error_code}`))].join(', ') || 'none'})`);- expect(unexplained).toEqual([]);- });+ const r = await run.result;+ b.fired[b.plan[0]] = await dropped.catch(() => null);+ b.keepLog('dropped-run.log', `${r.out}\n${r.err}`);+ stall = worstStall(r.err);+ b.note(`dropped run: exit ${r.code} in ${(r.ms / 1000).toFixed(1)}s, worst stall ${stall}s`);+ await b.recover();+ holdsAfter = ((await b.status())?.holds as unknown[] | undefined)?.length ?? 0;+ }, SCENARIO_TIMEOUT_MS);+ afterAll(() => b.teardown(), 120_000);+ test(as('wedge', 'the pooler drop created no hold'), () => b.verdict(holdsAfter > holdsBefore ? [`${holdsAfter - holdsBefore} new hold(s) after the pooler drop`] : []));+ // A dropped pooled connection is an owner losing its session: the drain resumes within the owner-kill bound, not a publication lease.+ test(as('wedge', `the run resumed within ${OWNER_KILL_STALL_BOUND_S}s of the pooler drop`), () =>+ b.verdict(stall > OWNER_KILL_STALL_BOUND_S ? [`the dropped run stalled ${stall}s on one step`] : []));+ oracleTests(b, () => ({ bigPage: false }));+});- test(as('wedge', 'the cursor reached HEAD'), async () => {- const [source] = await engine!.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [SOURCE]);- expect(source.last_commit).toBe(git('rev-parse', 'HEAD'));- });+// ---------------------------------------------------------------- (g): two concurrent drainers++scenario(['g'], 'a --all run beside a serve draining the same source converges', () => {+ const b = new Brain('two-drainers', ['g']);+ const notes = Math.min(NOTES, 200);+ beforeAll(async () => {+ await b.setup(brain => brain.writeNotes(Array.from({ length: notes }, (_, i) => i), 'Initial', 'fixture'));+ b.writeNotes(Array.from({ length: Math.min(notes, 120) }, (_, i) => i), 'Round one', 'round one');+ b.plan = ['a delegated sync drains in the serve while sync --all --no-delegate drains beside it'];+ const serve = new StdioServe(b);+ await serve.start();+ const [delegated, all] = await Promise.all([b.sync(['--no-pull', '--json']).result,+ b.spawnCli(['sync', '--all', '--no-pull', '--no-delegate', '--json']).result]);+ b.keepLog('delegated.log', `${delegated.out}\n${delegated.err}`); b.keepLog('all.log', `${all.out}\n${all.err}`);+ b.note(`delegated sync exit ${delegated.code}; --all exit ${all.code}`);+ await serve.stop();+ await b.recover();+ }, SCENARIO_TIMEOUT_MS);+ afterAll(() => b.teardown(), 120_000);+ oracleTests(b, () => ({ bigPage: false }));+});- test(as('lost_write', 'the large page keeps every fence fact exactly once and loses no timeline entry'), async () => {- const { problems, timelineDuplicates, timelineStrays } = await childRowProblems();- note(`large page timeline (measured, not asserted): ${timelineDuplicates} duplicate rows, ${timelineStrays} rows not in the file`);- expect(problems).toEqual([]);+// ---------------------------------------------------------------- (systemic): a refusal on every page write++for (const sqlstate of ['P0001', '55000'] as const) {+ scenario(['systemic'], `a systemic ${sqlstate} refusal stops the run with a named blocker and converges once lifted`, () => {+ const b = new Brain(`systemic-${sqlstate}`, ['systemic']);+ const notes = Math.min(NOTES, 200);+ let refused: { code: number; envelope: Record<string, unknown> | null; terminal: number } | null = null;+ beforeAll(async () => {+ await b.setup(brain => brain.writeNotes(Array.from({ length: notes }, (_, i) => i), 'Initial', 'fixture'));+ b.writeNotes(Array.from({ length: Math.min(notes, 40) }, (_, i) => i), 'Round one', 'round one');+ b.plan = [`trigger on pages raising SQLSTATE ${sqlstate} (an unregistered raiser) for one sync run, then dropped`];+ await b.engine!.executeRaw(`CREATE FUNCTION convergence_systemic_refusal() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION USING ERRCODE = '${sqlstate}', MESSAGE = 'convergence harness: systemic refusal'; END $$`);+ await b.engine!.executeRaw('CREATE TRIGGER convergence_systemic_refusal BEFORE INSERT OR UPDATE ON pages FOR EACH ROW EXECUTE FUNCTION convergence_systemic_refusal()');+ b.fired[b.plan[0]] = 'installed';+ const at = await b.now();+ const r = await b.sync(['--no-pull', '--no-delegate', '--json']).result;+ b.keepLog('refused-run.log', `${r.out}\n${r.err}`);+ await b.engine!.executeRaw('DROP TRIGGER convergence_systemic_refusal ON pages; DROP FUNCTION convergence_systemic_refusal()');+ const terminal = (await b.engine!.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests WHERE operation='submit_job'+ AND created_at > $1::timestamptz AND state IN ('failed','conflict','cancelled')`, [at]))[0].n;+ refused = { code: r.code, envelope: lastJson(r.out), terminal };+ b.note(`refused run: exit ${r.code} in ${(r.ms / 1000).toFixed(1)}s outcome=${String(refused.envelope?.outcome ?? refused.envelope?.sync_status ?? 'none')}; ${terminal} terminal non-committed request(s)`);+ await b.recover();+ }, SCENARIO_TIMEOUT_MS);+ afterAll(() => b.teardown(), 120_000);+ test(as('wedge', 'the refused run does not report success and its receipt names the SQLSTATE'), () => b.verdict([+ ...(refused?.code !== 0 && refused?.envelope?.outcome !== 'synced' ? [] : [`the refused run reported success (exit ${refused?.code}, outcome ${String(refused?.envelope?.outcome)})`]),+ ...(JSON.stringify(refused?.envelope ?? {}).includes(sqlstate) ? [] : [`the refused run's receipt does not name ${sqlstate}: ${JSON.stringify(refused?.envelope).slice(0, 400)}`]),+ ]));+ oracleTests(b, () => ({ bigPage: false }));});+}++// ---------------------------------------------------------------- (knock-on): one page, one fate++scenario(['knock-on'], 'one failed page inside a bulk group cancels no other page of the run', () => {+ const b = new Brain('knock-on', ['knock-on']);+ const notes = Math.min(NOTES, 200);+ const refused = noteSlug(5);+ let cancelled: string[] = [];+ beforeAll(async () => {+ await b.setup(brain => brain.writeNotes(Array.from({ length: notes }, (_, i) => i), 'Initial', 'fixture'));+ const changed = Array.from({ length: Math.min(notes, 80) }, (_, i) => i);+ b.plan = ['throw SQLSTATE P0001 once at publication:before_commit #5 (submit_job)',+ `trigger on pages raising SQLSTATE P0001 for ${refused} only, for one sync run, then dropped`];+ const at = await b.now();+ b.writeNotes(changed, 'Round one', 'round one');+ const tag = 'throw';+ const r = await b.sync(['--no-pull', '--no-delegate', '--json'], { point: 'publication:before_commit', nth: 5, operation: 'submit_job', marker: b.marker(tag), action: 'throw', sqlstate: 'P0001' }).result;+ b.keepLog('failed-run.log', `${r.out}\n${r.err}`);+ const fired = b.recordFault(tag, b.plan[0]);+ const failed = fired ? (JSON.parse(fired) as { requestId?: string }).requestId : undefined;+ b.note(`one-shot failure run: exit ${r.code}`);+ b.writeNotes(changed, 'Round two', 'round two');+ await b.engine!.executeRaw(`CREATE FUNCTION convergence_page_refusal() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN IF NEW.slug = '${refused}' THEN RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = 'convergence harness: page refusal'; END IF; RETURN NEW; END $$`);+ await b.engine!.executeRaw('CREATE TRIGGER convergence_page_refusal BEFORE INSERT OR UPDATE ON pages FOR EACH ROW EXECUTE FUNCTION convergence_page_refusal()');+ b.fired[b.plan[1]] = 'installed';+ const refusedRun = await b.sync(['--no-pull', '--no-delegate', '--json']).result;+ b.keepLog('refused-page-run.log', `${refusedRun.out}\n${refusedRun.err}`);+ await b.engine!.executeRaw('DROP TRIGGER convergence_page_refusal ON pages; DROP FUNCTION convergence_page_refusal()');+ cancelled = (await b.engine!.executeRaw<{ request_id: string; slug: string; error_code: string | null }>(+ `SELECT request_id::text, slug, error_code FROM persistence_requests WHERE operation='submit_job' AND created_at > $1::timestamptz AND state='cancelled'+ AND request_id::text <> $2 AND slug <> $3`, [at, failed ?? '', refused])).map(row => `${row.slug} (${row.error_code})`);+ b.note(`refused-page run: exit ${refusedRun.code}; ${cancelled.length} other request(s) cancelled`);+ await b.recover();+ }, SCENARIO_TIMEOUT_MS);+ afterAll(() => b.teardown(), 120_000);+ test(as('wedge', 'the failed page cancelled no other page of its run'), () => b.verdict(cancelled.map(c => `cancelled as a knock-on: ${c}`)));+ oracleTests(b, () => ({ bigPage: false }));});