Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

synthesize_concepts: fold punctuation spelling variants into one concept page (#5965)

garrytan1fd3be9dc46a
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index ec34078a9b..d867764bd1 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -35,4 +35,4 @@
- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.
- `src/core/bootstrap/template-repo.ts` + `scripts/generate-template-repo.ts` — deterministic public-template generation (render `--minimal` + placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.
- `scripts/check-bootstrap-tag.sh` / `scripts/check-bootstrap-templates.sh` — CI guards: sanctioned distribution ref only (`latest-stable`; the release job advances it after assets publish) + runbook stamp == VERSION; template↔question-bank token bijection + placeholder-only assertion + offline generator↔vendored byte-diff + runbook-phase↔status.ts consistency. Both skip gracefully when their subjects are absent.
-- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — a `concepts/<x>` page whose frontmatter lacks `synthesized_by: synthesize_concepts-*` belongs to a human or another writer: the phase checks it before any LLM spend, never rewrites it, and reports it in `details.skipped_human_owned` (pinned by `test/cycle/synthesize-concepts-human-owned.test.ts`). Concept refs are normalized before grouping (`conceptStemFor`: last path segment through `slugifySegment`, validated by `validatePageSlug`; one atom counts once per concept), so spelling variants share one page and no slug carries a space. Each page records `member_hash` (member atom slugs, titles and bodies without their `## Facts` / `## Takes` sections, which the prompt also omits, plus the synthesis model; a page still carrying the full-body hash whose inputs are unchanged is rehashed without a model call, `details.rehashed`; a narrative a `chat_fallback_chain` model wrote is hashed under that model, so the next cycle re-synthesizes it); an unchanged hash on an `llm` or `deterministic_tier` page is skipped without spend (`details.skipped_unchanged`), and a budget or error fallback never replaces an existing `llm` narrative (`details.kept_existing_narrative`); fallback pages retry next cycle. Pinned by `test/cycle/synthesize-concepts-identity.test.ts`. Eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`. The phase budget is `cycle.synthesize_concepts.budget_usd` (finite USD above 0, default 1.5; `config set` refuses other values, a stored invalid value keeps the default with a named-key warning, specs in `src/core/cycle/phase-config-values.ts`); groups refused at the cap are counted in the summary and `details.warnings`. Pinned by `test/cycle-synthesize-concepts-budget-config.test.ts`. A narrative whose stop reason is `length`, `refusal` or `content_filter` is a failure (template fallback for a new concept; an existing `llm` page and its `member_hash` stay), and failed narratives are bounded per concept and member hash by `cycle/concept-retry-bound.ts` (`ConceptRetryBound`, DB-only config key `dream.concepts.failed_attempts`, `MAX_CONCEPT_ATTEMPTS` = 3): a bounded concept is skipped before any spend into `details.skipped_retry_bound` until its members change, a narrative succeeds, or the key is unset (`test/cycle/synthesize-concepts-stop-reason.test.ts`).
+- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — a `concepts/<x>` page whose frontmatter lacks `synthesized_by: synthesize_concepts-*` belongs to a human or another writer: the phase checks it before any LLM spend, never rewrites it, and reports it in `details.skipped_human_owned` (pinned by `test/cycle/synthesize-concepts-human-owned.test.ts`). Concept refs are normalized before grouping (`conceptStemFor`: last path segment through `slugifySegment`, validated by `validatePageSlug`; one atom counts once per concept), so case and spacing variants share one page and no slug carries a space; punctuation variants (`network-effects` / `networkeffects`) fold per run through `cycle/concept-redirects.ts` `addSpellingRedirects` (#5965; documented with `concept-publication.ts` in `core-cycle-continued.md`). Each page records `member_hash` (member atom slugs, titles and bodies without their `## Facts` / `## Takes` sections, which the prompt also omits, plus the synthesis model; a page still carrying the full-body hash whose inputs are unchanged is rehashed without a model call, `details.rehashed`; a narrative a `chat_fallback_chain` model wrote is hashed under that model, so the next cycle re-synthesizes it); an unchanged hash on an `llm` or `deterministic_tier` page is skipped without spend (`details.skipped_unchanged`), and a budget or error fallback never replaces an existing `llm` narrative (`details.kept_existing_narrative`); fallback pages retry next cycle. Pinned by `test/cycle/synthesize-concepts-identity.test.ts`. Eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`. The phase budget is `cycle.synthesize_concepts.budget_usd` (finite USD above 0, default 1.5; `config set` refuses other values, a stored invalid value keeps the default with a named-key warning, specs in `src/core/cycle/phase-config-values.ts`); groups refused at the cap are counted in the summary and `details.warnings`. Pinned by `test/cycle-synthesize-concepts-budget-config.test.ts`. A narrative whose stop reason is `length`, `refusal` or `content_filter` is a failure (template fallback for a new concept; an existing `llm` page and its `member_hash` stay), and failed narratives are bounded per concept and member hash by `cycle/concept-retry-bound.ts` (`ConceptRetryBound`, DB-only config key `dream.concepts.failed_attempts`, `MAX_CONCEPT_ATTEMPTS` = 3): a bounded concept is skipped before any spend into `details.skipped_retry_bound` until its members change, a narrative succeeds, or the key is unset (`test/cycle/synthesize-concepts-stop-reason.test.ts`).
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index 51ad22373e..72ea73ccd4 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -21,6 +21,6 @@ Synthesis, patterns, consolidation and connector atom gating.
- `src/core/cycle/triage-rescue.ts` — THE dream triage gate (`passesTriageGate`) + the verified-segment rescue (`applyTriageRescue`). Rescue fires only for scores in `[floor, threshold)` (floor inclusive; at/above threshold is the plain gate's job) with content_type in the buried-signal allowlist (default mixed/reflection/idea/strategy/people — never routine/technical) and ≥ minSegments of the judge's own segments verifying as normalized transcript substrings (`normForGrounding`, ≥40 chars, deduped by normalized quote — repetition is not more evidence). $0 — no LLM calls; fabricated segments cannot fire it; works on cached verdicts (gate-time only). Fail-closed on every malformed shape (null score, missing/short/non-string segments), never throws. `minSegments: 0` is the kill switch (gate degenerates to the plain threshold). ONE-GATE RULE: `runTriagePass` (report construction — `worth`/`rescued`/telemetry/dry-run), the synthesize fan-out, and `dream retriage` (reconcile-queue cancels + `--audit-rejects` sampling) all read this predicate — a second hand-rolled `score >= threshold` check is how an operator sweep cancels exactly the jobs the rescue admitted. Config: `dream.triage.rescue_floor` / `rescue_min_segments` / `rescue_content_types`. Pinned by `test/cycle-triage-rescue.test.ts` + the rescue suites in `test/cycle-synthesize-triage.test.ts` / `test/dream-retriage.test.ts`. System One S7: a decide verdict (`model` starting with `DECIDE_VERDICT_PREFIX`) is gated against the S7 slot threshold (the optional fifth argument) and never enters the rescue band.
- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory, then calls `writePageThrough` (which honours `sync.write_through=off`) and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. Tests: `test/cycle/derived-write-through.test.ts`.
-- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's file holds an edit the database has not imported (narrative, frontmatter, tags, type or title; formatting is ignored), and otherwise composes the new narrative with the latest fences (from the page's file when it has one), so a take added during synthesis survives. The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds reported in the phase details. Tests: `test/managed-writers-w3.test.ts`. #6161: `preserveCanonicalFences` also carries curated `## Facets` / `## Merged` sections verbatim (`cycle/concept-sections.ts`; a model-written copy is dropped, and the lossless check covers them), and `synthesize-concepts.ts` groups atoms through `cycle/concept-redirects.ts` `loadConceptRedirects` (`merged_into` on any live concept page, `aliases` on phase-owned ones; one hop, two-way redirects ignored) and skips a tombstoned concept page as `skipped_deleted` instead of resurrecting it (`test/cycle/synthesize-concepts-merge.test.ts`).
+- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's file holds an edit the database has not imported (narrative, frontmatter, tags, type or title; formatting is ignored), and otherwise composes the new narrative with the latest fences (from the page's file when it has one), so a take added during synthesis survives. The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds reported in the phase details. Tests: `test/managed-writers-w3.test.ts`. #6161: `preserveCanonicalFences` also carries curated `## Facets` / `## Merged` sections verbatim (`cycle/concept-sections.ts`; a model-written copy is dropped, and the lossless check covers them), and `synthesize-concepts.ts` groups atoms through `cycle/concept-redirects.ts` `loadConceptRedirects` (`merged_into` on any live concept page, `aliases` on phase-owned ones; one hop, two-way redirects ignored) and skips a tombstoned concept page as `skipped_deleted` instead of resurrecting it (`test/cycle/synthesize-concepts-merge.test.ts`). #5965: the same module folds spelling variants for one run: `addSpellingRedirects` groups the post-redirect stems by `spellingFoldKey` (ASCII `-`, `_` and `.` removed; Unicode kept), and a group of two or more stems redirects every stem to the one that already has a live top-level `concepts/<stem>` page (`loadLiveConceptStems`), else to the most frequent spelling (tie: the hyphenated one, then alphabetical); a group where two or more spellings already have live pages is left alone ([R28]: `re-sign` / `resign` are different concepts and only the human merge path joins them). The redirects are in-memory only (no `merged_into` write); the grouping applies `canonicalConceptStem` twice (human hop, then spelling hop), and the phase receipt lists the folds in `details.folded_spellings`. Pinned by `test/cycle-synthesize-concepts-grouping.test.ts`.
- `src/core/cycle/connector-atoms.ts` — the connector atom setting (#5856). `CONNECTOR_ATOM_PAGES_KEY` (`cycle.extract_atoms.connector_pages`, on when unset; `connectorAtomPagesEnabled` treats only false/0/off/no as opted out) gates `CONNECTOR_ATOM_PAGE_TYPES` (`email`, `meeting`) of sources whose `config.kind` is a connector kind (`CONNECTOR_SOURCE_KINDS`). `connectorAtomExclusionSql` returns the `pages p` predicate atom discovery and the backlog count append (empty unless opted out), so the routine cycle, `dream --drain` and autopilot auto-drain extract connector mail and calendar pages under the auto-drain budget until the user opts out. Other page types of a connector source and every checkout-backed page are unaffected. Tests: `test/connector-atom-pages.test.ts`, `test/autopilot-auto-drain-dispatch.test.ts`, and the `atom_drain_default_on` / `atom_drain_opted_out` cases of `test/helpers/managed-connector-job-contract.ts`, run by `test/managed-connector-job-contract.test.ts` and its Postgres twin `test/e2e/managed-connector-job-contract.test.ts`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index fb010ce416..c52f2f4a9d 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -380,6 +380,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.157.0', text: 'A `remember` (or any single-fact write) that repeats a fact already stored word for word for the same entity, or with no resolved entity at all, now returns the existing fact (`status: duplicate`) instead of inserting a second row, including on brains without an embedding key; a remote or unattributed caller never dedups against a fact that came from a private source. A write whose entity could not be resolved and fell back to slugifying the name now stores the fact with no entity instead of minting a placeholder entity slug, so the stub guard no longer refuses later writes about that name; search and `recall` still find the fact by its text.' },
{ since: '0.60.157.0', text: 'A top-level call statement in a JavaScript, TypeScript, TSX, Python or Ruby file (a `describe(...)` / `it(...)` block, `app.use(...)`, `print(helper())`, `RSpec.describe ... do`) is now its own chunk, `symbol_type` `module` and `symbol_name` `__module__`, so the calls inside it get edges: `code-callers helper` lists the test body as `<file-basename>::__module__`. Files with such statements gain chunks, so the next `gbrain sync` walks each source once and re-chunks and re-embeds only its files in those five languages (priced by the cost gate as `grammar_drift`); `gbrain reindex-code` does the same now. Definition-only files keep their chunks and vectors.' },
{ since: '0.60.157.0', text: 'The entity counters in `get_health` / `gbrain health` (`entity_page_count`, `link_coverage`, `timeline_coverage`, `most_connected`) and doctor\'s `graph_coverage` and `orphan_ratio` gates now count the page types the active schema pack declares with `primitive: entity` (`yc`, `civic` and `organization` included on gbrain-base; a custom pack\'s own entity types; `person` or `company` only while the pack does not reclassify them), resolved per source when sources carry their own pack. Brains whose entities are pack types move from 0 entities and `null` ratios to real numbers, and a doctor score can drop where coverage is low. A pack that does not load now reports `entity_types_status: pack_unavailable` with 0 entities and a `graph_coverage` warn instead of counting the old hardcoded list.' },
+ { since: '0.60.157.0', text: 'Dream `synthesize_concepts` now writes one concept page for spellings of a label that differ only by hyphens, underscores or dots (`network-effects`, `network_effects`, `networkeffects`): the spelling that already has a live `concepts/` page wins, otherwise the one most atoms use (a tie goes to the hyphenated form), and the other spellings redirect to it for that run without any page write. Two spellings that both already have live pages (`re-sign` / `resign`, `co-op` / `coop`) are kept apart; merging those stays the human redirect path (`merged_into` / `aliases`). Existing duplicate pages are not merged for you: `details.folded_spellings` on the phase receipt names each fold.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cycle/concept-redirects.ts b/src/core/cycle/concept-redirects.ts
index 6d968c9ad2..b88140d4b7 100644
--- a/src/core/cycle/concept-redirects.ts
+++ b/src/core/cycle/concept-redirects.ts
@@ -1,10 +1,26 @@
/**
- * #6161: concept merges a human made, read back as stem redirects for
- * synthesize_concepts' grouping. The concept-synthesis skill merges concept B
- * into A by archiving B under `concepts/_merged/` with `merged_into: A` and
- * listing B in A's `aliases`. Either record redirects B's atoms to A, so the
- * phase grows A instead of recreating B. Aliases count only on pages the phase
- * owns (`synthesized_by: synthesize_concepts…`), the pages a merge targets.
+ * Stem redirects for synthesize_concepts' grouping: every concept ref an atom
+ * carries is slugified to a stem, then sent through these redirects before
+ * atoms are grouped into one page per stem. Two kinds of redirect live in the
+ * same in-memory map; neither writes a page.
+ *
+ * #6161: concept merges a human made. The concept-synthesis skill merges
+ * concept B into A by archiving B under `concepts/_merged/` with
+ * `merged_into: A` and listing B in A's `aliases`. Either record redirects B's
+ * atoms to A, so the phase grows A instead of recreating B. Aliases count only
+ * on pages the phase owns (`synthesized_by: synthesize_concepts…`), the pages a
+ * merge targets. Read back by `loadConceptRedirects`.
+ *
+ * #5965: spelling variants of one label. `network-effects`, `network_effects`
+ * and `networkeffects` are one concept, so `addSpellingRedirects` folds the
+ * stems of a run that differ only by ASCII `-`, `_` and `.` onto one of them
+ * for that run: the spelling that already has a live `concepts/<stem>` page
+ * wins (a page is never re-created under a new spelling), else the spelling
+ * most atoms use, a tie going to the hyphenated one. Two spellings that both
+ * have live pages are left alone ([R28]: `re-sign` / `resign` and `co-op` /
+ * `coop` are different concepts; only the human merge path above joins them).
+ * These redirects exist for the run only; the grouping applies them after the
+ * human hop, so `canonicalConceptStem` is called twice.
*/
import type { BrainEngine } from '../engine.ts';
@@ -35,3 +51,48 @@ export function canonicalConceptStem(stem: string, redirects: Map<string, string
const target = redirects.get(stem);
return target && redirects.get(target) !== stem ? target : stem;
}
+
+/** The stems of the live top-level `concepts/<stem>` pages of a source (archived `concepts/_merged/…` pages excluded). */
+export async function loadLiveConceptStems(engine: BrainEngine, sourceId: string,
+ stemFor: (ref: string) => string | null): Promise<Set<string>> {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = $1 AND slug LIKE 'concepts/%' AND slug NOT LIKE 'concepts/%/%' AND deleted_at IS NULL`, [sourceId]);
+ return new Set(rows.map((r) => stemFor(r.slug)).filter((s): s is string => s !== null));
+}
+
+/** #5965: the key two stems share when they differ only by ASCII `-`, `_` and `.` (Unicode is kept as is). */
+export function spellingFoldKey(stem: string): string {
+ return stem.replace(/[-_.]/g, '');
+}
+
+/**
+ * #5965: adds a redirect from every losing spelling of a run to its winner
+ * (see the module comment for the rule) and returns the pairs added. `atomCounts`
+ * is the number of atoms per stem after the human redirects were applied; a
+ * stem that already redirects somewhere is never folded again.
+ */
+export function addSpellingRedirects(redirects: Map<string, string>, atomCounts: Map<string, number>,
+ liveStems: Set<string>): Array<{ from: string; to: string }> {
+ const groups = new Map<string, string[]>();
+ for (const stem of atomCounts.keys()) {
+ if (redirects.has(stem)) continue;
+ const key = spellingFoldKey(stem);
+ groups.set(key, [...groups.get(key) ?? [], stem]);
+ }
+ const added: Array<{ from: string; to: string }> = [];
+ for (const stems of groups.values()) {
+ if (stems.length < 2) continue;
+ const live = stems.filter((s) => liveStems.has(s));
+ if (live.length > 1) continue;
+ const winner = live[0] ?? [...stems].sort((a, b) =>
+ (atomCounts.get(b) ?? 0) - (atomCounts.get(a) ?? 0) ||
+ Number(b.includes('-')) - Number(a.includes('-')) ||
+ a.localeCompare(b))[0]!;
+ for (const stem of stems) {
+ if (stem === winner) continue;
+ redirects.set(stem, winner);
+ added.push({ from: stem, to: winner });
+ }
+ }
+ return added.sort((a, b) => a.from.localeCompare(b.from));
+}
diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts
index bd6caa15bf..c38c4f3fbe 100644
--- a/src/core/cycle/synthesize-concepts.ts
+++ b/src/core/cycle/synthesize-concepts.ts
@@ -43,7 +43,7 @@ import { validatePageSlug } from '../ops/context.ts';
import { privatePagesFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';
import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';
import { derivedWriteThrough } from './derived-write-through.ts';
-import { canonicalConceptStem, loadConceptRedirects } from './concept-redirects.ts';
+import { addSpellingRedirects, canonicalConceptStem, loadConceptRedirects, loadLiveConceptStems } from './concept-redirects.ts';
import {
addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishClassicConcept, publishManagedConcept, stripFenceSections,
} from './concept-publication.ts';
@@ -216,12 +216,11 @@ export async function runPhaseSynthesizeConcepts(
};
}
- // 2. Group atoms by normalized concept slug (#6161: a merged concept groups under its canonical one); one atom counts once per concept.
- const redirects = await loadConceptRedirects(engine, opts.sourceId ?? 'default', conceptStemFor).catch(() => new Map<string, string>());
+ // 2. Group atoms by concept stem (#6161 human redirects, then #5965 spelling folds; see resolveAtomConceptStems); one atom counts once per concept.
+ const { atomStems, foldedSpellings } = await resolveAtomConceptStems(engine, opts.sourceId ?? 'default', atoms);
const groups = new Map<string, { slugs: string[]; titles: string[]; bodies: string[]; visibilities: Visibility[] }>();
- for (const atom of atoms) {
- const conceptSlugs = new Set(atom.concept_refs.map(conceptStemFor).filter((s): s is string => s !== null).map((stem) => canonicalConceptStem(stem, redirects)));
- for (const conceptSlug of conceptSlugs) {
+ for (const [i, atom] of atoms.entries()) {
+ for (const conceptSlug of atomStems[i]!) {
const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [], visibilities: [] };
existing.slugs.push(atom.slug);
existing.titles.push(atom.title);
@@ -644,6 +643,7 @@ export async function runPhaseSynthesizeConcepts(
rehashed,
kept_existing_narrative: keptExistingNarrative,
skipped_retry_bound: skippedRetryBound,
+ folded_spellings: foldedSpellings,
publication_deferred: publicationDeferred,
publication_held: publicationHeld,
...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),
@@ -655,6 +655,24 @@ export async function runPhaseSynthesizeConcepts(
};
}
+/**
+ * Each atom's concept stems, one entry per atom: the ref's stem through the
+ * human redirects (#6161), then through the run's spelling folds (#5965:
+ * `network-effects` / `networkeffects` become one stem; the live page's
+ * spelling wins, else the most frequent, tie to the hyphenated one; two live
+ * spellings are left apart). The folds are reported, never written.
+ */
+async function resolveAtomConceptStems(engine: BrainEngine, sourceId: string, atoms: Array<{ concept_refs: string[] }>):
+ Promise<{ atomStems: Set<string>[]; foldedSpellings: Array<{ from: string; to: string }> }> {
+ const redirects = await loadConceptRedirects(engine, sourceId, conceptStemFor).catch(() => new Map<string, string>());
+ const afterHumanHop = atoms.map((atom) => new Set(atom.concept_refs.map(conceptStemFor).filter((s): s is string => s !== null).map((stem) => canonicalConceptStem(stem, redirects))));
+ const atomCounts = new Map<string, number>();
+ for (const stems of afterHumanHop) for (const stem of stems) atomCounts.set(stem, (atomCounts.get(stem) ?? 0) + 1);
+ const liveStems = await loadLiveConceptStems(engine, sourceId, conceptStemFor).catch(() => new Set<string>());
+ const foldedSpellings = addSpellingRedirects(redirects, atomCounts, liveStems);
+ return { atomStems: afterHumanHop.map((stems) => new Set([...stems].map((stem) => canonicalConceptStem(stem, redirects)))), foldedSpellings };
+}
+
/**
* The concept an atom's concept ref names, as the stem of its `concepts/`
* slug. LLM refs vary in case, spacing and prefix ("Network Effects",
diff --git a/test/cycle-synthesize-concepts-grouping.test.ts b/test/cycle-synthesize-concepts-grouping.test.ts
new file mode 100644
index 0000000000..fb29498be4
--- /dev/null
+++ b/test/cycle-synthesize-concepts-grouping.test.ts
@@ -0,0 +1,108 @@
+// #5965: hyphenation variants of one concept label (`network-effects`,
+// `networkeffects`, `Network Effects`) used to be three grouping keys, so one
+// concept got two pages. synthesize_concepts now folds stems that differ only
+// by ASCII `-`, `_` and `.` into one page per run.
+//
+// Protects: one page per spelling group; a spelling that already has a live
+// page keeps winning across reruns (no page is re-created under a new
+// spelling); a group with no live page takes the most frequent spelling, a tie
+// the hyphenated one; the losing spellings are in-run redirects only (no page
+// write); and two spellings that BOTH have live pages (`re-sign` / `resign`,
+// `co-op` / `coop`) are never merged automatically ([R28]: the human redirect
+// path of #6161 owns that).
+// Fails when: the grouping key keeps the punctuation, the live-page rule
+// yields to atom count, or the fold merges two live pages.
+// Why not existing coverage: synthesize-concepts-merge.test.ts pins explicit
+// human redirects; nothing pins spelling folds.
+// No new production seam: `_atoms` and `_chat` already exist.
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseSynthesizeConcepts } from '../src/core/cycle/synthesize-concepts.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 240000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); }, 120000);
+
+type Atom = { slug: string; title: string; body: string; concept_refs: string[]; visibility: 'world' };
+const atom = (slug: string, ...refs: string[]): Atom => ({ slug, title: slug, body: `Body of ${slug}.`, concept_refs: refs, visibility: 'world' });
+const atoms = (...labels: string[]): Atom[] => labels.map((label, i) => atom(`atoms/a${i}`, label));
+// No model is ever called: a T1/T2 group whose chat throws falls back to the
+// deterministic narrative, which still writes the page.
+const noModel = (): never => { throw new Error('no model calls in this test'); };
+const run = (list: Atom[]) => runPhaseSynthesizeConcepts(engine, { _atoms: list, sourceId: 'default', _chat: noModel });
+const page = (slug: string) => engine.getPage(slug, { sourceId: 'default' });
+const conceptSlugs = async (): Promise<string[]> => (await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = 'default' AND slug LIKE 'concepts/%' AND deleted_at IS NULL ORDER BY slug`)).map((r) => r.slug);
+const folded = (r: Awaited<ReturnType<typeof run>>) => (r.details as { folded_spellings?: Array<{ from: string; to: string }> }).folded_spellings;
+
+describe('synthesize_concepts folds punctuation spelling variants (#5965)', () => {
+ test('network-effects ×2, networkeffects ×2, Network Effects ×1 → one page with every atom', async () => {
+ const r = await run(atoms('network-effects', 'networkeffects', 'Network Effects', 'network-effects', 'networkeffects'));
+ expect(await conceptSlugs()).toEqual(['concepts/network-effects']);
+ expect((await page('concepts/network-effects'))!.frontmatter.mention_count).toBe(5);
+ expect(folded(r)).toEqual([{ from: 'networkeffects', to: 'network-effects' }]);
+ }, 120000);
+
+ test('the spelling that already has a live page wins, even against more atoms', async () => {
+ await run(atoms('networkeffects', 'networkeffects'));
+ expect(await conceptSlugs()).toEqual(['concepts/networkeffects']);
+ await run(atoms('network-effects', 'network-effects', 'network-effects', 'networkeffects', 'networkeffects'));
+ expect(await conceptSlugs()).toEqual(['concepts/networkeffects']);
+ expect((await page('concepts/networkeffects'))!.frontmatter.mention_count).toBe(5);
+ }, 120000);
+
+ test('no live page: the most frequent spelling wins', async () => {
+ await run(atoms('net_work', 'net_work', 'net_work', 'net-work', 'net-work', 'network'));
+ expect(await conceptSlugs()).toEqual(['concepts/net_work']);
+ expect((await page('concepts/net_work'))!.frontmatter.mention_count).toBe(6);
+ }, 120000);
+
+ test('no live page, equal counts: the hyphenated spelling wins', async () => {
+ await run(atoms('networkeffects', 'networkeffects', 'network-effects', 'network-effects'));
+ expect(await conceptSlugs()).toEqual(['concepts/network-effects']);
+ }, 120000);
+
+ test('an atom naming two spellings of one concept counts once', async () => {
+ await run([atom('atoms/x', 'network-effects', 'networkeffects'), atom('atoms/y', 'network-effects'), atom('atoms/z', 'networkeffects')]);
+ expect(await conceptSlugs()).toEqual(['concepts/network-effects']);
+ expect((await page('concepts/network-effects'))!.frontmatter.mention_count).toBe(3);
+ }, 120000);
+
+ test('[R28] two spellings that both have live pages are not merged (re-sign / resign, co-op / coop)', async () => {
+ // Each spelling earned its own page in earlier runs (atoms of different meanings).
+ await run([...atoms('re-sign', 're-sign'), atom('atoms/c0', 'co-op'), atom('atoms/c1', 'co-op')]);
+ await run([...atoms('resign', 'resign'), atom('atoms/c0', 'coop'), atom('atoms/c1', 'coop')]);
+ expect(await conceptSlugs()).toEqual(['concepts/co-op', 'concepts/coop', 'concepts/re-sign', 'concepts/resign']);
+ const r = await run([
+ ...atoms('re-sign', 're-sign', 'resign', 'resign', 'resign'),
+ atom('atoms/c0', 'co-op'), atom('atoms/c1', 'co-op'), atom('atoms/c2', 'coop'), atom('atoms/c3', 'coop'),
+ ]);
+ expect(await conceptSlugs()).toEqual(['concepts/co-op', 'concepts/coop', 'concepts/re-sign', 'concepts/resign']);
+ expect(folded(r)).toEqual([]);
+ expect((await page('concepts/re-sign'))!.frontmatter.mention_count).toBe(2);
+ expect((await page('concepts/resign'))!.frontmatter.mention_count).toBe(3);
+ }, 120000);
+
+ test('a deleted page is not a live spelling', async () => {
+ await run(atoms('networkeffects', 'networkeffects'));
+ await engine.softDeletePage('concepts/networkeffects', { sourceId: 'default' });
+ await run(atoms('network-effects', 'network-effects', 'network-effects', 'networkeffects', 'networkeffects'));
+ expect(await conceptSlugs()).toEqual(['concepts/network-effects']);
+ expect((await page('concepts/network-effects'))!.frontmatter.mention_count).toBe(5);
+ }, 120000);
+
+ test('losing spellings are redirects for the run only: no page is written for them', async () => {
+ await run(atoms('network-effects', 'networkeffects'));
+ expect(await conceptSlugs()).toEqual(['concepts/network-effects']);
+ const [{ n }] = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages WHERE slug LIKE 'concepts/%' AND (frontmatter->>'merged_into') IS NOT NULL`);
+ expect(Number(n)).toBe(0);
+ }, 120000);
+});