Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cycle): adopt a same-page atom whose title changed only in case (#5031)
time-attack600848553d5f
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 0b04d15e4c..401ecc279d 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -31,7 +31,7 @@ src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (src/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #4618: seat sidecar call before the segment spool (helper recordOpenclawSeat)src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle.ts runCycle 1271 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch; +10 GBRA-49: edge_contradictions phase dispatch block (adapter in cycle/edge-contradictions.ts)-src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 789 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts)+src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 790 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker); +2 fix wave 9 lane P (#5041): opt-in write-through hook creation and its per-item call (derived-write-through.ts); +1 #5031: per-run page-atom title memo for the case-insensitive adoption fallbacksrc/core/cycle/extract-atoms.ts runPhaseExtractAtoms>withBudgetTracker(#1) 316 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +11 #5809/#5832: per-item and pre-commit abort checks, chat-call signal, abortable pacing, catch-side stopsrc/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 0a87987ead..cccf343bcc 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -15,7 +15,7 @@ src/core/ai/gateway.ts 4423 ratchet +7 fix wave 5 (#5137): provider-key redactorsrc/commands/sync.ts 512 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event fieldsrc/core/cycle.ts 3254 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); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts)src/core/cycle/synthesize.ts 3195 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); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition-src/core/cycle/extract-atoms.ts 1621 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +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); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts)+src/core/cycle/extract-atoms.ts 1638 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +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); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run)src/core/engine.ts 2707 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); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_isosrc/core/import-file.ts 2179 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; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied)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 nullablediff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex d6779cc8ac..6812210b9f 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -675,6 +675,7 @@ export async function runPhaseExtractAtoms(const managed = await managedAtomSession(engine, sourceId, opts._managedRetry, opts.attempt?.writeWait);const atomFiles = await derivedWriteThrough(engine, 'extract_atoms', sourceId, { managed: managed !== null, dryRun: opts.dryRun ?? false });const writeRequests: WriteReceipt[] = [];+ const pageAtomTitles = new Map<string, Map<string, string[]>>();// 1a. Get transcripts (test seam OR production discovery).// v0.41.2.1: config loader switched to loadConfigWithEngine() so the@@ -1180,7 +1181,7 @@ export async function runPhaseExtractAtoms(const srcRef = item.kind === 'transcript' ? item.filePath : item.slug;const slug =item.kind === 'page'- ? await resolvePageAtomSlug(engine, atom.title, item.slug, sourceId, undatedDate)+ ? await resolvePageAtomSlug(engine, atom.title, item.slug, sourceId, undatedDate, pageAtomTitles): atomSlug(atom.title, srcRef, undefined, undatedDate);const originFrontmatter =item.kind === 'transcript'@@ -1557,7 +1558,12 @@ function atomSlug(title: string, srcRef: string, sourcePageSlug?: string, undate* 3. A legacy-slug atom bound to a DIFFERENT source locator (the #4733* collision class) is left untouched; the new-shape slug lands beside* it — that separation is the whole point of the locator fold.- * Both reads are scoped to the write's source (unscoped-check/scoped-write).+ * 4. Neither exact slug exists: a case-only title change would mint a+ * duplicate (#5030). The first miss for a source page loads that page's+ * live bound atoms once per run into `pageAtomTitles`; exactly one match+ * on the JS-lowercased title (SQL LOWER() differs for some non-ASCII+ * titles) is adopted, while zero or several mint the new-shape slug.+ * Every read is scoped to the write's source (unscoped-check/scoped-write).*/async function resolvePageAtomSlug(engine: BrainEngine,@@ -1565,6 +1571,7 @@ async function resolvePageAtomSlug(sourcePageSlug: string,sourceId: string,undatedDate: string,+ pageAtomTitles: Map<string, Map<string, string[]>>,): Promise<string> {const slug = atomSlug(title, sourcePageSlug, sourcePageSlug, undatedDate);if (await engine.getPage(slug, { sourceId })) return slug;@@ -1573,7 +1580,17 @@ async function resolvePageAtomSlug(if (legacy && legacy.type === 'atom' && isCompatibleAtomBinding(legacy.frontmatter, sourcePageSlug)) {return legacySlug;}- return slug;+ let titles = pageAtomTitles.get(sourcePageSlug);+ if (!titles) {+ titles = new Map();+ const rows = await engine.executeRaw<{ slug: string; title: string }>(+ `SELECT slug, title FROM pages WHERE type = 'atom' AND deleted_at IS NULL AND source_id = $1 AND frontmatter->>'source_slug' = $2`,+ [sourceId, sourcePageSlug]);+ for (const row of rows) titles.set(row.title.toLowerCase(), [...(titles.get(row.title.toLowerCase()) ?? []), row.slug]);+ pageAtomTitles.set(sourcePageSlug, titles);+ }+ const variants = titles.get(title.toLowerCase()) ?? [];+ return variants.length === 1 ? variants[0]! : slug;}/**diff --git a/test/extract-atoms-provenance-links.test.ts b/test/extract-atoms-provenance-links.test.tsindex 6ff89d56dc..02639665d8 100644--- a/test/extract-atoms-provenance-links.test.ts+++ b/test/extract-atoms-provenance-links.test.ts@@ -18,6 +18,8 @@* emitting the same atom title can't alias one slug, plus the fail-closed* binding guard and the upgrade path for pre-#4733 title-only-hash rows.*+ * Also pins the #5030 same-page case-insensitive adoption fallback.+ ** PGLite round-trip with a stubbed chat gateway (no model calls).*/@@ -25,6 +27,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { createHash } from 'crypto';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from './helpers/extract-atoms-page-fixtures.ts';+import { slugifySegment } from '../src/core/sync.ts';import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';let engine: PGLiteEngine;@@ -638,3 +641,411 @@ describe('provenance edges are banked BEFORE the completion flip (#4733)', () =>}});});++/**+ * #5030: case-only title drift used to mint duplicate atoms. Two extractions+ * of the same claim from the same source page whose titles differed only in+ * letter case hashed to different identity slugs. resolvePageAtomSlug now+ * falls back, after both exact-slug probes miss, to this page's live bound+ * atoms (loaded once per page per run), matched with JS `.toLowerCase()`, and+ * adopts exactly one match; zero or several mint the new-shape slug. Atom+ * slug hashing is unchanged.+ */+function expectedAtomStem(title: string): string {+ // Mirrors atomSlugStem exactly (private to extract-atoms.ts): slugify,+ // truncate to 60 chars, re-strip a trailing dash the truncation can expose.+ return slugifySegment(title).slice(0, 60).replace(/-+$/g, '') || 'untitled';+}++describe('case-insensitive same-page atom adoption (#5030)', () => {+ test('core regression: re-extracting the same claim with a different-case title leaves exactly ONE live atom', async () => {+ const sourceSlug = 'writings/2026-09-05-case-regression-page';+ await engine.putPage(sourceSlug, {+ type: 'note', title: 'Case regression source',+ compiled_truth: 'A claim whose title case may drift between extractions.', timeline: '',+ });++ const first = await runPhaseExtractAtoms(engine, {+ _transcripts: [],+ _pages: [{+ slug: sourceSlug,+ content: 'A claim whose title case may drift between extractions.',+ contentHash: 'case000000000001',+ }],+ _chat: stubChat('12-month price momentum predicts next-month returns'),+ });+ expect(first.status).toBe('ok');+ expect(first.details?.atoms_extracted).toBe(1);++ // Body edit (new content hash) but the same claim, re-titled with+ // different letter case only.+ const second = await runPhaseExtractAtoms(engine, {+ _transcripts: [],+ _pages: [{+ slug: sourceSlug,+ content: 'A claim whose title case may drift between extractions, reworded.',+ contentHash: 'case000000000002',+ }],+ _chat: stubChat('12-Month Price Momentum Predicts Next-Month Returns'),+ });+ expect(second.status).toBe('ok');+ expect(second.details?.atoms_extracted).toBe(1);++ const atoms = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages+ WHERE type = 'atom' AND frontmatter->>'source_slug' = $1 AND deleted_at IS NULL`,+ [sourceSlug],+ );+ expect(atoms[0]!.n).toBe(1);+ const links = (await engine.getLinks(sourceSlug)).filter(l => l.link_source === 'atom-provenance');+ expect(links).toHaveLength(1);+ });++ test('an existing same-page atom is adopted in place when the title changes only in case', async () => {+ const seedTitle = 'Existing Different Case Title';+ const sourceSlug = 'writings/2026-09-03-existing-different-case';+ const oldHash = createHash('sha256').update(`${sourceSlug}\0${seedTitle}`).digest('hex').slice(0, 8);+ const oldSlug = `atoms/2026-09-03/${expectedAtomStem(seedTitle)}-${oldHash}`;+ await engine.putPage(oldSlug, {+ type: 'atom', title: seedTitle,+ compiled_truth: 'Existing atom body.', timeline: '',+ frontmatter: { source_slug: sourceSlug, source_hash: 'cccc666677778888', atom_type: 'insight' },+ });+ await engine.putPage(sourceSlug, {+ type: 'note', title: 'Existing different case source', compiled_truth: 'Edited body, take two.', timeline: '',+ });++ const differentCaseTitle = 'EXISTING DIFFERENT CASE TITLE';+ const result = await runPhaseExtractAtoms(engine, {+ _transcripts: [],+ _pages: [{ slug: sourceSlug, content: 'Edited body, take two.', contentHash: 'dddd222233334444' }],+ _chat: stubChat(differentCaseTitle),+ });+ expect(result.status).toBe('ok');+ expect(result.details?.failures).toEqual([]);+ expect(result.details?.atoms_extracted).toBe(1);++ const seeded = await engine.getPage(oldSlug, { sourceId: 'default' });+ expect(seeded).not.toBeNull();+ expect(seeded!.frontmatter.source_slug).toBe(sourceSlug);+ expect(seeded!.frontmatter.source_hash).toBe('dddd222233334444');++ const atoms = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages+ WHERE type = 'atom' AND frontmatter->>'source_slug' = $1 AND deleted_at IS NULL`,+ [sourceSlug],+ );+ expect(atoms[0]!.n).toBe(1);+ const links = (await engine.getLinks(sourceSlug)).filter(l => l.link_source === 'atom-provenance');+ expect(links).toHaveLength(1);+ expect(links[0]!.to_slug).toBe(oldSlug);+ });++ test('ambiguous: two or more pre-existing case-variant candidates are NOT guessed between — a fresh slug is minted instead', async () => {+ const sourceSlug = 'writings/2026-09-02-ambiguous-case-page';+ await engine.putPage(sourceSlug, {+ type: 'note', title: 'Ambiguous case source',+ compiled_truth: 'A claim with an ambiguous title history.', timeline: '',+ });++ // Two case-variant atoms already bound to this page. Neither sits at the+ // third title's exact address, so only the fallback can see them.+ const titleA = 'Ambiguous Duplicate Title';+ const titleB = 'AMBIGUOUS DUPLICATE TITLE';+ const hashA = createHash('sha256').update(`${sourceSlug}\0${titleA}`).digest('hex').slice(0, 8);+ const hashB = createHash('sha256').update(`${sourceSlug}\0${titleB}`).digest('hex').slice(0, 8);+ const slugA = `atoms/2026-09-02/${expectedAtomStem(titleA)}-${hashA}`;+ const slugB = `atoms/2026-09-02/${expectedAtomStem(titleB)}-${hashB}`;+ expect(slugA).not.toBe(slugB); // sanity: two genuinely distinct pre-existing rows++ await engine.putPage(slugA, {+ type: 'atom', title: titleA, compiled_truth: 'Duplicate atom A.', timeline: '',+ frontmatter: { source_slug: sourceSlug, source_hash: 'eeee111122223333', atom_type: 'insight' },+ });+ await engine.putPage(slugB, {+ type: 'atom', title: titleB, compiled_truth: 'Duplicate atom B.', timeline: '',+ frontmatter: { source_slug: sourceSlug, source_hash: 'ffff444455556666', atom_type: 'insight' },+ });++ // Re-extraction returns yet a THIRD case variant of the same title. Must+ // not throw, and must not silently adopt either pre-existing duplicate.+ const thirdCaseTitle = 'ambiguous Duplicate title';+ const result = await runPhaseExtractAtoms(engine, {+ _transcripts: [],+ _pages: [{ slug: sourceSlug, content: 'A claim with an ambiguous title history.', contentHash: 'gggg777788889999' }],+ _chat: stubChat(thirdCaseTitle),+ });+ expect(result.status).toBe('ok');+ expect(result.details?.failures).toEqual([]);+ expect(result.details?.atoms_extracted).toBe(1);++ // Neither pre-existing duplicate was adopted/rewritten. (The completed+ // extraction's stale-atom cleanup may soft-delete them, so read the rows+ // directly rather than via getPage, which hides soft-deleted pages.)+ const dupRows = await engine.executeRaw<{ slug: string; source_hash: string }>(+ `SELECT slug, frontmatter->>'source_hash' AS source_hash FROM pages+ WHERE slug = ANY($1::text[]) AND source_id = 'default'`,+ [[slugA, slugB]],+ );+ const hashBySlug = new Map(dupRows.map((r) => [r.slug, r.source_hash]));+ expect(hashBySlug.get(slugA)).toBe('eeee111122223333');+ expect(hashBySlug.get(slugB)).toBe('ffff444455556666');++ // A third, FRESH slug was minted instead of guessing between them.+ const newHash = createHash('sha256')+ .update(`${sourceSlug}\0${thirdCaseTitle}`)+ .digest('hex').slice(0, 8);+ const freshSlug = `atoms/2026-09-02/${expectedAtomStem(thirdCaseTitle)}-${newHash}`;+ expect(freshSlug).not.toBe(slugA);+ expect(freshSlug).not.toBe(slugB);+ const fresh = await engine.getPage(freshSlug, { sourceId: 'default' });+ expect(fresh).not.toBeNull();+ expect(fresh!.frontmatter.source_hash).toBe('gggg777788889999');++ const atoms = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages+ WHERE type = 'atom' AND frontmatter->>'source_slug' = $1 AND deleted_at IS NULL`,+ [sourceSlug],+ );+ // Only the freshly minted atom stays live: the two stale pre-existing+ // duplicates are retired by the completed extraction's stale-atom cleanup.+ expect(atoms[0]!.n).toBe(1);+ });++ test('two titles sharing the same 60-char truncated stem stay on DISTINCT slugs (the full title is hashed, never the truncated stem)', async () => {+ const sourceSlug = 'writings/2026-09-01-shared-stem-page';+ await engine.putPage(sourceSlug, {+ type: 'note', title: 'Shared stem source',+ compiled_truth: 'A page yielding two claims with a shared title prefix.', timeline: '',+ });++ const sharedPrefix = Array(6).fill('sharedstemword').join(' '); // well over 60 chars once slugified+ const titleAlpha = `${sharedPrefix} variant Alpha unique tail`;+ const titleBeta = `${sharedPrefix} variant Beta unique tail`;+ // Sanity: this test is only meaningful if the two titles really do+ // collapse to the identical 60-char stem — confirm that up front.+ expect(expectedAtomStem(titleAlpha)).toBe(expectedAtomStem(titleBeta));++ const twoAtomsChat = async (): Promise<ChatResult> => ({+ text: JSON.stringify([+ { title: titleAlpha, atom_type: 'insight', body: 'Alpha claim body.' },+ { title: titleBeta, atom_type: 'insight', body: 'Beta claim body.' },+ ]),+ blocks: [{ type: 'text', text: '' }],+ stopReason: 'end',+ usage: { input_tokens: 500, output_tokens: 200, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5',+ providerId: 'anthropic',+ });++ const result = await runPhaseExtractAtoms(engine, {+ _transcripts: [],+ _pages: [{+ slug: sourceSlug,+ content: 'A page yielding two claims with a shared title prefix.',+ contentHash: 'stem000000000001',+ }],+ _chat: twoAtomsChat,+ });+ expect(result.status).toBe('ok');+ expect(result.details?.atoms_extracted).toBe(2);++ const hashAlpha = createHash('sha256').update(`${sourceSlug}\0${titleAlpha}`).digest('hex').slice(0, 8);+ const hashBeta = createHash('sha256').update(`${sourceSlug}\0${titleBeta}`).digest('hex').slice(0, 8);+ expect(hashAlpha).not.toBe(hashBeta);++ const stem = expectedAtomStem(titleAlpha);+ const slugAlpha = `atoms/2026-09-01/${stem}-${hashAlpha}`;+ const slugBeta = `atoms/2026-09-01/${stem}-${hashBeta}`;+ const atomAlpha = await engine.getPage(slugAlpha, { sourceId: 'default' });+ const atomBeta = await engine.getPage(slugBeta, { sourceId: 'default' });+ expect(atomAlpha).not.toBeNull();+ expect(atomBeta).not.toBeNull();+ expect(atomAlpha!.compiled_truth).toContain('Alpha claim body');+ expect(atomBeta!.compiled_truth).toContain('Beta claim body');++ const atoms = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages+ WHERE type = 'atom' AND frontmatter->>'source_slug' = $1 AND deleted_at IS NULL`,+ [sourceSlug],+ );+ expect(atoms[0]!.n).toBe(2);+ });++ test('an UNBOUND (pre-binding-era) atom with a matching case-variant title is NOT adopted — the fallback is scoped to same-page-bound atoms only', async () => {+ const sourceSlug = 'writings/2026-08-31-unbound-title-collision-page';+ const title = 'Unbound Title Collision Claim';+ // An unbound atom (no source_slug, no source_path at all — the+ // pre-binding-era shape `isCompatibleAtomBinding` treats as compatible+ // for the LEGACY-SLUG path). Its slug is unrelated to this page/run —+ // it is NOT at either the new-shape or legacy-shape address the+ // extraction would compute, so it can only be found (if at all) by the+ // case-insensitive title-search fallback under test.+ const unboundSlug = 'atoms/2026-01-01/some-unrelated-pre-binding-atom-11112222';+ await engine.putPage(unboundSlug, {+ type: 'atom', title,+ compiled_truth: 'An unbound atom that happens to share a title, case-insensitively.', timeline: '',+ frontmatter: { source_hash: 'aaaa111122223333', atom_type: 'insight' }, // no source_slug/source_path+ });+ await engine.putPage(sourceSlug, {+ type: 'note', title: 'Unbound collision source', compiled_truth: 'Body.', timeline: '',+ });++ const result = await runPhaseExtractAtoms(engine, {+ _transcripts: [],+ _pages: [{ slug: sourceSlug, content: 'Body.', contentHash: 'bbbb555566667777' }],+ _chat: stubChat(title.toUpperCase()), // case-variant of the unbound atom's title+ });+ expect(result.status).toBe('ok');+ expect(result.details?.failures).toEqual([]);+ expect(result.details?.atoms_extracted).toBe(1);++ // The unbound atom must be untouched — not adopted, binding not changed.+ const unbound = await engine.getPage(unboundSlug, { sourceId: 'default' });+ expect(unbound).not.toBeNull();+ expect(unbound!.frontmatter.source_hash).toBe('aaaa111122223333');+ expect(unbound!.frontmatter.source_slug ?? null).toBeNull();++ // A FRESH atom was minted for this page instead of claiming the unbound one.+ const atoms = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages+ WHERE type = 'atom' AND frontmatter->>'source_slug' = $1 AND deleted_at IS NULL`,+ [sourceSlug],+ );+ expect(atoms[0]!.n).toBe(1);+ });++ test('non-ASCII case variance (Greek): adoption is matched with JavaScript `.toLowerCase()`, not SQL `LOWER()`, which disagree for some titles', async () => {+ // PostgreSQL/PGLite's LOWER('ΟΣ') is 'οσ'; JavaScript's 'ΟΣ'.toLowerCase()+ // is 'ος' (a different final sigma form). If the case-insensitive+ // fallback's title comparison were pushed into SQL, this exact adoption+ // would silently miss and mint a duplicate — the defect this test guards.+ const seedTitle = 'ΟΣ';+ const reExtractedTitle = 'ος';+ expect(seedTitle.toLowerCase()).toBe(reExtractedTitle); // sanity: JS agrees they're the same identity+ const sourceSlug = 'writings/2026-08-30-greek-case-page';+ const oldHash = createHash('sha256').update(`${sourceSlug}\0${seedTitle}`).digest('hex').slice(0, 8);+ const oldSlug = `atoms/2026-08-30/${expectedAtomStem(seedTitle)}-${oldHash}`;+ await engine.putPage(oldSlug, {+ type: 'atom', title: seedTitle,+ compiled_truth: 'Existing atom body with a Greek title.', timeline: '',+ frontmatter: { source_slug: sourceSlug, source_hash: 'cccc888899990000', atom_type: 'insight' },+ });+ await engine.putPage(sourceSlug, {+ type: 'note', title: 'Greek case source', compiled_truth: 'Edited body.', timeline: '',+ });++ const result = await runPhaseExtractAtoms(engine, {+ _transcripts: [],+ _pages: [{ slug: sourceSlug, content: 'Edited body.', contentHash: 'dddd333344445555' }],+ _chat: stubChat(reExtractedTitle),+ });+ expect(result.status).toBe('ok');+ expect(result.details?.failures).toEqual([]);+ expect(result.details?.atoms_extracted).toBe(1);++ const seeded = await engine.getPage(oldSlug, { sourceId: 'default' });+ expect(seeded).not.toBeNull();+ expect(seeded!.frontmatter.source_hash).toBe('dddd333344445555'); // adopted, not orphaned++ const atoms = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages+ WHERE type = 'atom' AND frontmatter->>'source_slug' = $1 AND deleted_at IS NULL`,+ [sourceSlug],+ );+ expect(atoms[0]!.n).toBe(1); // no duplicate minted under the Unicode-different SQL LOWER() form+ });+ test('the page-atom scan runs once per source page per run, however many atoms miss', async () => {+ const pages = ['writings/2026-08-29-scan-count-a', 'writings/2026-08-29-scan-count-b'];+ for (const slug of pages) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Three fresh claims.', timeline: '' });+ }+ let scans = 0;+ const counting = new Proxy(engine, {+ get(target, key) {+ if (key === 'executeRaw') return (sql: string, params?: unknown[]) => {+ if (/SELECT slug, title FROM pages WHERE type = 'atom'/.test(sql)) scans++;+ return target.executeRaw(sql, params);+ };+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ const threeAtoms = async (): Promise<ChatResult> => ({+ text: JSON.stringify(['First fresh claim', 'Second fresh claim', 'Third fresh claim']+ .map(title => ({ title, atom_type: 'insight', body: `${title} body.` }))),+ blocks: [{ type: 'text', text: '' }],+ stopReason: 'end',+ usage: { input_tokens: 500, output_tokens: 200, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5',+ providerId: 'anthropic',+ });+ const result = await runPhaseExtractAtoms(counting, {+ _transcripts: [],+ _pages: pages.map((slug, i) => ({ slug, content: 'Three fresh claims.', contentHash: `scan00000000000${i}` })),+ _chat: threeAtoms,+ });+ expect(result.status).toBe('ok');+ expect(result.details?.atoms_extracted).toBe(6);+ expect(scans).toBe(2);+ });++ test('a case-variant title bound to a DIFFERENT page is never adopted', async () => {+ const otherPage = 'writings/2026-08-28-other-origin-page';+ const sourceSlug = 'writings/2026-08-28-this-origin-page';+ const title = 'Other Origin Claim';+ const otherSlug = 'atoms/2026-08-28/other-origin-claim-0a0b0c0d';+ await engine.putPage(otherSlug, {+ type: 'atom', title, compiled_truth: 'Atom from another page.', timeline: '',+ frontmatter: { source_slug: otherPage, source_hash: 'abab000011112222', atom_type: 'insight' },+ });+ await engine.putPage(sourceSlug, { type: 'note', title: 'This origin', compiled_truth: 'Body.', timeline: '' });++ const result = await runPhaseExtractAtoms(engine, {+ _transcripts: [],+ _pages: [{ slug: sourceSlug, content: 'Body.', contentHash: 'cdcd333344445555' }],+ _chat: stubChat(title.toUpperCase()),+ });+ expect(result.status).toBe('ok');+ expect(result.details?.atoms_extracted).toBe(1);++ const other = await engine.getPage(otherSlug, { sourceId: 'default' });+ expect(other!.frontmatter.source_slug).toBe(otherPage);+ expect(other!.frontmatter.source_hash).toBe('abab000011112222');+ const mine = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE type = 'atom' AND frontmatter->>'source_slug' = $1 AND deleted_at IS NULL`,+ [sourceSlug],+ );+ expect(mine.map(r => r.slug)).not.toContain(otherSlug);+ expect(mine).toHaveLength(1);+ });++ test('a soft-deleted same-page case variant is not adopted', async () => {+ const sourceSlug = 'writings/2026-08-27-deleted-variant-page';+ const title = 'Deleted Variant Claim';+ const deletedSlug = 'atoms/2026-08-27/deleted-variant-claim-1a2b3c4d';+ await engine.putPage(deletedSlug, {+ type: 'atom', title, compiled_truth: 'Retired atom.', timeline: '',+ frontmatter: { source_slug: sourceSlug, source_hash: 'efef666677778888', atom_type: 'insight' },+ });+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = $1 AND source_id = 'default'`, [deletedSlug]);+ await engine.putPage(sourceSlug, { type: 'note', title: 'Deleted variant source', compiled_truth: 'Body.', timeline: '' });++ const result = await runPhaseExtractAtoms(engine, {+ _transcripts: [],+ _pages: [{ slug: sourceSlug, content: 'Body.', contentHash: 'fafa999900001111' }],+ _chat: stubChat(title.toLowerCase()),+ });+ expect(result.status).toBe('ok');+ expect(result.details?.atoms_extracted).toBe(1);++ const rows = await engine.executeRaw<{ slug: string; source_hash: string; deleted: boolean }>(+ `SELECT slug, frontmatter->>'source_hash' AS source_hash, deleted_at IS NOT NULL AS deleted+ FROM pages WHERE type = 'atom' AND frontmatter->>'source_slug' = $1 AND source_id = 'default'`,+ [sourceSlug],+ );+ const retired = rows.find(r => r.slug === deletedSlug);+ expect(retired).toMatchObject({ source_hash: 'efef666677778888', deleted: true });+ expect(rows.filter(r => !r.deleted)).toHaveLength(1);+ });+});