Skip to content

N1 — Topic canonicalization: repeated facts converge onto one topic - #54

Merged
aspotton merged 7 commits into
mainfrom
feat/topic-canonicalization
Oct 11, 2026
Merged

aspotton merged 7 commits into
mainfrom
feat/topic-canonicalization

Conversation

@aspotton

@aspotton aspotton commented Oct 10, 2026 •

Copy link
Copy Markdown
Owner

N1 — Topic canonicalization: repeated facts converge onto one topic

Why. The live store carries 2,121 active memories across 1,760 topics; 87% have observation_count = 1 because the exact-string topic gates never match slug variants (deploy vs deployment). Duplicates never reinforce, topic summaries never trigger, and consolidation can't find its duplicates. This PR makes topic identity converge deterministically — the LLM only proposes; code owns every mutation (invariant 2).

What (one commit per step):

  • feat(text): topic_slug_similarity — 0.5·jaccard + 0.5·containment over separator-split tokens with ≥4-char prefix equivalence, numeric-token exclusion, and a hard both-sided digit-multiset veto. Every case-table value pinned in tests/test_topic_slug_similarity.py; the 0.583/0.833 fixture-separation margins are pinned so a future weight change fails loudly.
  • feat(config): memory.topic_canonical_floor (0.85) and memory.topic_canonicalization_prompt_topics (40; 0 disables).
  • feat(database): list_topic_counts() + rename_topics() — one BEGIN IMMEDIATE transaction keeping memories, topic_updates, pending/crashed-running job payloads (json_set, content bytes survive), consolidation:last: checkpoints (MIN merge), the topics table (mapping-scoped deletes, survivor counts refreshed), and FTS (single guarded post-commit rebuild) consistent; idempotent by whole-DB dump equality.
  • feat(learning): apply-time canonicalization onto the count/age/lexicographic representative before any gate sees a candidate; the supersede/refine gates accept topic equivalence instead of exact-string copy (this is the IS-3 fix — corrections are no longer silently dropped on extractor copy-drift); the reinforce path adopts a named target's topic only; memory_type stays exact everywhere and no numeric threshold moved. Extraction prompt shows a bounded, deduped existing-topics list to reuse plus one boilerplate-suppression sentence.
  • feat(runtime): one-time idempotent startup backfill (union-find clusters → rename_topics → done flag stamped LAST), running before the interrupted-jobs/dirty-topic recoveries and ungated on learning.enabled.
  • test(benchmarks): topic-discipline scenario as the standing regression gate (flip-proved: with digit-varying slugs it FAILS, so it tests canonicalization, not tautology) + AGENTS/ROADMAP notes.

