Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): align Observer A Path B merge inputs at the doc boundary (#1799)
Nick Gomez8aaea36b92da
diff --git a/.changeset/pathb-doc-boundary-alignment.md b/.changeset/pathb-doc-boundary-alignment.mdnew file mode 100644index 000000000..a99b2c2b9--- /dev/null+++ b/.changeset/pathb-doc-boundary-alignment.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Editing near the top of a frontmatter document can no longer duplicate the first paragraph or silently delete the blank line after the frontmatter. When a WYSIWYG edit raced an unabsorbed source-mode edit, the server's three-way merge received inputs from two different byte-spaces — the editor-derived input structurally lacks the blank line between the frontmatter close fence and the body — so the line-based merge misread the user's edited first paragraph as replacing that blank line and resurrected a second copy of it, deleted the blank line from the document, and could double a trailing-whitespace keystroke on the close fence. All three merge inputs are now projected into one doc-boundary byte-space before merging, and the document's own boundary bytes are re-attached to the result verbatim — blank lines you typed (or deleted) after the frontmatter survive merges byte-exactly.diff --git a/packages/app/tests/integration/c13-pathb-doc-boundary.test.ts b/packages/app/tests/integration/c13-pathb-doc-boundary.test.tsnew file mode 100644index 000000000..5bb29adc7--- /dev/null+++ b/packages/app/tests/integration/c13-pathb-doc-boundary.test.ts@@ -0,0 +1,99 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { setTimeout as wait } from 'node:timers/promises';+import * as Y from 'yjs';+import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';+import {+ agentWriteMd,+ createTestClients,+ createTestServer,+ pollUntil,+ serializeFragment,+ type TestServer,+} from './test-harness';++let server: TestServer;++beforeAll(async () => {+ server = await createTestServer();+}, HARNESS_BOOT_TIMEOUT_MS);++afterAll(async () => {+ await server.cleanup();+});++const FM = '---\ntitle: Boundary alignment\n---\n';+const RAW = `${FM}\nFirst paragraph body.\n\nSecond paragraph stays.\n`;+const EXPECTED_CONVERGED = `${FM}\nZFirst paragraph body. \n\nSecond paragraph stays.\n`;++function findTextNodeContaining(+ node: Y.XmlFragment | Y.XmlElement,+ needle: string,+): Y.XmlText | null {+ for (let i = 0; i < node.length; i++) {+ const child = node.get(i);+ if (child instanceof Y.XmlText && child.toString().includes(needle)) return child;+ if (child instanceof Y.XmlElement) {+ const found = findTextNodeContaining(child, needle);+ if (found) return found;+ }+ }+ return null;+}++describe('C13: Path B doc-boundary alignment across clients', () => {+ test('concurrent source + WYSIWYG edits on an FM doc — no duplication, boundary blank line survives on every client', async () => {+ const docName = `c13-boundary-${crypto.randomUUID()}`;+ const clients = await createTestClients(server.port, {+ count: 2,+ docName,+ perClientOptions: { skipInvariantWatcher: true },+ });+ try {+ await agentWriteMd(server.port, RAW, { docName, position: 'replace' });+ await pollUntil(() => clients.every((c) => c.ytext.toString() === RAW), 5000);+ await wait(500);++ const b = clients[1];+ b.doc.transact(() => {+ b.ytext.insert(+ b.ytext.toString().indexOf('First paragraph body.') + 'First paragraph body.'.length,+ ' ',+ );+ });+ await pollUntil(+ () => clients.every((c) => c.ytext.toString().includes('First paragraph body. \n')),+ 5000,+ );+ await wait(300);++ const a = clients[0];+ a.doc.transact(() => {+ const textNode = findTextNodeContaining(a.fragment, 'First paragraph');+ if (!textNode) throw new Error('no fragment text node containing "First paragraph"');+ textNode.insert(0, 'Z');+ });+ await pollUntil(() => clients.every((c) => c.ytext.toString().includes('ZFirst')), 5000);+ await wait(500);+ await pollUntil(+ () => clients.every((c) => serializeFragment(c.fragment).includes('ZFirst paragraph body')),+ 5000,+ );++ for (const c of clients) {+ const text = c.ytext.toString();+ const para1Count = text.split('First paragraph body').length - 1;+ expect(para1Count).toBe(1);+ expect(text).toContain('---\n\n');+ expect(text).toContain('ZFirst paragraph body. \n');+ expect(text).toBe(EXPECTED_CONVERGED);++ const fragMd = serializeFragment(c.fragment);+ expect(fragMd.split('First paragraph body').length - 1).toBe(1);+ expect(fragMd).toContain('ZFirst paragraph body');+ }+ expect(clients[0].ytext.toString()).toBe(clients[1].ytext.toString());+ } finally {+ for (const c of clients) await c.cleanup();+ }+ });+});diff --git a/packages/core/src/bridge/doc-boundary-space.test.ts b/packages/core/src/bridge/doc-boundary-space.test.tsnew file mode 100644index 000000000..116d93bab--- /dev/null+++ b/packages/core/src/bridge/doc-boundary-space.test.ts@@ -0,0 +1,166 @@+import { describe, expect, test } from 'bun:test';+import {+ projectMergeBoundarySpace,+ reattachLeadingDocBoundary,+ splitLeadingDocBoundary,+} from './doc-boundary-space.ts';++const FM = '---\ntitle: Boundary\n---\n';++describe('splitLeadingDocBoundary', () => {+ test('FM doc with the canonical single blank line', () => {+ const split = splitLeadingDocBoundary(`${FM}\nBody line.\n`);+ expect(split.boundary).toBe('\n');+ expect(split.text).toBe(`${FM}Body line.\n`);+ });++ test('FM doc with no boundary is identity', () => {+ const split = splitLeadingDocBoundary(`${FM}Body line.\n`);+ expect(split.boundary).toBe('');+ expect(split.text).toBe(`${FM}Body line.\n`);+ });++ test('multi-newline run is captured greedily and verbatim', () => {+ const split = splitLeadingDocBoundary(`${FM}\n\n\nBody.\n`);+ expect(split.boundary).toBe('\n\n\n');+ expect(split.text).toBe(`${FM}Body.\n`);+ });++ test('CRLF run', () => {+ const fmCrlf = '---\r\ntitle: x\r\n---\r\n';+ const split = splitLeadingDocBoundary(`${fmCrlf}\r\n\r\nBody.\r\n`);+ expect(split.boundary).toBe('\r\n\r\n');+ expect(split.text).toBe(`${fmCrlf}Body.\r\n`);+ });++ test('no FM region: doc-start run is the boundary', () => {+ const split = splitLeadingDocBoundary('\n\nBody only.\n');+ expect(split.boundary).toBe('\n\n');+ expect(split.text).toBe('Body only.\n');+ });++ test('FM-only doc: boundary is the run after the close fence, body empty', () => {+ const split = splitLeadingDocBoundary(`${FM}\n`);+ expect(split.boundary).toBe('\n');+ expect(split.text).toBe(FM);+ });++ test('empty string is identity', () => {+ expect(splitLeadingDocBoundary('')).toEqual({ boundary: '', text: '' });+ });++ test('no-split guard: doc-start run shadowing an FM-shaped block is refused', () => {+ const shadowed = `\n${FM}Body.\n`;+ expect(splitLeadingDocBoundary(shadowed)).toEqual({ boundary: '', text: shadowed });+ });+});++describe('reattachLeadingDocBoundary', () => {+ test('empty boundary is identity', () => {+ expect(reattachLeadingDocBoundary(`${FM}Body.\n`, '')).toBe(`${FM}Body.\n`);+ });++ test('re-inserts between FM region and body', () => {+ expect(reattachLeadingDocBoundary(`${FM}Body.\n`, '\n')).toBe(`${FM}\nBody.\n`);+ });++ test('no FM region: attaches at doc start', () => {+ expect(reattachLeadingDocBoundary('Body.\n', '\n\n')).toBe('\n\nBody.\n');+ });++ test('FM-only doc: boundary becomes the trailing run', () => {+ expect(reattachLeadingDocBoundary(FM, '\n')).toBe(`${FM}\n`);+ });+});++describe('projectMergeBoundarySpace', () => {+ test('FM doc with the canonical blank line is unchanged', () => {+ expect(projectMergeBoundarySpace(`${FM}\nBody.\n`)).toBe(`${FM}\nBody.\n`);+ });++ test('FM doc without a boundary gains the single separator', () => {+ expect(projectMergeBoundarySpace(`${FM}Body.\n`)).toBe(`${FM}\nBody.\n`);+ });++ test('multi-newline boundary normalizes to one separator', () => {+ expect(projectMergeBoundarySpace(`${FM}\n\n\nBody.\n`)).toBe(`${FM}\nBody.\n`);+ });++ test('FM-less doc has its doc-start run stripped', () => {+ expect(projectMergeBoundarySpace('\n\nBody only.\n')).toBe('Body only.\n');+ });++ test('FM-less doc without a run is unchanged', () => {+ expect(projectMergeBoundarySpace('Body only.\n')).toBe('Body only.\n');+ });++ test('empty string is unchanged', () => {+ expect(projectMergeBoundarySpace('')).toBe('');+ });++ test('guard-refused shape passes through unchanged', () => {+ const shadowed = `\n${FM}Body.\n`;+ expect(projectMergeBoundarySpace(shadowed)).toBe(shadowed);+ });++ test('idempotent and content-preserving outside the boundary slot', () => {+ const inputs = [+ `${FM}\nBody.\n`,+ `${FM}Body.\n`,+ `${FM}\n\n\nBody.\n`,+ '\nBody only.\n',+ 'Body only.\n',+ `${FM}\n|a|b|\n|-|-|\n`,+ ];+ for (const x of inputs) {+ const once = projectMergeBoundarySpace(x);+ expect(projectMergeBoundarySpace(once)).toBe(once);+ expect(splitLeadingDocBoundary(once).text).toBe(splitLeadingDocBoundary(x).text);+ }+ });+});++describe('round-trip law: reattach(split(x).text, split(x).boundary) === x', () => {+ const fms = [+ '',+ FM,+ '---\n---\n', // empty FM block+ '--- \ntitle: ws fence\n---\t\n', // whitespace-bearing fences (post-#1783 recognition)+ '---\r\ntitle: crlf\r\n---\r\n',+ ];+ const boundaries = ['', '\n', '\n\n', '\n\n\n\n', '\r\n', '\r\n\r\n'];+ const bodies = [+ '',+ 'One paragraph.\n',+ 'First paragraph body. \n\nSecond paragraph stays.\n',+ '|a|b|\n|-|-|\n|c|d|\n', // un-padded NG-class table — storage never sanitizes+ '---\nlooks like FM\n---\nbut is body\n',+ 'no trailing newline',+ ];++ test('holds over composed fm × boundary × body shapes', () => {+ for (const fm of fms) {+ for (const boundary of boundaries) {+ for (const body of bodies) {+ const x = fm + boundary + body;+ const split = splitLeadingDocBoundary(x);+ expect(reattachLeadingDocBoundary(split.text, split.boundary)).toBe(x);+ }+ }+ }+ });++ test('stripped text never begins its body with a newline (no boundary doubling)', () => {+ for (const fm of fms) {+ for (const boundary of boundaries) {+ for (const body of bodies) {+ const split = splitLeadingDocBoundary(fm + boundary + body);+ const resplit = splitLeadingDocBoundary(split.text);+ if (split.boundary !== '') {+ expect(resplit.boundary).toBe('');+ }+ }+ }+ }+ });+});diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsnew file mode 100644index 000000000..8890f6739--- /dev/null+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -0,0 +1,31 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';++const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;++export interface DocBoundarySplit {+ boundary: string;+ text: string;+}++export function splitLeadingDocBoundary(text: string): DocBoundarySplit {+ const { frontmatter, body } = stripFrontmatter(text);+ const match = body.match(LEADING_BOUNDARY_RE);+ if (!match) return { boundary: '', text };+ const strippedBody = body.slice(match[0].length);+ if (frontmatter === '' && FRONTMATTER_RE.test(strippedBody)) {+ return { boundary: '', text };+ }+ return { boundary: match[0], text: frontmatter + strippedBody };+}++export function reattachLeadingDocBoundary(text: string, boundary: string): string {+ if (boundary === '') return text;+ const { frontmatter, body } = stripFrontmatter(text);+ return frontmatter + boundary + body;+}++export function projectMergeBoundarySpace(text: string): string {+ const stripped = splitLeadingDocBoundary(text).text;+ if (stripFrontmatter(stripped).frontmatter === '') return stripped;+ return reattachLeadingDocBoundary(stripped, '\n');+}diff --git a/packages/core/src/bridge/index.ts b/packages/core/src/bridge/index.tsindex 8024ca5af..654e99a6f 100644--- a/packages/core/src/bridge/index.ts+++ b/packages/core/src/bridge/index.ts@@ -24,6 +24,12 @@ export {toBridgeInvariantLog,} from './bridge-invariant.ts';export { type DiffChange, diffLinesFast } from './diff-lines.ts';+export {+ type DocBoundarySplit,+ projectMergeBoundarySpace,+ reattachLeadingDocBoundary,+ splitLeadingDocBoundary,+} from './doc-boundary-space.ts';export {applyPatchToFm,applyPathDeleteToFm,diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex a5d524ce3..1bd2b2373 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -25,6 +25,7 @@ export {bindFrontmatterDoc,classifySeverity,type DiffChange,+ type DocBoundarySplit,defaultScheduler,detectAppliedToleranceClasses,detectFmRegion,@@ -54,11 +55,14 @@ export {type ParsedFmRegion,parseFencedFmRegion,parseFmRegion,+ projectMergeBoundarySpace,readFmKeys,readFmMap,readFmRegionWithError,+ reattachLeadingDocBoundary,type Scheduler,setToleranceTelemetryHook,+ splitLeadingDocBoundary,type ToleranceClassSeverity,type ToleranceFireRecord,type ToleranceTelemetryHook,diff --git a/packages/server/src/server-observers.path-b-doc-boundary.test.ts b/packages/server/src/server-observers.path-b-doc-boundary.test.tsnew file mode 100644index 000000000..1764d223d--- /dev/null+++ b/packages/server/src/server-observers.path-b-doc-boundary.test.ts@@ -0,0 +1,311 @@+/**+ * Path B merge-input doc-boundary alignment — user-outcome contract.+ *+ * mergeThreeWay is a line-based diff3 over raw bytes: its three inputs+ * (baseline, userText, agentText) must share ONE doc-boundary byte-space.+ * The Path B compose in `runObserverASyncImpl` builds userText from+ * `prependFrontmatter(fm, serialize(fragment))` — a live Y.XmlFragment+ * structurally cannot carry the `sourceDocBoundary` doc-node attr (pinned by+ * packages/app/tests/fidelity/doc-boundary-fragment-drop.test.ts), so the+ * user's blank line between the FM close fence and the body is missing from+ * userText while baseline/agentText (raw Y.Text bytes) carry it. diff3's+ * line alignment then reads the user's edited first body line into the+ * blank-line slot and presents the original paragraph as user-deleted; the+ * conflict resolution resurrects the agent's copy next to the user's copy.+ *+ * These tests pin the user-visible outcome on the real observer pipeline+ * (real setupServerObservers + composeAndWriteRawBody on a raw Y.Doc):+ * after an in-tolerance W2 source edit (unabsorbed — Observer B early-exits+ * within normalizeBridge tolerance) plus a WYSIWYG edit, the merged Y.Text+ * must carry BOTH edits verbatim and fabricate nothing:+ * (a) no content duplication,+ * (b) the user's doc-boundary blank line survives (storage never+ * sanitizes — the blank line is user bytes in the body region),+ * (c) a fence-line keystroke survives byte-exactly (`--- ` stays `--- `,+ * not `--- `). These byte-exact pins are the strengthening+ * counterpart to the deliberately-weakened class pins+ * (`/^---[ \t]+$/`) in server-observers.fm-fence-hazard.test.ts —+ * additive; the class pins stay as-is.+ *+ * The expected bytes are defined by the aligned-input oracle: feeding+ * mergeThreeWay the same edits with all three inputs in one boundary+ * byte-space merges cleanly with both edits landing verbatim.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import {+ BridgeMergeContentLossError,+ MarkdownManager,+ prependFrontmatter,+ reattachLeadingDocBoundary,+ sharedExtensions,+ splitLeadingDocBoundary,+ stripFrontmatter,+} from '@inkeep/open-knowledge-core';+import { getSchema } from '@tiptap/core';+import * as Y from 'yjs';+import { composeAndWriteRawBody } from './bridge-intake.ts';+import { __resetBridgeWatchdogForTests } from './bridge-watchdog.ts';+import { FILE_WATCHER_ORIGIN } from './external-change.ts';+import { getMetrics, resetMetrics } from './metrics.ts';+import { setupServerObservers } from './server-observers.ts';++const mdManager = new MarkdownManager({ extensions: sharedExtensions });+const schema = getSchema(sharedExtensions);++const USER_TYPING_ORIGIN = {+ source: 'connection' as const,+ context: { origin: 'user-typing' },+};++const FM = '---\ntitle: Boundary alignment\n---\n';+const RAW = `${FM}\nFirst paragraph body.\n\nSecond paragraph stays.\n`;++function canonicalOf(raw: string): string {+ const { frontmatter, body } = stripFrontmatter(raw);+ return prependFrontmatter(frontmatter, mdManager.serialize(mdManager.parseWithFallback(body)));+}++function seedThenAttach(raw: string, docName: string) {+ __resetBridgeWatchdogForTests();+ resetMetrics();+ const doc = new Y.Doc();+ const xmlFragment = doc.getXmlFragment('default');+ const ytext = doc.getText('source');+ doc.transact(() => {+ composeAndWriteRawBody(doc, raw, 'file-watcher');+ }, FILE_WATCHER_ORIGIN);+ const cleanup = setupServerObservers({ doc, xmlFragment, ytext, mdManager, schema, docName });+ return { doc, xmlFragment, ytext, cleanup };+}++function findTextNodeContaining(+ node: Y.XmlFragment | Y.XmlElement,+ needle: string,+): Y.XmlText | null {+ for (let i = 0; i < node.length; i++) {+ const child = node.get(i);+ if (child instanceof Y.XmlText && child.toString().includes(needle)) return child;+ if (child instanceof Y.XmlElement) {+ const found = findTextNodeContaining(child, needle);+ if (found) return found;+ }+ }+ return null;+}++function typeIntoParagraph(doc: Y.Doc, xmlFragment: Y.XmlFragment, needle: string): void {+ doc.transact(() => {+ const textNode = findTextNodeContaining(xmlFragment, needle);+ if (!textNode) throw new Error(`no fragment text node containing ${JSON.stringify(needle)}`);+ textNode.insert(0, 'Z');+ }, USER_TYPING_ORIGIN);+}++function typeIntoSource(doc: Y.Doc, ytext: Y.Text, index: number, ws: string): void {+ doc.transact(() => {+ ytext.insert(index, ws);+ }, USER_TYPING_ORIGIN);+}++describe('Path B doc-boundary alignment: diverged-branch merge fabrication', () => {+ test('precondition: the fixture is round-trip byte-stable', () => {+ expect(canonicalOf(RAW)).toBe(RAW);+ });++ test('first body paragraph is not duplicated; both edits land verbatim', () => {+ const { doc, xmlFragment, ytext, cleanup } = seedThenAttach(RAW, 'pathb-boundary-dup');+ expect(ytext.toString()).toBe(RAW);++ typeIntoSource(+ doc,+ ytext,+ RAW.indexOf('First paragraph body.') + 'First paragraph body.'.length,+ ' ',+ );+ typeIntoParagraph(doc, xmlFragment, 'First paragraph');++ const finalText = ytext.toString();+ const para1Count = finalText.split('First paragraph body').length - 1;+ expect(para1Count).toBe(1);+ expect(finalText).toContain('ZFirst paragraph body. \n');+ expect(finalText).toContain('Second paragraph stays.');++ cleanup();+ });++ test('the user doc-boundary blank line survives the merge byte-exactly', () => {+ const { doc, xmlFragment, ytext, cleanup } = seedThenAttach(RAW, 'pathb-boundary-blank');++ typeIntoSource(+ doc,+ ytext,+ RAW.indexOf('First paragraph body.') + 'First paragraph body.'.length,+ ' ',+ );+ typeIntoParagraph(doc, xmlFragment, 'First paragraph');++ const finalText = ytext.toString();+ expect(finalText).toContain('---\n\n');+ expect(finalText).toBe(`${FM}\nZFirst paragraph body. \n\nSecond paragraph stays.\n`);++ cleanup();+ });+});++interface CloseFenceVariant {+ name: string;+ slug: string;+ ws: string;+ editNeedle: string;+ expectedFinal: string;+}++const CLOSE_FENCE_VARIANTS: CloseFenceVariant[] = [+ {+ name: 'trailing space, adjacent WYSIWYG edit',+ slug: 'space-adjacent',+ ws: ' ',+ editNeedle: 'First paragraph',+ expectedFinal: `---\ntitle: Boundary alignment\n--- \n\nZFirst paragraph body.\n\nSecond paragraph stays.\n`,+ },+ {+ name: 'trailing tab, adjacent WYSIWYG edit',+ slug: 'tab-adjacent',+ ws: '\t',+ editNeedle: 'First paragraph',+ expectedFinal: `---\ntitle: Boundary alignment\n---\t\n\nZFirst paragraph body.\n\nSecond paragraph stays.\n`,+ },+ {+ name: 'trailing space, distal WYSIWYG edit',+ slug: 'space-distal',+ ws: ' ',+ editNeedle: 'Second paragraph',+ expectedFinal: `---\ntitle: Boundary alignment\n--- \n\nFirst paragraph body.\n\nZSecond paragraph stays.\n`,+ },+ {+ name: 'trailing tab, distal WYSIWYG edit',+ slug: 'tab-distal',+ ws: '\t',+ editNeedle: 'Second paragraph',+ expectedFinal: `---\ntitle: Boundary alignment\n---\t\n\nFirst paragraph body.\n\nZSecond paragraph stays.\n`,+ },+];++describe('Path B doc-boundary alignment: close-fence keystroke byte-exactness', () => {+ for (const variant of CLOSE_FENCE_VARIANTS) {+ test(`${variant.name}: keystroke survives verbatim, no fabricated whitespace`, () => {+ const { doc, xmlFragment, ytext, cleanup } = seedThenAttach(+ RAW,+ `pathb-close-fence-${variant.slug}`,+ );++ typeIntoSource(doc, ytext, RAW.indexOf('\n---\n') + '\n---'.length, variant.ws);+ expect(ytext.toString()).toContain(`---${variant.ws}\n`);++ typeIntoParagraph(doc, xmlFragment, variant.editNeedle);++ const finalText = ytext.toString();+ const closeFence = finalText+ .split('\n')+ .slice(1)+ .find((line) => /^---[ \t]*$/.test(line));+ expect(closeFence).toBe(`---${variant.ws}`);+ expect(finalText).toBe(variant.expectedFinal);++ cleanup();+ });+ }+});++describe('in-sync residual merge (sibling router branch) — byte-preservation guard', () => {+ test('NG-residual doc: WYSIWYG cell edit preserves un-padded table bytes and boundary blank line', () => {+ const rawResidual = `${FM}\n|a|b|\n|-|-|\n|1|2|\n\nSecond paragraph stays.\n`;+ const { doc, xmlFragment, ytext, cleanup } = seedThenAttach(rawResidual, 'pathb-residual-ng');++ typeIntoParagraph(doc, xmlFragment, 'a');++ expect(ytext.toString()).toBe(`${FM}\n|Za|b|\n|-|-|\n|1|2|\n\nSecond paragraph stays.\n`);++ cleanup();+ });+});++describe('Path B doc-boundary alignment: content-loss recovery arm re-projects the boundary', () => {+ const ENV_KEYS = ['NODE_ENV', 'OK_RETHROW_BRIDGE_LOSS'] as const;+ let savedEnv: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>;++ beforeEach(() => {+ savedEnv = {};+ for (const key of ENV_KEYS) savedEnv[key] = process.env[key];+ process.env.NODE_ENV = 'production';+ delete process.env.OK_RETHROW_BRIDGE_LOSS;+ });++ afterEach(() => {+ for (const key of ENV_KEYS) {+ const value = savedEnv[key];+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ });++ const FM2 = '---\ntitle: Boundary recovery\n---\n';+ const RAW_NG = `${FM2}\n\nFirst paragraph body.\n\nSecond paragraph stays.\n`;++ test('applies the boundary-reattached as-computed bytes, not raw info.result', () => {+ __resetBridgeWatchdogForTests();+ resetMetrics();++ const asComputedMergeSpace = `${FM2}\nZFirst paragraph body. \n\nSecond paragraph stays.\n`;+ const throwingMerge = (): never => {+ throw new BridgeMergeContentLossError({+ baseline: RAW_NG,+ userText: asComputedMergeSpace,+ agentText: RAW_NG,+ result: asComputedMergeSpace,+ lostSubstrings: ['a-dropped-line'],+ which: 'substring',+ side: 'user',+ });+ };++ const doc = new Y.Doc();+ const xmlFragment = doc.getXmlFragment('default');+ const ytext = doc.getText('source');+ doc.transact(() => {+ composeAndWriteRawBody(doc, RAW_NG, 'file-watcher');+ }, FILE_WATCHER_ORIGIN);+ const cleanup = setupServerObservers({+ doc,+ xmlFragment,+ ytext,+ mdManager,+ schema,+ docName: 'pathb-boundary-recovery',+ mergeThreeWay: throwingMerge,+ });+ expect(ytext.toString()).toBe(RAW_NG);++ typeIntoSource(+ doc,+ ytext,+ RAW_NG.indexOf('First paragraph body.') + 'First paragraph body.'.length,+ ' ',+ );+ typeIntoParagraph(doc, xmlFragment, 'First paragraph');++ expect(getMetrics().bridgeMergeContentLoss).toBe(1);++ const finalText = ytext.toString();+ expect(finalText).toContain(`${FM2}\n\n`);+ const boundary = splitLeadingDocBoundary(RAW_NG).boundary;+ const expected = reattachLeadingDocBoundary(+ splitLeadingDocBoundary(asComputedMergeSpace).text,+ boundary,+ );+ expect(finalText).toBe(expected);+ expect(finalText).toBe(`${FM2}\n\nZFirst paragraph body. \n\nSecond paragraph stays.\n`);++ cleanup();+ });+});diff --git a/packages/server/src/server-observers.ts b/packages/server/src/server-observers.tsindex 49b57d054..0e8a13b9e 100644--- a/packages/server/src/server-observers.ts+++ b/packages/server/src/server-observers.ts@@ -8,6 +8,9 @@ import {mergeThreeWay,normalizeBridge,prependFrontmatter,+ projectMergeBoundarySpace,+ reattachLeadingDocBoundary,+ splitLeadingDocBoundary,stripFrontmatter,} from '@inkeep/open-knowledge-core';import type { Schema } from '@tiptap/pm/model';@@ -151,6 +154,7 @@ export interface SetupServerObserversOpts {resolveEmbed?: (basename: string, sourcePath: string) => string | null;resolveSize?: (basename: string, sourcePath: string) => number | null;onDispatch?: ObserverDispatchHook;+ mergeThreeWay?: typeof mergeThreeWay;}function settlesSplitBrain(settledText: string, md: string, normMdPre?: string): boolean {@@ -365,16 +369,27 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => voidapplyIncrementalDiff(ytext, currentText, md);} else {const mergeBase = ytextInSync ? lastSyncedCanonicalMd : preMergeBaseline;+ const { boundary } = splitLeadingDocBoundary(currentText);+ const projectMerged = (merged: string): string =>+ reattachLeadingDocBoundary(splitLeadingDocBoundary(merged).text, boundary);+ const mergeThreeWayFn = opts.mergeThreeWay ?? mergeThreeWay;try {- const mergedText = mergeThreeWay(mergeBase, md, currentText);+ const mergedText = projectMerged(+ mergeThreeWayFn(+ projectMergeBoundarySpace(mergeBase),+ projectMergeBoundarySpace(md),+ projectMergeBoundarySpace(currentText),+ ),+ );applyFastDiff(ytext, currentText, mergedText);pathBState.mergedText = mergedText;} catch (mergeErr) {if (!(mergeErr instanceof BridgeMergeContentLossError)) throw mergeErr;handleBridgeMergeLoss(mergeErr, preMergeBaseline);if (shouldRethrowBridgeMergeLoss()) throw mergeErr;- applyFastDiff(ytext, currentText, mergeErr.info.result);- pathBState.mergedText = mergeErr.info.result;+ const asComputed = projectMerged(mergeErr.info.result);+ applyFastDiff(ytext, currentText, asComputed);+ pathBState.mergedText = asComputed;}}}, OBSERVER_SYNC_ORIGIN);