Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(persistence): #5984 round-trip diet 2 — preimage/postimage reads, per-transaction memos, stable chunk insert, set-based group completion, pipelined independent statements

garrytan103fa189eb44
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index c8d143f471..20db228011 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,12 +16,12 @@ src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3224 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224)
src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)
src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
-src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
+src/core/engine.ts 2682 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet)
src/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)
-src/core/pglite-engine.ts 2926 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)
-src/core/postgres-engine.ts 2917 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured)
+src/core/pglite-engine.ts 2927 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts)
+src/core/postgres-engine.ts 2918 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts)
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2124 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field)
src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index f2ac3a5ced..3041d7ea8f 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -82,14 +82,17 @@ export async function upsertChunksOnce(
// Source-scope the page-id lookup. Without this filter, multi-source
// brains where the slug exists in 2+ sources return >1 row and the
// chunk replacement targets the wrong page (or fans out across pages).
- const pages = (await exec.run<{ id: number }>(sqlFragment`SELECT id FROM pages WHERE slug = ${slug} AND source_id = ${sourceId} FOR UPDATE`)).rows;
- if (pages.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);
- const pageId = pages[0].id;
-
// #5984: `sealChunkerVersion` is a complete replacement: the caller deleted
// every chunk of the page earlier in this transaction, so nothing stale can
- // remain, and the page is sealed at that chunker version after the insert.
+ // remain, and the seal (which also locks the page row and yields its id)
+ // commits only together with the insert below.
const seal = opts?.sealChunkerVersion;
+ const pages = (await exec.run<{ id: number }>(seal === undefined
+ ? sqlFragment`SELECT id FROM pages WHERE slug = ${slug} AND source_id = ${sourceId} FOR UPDATE`
+ : sqlFragment`UPDATE pages SET chunker_version = ${seal} WHERE slug = ${slug} AND source_id = ${sourceId} RETURNING id`)).rows;
+ if (pages.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);
+ const pageId = pages[0].id;
+
if (seal === undefined) {
// A fragment write cannot certify the full-body fence boundary. Import seals
// only after its complete replacement succeeds in the same transaction.
@@ -104,10 +107,7 @@ export async function upsertChunksOnce(
await exec.run(sqlFragment`DELETE FROM content_chunks WHERE page_id = ${pageId}`);
return;
}
- } else if (chunks.length === 0) {
- await exec.run(sqlFragment`UPDATE pages SET chunker_version = ${seal} WHERE id = ${pageId}`);
- return;
- }
+ } else if (chunks.length === 0) return;
// Batch upsert: build a single multi-row INSERT ON CONFLICT statement.
// v0.19.0: includes language/symbol_name/symbol_type/start_line/end_line
@@ -304,7 +304,6 @@ export async function upsertChunksOnce(
modality = EXCLUDED.modality,
embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)`);
await exec.query(text, params);
- if (seal !== undefined) await exec.run(sqlFragment`UPDATE pages SET chunker_version = ${seal} WHERE id = ${pageId}`);
}
export async function getChunks(
diff --git a/src/core/engine.ts b/src/core/engine.ts
index b162753872..f3c506cecc 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2275,7 +2275,8 @@ export interface BrainEngine {
* without it the bare-slug lookup snapshots whichever row Postgres returns
* first when the slug exists across multiple sources.
*/
- createVersion(slug: string, opts?: { sourceId?: string }): Promise<PageVersion>;
+ /** `preimage` (#5984): the caller's own read of the page under its page guard in this transaction; versioned without a re-read. */
+ createVersion(slug: string, opts?: { sourceId?: string; preimage?: PageSnapshot }): Promise<PageVersion>;
/**
* v0.31.8 (D12 + D16): `opts.sourceId` source-scopes the page-id lookup.
* When omitted, returns versions for every same-slug page across sources
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 74a9ee1d8b..75a420d7a8 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -32,6 +32,7 @@ import { embedBatchKeepingUsable, embedBatchWithBackoff } from './embed-retry.ts
import { isEmbeddingZeroNormError, type EmbeddingZeroNormError } from './ai/embedding-guard.ts';
import { slugifyPath, slugifyCodePath, isCodeFilePath, hasMalformedPathSegment } from './sync.ts';
import type { ChunkInput, Page, PageInput, PageType } from './types.ts';
+import type { PageSnapshot } from './page-state/types.ts';
import { computeEffectiveDate, fallbackCreatedAt, isValidTimeZone } from './effective-date.ts';
import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';
import { logSlugFallback } from './audit-slug-fallback.ts';
@@ -224,13 +225,7 @@ export async function importFromContent(
opts: {
/** Coordinator seam: prepare without publishing, then commit under its guarded transaction. */
prepare?: (prepared: import('./persistence/prepared-import.ts').PreparedContentImport) => Promise<ImportResult>;
- /**
- * #5984, with `prepare`: the publication coordinator proves the page's base
- * revision under its page guard before apply, and the caller reads the page
- * once after apply, seals its text projection from that read and checks the
- * read-back against `contentHash`. apply then skips its own base re-read,
- * text-projection seal and read-back.
- */
+ /** #5984, with `prepare`: the coordinator proves the base revision under its page guard, and the caller seals the text projection and checks the read-back (`contentHash`) from its own read after apply; apply skips all three. */
coordinated?: boolean;
/** Internal canonical metadata, after protected-body overlays and before hashing. */
prepareFrontmatter?: (page: ParsedPage) => void;
@@ -830,10 +825,10 @@ export async function importFromContent(
const txOpts = { sourceId: sourceId ?? 'default' };
let persistedProjection: ProjectionSnapshot | null = null;
const timeZone = await loadBrainTimeZone(engine);
- const applyPrepared = async (tx: BrainEngine) => {
+ const applyPrepared = async (tx: BrainEngine, preimage?: PageSnapshot | null) => {
if (!opts.coordinated) await assertImportBase(tx, slug, txOpts.sourceId, existing);
await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug);
- if (existing) await tx.createVersion(slug, txOpts);
+ if (existing) await tx.createVersion(slug, preimage ? { ...txOpts, preimage } : txOpts);
// v0.29.1 — compute effective_date from frontmatter precedence chain.
// Filename comes from importFromFile path (basename) or the slug tail
@@ -912,8 +907,6 @@ export async function importFromContent(
if (chunks.length > 0) {
const embeddingColumn = await stampEmbeddingInputs(tx, chunks, null,
{ title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });
- // A complete replacement of the chunks deleted above: the full-body seal
- // (`chunker_version`) is stamped by the same upsert, after its insert.
await tx.upsertChunks(slug, chunks, { ...txOpts, ...(embeddingColumn ? { embeddingColumn } : {}), sealChunkerVersion: MARKDOWN_CHUNKER_VERSION });
// v0.41.31: stamp embedding provenance when this import actually
// embedded (not --no-embed), so a later model/dims swap is detectable
@@ -928,12 +921,9 @@ export async function importFromContent(
}
}
} else {
- // Content is empty — delete stale chunks so they don't ghost in search results
- await tx.deleteChunks(slug, txOpts);
- // Seal only the completed, full-body sanitized replacement. A body-only
- // write or a failed transaction must never certify old stored fragments.
- await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3',
- [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);
+ // Seal only the completed, full-body sanitized replacement (the upsert above seals its own); a
+ // body-only write or a failed transaction must never certify old stored fragments.
+ await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3', [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);
}
if (!opts.coordinated) await sealPageTextProjection(tx, slug, txOpts.sourceId);
diff --git a/src/core/page-state/versions.ts b/src/core/page-state/versions.ts
index ee9b9636e6..65d5b64d60 100644
--- a/src/core/page-state/versions.ts
+++ b/src/core/page-state/versions.ts
@@ -1,17 +1,26 @@
import type { BrainEngine } from '../engine.ts';
import type { PageVersion } from '../types.ts';
+import type { PageSnapshot } from './types.ts';
-/** Version the same canonical view an API reader receives, including withdrawals. */
-export async function createPageVersion(engine: BrainEngine, slug: string, sourceId: string): Promise<PageVersion> {
- return engine.transaction(async tx => {
- await tx.lockPageKeys([{ sourceId, slug }]);
- const snapshot = await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true });
- if (!snapshot) throw new Error(`createVersion failed: page "${slug}" (source=${sourceId}) not found`);
+/**
+ * Version the same canonical view an API reader receives, including withdrawals.
+ * `preimage` (#5984) is the caller's own read of the page under its page guard
+ * in this transaction; it is versioned as read, without a second read.
+ */
+export async function createPageVersion(engine: BrainEngine, slug: string, sourceId: string, preimage?: PageSnapshot): Promise<PageVersion> {
+ const insert = async (tx: BrainEngine, snapshot: PageSnapshot) => {
const { page, tags, revision } = snapshot;
const rows = await tx.executeRaw<PageVersion>(`INSERT INTO page_versions
(page_id,compiled_truth,frontmatter,knowledge_revision,timeline,title,type,tags,is_deleted,source_path)
VALUES ($1,$2,$3::text::jsonb,$4::uuid,$5,$6,$7,$8::text::jsonb,$9,$10) RETURNING *`,
[page.id, page.compiled_truth, JSON.stringify(page.frontmatter), revision, page.timeline, page.title, page.type, JSON.stringify(tags), page.deleted_at != null, page.source_path ?? null]);
return { ...rows[0], snapshot_at: new Date(rows[0].snapshot_at) };
+ };
+ if (preimage) return insert(engine, preimage);
+ return engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId, slug }]);
+ const snapshot = await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ if (!snapshot) throw new Error(`createVersion failed: page "${slug}" (source=${sourceId}) not found`);
+ return insert(tx, snapshot);
});
}
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 3eab73369b..35f65a2d5e 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -42,8 +42,12 @@ interface PreparedMutationBase {
deferEmbedding?: boolean;
/** Why a page write bound to a worktree publishes no file (receipt `write_through.skipped`). */
databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only';
- /** Must perform only transaction-composable database work. */
- apply(tx: BrainEngine): Promise<Record<string, unknown>>;
+ /**
+ * Must perform only transaction-composable database work. `preimage` (#5984)
+ * is the publisher's read of the page under its page guard, after the revision
+ * check; apply may use it instead of reading the page again.
+ */
+ apply(tx: BrainEngine, preimage?: PageSnapshot | null): Promise<Record<string, unknown>>;
/**
* #5984: set by apply to its own read of the page (including deleted rows)
* after its last write to the page; the publisher takes the receipt revision
@@ -269,11 +273,12 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
if (!current || current.execution_token !== row.execution_token || current.state !== 'running') throw opError('write_claim_lost', 'Execution claim changed before publication.',
`Another worker took over request ${row.request_id} (its execution claim expired or was reassigned) before this attempt published, so this attempt wrote nothing and the current holder decides the outcome. Inspect the request rather than resubmitting it.`,
{ fix: requestFix(row) });
+ let snapshot: PageSnapshot | null = null;
if (skill) await assertSharedSkillPersistence(tx, row.source_id);
else {
await assertKnowledgePublicationAllowed(tx, row, prepared.file);
await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug },...(prepared.additionalPageKeys??[])]);
- const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
await authorizePageVisibility(tx, row.authority, row.slug);
if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page was deleted or recreated.');
await assertUnboundPublication(tx, row, snapshot?.page.source_path);
@@ -310,7 +315,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
await hooks.boundary?.('after_publication', row);
}
prepared.postimage = undefined;
- const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx), requestAttribution(row));
+ const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx, snapshot), requestAttribution(row));
if (!skill) await classifyUnboundPage(tx, row);
if (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
const final = skill ? null : await publicationPostimage(tx, row, prepared);
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 02928c69ce..be518f41d0 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -79,7 +79,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
await member.validate?.(tx);
await setMemberAttribution(tx, requestAttribution(row));
member.postimage = undefined;
- const outcome = await member.apply(tx);
+ const outcome = await member.apply(tx, snapshot);
await classifyUnboundPage(tx, row);
if (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
const final = await publicationPostimage(tx, row, member);
diff --git a/src/core/persistence/prepared-import.ts b/src/core/persistence/prepared-import.ts
index 6e22a470a6..34ca4bc3c9 100644
--- a/src/core/persistence/prepared-import.ts
+++ b/src/core/persistence/prepared-import.ts
@@ -1,4 +1,5 @@
import type { BrainEngine } from '../engine.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
import type { ImportResult, ParsedPage } from '../import-file.ts';
/** Parsing/provider work is complete. apply must run under the coordinator's transaction. */
@@ -11,5 +12,6 @@ export interface PreparedContentImport {
contentHash?: string;
result: ImportResult;
validate(tx: BrainEngine): Promise<void>;
- apply(tx: BrainEngine): Promise<void>;
+ /** `preimage` (#5984): the publisher's guarded read of this page at the observed revision (see PreparedMutation.apply). */
+ apply(tx: BrainEngine, preimage?: PageSnapshot | null): Promise<void>;
}
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 9be43a4e59..e3b5aac082 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -15,7 +15,7 @@ import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
import { sameCanonicalImport } from '../page-state/import-guard.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { sealPageTextProjection } from '../page-state/projections.ts';
-import { pipelined } from '../page-state/transactions.ts';
+import { pipelined, transactionMemo } from '../page-state/transactions.ts';
import { prepareCanonicalProjections } from './canonical-projections.ts';
import { digest, sha256 } from './digest.ts';
import { preserveProtectedTakes } from './protected-takes.ts';
@@ -36,7 +36,7 @@ import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source
import { checkpointRetryCommand, findIncompleteSyncReceipt } from './checkpoint-validation.ts';
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { CHUNKER_VERSION } from '../chunkers/code.ts';
-import { clearGitHold, recordSyncImportProvenance } from './sync-holds.ts';
+import { clearGitHold, countGitHolds, recordSyncImportProvenance } from './sync-holds.ts';
import { VERSION } from '../../version.ts';
/** The options that select a managed sync cursor (its key), recorded so a refusal can print the exact retry. */
@@ -170,7 +170,10 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
'Its intent records an unowned path on something other than a deletion.');
const originPageId = p.unownedDeletion ? null : row.page_id;
const releaseHold = async (tx: BrainEngine, path: string | null = p.path) => {
- if (p.holdObservedAt && path !== null) await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path, observedAt: p.holdObservedAt });
+ if (!p.holdObservedAt || path === null) return;
+ // #5984: a source without holds (one summary read per transaction) has none to clear.
+ if (await transactionMemo(tx, `git-holds:${row.source_id}:${row.source_incarnation}`, () => countGitHolds(tx, row.source_id, row.source_incarnation)) === 0) return;
+ await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path, observedAt: p.holdObservedAt });
};
await assertManagedSyncActive(engine);
if (p.kind !== 'managed_sync_delete' && (!p.processingOptions ||
@@ -305,8 +308,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
`A canonical file now occupies the path of page ${row.slug}, written while ${row.source_id} was unbound; neither copy was overwritten. Rename or remove the file and commit, or copy what you need into the page first.`);
}
if (p.kind === 'managed_sync_delete') return { observedRevision: snapshot?.revision ?? null, noop: !snapshot || snapshot.page.deleted_at != null,
- validate, apply: async tx => {
- if (snapshot && snapshot.page.deleted_at == null) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }
+ validate, apply: async (tx, preimage) => {
+ if (snapshot && snapshot.page.deleted_at == null) { await tx.createVersion(row.slug, preimage ? { ...source, preimage } : source); await tx.softDeletePage(row.slug, source); }
await releaseHold(tx);
return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };
} };
@@ -417,7 +420,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
deferEmbedding: p.processingOptions?.noEmbed,
...(writeback ? { file: { root, path: join(root, p.path), content: serializePageToMarkdown(renderedPage, tags), expectedBeforeHash: p.rawHash } } : {}),
...(mirrorReadOnly ? { databaseOnlyReason: 'mirror_read_only' as const } : {}),
- apply: async tx => {
+ apply: async (tx, preimage) => {
let applied = ready;
if (renamed) {
// The page moves first, keeping its id, inbound links and history and leaving
@@ -432,7 +435,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
await movedImport.validate(tx);
applied = movedImport;
}
- await applied.apply(tx);
+ // A moved page is versioned from its own (rename source) read.
+ await applied.apply(tx, renamed ? undefined : preimage);
// Hash no-ops still repair a missing physical origin under the same guard.
await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
// #5984: the one read of the page after its last page write (the projections
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 542ca25b60..b5bab0f405 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2539,8 +2539,8 @@ export class PGLiteEngine implements BrainEngine {
}
// Versions
- async createVersion(slug: string, opts?: { sourceId?: string }): Promise<PageVersion> {
- return createPageVersion(this, slug, opts?.sourceId ?? 'default');
+ async createVersion(slug: string, opts?: { sourceId?: string; preimage?: PageSnapshot }): Promise<PageVersion> {
+ return createPageVersion(this, slug, opts?.sourceId ?? 'default', opts?.preimage);
}
async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<PageVersion[]> {
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index dba7590796..e02a10d3ed 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2315,8 +2315,8 @@ export class PostgresEngine implements BrainEngine {
}
// Versions
- async createVersion(slug: string, opts?: { sourceId?: string }): Promise<PageVersion> {
- return createPageVersion(this, slug, opts?.sourceId ?? 'default');
+ async createVersion(slug: string, opts?: { sourceId?: string; preimage?: PageSnapshot }): Promise<PageVersion> {
+ return createPageVersion(this, slug, opts?.sourceId ?? 'default', opts?.preimage);
}
async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<PageVersion[]> {
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 441a8aaffb..8774526eed 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -678,9 +678,10 @@
"via": "unsafe"
},
{
- "paramCount": 15,
+ "paramCount": 2,
"unsafeOptions": {
- "prepare": false,
+ "cancelFence": false,
+ "prepare": true,
"simple": false
},
"via": "unsafe"
@@ -759,9 +760,10 @@
"via": "unsafe"
},
{
- "paramCount": 18,
+ "paramCount": 2,
"unsafeOptions": {
- "prepare": false,
+ "cancelFence": false,
+ "prepare": true,
"simple": false
},
"via": "unsafe"
@@ -831,9 +833,10 @@
"via": "unsafe"
},
{
- "paramCount": 17,
+ "paramCount": 2,
"unsafeOptions": {
- "prepare": false,
+ "cancelFence": false,
+ "prepare": true,
"simple": false
},
"via": "unsafe"
@@ -984,9 +987,10 @@
"via": "unsafe"
},
{
- "paramCount": 15,
+ "paramCount": 2,
"unsafeOptions": {
- "prepare": false,
+ "cancelFence": false,
+ "prepare": true,
"simple": false
},
"via": "unsafe"
diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.json
index dd5c34accb..6f1a2f9969 100644
--- a/test/fixtures/goldens/sql-text/chunks.json
+++ b/test/fixtures/goldens/sql-text/chunks.json
@@ -680,23 +680,10 @@
"lane": "tx",
"params": [
"number",
- "number",
- "string",
- "string",
- "string",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
"string"
],
- "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) VALUES ($1, $2, $3, $4, NULL, $5, $6, NULL, NULL, NULL, $7, $8, $9, $10, $11, $12::text[], $13, $14, $15, NULL) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
- "textSha256": "cb77c3aafb2ebc371823d4f981927eb7e47e32b8118bc22a3febae149ada2443"
+ "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
+ "textSha256": "f0dc7197c233b4ee91dd77108bc7f294d449811f43fbadd7927c25e4f7a0ec1f"
},
{
"event": "commit",
@@ -781,26 +768,10 @@
"lane": "tx",
"params": [
"number",
- "number",
- "string",
- "string",
- "string",
- "string",
- "null",
- "string",
- "string",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
"string"
],
- "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) VALUES ($1, $2, $3, $4, $5::vector, $6, $7, now(), md5($8), $9, $10, $11, $12, $13, $14, $15::text[], $16, $17, $18, NULL) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
- "textSha256": "c4d287834de506dd5e55a80647449750e49b1e2a36ad02ef023bfd8b6b7f384d"
+ "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
+ "textSha256": "f0dc7197c233b4ee91dd77108bc7f294d449811f43fbadd7927c25e4f7a0ec1f"
},
{
"event": "commit",
@@ -879,25 +850,10 @@
"lane": "tx",
"params": [
"number",
- "number",
- "string",
- "string",
- "string",
- "string",
- "null",
- "string",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
"string"
],
- "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding_voyage\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) VALUES ($1, $2, $3, $4, $5::vector, $6, $7, now(), md5($8), NULL, $9, $10, $11, $12, $13, $14::text[], $15, $16, $17, NULL) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding_voyage\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding_voyage\" WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.\"embedding_voyage\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding_voyage\" ELSE content_chunks.\"embedding_voyage\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding_voyage\" IS NULL THEN NULL WHEN content_chunks.\"embedding_voyage\" IS NULL AND EXCLUDED.\"embedding_voyage\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
- "textSha256": "28390a3323a9d15c4ec1cdac8e9ba4f4295a85ed3aac10260f9026ee983b7196"
+ "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding_voyage\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding_voyage\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding_voyage\" WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.\"embedding_voyage\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding_voyage\" ELSE content_chunks.\"embedding_voyage\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding_voyage\" IS NULL THEN NULL WHEN content_chunks.\"embedding_voyage\" IS NULL AND EXCLUDED.\"embedding_voyage\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
+ "textSha256": "5bda6091d4af919745901fa63a0aa3cd2b37ab0f09c985e31daee1220efe102d"
},
{
"event": "commit",
@@ -1065,23 +1021,10 @@
"lane": "tx",
"params": [
"number",
- "number",
- "string",
- "string",
- "string",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
- "null",
"string"
],
- "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) VALUES ($1, $2, $3, $4, NULL, $5, $6, NULL, NULL, NULL, $7, $8, $9, $10, $11, $12::text[], $13, $14, $15, NULL) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
- "textSha256": "cb77c3aafb2ebc371823d4f981927eb7e47e32b8118bc22a3febae149ada2443"
+ "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
+ "textSha256": "f0dc7197c233b4ee91dd77108bc7f294d449811f43fbadd7927c25e4f7a0ec1f"
},
{
"event": "commit",
diff --git a/test/import-file.test.ts b/test/import-file.test.ts
index 0562fa2477..ad43552dcd 100644
--- a/test/import-file.test.ts
+++ b/test/import-file.test.ts
@@ -530,9 +530,12 @@ describe('importFile — CJK wave (v0.32.7)', () => {
const calls = (engine as any)._calls;
const putCall = calls.find((c: any) => c.method === 'putPage');
expect(putCall.args[1].chunker_version).toBeUndefined();
+ // #5984: a non-empty replacement is sealed by its own upsert (after the insert); an empty one by one stamp.
const stamps = calls.filter((c: any) => c.method === 'executeRaw' && isVersionStamp(c.args[0]));
- expect(stamps).toHaveLength(1);
- expect(stamps[0].args[1]).toEqual([MARKDOWN_CHUNKER_VERSION, 'default', slug]);
+ const sealedUpserts = calls.filter((c: any) => c.method === 'upsertChunks' && c.args[2]?.sealChunkerVersion !== undefined);
+ expect(stamps.length + sealedUpserts.length).toBe(1);
+ if (stamps.length) expect(stamps[0].args[1]).toEqual([MARKDOWN_CHUNKER_VERSION, 'default', slug]);
+ else expect(sealedUpserts[0].args).toMatchObject([slug, expect.any(Array), { sourceId: 'default', sealChunkerVersion: MARKDOWN_CHUNKER_VERSION }]);
}
test('REGRESSION: pure-CJK filename with NO frontmatter slug imports cleanly as CJK slug', async () => {
diff --git a/test/managed-sync-group-completion.test.ts b/test/managed-sync-group-completion.test.ts
new file mode 100644
index 0000000000..2ea846a43b
--- /dev/null
+++ b/test/managed-sync-group-completion.test.ts
@@ -0,0 +1,189 @@
+/**
+ * #5984 round-trip diet: set-based group completion (one statement for every
+ * member, short RETURNING rolls back to the single path with each member's own
+ * code), the counter-hold bound, and the one preimage + one postimage read a
+ * managed-sync page publication makes on create, update and delete. Runs on
+ * PGLite and, with DATABASE_URL, on Postgres.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { completeGroup } from '../src/core/persistence/group-publish.ts';
+import { completeWrite, LOCK_COUNTERS_SQL } from '../src/core/persistence/journal.ts';
+import { principalKey, requestPrincipal, type WriteRequest } from '../src/core/persistence/model.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-group-completion-'));
+const engines: BrainEngine[] = [];
+const sources: string[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+const commit = (root: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes'); };
+const note = (i: number, body = `A durable observation number ${i}.`) => `---\ntitle: Note ${i}\n---\n${body}\n`;
+async function fixture(engine: BrainEngine, count: number) {
+ const id = `grp-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (let i = 0; i < count; i++) writeFileSync(join(root, 'notes', `n${i}.md`), note(i));
+ commit(root);
+ 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,\'{}\')', [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+const sync = (engine: BrainEngine, sourceId: string) => performSync(engine, { sourceId, noPull: true, noEmbed: true, noExtract: true, drain: true });
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ await engine.disconnect();
+ }
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+/** Committed page requests of a synced source, put back into the running state with fresh claims and their counter reservations restored. */
+async function reopen(engine: BrainEngine, sourceId: string): Promise<WriteRequest[]> {
+ const rows = await engine.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',execution_token=gen_random_uuid(),completed_at=NULL,published_at=NULL,
+ claim_expires_at=now()+interval '5 minutes' WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' RETURNING *`, [sourceId]);
+ rows.sort((a, b) => Number(a.sequence) - Number(b.sequence));
+ const bytes = rows.reduce((sum, row) => sum + Number(row.intent_bytes), 0);
+ await engine.executeRaw('UPDATE persistence_counters SET outstanding_count=outstanding_count+$2,intent_bytes=intent_bytes+$3 WHERE key=ANY($1::text[])',
+ [['brain', principalKey(requestPrincipal(rows[0]!))], rows.length, bytes]);
+ return rows;
+}
+async function counters(engine: BrainEngine, row: WriteRequest): Promise<Record<string, string>> {
+ const rows = await engine.executeRaw<{ key: string; outstanding_count: string; intent_bytes: string }>(
+ 'SELECT key,outstanding_count::text,intent_bytes::text FROM persistence_counters WHERE key=ANY($1::text[]) ORDER BY key', [['brain', principalKey(requestPrincipal(row))]]);
+ return Object.fromEntries(rows.map(r => [r.key, `${r.outstanding_count}/${r.intent_bytes}`]));
+}
+const states = async (engine: BrainEngine, rows: WriteRequest[]) => (await engine.executeRaw<{ id: string; state: string; execution_token: string | null }>(
+ 'SELECT id,state,execution_token FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence', [rows.map(row => row.id)]));
+const outcomes = (rows: WriteRequest[]) => rows.map(row => ({ status: 'created', slug: row.slug, source_id: row.source_id }));
+
+test('set-based completion commits every member in one statement and releases their counter reservations', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, 4);
+ await sync(engine, f.id);
+ await disposePersistenceConsumer(engine);
+ const settled = await counters(engine, (await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' LIMIT 1", [f.id]))[0]!);
+ const rows = await reopen(engine, f.id);
+ expect(rows).toHaveLength(4);
+ const done = await engine.transaction(tx => completeGroup(tx, rows, outcomes(rows)));
+ expect(done.map(row => [row.id, row.state])).toEqual(rows.map(row => [row.id, 'committed']));
+ expect(done.every(row => { const r = row as unknown as Record<string, unknown>; return r.published_at != null && r.consumer_version != null && row.outcome?.slug === row.slug; })).toBe(true);
+ expect((done[0] as unknown as Record<string, unknown>).principal_key).toBeUndefined();
+ expect(await counters(engine, rows[0]!)).toEqual(settled);
+ }
+}), 300_000);
+
+for (const fault of ['claim lost', 'already terminal', 'terminal reservation exceeded'] as const) {
+ test(`a short RETURNING (${fault}) rolls the group back and the single path gives each member its own outcome`, async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, 3);
+ await sync(engine, f.id);
+ await disposePersistenceConsumer(engine);
+ const rows = await reopen(engine, f.id);
+ const before = await counters(engine, rows[0]!);
+ const victim = rows[1]!;
+ if (fault === 'claim lost') await engine.executeRaw('UPDATE persistence_requests SET execution_token=gen_random_uuid() WHERE id=$1::uuid', [victim.id]);
+ if (fault === 'already terminal') await engine.executeRaw("UPDATE persistence_requests SET state='failed',execution_token=NULL,error_code='storage_error' WHERE id=$1::uuid", [victim.id]);
+ if (fault === 'terminal reservation exceeded') await engine.executeRaw('UPDATE persistence_requests SET terminal_reservation=1 WHERE id=$1::uuid', [victim.id]);
+ const tampered = await states(engine, rows);
+ await expect(engine.transaction(tx => completeGroup(tx, rows, outcomes(rows)))).rejects.toMatchObject({ code: 'write_claim_lost' });
+ // Nothing committed and no counter moved: the whole group rolled back.
+ expect(await states(engine, rows)).toEqual(tampered);
+ expect(await counters(engine, rows[0]!)).toEqual(before);
+ // The single path: the first member commits, the faulted member keeps completeWrite's exact outcome.
+ expect((await engine.transaction(tx => completeWrite(tx, rows[0]!, 'committed', outcomes(rows)[0]!))).state).toBe('committed');
+ const single = engine.transaction(tx => completeWrite(tx, victim, 'committed', outcomes(rows)[1]!));
+ if (fault === 'claim lost') await expect(single).rejects.toMatchObject({ code: 'write_claim_lost' });
+ if (fault === 'already terminal') expect(await single).toMatchObject({ state: 'failed', error_code: 'storage_error' });
+ if (fault === 'terminal reservation exceeded') await expect(single).rejects.toMatchObject({ code: 'queue_capacity' });
+ }
+ }), 300_000);
+}
+
+test('the counters are held for the lock and one completion statement, pipelined on Postgres', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, 5);
+ await sync(engine, f.id);
+ await disposePersistenceConsumer(engine);
+ const rows = await reopen(engine, f.id);
+ const issued: Array<{ sql: string; earlierPending: boolean }> = [];
+ let pending = 0;
+ await engine.transaction(async tx => {
+ const recording = new Proxy(tx, { get(target, key, receiver) {
+ if (key !== 'executeRaw') return Reflect.get(target, key, receiver);
+ return (sql: string, params?: unknown[]) => {
+ issued.push({ sql, earlierPending: pending > 0 });
+ pending++;
+ return target.executeRaw(sql, params).finally(() => { pending--; });
+ };
+ } });
+ await completeGroup(recording, rows, outcomes(rows));
+ });
+ const lock = issued.findIndex(s => s.sql === LOCK_COUNTERS_SQL);
+ expect(lock).toBe(2);
+ // Under the counter lock: the lock itself and one UPDATE, whatever the group size; COMMIT follows.
+ expect(issued.slice(lock)).toHaveLength(2);
+ expect(issued[lock + 1]!.sql).toContain('UPDATE persistence_requests r SET');
+ if (engine.kind === 'postgres') expect(issued[lock + 1]!.earlierPending).toBe(true);
+ }
+}), 300_000);
+
+test('a page publication reads the page once before and once after apply, on create, update and delete', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const reads = new Map<string, number>();
+ const original = engine.readPageSnapshot;
+ const counted = function (this: BrainEngine & { _pageTransaction?: boolean }, ...args: Parameters<BrainEngine['readPageSnapshot']>) {
+ if (this._pageTransaction && args[1]?.sourceId?.startsWith('grp-') && args[0].startsWith('notes/')) reads.set(args[0], (reads.get(args[0]) ?? 0) + 1);
+ return original.apply(this, args);
+ };
+ (engine as { readPageSnapshot: unknown }).readPageSnapshot = counted;
+ try {
+ const f = await fixture(engine, 3);
+ await sync(engine, f.id);
+ expect(Object.fromEntries(reads)).toEqual({ 'notes/n0': 2, 'notes/n1': 2, 'notes/n2': 2 });
+ reads.clear();
+ writeFileSync(join(f.root, 'notes', 'n1.md'), note(1, 'An updated observation.'));
+ rmSync(join(f.root, 'notes', 'n2.md'));
+ commit(f.root);
+ await sync(engine, f.id);
+ expect(Object.fromEntries(reads)).toEqual({ 'notes/n1': 2, 'notes/n2': 2 });
+ const receipts = await engine.executeRaw<{ slug: string; kind: string; revision: string | null; status: string }>(
+ `SELECT slug,intent->>'kind' AS kind,outcome->>'revision' AS revision,outcome->>'status' AS status FROM persistence_requests
+ WHERE source_id=$1 AND state='committed' AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete') ORDER BY sequence`, [f.id]);
+ const pages = new Map((await engine.executeRaw<{ slug: string; revision: string; deleted: boolean }>(
+ 'SELECT slug,knowledge_revision::text AS revision,deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1', [f.id])).map(p => [p.slug, p]));
+ const last = new Map(receipts.map(r => [`${r.slug}:${r.kind}`, r]));
+ // Each receipt carries the revision the page holds after its publication.
+ expect(last.get('notes/n0:managed_sync_import')).toMatchObject({ status: 'created', revision: pages.get('notes/n0')!.revision });
+ expect(last.get('notes/n1:managed_sync_import')).toMatchObject({ status: 'updated', revision: pages.get('notes/n1')!.revision });
+ expect(last.get('notes/n2:managed_sync_delete')).toMatchObject({ status: 'soft_deleted', revision: pages.get('notes/n2')!.revision });
+ expect(pages.get('notes/n2')!.deleted).toBe(true);
+ expect((await engine.getPage('notes/n1', { sourceId: f.id }))?.compiled_truth).toContain('An updated observation.');
+ // The text projection is sealed at the published revision.
+ const [sealed] = await engine.executeRaw<{ ok: boolean }>("SELECT text_projection_revision=knowledge_revision AS ok FROM pages WHERE source_id=$1 AND slug='notes/n1'", [f.id]);
+ expect(sealed!.ok).toBe(true);
+ } finally {
+ (engine as { readPageSnapshot: unknown }).readPageSnapshot = original;
+ }
+ }
+}), 300_000);