Local-first 🧠memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
fix(brain): merged pages leave the dedup pool, and the write seam refuses cycles (v1.53.1) (#182)
Sol Aitken23e6b81ef6bc
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 7cda86d0..ed3ac2d4 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.53.0",+ "version": "1.53.1","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex be905bd4..ac0943c1 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.53.0",+ "version": "1.53.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex af246156..ef2391a4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,20 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.53.1] - 2026-08-27++Reported as [#180](https://github.com/itechmeat/open-second-brain/issues/180) by [@BlackKite84](https://github.com/BlackKite84): `o2b brain page-dedup` merges a duplicate pair, stamps `merged_into` on the secondary, and then proposes the same merge again on the next scan, forever. Confirmed as filed, and the seam the report named - `findDuplicateCandidates`, which never read the pointer the merge writes - is the right one; it is the single chokepoint behind `page-dedup`, `brain actions`, the digest, `brain_doctor`, `vault_health` and the operator trust verdict, so one filter closes all six. Verification found two escalations the report did not mention, and both raise this from a noisy digest to a silent vault mutation: on pages with no `created_at` the canonical ordering falls back to an mtime the merge itself moves, so a second `--apply` reverses the pair and writes a merge CYCLE that leaves `lint --consolidate` unable to repair any link to either page; and `setMergedInto` overwrote an existing `merged_into` without asking, so a deliberate operator merge was repointed at whatever canonical the next run picked. One side-claim in the report is rejected: identical text under different scopes cannot re-collapse, because the composite scope is already folded into the dedup key and a test has pinned that since v1.37.0.++### Fixed++- **A page a merge already resolved leaves the dedup candidate pool.** Any `merged_into` pointer takes the page out of candidacy, not just one aimed at another member of the same group - the narrower reading the issue proposed leaves the two cases that cost something. A pointer aimed OUTSIDE the group kept the page a candidate and let the next `--apply` overwrite the operator's own merge decision, and a chain that leaves the group and comes back (`b -> x -> a`) survived a one-hop test. A dangling target counts as resolved too: the canonical was lost, which is a lint problem and never a licence to re-merge the page somewhere else. Members are dropped individually rather than whole groups skipped, so a third page duplicating the canonical after an earlier merge is still proposed. The predicate is defined once and the two sibling detectors with the same blind spot adopt it - the digest's `## Merge suggestions` and the hygiene `dedup` detector, both of which repeated the finding in their own sections - which needed `parsePreference` to expose `merged_into` so the digest's pre-parsed path reaches the same verdict as the filesystem one.+- **The merged-into write seam refuses cycles and silent repoints.** `setMergedInto` checked for a self-pointer and nothing else. It now reads the existing pointer first: re-setting the same canonical writes nothing and reports `changed: false`, a different canonical is refused by name unless the caller passes an explicit repoint, and a canonical whose chain already resolves back through the secondary is refused before a byte is written. The guard stays even though the dedup pass can no longer propose either write - the proposer is one caller, and this is where the damage happened. The chain walk behind the resolver and the new cycle guard is now one function, with the resolver's `CYCLE` / `DEPTH` / `MALFORMED` behaviour, dangling targets included, unchanged.++### Notes++- The N2 idempotency test pinned the defect: it asserted the merged pair was still reported on the rerun. The invariant it exists to defend - "a rerun re-collapses nothing new" - is strengthened rather than broken by dropping resolved members, so it keeps its title and now asserts zero clusters. `page-id.test.ts`'s "updates an existing pointer" pinned the silent overwrite and is rewritten as the refusal / explicit-repoint pair it should always have been.+- A `merged-into-dangling` doctor lint is deferred. A new doctor code needs an entry in `DIAGNOSTIC_SIGNALS` or `DOCTOR_EXIT_EXCLUSIONS` under the exit census, plus a frontmatter pass the doctor context does not carry - registration machinery rather than the small reporting-only addition it looked like from outside.+## [1.53.0] - 2026-08-27Hermes injected recall on every gated turn without ever telling the vault what the turn was about, and [@Yori940619](https://github.com/Yori940619) named it in [#181](https://github.com/itechmeat/open-second-brain/pull/181): the pack was query-blind, and the pages that would have mattered lost the budget to whichever confirmed preferences happened to sort first. The diagnosis is right and the preference-first ordering the pull request argued for is the right instinct. The mechanism it proposed is the part that changed. Recall would have moved onto raw `brain_search`, and that path is the one place a curated injection must not go: it runs no prompt-injection guard, post-filters a general ranker instead of enumerating the preference directory, returns retired and merely-demoted superseded pages, never consults owner-scope delivery, enforces no response-level token budget, and issues no receipt. The fix belongs one layer down, inside the lane, and that is where it landed.@@ -7374,6 +7388,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.53.1]: https://github.com/itechmeat/open-second-brain/compare/v1.53.0...v1.53.1[1.53.0]: https://github.com/itechmeat/open-second-brain/compare/v1.52.1...v1.53.0[1.52.1]: https://github.com/itechmeat/open-second-brain/compare/v1.52.0...v1.52.1[1.52.0]: https://github.com/itechmeat/open-second-brain/compare/v1.51.0...v1.52.0diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 383a047b..5211fbab 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.53.0",+ "version": "1.53.1","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 6095381e..52e851ed 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.53.0",+ "version": "1.53.1","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex a4a090c2..d4a34e94 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.53.0"+version: "1.53.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 00e25eba..0bd8b3c4 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.53.0",+ "version": "1.53.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex a4a090c2..d4a34e94 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.53.0"+version: "1.53.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 32de7f82..e6dda740 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.53.0"+version = "1.53.1"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/core/brain/hygiene/detectors/dedup.ts b/src/core/brain/hygiene/detectors/dedup.tsindex 07813e10..8b58ff35 100644--- a/src/core/brain/hygiene/detectors/dedup.ts+++ b/src/core/brain/hygiene/detectors/dedup.ts@@ -24,6 +24,7 @@ import { makeProvider } from "../../../search/embeddings/provider.ts";import { providerProducesVectors } from "../../../search/embeddings/contract.ts";import type { EmbeddingProvider } from "../../../search/embeddings/contract.ts";import { findMergeCandidates } from "../../merge-candidates.ts";+import { isMergeResolved, mergePointerLookup } from "../../page-meta/page-id.ts";import { brainDirs } from "../../paths.ts";import { parsePreference } from "../../preference.ts";import { hygieneFindingId } from "./id.ts";@@ -64,6 +65,8 @@ interface PrefCandidate {readonly topic: string;readonly scope: string | null;readonly principle: string;+ /** The `merged_into:` pointer the page carries, or `null`. */+ readonly mergedInto: string | null;}function listPreferenceCandidates(vault: string): PrefCandidate[] {@@ -79,13 +82,19 @@ function listPreferenceCandidates(vault: string): PrefCandidate[] {topic: pref.topic,scope: pref.scope ?? null,principle: pref.principle,+ mergedInto: pref.merged_into ?? null,});} catch {continue;}if (out.length >= DEDUP_CANDIDATE_CAP) break;}- return out;+ // A page a merge already resolved is not a duplicate to nominate again+ // (GitHub #180) - the same predicate `page-dedup` and the digest's+ // merge suggestions ask. Filtered after the cap rather than before it+ // so the bound stays a bound on files READ.+ const pointerOf = mergePointerLookup(out.map((c) => [c.id, c.mergedInto] as const));+ return out.filter((c) => !isMergeResolved(c.id, pointerOf));}function cosine(a: ReadonlyArray<number>, b: ReadonlyArray<number>): number {diff --git a/src/core/brain/merge-candidates.ts b/src/core/brain/merge-candidates.tsindex 76bd1a5c..988c96a4 100644--- a/src/core/brain/merge-candidates.ts+++ b/src/core/brain/merge-candidates.ts@@ -12,11 +12,16 @@* Callers that already parsed the preferences (digest, doctor)* pass them in via `opts.preferences` to avoid a second pass over* `Brain/preferences/`.+ *+ * Pages a merge already resolved are excluded, through the predicate+ * `page-dedup` and the hygiene dedup detector share+ * ({@link isMergeResolved}).*/import { existsSync, readdirSync } from "node:fs";import { join } from "node:path";+import { isMergeResolved, mergePointerLookup } from "./page-meta/page-id.ts";import { brainDirs } from "./paths.ts";import { parsePreference } from "./preference.ts";import { findSimilarPairs, tokenise } from "./similarity.ts";@@ -72,6 +77,7 @@ export function findMergeCandidates();}const prefs = opts.preferences ?? readPreferences(vault);+ const pointerOf = mergePointerLookup(prefs.map((p) => [p.id, p.merged_into ?? null] as const));const entries = [];for (const p of prefs) {@@ -81,6 +87,11 @@ export function findMergeCandidates() {continue;}+ // A page a merge already resolved is not a merge candidate again+ // (GitHub #180). Same predicate `page-dedup` and the hygiene dedup+ // detector ask, so the three surfaces cannot drift into three+ // different opinions of what "already merged" means.+ if (isMergeResolved(p.id, pointerOf)) continue;entries.push({id: p.id,bucketKey: `${p.topic}\x00${p.scope ?? ""}`,diff --git a/src/core/brain/page-dedup.ts b/src/core/brain/page-dedup.tsindex 4e4893b4..f5dc7eba 100644--- a/src/core/brain/page-dedup.ts+++ b/src/core/brain/page-dedup.ts@@ -30,7 +30,12 @@ import { compositeScopeKey, scopeFromFrontmatter } from "../scope-key.ts";import { matchScope, mayDescend, resolveVaultScope } from "../vault-scope/index.ts";import { pathCovers, type VaultScopeRules } from "../vault-scope/defaults.ts";import { brainDirs, BRAIN_ROOT_REL } from "./paths.ts";-import { setMergedInto } from "./page-meta/page-id.ts";+import {+ isMergeResolved,+ mergePointerLookup,+ readMergedInto,+ setMergedInto,+} from "./page-meta/page-id.ts";import { normalizeForDedup } from "./text/normalize.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";@@ -46,6 +51,12 @@ export interface PageRecord {readonly principle: string;/** Creation timestamp from frontmatter; missing entries fall back to mtime. */readonly createdAtMs: number;+ /**+ * The `merged_into:` pointer this page carries, or `null`. Present so+ * the grouping pass can tell a page a merge already resolved from one+ * still awaiting a decision, without a second read of the frontmatter.+ */+ readonly mergedInto: string | null;}export interface DedupCandidate {@@ -102,6 +113,7 @@ function readPageRecords(vault: string): PageRecord[] {topic,principle,createdAtMs: Number.isFinite(createdAtMs) ? createdAtMs : 0,+ mergedInto: readMergedInto(meta),});}}@@ -114,9 +126,20 @@ function readPageRecords(vault: string): PageRecord[] {* page with the oldest `created_at` (and the lowest id as* tie-breaker), which biases toward keeping the first-recorded* version of any rule.+ *+ * Pages a merge already resolved leave the pool before the canonical is+ * picked (GitHub #180). Without that filter the pass re-proposed every+ * merge it had ever applied, forever: the pointer it writes is invisible+ * to the key, so the finished cluster looked exactly like an untouched+ * one to this function and to the six surfaces that read through it.+ * That was not only noise - re-applying rewrote a deliberate+ * `merged_into` at a new canonical, and on pages with no `created_at`+ * (where the ordering falls back to an mtime the merge itself moved) the+ * second pass reversed the pair and wrote a cycle.*/export function findDuplicateCandidates(vault: string): DedupReport {const records = readPageRecords(vault);+ const pointerOf = mergePointerLookup(records.map((r) => [r.id, r.mergedInto] as const));const byKey = new Map<string, PageRecord[]>();for (const r of records) {if (r.key.trim().length === 0) continue; // skip empty / malformed pages@@ -126,17 +149,21 @@ export function findDuplicateCandidates(vault: string): DedupReport {}const candidates: DedupCandidate[] = [];for (const [key, group] of byKey) {- if (group.length < 2) continue;- group.sort((a, b) => {+ // Resolved members are dropped rather than the whole group skipped:+ // a third page that duplicates the canonical after an earlier merge+ // is still a real finding.+ const live = group.filter((r) => !isMergeResolved(r.id, pointerOf));+ if (live.length < 2) continue;+ live.sort((a, b) => {if (a.createdAtMs !== b.createdAtMs) return a.createdAtMs - b.createdAtMs;return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;});- const canonical = group[0]!;+ const canonical = live[0]!;candidates.push({key,- pages: Object.freeze(group.slice()),+ pages: Object.freeze(live.slice()),canonical,- secondaries: Object.freeze(group.slice(1)),+ secondaries: Object.freeze(live.slice(1)),});}candidates.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));@@ -568,6 +595,12 @@ export interface MergePageResult {* so the caller can report it. Idempotent: calling twice with the* same arguments leaves the merged-into pointer in place and yields* `wikilinksUpdated: 0` on the second call.+ *+ * Raises `MergeChainError` rather than writing when the secondary+ * already points at a different canonical, or when the canonical+ * already resolves back through the secondary. Neither is reachable+ * from {@link findDuplicateCandidates} any more, which is the point: a+ * merge this pass proposes is one it has established is still open.*/export function mergePage(vault: string,diff --git a/src/core/brain/page-meta/page-id.ts b/src/core/brain/page-meta/page-id.tsindex 2c21d0fc..24b194d9 100644--- a/src/core/brain/page-meta/page-id.ts+++ b/src/core/brain/page-meta/page-id.ts@@ -9,6 +9,13 @@* bounded at {@link MERGE_CHAIN_MAX_DEPTH} so a cycle (which should* never happen but is cheap to defend against) fails loud rather* than recursing forever.+ *+ * A cycle DID happen (GitHub #180), so "should never" is now enforced+ * where the pointer is written rather than only survived where it is+ * read: {@link setMergedInto} refuses a write that would close a loop+ * and refuses to silently repoint a page that is already merged.+ * {@link isMergeResolved} is the one definition of "already merged"+ * every duplicate detector in the project asks.*/import { existsSync, readFileSync } from "node:fs";@@ -21,10 +28,18 @@ import { assertVaultIdentityForWrite } from "../vault-identity.ts";export const MERGE_CHAIN_MAX_DEPTH = 5;+/**+ * What went wrong with a merge chain, or with a write that would have+ * broken one. `REPOINT` is a refusal rather than a corruption: the page+ * on disk is intact and the caller asked for something it has to say+ * out loud.+ */+export type MergeChainErrorCode = "CYCLE" | "DEPTH" | "MALFORMED" | "REPOINT";+export class MergeChainError extends Error {- readonly code: "CYCLE" | "DEPTH" | "MALFORMED";+ readonly code: MergeChainErrorCode;readonly id: string;- constructor(code: "CYCLE" | "DEPTH" | "MALFORMED", id: string, message: string) {+ constructor(code: MergeChainErrorCode, id: string, message: string) {super(message);this.name = "MergeChainError";this.code = code;@@ -44,6 +59,57 @@ export function readMergedInto(meta: Readonly<Record<string, unknown>>): stringreturn null;}+/**+ * What a page id points at, for a set of pages a caller already holds.+ *+ * The merge graph lives in frontmatter, so every question about it is+ * really a question about a pointer lookup. Passing the lookup rather+ * than a vault path is what lets one definition of "already resolved"+ * serve a detector working from records it has parsed and a writer+ * working from files on disk.+ */+export type MergePointerLookup = (id: string) => string | null;++/**+ * A {@link MergePointerLookup} over pages already in memory. Entries are+ * `[id, pointer]` pairs; a `null` or empty pointer means the page+ * carries none.+ */+export function mergePointerLookup(+ entries: Iterable<readonly [string, string | null]>,+): MergePointerLookup {+ const pointers = new Map<string, string>();+ for (const [id, target] of entries) {+ if (target !== null && target.trim().length > 0) pointers.set(id, target.trim());+ }+ return (id) => pointers.get(id) ?? null;+}++/**+ * True when a merge has already resolved this page into another one -+ * the single definition every duplicate detector asks (GitHub #180).+ *+ * The test is the presence of a pointer, not where the pointer leads,+ * and that IS the transitive answer rather than an approximation of one:+ * a chain (`b -> x -> a`), a pointer that leaves the group entirely, and+ * a pointer whose target nobody kept all begin with a pointer on this+ * page. A page that has been de-canonicalised is not a merge candidate+ * again whatever its canonical turned out to be, so following the chain+ * further could only ever confirm what the first hop already said.+ *+ * A DANGLING target is deliberately included. It means the merge+ * happened and the canonical was later lost - a lint problem, never a+ * licence to re-merge the page at some new canonical and overwrite the+ * record of the first decision.+ *+ * Where the chain leads does matter to the write seam, which has to+ * refuse a pointer that would close a loop; that question is+ * {@link resolveCanonicalId}'s, and it walks.+ */+export function isMergeResolved(id: string, pointerOf: MergePointerLookup): boolean {+ return pointerOf(id) !== null;+}+/*** Strict page-id format: `pref-<slug>` or `ret-<slug>` where the* slug matches the same `[a-z0-9-]+` shape `validateSlug` enforces.@@ -64,6 +130,67 @@ function pageIdToPath(vault: string, id: string): string | null {return join(dirs.retired, `${id}.md`);}+/**+ * The `merged_into:` pointer a page on disk carries, or `null`.+ *+ * `null` for a page id with no known prefix, for a target file nobody+ * kept, and for frontmatter that will not parse. All three end a walk+ * at the id that named them, which is what lets the caller say what is+ * wrong with THAT id rather than with the chain as a whole.+ */+function filePointerLookup(vault: string): MergePointerLookup {+ return (id) => {+ const path = pageIdToPath(vault, id);+ if (path === null || !existsSync(path)) return null;+ try {+ const [meta] = parseFrontmatter(path);+ return readMergedInto(meta);+ } catch {+ return null;+ }+ };+}++/** Why a {@link walkMergeChain} stopped where it did. */+type MergeWalkOutcome = "terminal" | "cycle" | "depth";++/** Where following one page's `merged_into:` chain led. */+interface MergeChainWalk {+ /** Ids visited in order, starting with the id the walk began at. */+ readonly visited: ReadonlyArray<string>;+ readonly outcome: MergeWalkOutcome;+ /**+ * The id the outcome is about: the terminal page, or the one the walk+ * came back to. Meaningless for `depth`, where no single id is at+ * fault.+ */+ readonly at: string;+}++/**+ * Follow a merge chain from `startId` through `pointerOf`, bounded at+ * {@link MERGE_CHAIN_MAX_DEPTH} hops.+ *+ * Reports rather than throws, because its two callers ask different+ * questions of the same walk: {@link resolveCanonicalId} wants the+ * destination and raises on a broken chain, while the write seam only+ * wants to know whether one particular id is already on the path.+ */+function walkMergeChain(startId: string, pointerOf: MergePointerLookup): MergeChainWalk {+ const visited: string[] = [];+ const seen = new Set<string>();+ let current = startId;+ for (let depth = 0; depth <= MERGE_CHAIN_MAX_DEPTH; depth++) {+ if (seen.has(current)) return { visited, outcome: "cycle", at: current };+ seen.add(current);+ visited.push(current);+ const next = pointerOf(current);+ if (next === null) return { visited, outcome: "terminal", at: current };+ current = next;+ }+ return { visited, outcome: "depth", at: startId };+}+/*** Follow the `merged_into:` chain from a starting page id to its* canonical destination. The walk terminates when a page has no@@ -74,53 +201,83 @@ function pageIdToPath(vault: string, id: string): string | null {* - `DEPTH` when the chain is longer than the cap.* - `MALFORMED` when an intermediate target id has neither `pref-`* nor `ret-` prefix.+ *+ * A DANGLING pointer is not an error: the id whose file is missing is+ * returned as terminal, so a reader sees the broken chain instead of a+ * throw on every read. An id with no known prefix reaches the same+ * terminal state - it can have no file and so no pointer - which is why+ * the malformed check reads the id the walk stopped at.*/export function resolveCanonicalId(vault: string, startId: string): string {- const visited = new Set<string>();- let current = startId;- for (let depth = 0; depth <= MERGE_CHAIN_MAX_DEPTH; depth++) {- if (visited.has(current)) {- throw new MergeChainError("CYCLE", current, `merge cycle detected at ${current}`);- }- visited.add(current);-- const path = pageIdToPath(vault, current);- if (path === null) {- throw new MergeChainError("MALFORMED", current, `page id has no known prefix: ${current}`);- }- if (!existsSync(path)) {- // Dangling pointer - the canonical page was moved or deleted.- // Treat the current id as terminal so we surface the broken- // chain to the caller without throwing on every read.- return current;- }- let meta: Record<string, unknown>;- try {- [meta] = parseFrontmatter(path);- } catch {- return current;- }- const next = readMergedInto(meta);- if (next === null) return current;- current = next;+ const walk = walkMergeChain(startId, filePointerLookup(vault));+ if (walk.outcome === "cycle") {+ throw new MergeChainError("CYCLE", walk.at, `merge cycle detected at ${walk.at}`);+ }+ if (walk.outcome === "depth") {+ throw new MergeChainError(+ "DEPTH",+ startId,+ `merge chain exceeds ${MERGE_CHAIN_MAX_DEPTH} hops starting at ${startId}`,+ );}- throw new MergeChainError(- "DEPTH",- startId,- `merge chain exceeds ${MERGE_CHAIN_MAX_DEPTH} hops starting at ${startId}`,- );+ if (!isValidPageId(walk.at)) {+ throw new MergeChainError("MALFORMED", walk.at, `page id has no known prefix: ${walk.at}`);+ }+ return walk.at;+}++export interface SetMergedIntoOptions {+ /**+ * Replace a pointer that names a DIFFERENT canonical, instead of+ * refusing. The caller is stating that it knows the page was already+ * merged somewhere and means to move it; nothing in this project sets+ * it today, and a batch pass must not.+ */+ readonly repoint?: boolean;+}++export interface SetMergedIntoResult {+ readonly secondary: string;+ /** The canonical the page points at now. */+ readonly canonical: string;+ /** What it pointed at before; `null` when it carried no pointer. */+ readonly previous: string | null;+ /** False when the page already said exactly this - no bytes written. */+ readonly changed: boolean;}/*** Stamp `merged_into: <canonical>` into the secondary page's* frontmatter and rewrite the file. The secondary keeps all other* fields and body content - the pointer is the only signal that a- * merge happened. Returns the resolved canonical id.+ * merge happened.** The caller is responsible for picking which side is the canonical* and which is the secondary; this function only writes the pointer.+ *+ * Two refusals, both added after GitHub #180 reproduced them (and both+ * kept at the seam that does the damage rather than only at the pass+ * that proposes a merge, since a proposer can be wrong and a second one+ * can be written):+ *+ * - A page already pointing at a DIFFERENT canonical is not+ * overwritten. That overwrite was silent, and it destroyed the+ * record of an operator's own merge decision on every re-run of a+ * batch pass. `repoint` is how a caller says it means to move one.+ * Re-setting the SAME canonical is not a repoint: it changes+ * nothing, writes nothing, and reports `changed: false`.+ * - A pointer whose canonical already resolves back through the+ * secondary is refused, because the pair would then resolve to+ * nothing at all: `resolveCanonicalId` raises `CYCLE` and+ * `lint --consolidate` loses the ability to repair any link to+ * either page.*/-export function setMergedInto(vault: string, secondaryId: string, canonicalId: string): string {+export function setMergedInto(+ vault: string,+ secondaryId: string,+ canonicalId: string,+ opts: SetMergedIntoOptions = {},+): SetMergedIntoResult {// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);if (!isValidPageId(secondaryId)) {@@ -149,32 +306,65 @@ export function setMergedInto(vault: string, secondaryId: string, canonicalId: sthrow new MergeChainError("MALFORMED", secondaryId, `secondary page not found: ${secondaryId}`);}const raw = readFileSync(secondaryPath, "utf8");- if (raw.startsWith("---\n")) {- // Inject `merged_into: <canonical>` right before the closing- // frontmatter fence. Idempotent: replace the existing line when- // present.- const end = raw.indexOf("\n---\n", 4);- if (end < 0) {- throw new MergeChainError(- "MALFORMED",- secondaryId,- `frontmatter has no closing fence: ${secondaryPath}`,- );- }- const head = raw.slice(0, end);- const tail = raw.slice(end);- const existingPattern = /^merged_into:\s.*$/m;- let nextHead: string;- if (existingPattern.test(head)) {- nextHead = head.replace(existingPattern, `merged_into: ${canonicalId}`);- } else {- nextHead = `${head}\nmerged_into: ${canonicalId}`;- }- const next = `${nextHead}${tail}`;- if (next !== raw) {- atomicWriteFileSync(secondaryPath, next);- }- return canonicalId;+ if (!raw.startsWith("---\n")) {+ throw new MergeChainError(+ "MALFORMED",+ secondaryId,+ `file has no frontmatter: ${secondaryPath}`,+ );}- throw new MergeChainError("MALFORMED", secondaryId, `file has no frontmatter: ${secondaryPath}`);+ // Inject `merged_into: <canonical>` right before the closing+ // frontmatter fence, replacing the existing line when present.+ const end = raw.indexOf("\n---\n", 4);+ if (end < 0) {+ throw new MergeChainError(+ "MALFORMED",+ secondaryId,+ `frontmatter has no closing fence: ${secondaryPath}`,+ );+ }+ const head = raw.slice(0, end);+ const tail = raw.slice(end);+ const existing = head.match(EXISTING_POINTER_RE);+ const previous = existing === null ? null : existing[1]!.trim();++ if (previous === canonicalId) {+ return Object.freeze({+ secondary: secondaryId,+ canonical: canonicalId,+ previous,+ changed: false,+ });+ }+ if (walkMergeChain(canonicalId, filePointerLookup(vault)).visited.includes(secondaryId)) {+ throw new MergeChainError(+ "CYCLE",+ secondaryId,+ `refusing to merge ${secondaryId} into ${canonicalId}: ${canonicalId} already resolves ` ++ `through ${secondaryId}`,+ );+ }+ if (previous !== null && opts.repoint !== true) {+ throw new MergeChainError(+ "REPOINT",+ secondaryId,+ `${secondaryId} is already merged into ${previous}; refusing to repoint it at ` ++ `${canonicalId} without an explicit repoint`,+ );+ }++ const nextHead =+ previous === null+ ? `${head}\nmerged_into: ${canonicalId}`+ : head.replace(EXISTING_POINTER_RE, `merged_into: ${canonicalId}`);+ atomicWriteFileSync(secondaryPath, `${nextHead}${tail}`);+ return Object.freeze({+ secondary: secondaryId,+ canonical: canonicalId,+ previous,+ changed: true,+ });}++/** The `merged_into:` line already in a page's frontmatter, if any. */+const EXISTING_POINTER_RE = /^merged_into:\s(.*)$/m;diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex 847fe8b8..e458f10c 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -78,6 +78,7 @@ import {isBrainMemoryLayer,} from "./types.ts";import { readCommitmentTier, validateCommitmentTier } from "./commitment.ts";+import { readMergedInto } from "./page-meta/page-id.ts";import type { PageLifecycle } from "./page-meta/lifecycle.ts";import type { PageTier } from "./page-meta/tier.ts";import { computeContentHash } from "./content-hash.ts";@@ -1009,6 +1010,7 @@ export function parsePreference(...(optionalScalarString(meta, "supersedes") !== undefined? { supersedes: optionalScalarString(meta, "supersedes") }: {}),+ ...(readMergedInto(meta) !== null ? { merged_into: readMergedInto(meta)! } : {}),...(readCommitmentTier(meta) !== null ? { commitment: readCommitmentTier(meta)! } : {}),...(meta["aliases"] !== undefined && Array.isArray(meta["aliases"])? { aliases: [...(meta["aliases"] as ReadonlyArray<string>)] }diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex db94fbbe..17acb78f 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -891,6 +891,16 @@ export interface BrainPreference {readonly freshness_trend?: string;/** Optional wikilink to a retired pref this one replaces. */readonly supersedes?: string;+ /**+ * Canonical page this one was merged into by the dedup pass, when it+ * carries the pointer. Read-only here: the pointer is written by+ * `setMergedInto`, never by the preference writer.+ *+ * Present on the parsed type so every duplicate detector can tell an+ * already-resolved page from a live one without a second walk of+ * `Brain/preferences/` (GitHub #180).+ */+ readonly merged_into?: string;/*** Optional commitment tier (Belief lifecycle suite, B3, t_e112c63c):* `exploring | leaning | decided | locked`. When set, the injectiondiff --git a/tests/cli/brain-page-dedup.test.ts b/tests/cli/brain-page-dedup.test.tsnew file mode 100644index 00000000..2d5eede5--- /dev/null+++ b/tests/cli/brain-page-dedup.test.ts@@ -0,0 +1,107 @@+/**+ * `o2b brain page-dedup` end to end, over the repro from GitHub #180.+ *+ * The issue was filed against the CLI, and the CLI is where the damage+ * happened: the second `--apply` of a cron loop re-merged a pair it had+ * already merged. The core tests own the predicate; this file owns what+ * an operator actually types.+ *+ * Claims pinned here:+ *+ * 1. The first `--apply` merges the pair and stamps `merged_into`.+ * 2. The dry run that follows it reports ZERO clusters for that pair -+ * the finished cluster is gone from the listing, not merely ranked+ * lower.+ * 3. A second `--apply` merges nothing and writes nothing. The fixture+ * carries no `created_at`, so the canonical ordering falls back to+ * the mtime the first merge moved - the exact condition under which+ * the second pass used to reverse the pair and write a merge cycle+ * into the vault.+ * 4. Neither page ends up in a cycle, so `brain lint --consolidate` can+ * still resolve every link to either of them.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-page-dedup-"));+ vault = join(tmp, "vault");+ mkdirSync(vault, { recursive: true });+ atomicWriteFileSync(join(tmp, "config.yaml"), `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath: join(tmp, "config.yaml") });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** One preference with no `created_at`, as a legacy / hand-authored page. */+function writePref(slug: string, body: string): string {+ const path = join(vault, "Brain", "preferences", `pref-${slug}.md`);+ writeFileSync(+ path,+ [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ "tags: [brain, brain/preference]",+ "topic: em-dashes",+ "_status: confirmed",+ "principle: never use em dashes",+ "unconfirmed_until: 2026-01-15T00:00:00Z",+ "---",+ "",+ body,+ "",+ ].join("\n"),+ "utf8",+ );+ return path;+}++function prefText(slug: string): string {+ return readFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), "utf8");+}++async function pageDedup(extra: string[]): Promise<Record<string, unknown>> {+ const res = await runCli(["brain", "page-dedup", "--vault", vault, "--json", ...extra]);+ expect(res.returncode).toBe(0);+ return JSON.parse(res.stdout) as Record<string, unknown>;+}++test("an applied merge is not proposed again, and a rerun writes no cycle", async () => {+ const aPath = writePref("a", "see also [[pref-b]]");+ writePref("b", "duplicate of the rule above");++ const first = await pageDedup(["--apply", "--yes"]);+ expect(first["clusters"]).toBe(1);+ expect(first["merged"]).toBe(1);+ expect(first["wikilinks_updated"]).toBe(1);+ expect(prefText("b")).toContain("merged_into: pref-a");++ // The wikilink rewrite touched `pref-a`, so its mtime is now newer+ // than `pref-b`'s - the ordering flip that used to reverse the pair.+ const second = await pageDedup([]);+ expect(second["candidates"]).toEqual([]);+ expect(second["scanned"]).toBe(2);++ const reapply = await pageDedup(["--apply", "--yes"]);+ expect(reapply["clusters"]).toBe(0);+ expect(reapply["merged"]).toBe(0);+ expect(readFileSync(aPath, "utf8")).not.toContain("merged_into");+ expect(prefText("b")).toContain("merged_into: pref-a");++ const lint = await runCli(["brain", "lint", "--consolidate", "--vault", vault]);+ expect(lint.returncode).toBe(0);+ expect(lint.stdout).not.toContain("merge cycle detected");+});diff --git a/tests/core/brain/hygiene-dedup.test.ts b/tests/core/brain/hygiene-dedup.test.tsindex 8398e86a..dbb64898 100644--- a/tests/core/brain/hygiene-dedup.test.ts+++ b/tests/core/brain/hygiene-dedup.test.ts@@ -16,7 +16,10 @@ import { join } from "node:path";import { tmpdir } from "node:os";import type { EmbeddingProvider } from "../../../src/core/search/embeddings/contract.ts";-import { detectSemanticDedup } from "../../../src/core/brain/hygiene/detectors/dedup.ts";+import {+ detectDedup,+ detectSemanticDedup,+} from "../../../src/core/brain/hygiene/detectors/dedup.ts";let vault: string;@@ -29,24 +32,21 @@ afterEach(() => {rmSync(vault, { recursive: true, force: true });});-function writePref(slug: string, topic: string, principle: string): void {- writeFileSync(- join(vault, "Brain", "preferences", `pref-${slug}.md`),- [- "---",- "kind: brain-preference",- `id: pref-${slug}`,- "tags: [brain, brain/preference]",- `topic: ${topic}`,- "_status: confirmed",- `principle: ${principle}`,- "created_at: 2026-01-01T00:00:00Z",- "unconfirmed_until: 2026-01-15T00:00:00Z",- "---",- "",- ].join("\n"),- "utf8",- );+function writePref(slug: string, topic: string, principle: string, mergedInto?: string): void {+ const lines = [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ "tags: [brain, brain/preference]",+ `topic: ${topic}`,+ "_status: confirmed",+ `principle: ${principle}`,+ "created_at: 2026-01-01T00:00:00Z",+ "unconfirmed_until: 2026-01-15T00:00:00Z",+ ];+ if (mergedInto !== undefined) lines.push(`merged_into: ${mergedInto}`);+ lines.push("---", "");+ writeFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), lines.join("\n"), "utf8");}function fixedVectorProvider(vectors: Readonly<Record<string, number[]>>): EmbeddingProvider {@@ -100,4 +100,35 @@ describe("detectSemanticDedup", () => {expect(result.method).toBe("lexical");expect(result.findings).toHaveLength(0);});++ test("a preference the merge already resolved is not nominated again", async () => {+ // Same fixture as the embedding test above, except `pref-b` now+ // carries the pointer a merge would have stamped on it. The hygiene+ // scan repeated this finding forever alongside `page-dedup` (GitHub+ // #180); both detectors now ask the one shared predicate.+ writePref("a", "writing-style", "Never use exclamation marks in docs");+ writePref("b", "doc-tone", "Do not use exclamation marks in documentation", "pref-a");+ const provider = fixedVectorProvider({+ "Never use exclamation marks in docs": [1, 0, 0],+ "Do not use exclamation marks in documentation": [0.999, 0.0447, 0],+ });+ const result = await detectSemanticDedup(vault, { provider });+ expect(result.findings).toHaveLength(0);+ });+});++describe("detectDedup", () => {+ test("nominates a near-duplicate pair", () => {+ writePref("x", "same-topic", "Collect the metrics before optimizing the code");+ writePref("y", "same-topic", "Collect the metrics before optimizing the code base");+ const findings = detectDedup(vault, { now: new Date(0) });+ expect(findings).toHaveLength(1);+ expect(findings[0]!.targets).toEqual(["pref-x", "pref-y"]);+ });++ test("a preference the merge already resolved is not nominated again", () => {+ writePref("x", "same-topic", "Collect the metrics before optimizing the code");+ writePref("y", "same-topic", "Collect the metrics before optimizing the code base", "pref-x");+ expect(detectDedup(vault, { now: new Date(0) })).toHaveLength(0);+ });});diff --git a/tests/core/brain/merge-candidates.test.ts b/tests/core/brain/merge-candidates.test.tsindex 1cc98ae3..d9310507 100644--- a/tests/core/brain/merge-candidates.test.ts+++ b/tests/core/brain/merge-candidates.test.ts@@ -15,7 +15,8 @@ import {JACCARD_MERGE_SUGGEST_THRESHOLD,MERGE_SUGGESTION_LIMIT,} from "../../../src/core/brain/merge-candidates.ts";-import { writePreference } from "../../../src/core/brain/preference.ts";+import { setMergedInto } from "../../../src/core/brain/page-meta/page-id.ts";+import { parsePreference, writePreference } from "../../../src/core/brain/preference.ts";import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";let vault: string;@@ -199,4 +200,47 @@ describe("findMergeCandidates", () => {const out = findMergeCandidates(vault);expect(out.length).toBe(MERGE_SUGGESTION_LIMIT);});++ test("a pair the merge already resolved does not surface again", () => {+ // The digest's `## Merge suggestions` section repeated an applied+ // merge forever, in step with `page-dedup` (GitHub #180). Both read+ // the one shared "already resolved" predicate now.+ makePref({+ slug: "imperative-commits",+ topic: "commits",+ principle: "Use imperative voice in commit subjects",+ });+ makePref({+ slug: "imperative-subjects",+ topic: "commits",+ principle: "Write commit subjects in imperative voice",+ });+ const before = findMergeCandidates(vault);+ expect(before.length).toBe(1);++ setMergedInto(vault, before[0]!.b, before[0]!.a);+ expect(findMergeCandidates(vault)).toEqual([]);+ });++ test("pre-parsed preferences carry the pointer the filter reads", () => {+ // The digest and the doctor hand their own parse in via+ // `opts.preferences` to avoid a second walk. That path has to reach+ // the same verdict as the filesystem one, or the fix holds on one+ // surface and not the other.+ makePref({+ slug: "imperative-commits",+ topic: "commits",+ principle: "Use imperative voice in commit subjects",+ });+ makePref({+ slug: "imperative-subjects",+ topic: "commits",+ principle: "Write commit subjects in imperative voice",+ });+ setMergedInto(vault, "pref-imperative-subjects", "pref-imperative-commits");+ const preferences = ["imperative-commits", "imperative-subjects"].map((slug) =>+ parsePreference(join(vault, "Brain", "preferences", `pref-${slug}.md`)),+ );+ expect(findMergeCandidates(vault, { preferences })).toEqual([]);+ });});diff --git a/tests/core/brain/page-dedup-scope.test.ts b/tests/core/brain/page-dedup-scope.test.tsindex 4b9d982e..5a90aea6 100644--- a/tests/core/brain/page-dedup-scope.test.ts+++ b/tests/core/brain/page-dedup-scope.test.ts@@ -4,6 +4,12 @@* (or scopeless, the pre-scope world) still collapses. Additive keying: a* scopeless page keys byte-identically to before, so existing global dedup* state is untouched and a rerun over old rows does not re-collapse.+ *+ * The N2 invariant below is STRENGTHENED by GitHub #180: a rerun used to+ * re-propose the pair it had just merged, and "no NEW cluster, no extra+ * secondary" was as much as this file asked of it. A merge now resolves+ * the secondary out of the candidate pool, so the rerun proposes nothing+ * at all - which satisfies "nothing new" strictly rather than by degrees.*/import { test, expect, beforeEach, afterEach } from "bun:test";@@ -74,18 +80,13 @@ test("N2 idempotency: a second dedup pass over pre-existing scopeless rows re-cofor (const s of c.secondaries) mergePage(vault, s.id, c.canonical.id);}- // Pass 2: rerun over the same rows. The scopeless scope key is unaffected- // by `merged_into`, so the same pair is found again - not a NEW cluster- // and not additional secondaries beyond the one already merged.+ // Pass 2: rerun over the same rows. The scope key is still unaffected by+ // `merged_into` - the pages keep grouping together - but the merged+ // secondary is no longer a candidate, so the finished cluster drops out+ // and the pass proposes nothing. Zero clusters is the strictest possible+ // reading of "re-collapses nothing new".const second = findDuplicateCandidates(vault);- expect(second.candidates).toHaveLength(1);- expect(second.candidates[0]!.secondaries.map((s) => s.id)).toEqual(- first.candidates[0]!.secondaries.map((s) => s.id),- );-- // Re-applying is a pure no-op: no additional wikilink rewrites happen.- const secondary = second.candidates[0]!.secondaries[0]!;- const canonical = second.candidates[0]!.canonical;- const rerun = mergePage(vault, secondary.id, canonical.id);- expect(rerun.wikilinksUpdated).toBe(0);+ expect(second.candidates).toHaveLength(0);+ // The pages are all still there - a merge is a pointer, not a delete.+ expect(second.scanned).toBe(2);});diff --git a/tests/core/brain/page-dedup.test.ts b/tests/core/brain/page-dedup.test.tsindex fdbbbd8b..c6ea1ad1 100644--- a/tests/core/brain/page-dedup.test.ts+++ b/tests/core/brain/page-dedup.test.ts@@ -8,6 +8,7 @@ import {mergePage,patchWikilinks,} from "../../../src/core/brain/page-dedup.ts";+import { MergeChainError } from "../../../src/core/brain/page-meta/page-id.ts";let vault: string;@@ -94,6 +95,92 @@ describe("findDuplicateCandidates", () => {});});+/**+ * A page a merge already resolved leaves the candidate pool (GitHub #180).+ *+ * Claims pinned here:+ *+ * 1. A secondary stamped `merged_into: <canonical>` is not proposed for+ * the same merge on the next scan - the cluster is finished.+ * 2. A pointer that leaves the group resolves the page just as one that+ * stays inside it does. The page was de-canonicalised; where its+ * canonical lives is not the dedup pass's question, and re-proposing+ * it is what silently overwrote an operator's merge decision.+ * 3. A chain that leaves the group and comes back (`b -> x -> a`, `x`+ * carrying unrelated text) resolves `b` as well - the predicate is+ * not a one-hop "points at a group member" test.+ * 4. A DANGLING pointer still means the page was resolved. A target+ * nobody kept is a lint problem, never a licence to re-merge.+ * 5. A group left with fewer than two live members proposes nothing.+ * 6. Resolving ONE member of a three-page group still proposes the+ * merge for the two that are live - the filter drops pages, it does+ * not abandon clusters.+ */+describe("findDuplicateCandidates skips pages a merge already resolved", () => {+ /** Rule text shared by every page meant to land in one group. */+ const DUPE = { topic: "writing", principle: "Use imperative voice" };++ test("a merged secondary is not proposed for the same merge again", () => {+ writePref("a", { ...DUPE, created_at: "2026-01-01T00:00:00Z" });+ writePref("b", { ...DUPE, created_at: "2026-02-01T00:00:00Z", merged_into: "pref-a" });+ const report = findDuplicateCandidates(vault);+ expect(report.scanned).toBe(2);+ expect(report.candidates).toHaveLength(0);+ });++ test("a pointer that leaves the group still resolves the page", () => {+ writePref("a", { ...DUPE, created_at: "2026-01-01T00:00:00Z" });+ writePref("b", { ...DUPE, created_at: "2026-02-01T00:00:00Z", merged_into: "pref-x" });+ // Unrelated text, so `pref-x` is in no group of its own and in+ // particular not in this one.+ writePref("x", {+ topic: "other",+ principle: "something else",+ created_at: "2025-01-01T00:00:00Z",+ });+ expect(findDuplicateCandidates(vault).candidates).toHaveLength(0);+ });++ test("a chain that leaves the group and comes back resolves the page", () => {+ writePref("a", { ...DUPE, created_at: "2026-01-01T00:00:00Z" });+ writePref("b", { ...DUPE, created_at: "2026-02-01T00:00:00Z", merged_into: "pref-x" });+ writePref("x", {+ topic: "other",+ principle: "something else",+ created_at: "2025-01-01T00:00:00Z",+ merged_into: "pref-a",+ });+ expect(findDuplicateCandidates(vault).candidates).toHaveLength(0);+ });++ test("a dangling pointer does not resurrect the page as a candidate", () => {+ writePref("a", { ...DUPE, created_at: "2026-01-01T00:00:00Z" });+ writePref("b", { ...DUPE, created_at: "2026-02-01T00:00:00Z", merged_into: "pref-gone" });+ expect(findDuplicateCandidates(vault).candidates).toHaveLength(0);+ });++ test("a group left with fewer than two live members proposes nothing", () => {+ writePref("a", { ...DUPE, created_at: "2026-01-01T00:00:00Z" });+ writePref("b", { ...DUPE, created_at: "2026-02-01T00:00:00Z", merged_into: "pref-a" });+ writePref("c", { ...DUPE, created_at: "2026-03-01T00:00:00Z", merged_into: "pref-a" });+ const report = findDuplicateCandidates(vault);+ expect(report.scanned).toBe(3);+ expect(report.candidates).toHaveLength(0);+ });++ test("one resolved member still leaves two live candidates", () => {+ writePref("a", { ...DUPE, created_at: "2026-01-01T00:00:00Z" });+ writePref("b", { ...DUPE, created_at: "2026-02-01T00:00:00Z", merged_into: "pref-a" });+ writePref("c", { ...DUPE, created_at: "2026-03-01T00:00:00Z" });+ const report = findDuplicateCandidates(vault);+ expect(report.candidates).toHaveLength(1);+ const candidate = report.candidates[0]!;+ expect(candidate.canonical.id).toBe("pref-a");+ expect(candidate.secondaries.map((s) => s.id)).toEqual(["pref-c"]);+ expect(candidate.pages.map((p) => p.id)).toEqual(["pref-a", "pref-c"]);+ });+});+describe("patchWikilinks", () => {test("rewrites plain [[oldTarget]] references", () => {const log = join(vault, "Brain", "log", "2026-05-25.md");@@ -192,4 +279,20 @@ describe("mergePage", () => {const second = mergePage(vault, "pref-dup", "pref-canon");expect(second.wikilinksUpdated).toBe(0);});++ test("refuses the reverse merge that would close a cycle", () => {+ // The GitHub #180 destroyer, at the seam that did the damage. Pages+ // with no `created_at` order by mtime, and the merge moves the+ // canonical's mtime, so a second pass over this pair used to pick+ // the reverse direction and write `a -> b` on top of `b -> a`.+ // `findDuplicateCandidates` no longer proposes it; the writer+ // refuses it whoever asks.+ writePref("a", { topic: "x", principle: "y" });+ writePref("b", { topic: "x", principle: "y" });+ mergePage(vault, "pref-b", "pref-a");+ const aPath = join(vault, "Brain", "preferences", "pref-a.md");+ const before = readFileSync(aPath, "utf8");+ expect(() => mergePage(vault, "pref-a", "pref-b")).toThrow(MergeChainError);+ expect(readFileSync(aPath, "utf8")).toBe(before);+ });});diff --git a/tests/core/brain/page-meta/page-id.test.ts b/tests/core/brain/page-meta/page-id.test.tsindex 8ab1857f..22f74951 100644--- a/tests/core/brain/page-meta/page-id.test.ts+++ b/tests/core/brain/page-meta/page-id.test.ts@@ -123,20 +123,93 @@ describe("setMergedInto", () => {expect(readFileSync(path, "utf8")).toContain("merged_into: pref-canonical");});- test("updates an existing pointer", () => {+ test("reports the write it performed", () => {+ writePref("canonical", { topic: "x", principle: "y" });+ writePref("secondary", { topic: "x", principle: "y" });+ const result = setMergedInto(vault, "pref-secondary", "pref-canonical");+ expect(result).toEqual({+ secondary: "pref-secondary",+ canonical: "pref-canonical",+ previous: null,+ changed: true,+ });+ });++ test("refuses to repoint a page that already points somewhere else", () => {+ // This used to be `updates an existing pointer`, and the silent+ // overwrite it pinned is how a second `page-dedup --apply` destroyed+ // an operator's deliberate merge (GitHub #180).writePref("a", { topic: "x", principle: "y" });writePref("b", { topic: "x", principle: "y" });- const path = writePref("c", {- topic: "x",- principle: "y",- merged_into: "pref-a",- });- setMergedInto(vault, "pref-c", "pref-b");+ const path = writePref("c", { topic: "x", principle: "y", merged_into: "pref-a" });+ const before = readFileSync(path, "utf8");+ try {+ setMergedInto(vault, "pref-c", "pref-b");+ throw new Error("expected throw");+ } catch (e) {+ expect(e).toBeInstanceOf(MergeChainError);+ expect((e as MergeChainError).code).toBe("REPOINT");+ }+ expect(readFileSync(path, "utf8")).toBe(before);+ });++ test("repoints when the caller asks for it explicitly", () => {+ writePref("a", { topic: "x", principle: "y" });+ writePref("b", { topic: "x", principle: "y" });+ const path = writePref("c", { topic: "x", principle: "y", merged_into: "pref-a" });+ const result = setMergedInto(vault, "pref-c", "pref-b", { repoint: true });+ expect(result.previous).toBe("pref-a");+ expect(result.changed).toBe(true);const yaml = readFileSync(path, "utf8");expect(yaml).toContain("merged_into: pref-b");expect(yaml).not.toContain("merged_into: pref-a");});+ test("re-setting the same target changes nothing and says so", () => {+ writePref("a", { topic: "x", principle: "y" });+ const path = writePref("b", { topic: "x", principle: "y", merged_into: "pref-a" });+ const before = readFileSync(path, "utf8");+ const result = setMergedInto(vault, "pref-b", "pref-a");+ expect(result.previous).toBe("pref-a");+ expect(result.changed).toBe(false);+ expect(readFileSync(path, "utf8")).toBe(before);+ });++ test("refuses a pointer that would close a cycle", () => {+ // The mtime-flip destroyer: `pref-b` is already merged into+ // `pref-a`, and a second pass that reversed the pair used to write+ // `pref-a -> pref-b` on top of it, leaving both pages unresolvable.+ writePref("a", { topic: "x", principle: "y" });+ writePref("b", { topic: "x", principle: "y", merged_into: "pref-a" });+ const path = join(vault, "Brain", "preferences", "pref-a.md");+ const before = readFileSync(path, "utf8");+ try {+ setMergedInto(vault, "pref-a", "pref-b");+ throw new Error("expected throw");+ } catch (e) {+ expect(e).toBeInstanceOf(MergeChainError);+ expect((e as MergeChainError).code).toBe("CYCLE");+ }+ expect(readFileSync(path, "utf8")).toBe(before);+ expect(resolveCanonicalId(vault, "pref-b")).toBe("pref-a");+ });++ test("refuses a cycle reached through a longer chain", () => {+ writePref("a", { topic: "x", principle: "y" });+ writePref("c", { topic: "x", principle: "y", merged_into: "pref-a" });+ writePref("b", { topic: "x", principle: "y", merged_into: "pref-c" });+ try {+ setMergedInto(vault, "pref-a", "pref-b");+ throw new Error("expected throw");+ } catch (e) {+ expect(e).toBeInstanceOf(MergeChainError);+ expect((e as MergeChainError).code).toBe("CYCLE");+ }+ expect(readFileSync(join(vault, "Brain", "preferences", "pref-a.md"), "utf8")).not.toContain(+ "merged_into",+ );+ });+test("rejects self-pointer", () => {writePref("a", { topic: "x", principle: "y" });expect(() => setMergedInto(vault, "pref-a", "pref-a")).toThrow(MergeChainError);