Safety properties (ratified across three adversarial planning-review rounds):

  • Date-distinct slugs are never merged pairwise — the digit veto scores them 0.0 regardless of everything else.
  • Misnamed-target corruption controls are pinned tests on both the supersede and reinforce paths: an unrelated named target is byte-identical before/after (worst documented ceiling: the new memory files under the named target's topic).
  • The backfill's digit veto is enforced at CLUSTER level, not just per edge: each union-find root carries the digit-multiset signatures of its dated members and a union is skipped whenever any two differ, so an undated bridge slug (x-start) can never transitively collapse two date-distinct siblings into one topic — it joins exactly one of them. (Caught by the final-wave reviewer with a reproduction on the exact live-store shape; fix commit fix(runtime): veto-aware transitive clustering....) The apply-time learner path never bridges anyway (single non-transitive snap per candidate).
  • Renames intentionally bump updated_at: renamed memories briefly look fresh to ranking until decay reconciles, and the (pre-existing, 1/min) consolidation pass does the rest. Expect a bounded summary-rebuild backlog on first boot after merge.

Verification transcript (local, orchestrator-run):

  • pytest -q → 486 passed, 0 failed (was 453 pre-PR; +33 new assertions incl. full-seed DB dumps, PK-collision, crash-resume zero-diff, corruption controls, and the undated-bridge clustering case)
  • python -m benchmarks.run → 15/15 scenarios, extraction P=R=1.000, retrieval P=R=1.000
  • Per-todo evidence: .omo/evidence/task-{1..6}-n1-topic-canonicalization.txt

This PR does not merge itself — execution protocol forbids merging; left open for manual review.

Co-Authored-By: Claude Opus 4.6 (via OpenCode) noreply@anthropic.com

Add topic_slug_tokens/topic_slug_similarity: 0.5*jaccard + 0.5*containment over separator-split slug tokens with >=4-char prefix equivalence, numeric-token exclusion, and a both-sided digit-multiset veto so date-distinct slugs never merge while undated-vs-dated variants score 1.0. Greedy pairwise matching (no transitive collapse). Weights pinned by N1 review rounds to keep existing fixture pairs (session-store-a/-b 0.583, session store 0.833) below the 0.85 floor. Retrieval-facing scorers unchanged.
memory.topic_canonical_floor (0.85) gates apply-time canonicalization and the startup backfill; memory.topic_canonicalization_prompt_topics (40) bounds the existing-topics list injected into the extraction prompt, 0 disables. Deliberately separate from supersede_similarity_floor (0.30). Docs subsection records the 87% observation_count=1 live-store evidence.
…job/checkpoint consistency

list_topic_counts() gives (topic, active_count, earliest_created) ordered count-DESC/topic-ASC for the canonicalization representative rule. rename_topics(mapping) runs one BEGIN IMMEDIATE transaction: memories retagged with intentional updated_at bump; topic_updates moves merge-safely under the (topic,memory_id) PK; pending+crashed-running job payloads get $.topic rewritten via json_set (content bytes survive; failed/done untouched); consolidation:last: checkpoints merge by MIN and variant keys go; topics rows deleted ONLY for zero-active mapping keys with survivor memory_count refreshed from live counts and non-mapping rows provably untouched. Post-commit, single fts_enabled-guarded _rebuild_fts_sync. Dirty-marking gated to canonical topics that gained rows AND reach the summary threshold. Idempotent by row-dump equality.
…fine gates, prompt topic list

Candidates snap deterministically onto the count/age/lex representative of existing topics at or above memory.topic_canonical_floor before any gate sees them (one list_topic_counts snapshot feeds both the gate and the prompt reusable-topic block, so the model is steered onto exactly the slugs the gate canonicalizes onto). The supersede (~410) and refine (~459) gates accept topic EQUIVALENCE instead of exact string copy, closing the copy-drift drop vector; memory_type stays EXACT everywhere and no numeric threshold moves. Reinforce candidates naming a shown, active target adopt its topic (topic only) so the exact-equality compatibility filter can match. Prompt gains the Existing-topics reuse block (capped, deduped against shown, 0 disables) and one boilerplate-suppression sentence. Corruption controls pinned: misnamed ids can never mutate the unrelated memory they name on the supersede and reinforce paths.
… startup

backfill_topic_canonicalization runs in build_runtime before the interrupted-jobs and dirty-topic recoveries (repair-then-recover ordering keeps summary re-enqueues pointed at canonical topics). Done-flag short-circuit; greedy union-find over distinct active topics at memory.topic_canonical_floor mirroring consolidation.build_clusters; representative = count DESC / earliest ASC / lexicographic ASC, identical to the learner's rule; mapping applied through the transactional rename_topics (FTS, jobs, checkpoints, topics table stay consistent); done flag stamped LAST so a crashed pass re-runs as a verified no-op. Data hygiene, ungated on learning.enabled: without learning.model the summary enqueue degrades to dirty-marking that startup recovery picks up. Known nuance (recorded): a no-digit bridge slug transitively joins two date-distinct variants into one cluster - inherent to the ratified union-find clustering; direct date-distinct pairs never share an edge.
Two-session, four-turn corpus scenario: the same decision learned under argocd-deploy-pipeline and its suffix variant argocd-deployment-pipeline must produce ONE memory with a reinforced turn-4 outcome and unchanged retrieval probes. Flip proof (captured, uncommitted): switching the pair to digit-varying dates fails the scenario 2/3, so the corpus tests canonicalization rather than tautology. AGENTS.md memory-learning rules now state apply-time canonicalization, topic equivalence at memory.topic_canonical_floor with memory_type still exact, and the refine-contract wording; ROADMAP N1 gains the Status line.
…pics apart

Final-wave F4 reproduced an IS-5 violation: an undated bridge slug (x-start) joined two date-distinct siblings transitively because the digit veto only gated direct edges - the live store contains exactly this shape (undated ...-execution-start ancestors with dated siblings). The both-sided veto is now enforced at cluster level: each union-find root carries the set of digit-multiset signatures of its dated members, and a union is skipped whenever ANY signature in one root differs from ANY in the other. Edge order and representative rule untouched; docstring corrected to state the transitive guarantee. Apply-time path unchanged (single non-transitive snap, structurally safe).
@aspotton
aspotton merged commit 64408d1 into main Oct 11, 2026
1 check passed
@aspotton
aspotton deleted the feat/topic-canonicalization branch October 11, 2026 19:31
@aspotton aspotton mentioned this pull request Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant