Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): bridge resting-divergence tolerance + fidelity follow-ups (#1812)

Nick Gomez26c3c653c56e
diff --git a/.changeset/markdown-fidelity-e2e.md b/.changeset/markdown-fidelity-e2e.md
index 43f1a8473..5ce0d4821 100644
--- a/.changeset/markdown-fidelity-e2e.md
+++ b/.changeset/markdown-fidelity-e2e.md
@@ -5,7 +5,7 @@
feat(markdown): end-to-end byte fidelity — markdown round-trips byte-exact, agents' untouched bytes survive concurrent edits
-The markdown engine no longer canonicalizes source formatting on the WYSIWYG/cross-surface edit path. Every producer-fixable byte-residual axis now round-trips byte-exact through `serialize(parse(x))`: table outer pipes, delimiter-row dashes and alignment padding, ordered-list numbering (`1. 1. 1.` stays), list marker spacing and continuation indents, fence length and info-string padding, strikethrough delimiter (`~` vs `~~`), task-checkbox case, wiki-link inner padding, opaque-extension embeds (`![[notes.foo]]` no longer downcasts to a plain link), inline math (`$x$` stays `$x$` instead of rewriting to `$$x$$`, with currency safety preserved), doc-start `---` thematic breaks (no longer rewritten to `***`, and a doc-start `---` no longer corrupts adjacent blocks), BOM, leading/trailing blank lines, inter-block blank-line counts, and tab-indented code. One visible consequence: a literal frontmatter-shaped block (`---`/`key: val`/`---`) ingested directly into the parse engine now renders as visible markdown (thematic break + setext heading) instead of being silently dropped.
+The markdown engine no longer canonicalizes source formatting on the WYSIWYG/cross-surface edit path. In plain terms: the exact bytes you type are the exact bytes saved — editing one paragraph in WYSIWYG no longer re-formats the rest of the file, and only blocks you actually edit can change shape on save. Every producer-fixable byte-residual axis now round-trips byte-exact through `serialize(parse(x))`: table outer pipes, delimiter-row dashes and alignment padding, ordered-list numbering (`1. 1. 1.` stays), list marker spacing and continuation indents, fence length and info-string padding, strikethrough delimiter (`~` vs `~~`), task-checkbox case, wiki-link inner padding, opaque-extension embeds (`![[notes.foo]]` no longer downcasts to a plain link), inline math (`$x$` stays `$x$` instead of rewriting to `$$x$$`, with currency safety preserved), doc-start `---` thematic breaks (no longer rewritten to `***`, and a doc-start `---` no longer corrupts adjacent blocks), BOM, leading/trailing blank lines, inter-block blank-line counts, and tab-indented code. One visible consequence: a literal frontmatter-shaped block (`---`/`key: val`/`---`) ingested directly into the parse engine now renders as visible markdown (thematic break + setext heading) instead of being silently dropped.
Silent data-loss fixes: boundary-whitespace emphasis (`<em>foo </em>`) now serializes to a re-parseable form instead of degrading to plain text; entity references in a fenced-code info string survive instead of being stripped; `[link](</my uri>)` parses as a link instead of literal text; inline code containing `|` inside a table cell keeps its escape instead of corrupting the table. The serializer also stops escaping bare `*`/`_`/`~` and line-start `=` where CommonMark does not require it.
diff --git a/.changeset/paragraph-continuation-indent-tolerance.md b/.changeset/paragraph-continuation-indent-tolerance.md
new file mode 100644
index 000000000..f619e490a
--- /dev/null
+++ b/.changeset/paragraph-continuation-indent-tolerance.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-core": patch
+---
+
+fix: documents containing CommonMark lazy-continuation lines (an indented line continuing the paragraph above it) no longer rest in a permanent bridge-divergence state. `normalizeBridge` gained a `paragraph-continuation-indent` tolerance class that treats the parser's indent-stripping on paragraph continuation lines as a comparison-equivalence, ending the perpetual split-brain telemetry, fuzz stalls, and stale-witness block duplication this construct could trigger. Comparison-only — stored bytes are never rewritten.
diff --git a/.changeset/tolerance-telemetry-wired.md b/.changeset/tolerance-telemetry-wired.md
new file mode 100644
index 000000000..bfdfb7df7
--- /dev/null
+++ b/.changeset/tolerance-telemetry-wired.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge-core": patch
+"@inkeep/open-knowledge-server": patch
+---
+
+fix: `OK_BRIDGE_TOLERANCE_TELEMETRY=1` now produces output — the tolerance-telemetry writer is wired into server boot (it was previously documented but never initialized), and writes through a rotating sink (~16 MB cap) instead of an unbounded append. The JSONL receives the full un-rate-limited fire stream (bounded on disk by rotation) so aggregate counts reflect real fire frequency; the console event and metric counter stay rate-limited per (site, class). Bridge drains on large documents also got cheaper: the residual-merge classification now runs its full-document normalize passes only on the drains where the classification can matter.
diff --git a/biome-plugins/class-proof-registration-discipline.grit b/biome-plugins/class-proof-registration-discipline.grit
index de27b7735..2ceb93a20 100644
--- a/biome-plugins/class-proof-registration-discipline.grit
+++ b/biome-plugins/class-proof-registration-discipline.grit
@@ -38,7 +38,7 @@ or {
},
register_diagnostic(
span = $call,
- message = "Class-proof registration missing `predicate` or `proof` option — both are required by `ClassProofOptions<M>`. Provide all three of `{ enumerate, predicate, proof }` to `defineClassProof()`. See https://github.com/inkeep/open-knowledge-legacy/blob/main/biome-plugins/README.md#class-proof-registration-disciplinegrit"
+ message = "Class-proof registration missing `predicate` or `proof` option — both are required by `ClassProofOptions<M>`. Provide all three of `{ enumerate, predicate, proof }` to `defineClassProof()`. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#class-proof-registration-disciplinegrit"
)
},
// Pattern B: any `defineClassProof` call at all. The override scope
@@ -47,7 +47,7 @@ or {
`defineClassProof($_, $_)` as $call where {
register_diagnostic(
span = $call,
- message = "Class-proof registered outside the canonical dir. Move the `defineClassProof(...)` call to `packages/md-conformance/src/class-proofs/proofs/<name>.ts` and export it from `run-all.ts` so it participates in the orchestrator manifest. See https://github.com/inkeep/open-knowledge-legacy/blob/main/biome-plugins/README.md#class-proof-registration-disciplinegrit"
+ message = "Class-proof registered outside the canonical dir. Move the `defineClassProof(...)` call to `packages/md-conformance/src/class-proofs/proofs/<name>.ts` and export it from `run-all.ts` so it participates in the orchestrator manifest. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#class-proof-registration-disciplinegrit"
)
}
}
diff --git a/biome-plugins/cst-pm-handler-todo-stub.grit b/biome-plugins/cst-pm-handler-todo-stub.grit
index 17ba7184b..6b05ff1a2 100644
--- a/biome-plugins/cst-pm-handler-todo-stub.grit
+++ b/biome-plugins/cst-pm-handler-todo-stub.grit
@@ -29,6 +29,6 @@ language js
$msg <: r"^['\"`]TODO: implement.*",
register_diagnostic(
span = $stmt,
- message = "Codemod-emitted handler stub still throws TODO marker - fill in the substrate-specific body so the handler is implemented per the ICstEngine contract. See https://github.com/inkeep/open-knowledge-legacy/blob/main/biome-plugins/README.md#cst-pm-handler-todo-stubgrit"
+ message = "Codemod-emitted handler stub still throws TODO marker - fill in the substrate-specific body so the handler is implemented per the ICstEngine contract. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#cst-pm-handler-todo-stubgrit"
)
}
diff --git a/biome-plugins/path-conditional-map-driven-origin.grit b/biome-plugins/path-conditional-map-driven-origin.grit
index 054f7ea5e..a07062448 100644
--- a/biome-plugins/path-conditional-map-driven-origin.grit
+++ b/biome-plugins/path-conditional-map-driven-origin.grit
@@ -32,6 +32,6 @@ language js
not $call <: `$_.transact($_, OBSERVER_SYNC_ORIGIN, $...)`,
register_diagnostic(
span = $call,
- message = "Observer-side transact call missing sanctioned origin. Pass `OBSERVER_SYNC_ORIGIN` as the second argument: `doc.transact(fn, OBSERVER_SYNC_ORIGIN)`. Bare `doc.transact(fn)` (or a wrong origin) routes the write to `openknowledge-service` and breaks per-session UndoManager attribution. See https://github.com/inkeep/open-knowledge-legacy/blob/main/biome-plugins/README.md#path-conditional-map-driven-origingrit"
+ message = "Observer-side transact call missing sanctioned origin. Pass `OBSERVER_SYNC_ORIGIN` as the second argument: `doc.transact(fn, OBSERVER_SYNC_ORIGIN)`. Bare `doc.transact(fn)` (or a wrong origin) routes the write to `openknowledge-service` and breaks per-session UndoManager attribution. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#path-conditional-map-driven-origingrit"
)
}
diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdx
index c7aafd638..8542ed4bf 100644
--- a/docs/content/reference/configuration.mdx
+++ b/docs/content/reference/configuration.mdx
@@ -72,6 +72,7 @@ Most users never set these — the schema settings above cover the common cases.
| --- | --- |
| `OPEN_KNOWLEDGE_GITHUB_CLIENT_ID` | Override the GitHub OAuth App client ID |
| `OK_SHOWALL_MAX_ENTRIES` | Max entries the **Show all files** disk walk returns before it stops and marks the list truncated (default `50000`) |
+| `OK_BRIDGE_TOLERANCE_TELEMETRY` | Set to `1` to record each bridge-tolerance-class fire as a JSONL line in `<project>/.ok/local/tolerance-telemetry.jsonl` (opt-in, local-only, off by default; unstable diagnostic for triaging markdown-fidelity incidents). **Records doc paths in cleartext** — independent of `telemetry.localSink`'s `attributeDenylist`, which redacts span/log attributes, not this file. Deliberately outside the `.ok/local/telemetry/` subtree `ok diagnose bundle` harvests, so the unredacted paths never ship in a bug bundle. |
| `OTEL_SDK_DISABLED` | OpenTelemetry OTLP push gate. Inverted sense: set to `false` to **enable** push (it is off by default). |
| `OK_EMBEDDINGS_API_KEY` | Fallback embeddings provider API key for [semantic search](#semantic-search), used when none is stored on disk. Prefer `ok embeddings set-key` (writes `~/.ok/secrets.yml`) for normal use; the env var is convenient for CI / scripted runs. |
diff --git a/packages/app/scripts/_measure-lib.sh b/packages/app/scripts/_measure-lib.sh
index b6d143df6..caa4688d4 100755
--- a/packages/app/scripts/_measure-lib.sh
+++ b/packages/app/scripts/_measure-lib.sh
@@ -184,11 +184,22 @@ require_jq() {
}
resolve_repo_root() {
- local root
- root="$(git rev-parse --show-toplevel 2>/dev/null)"
- if [[ -z "$root" ]]; then
- echo "error: not inside a git repository" >&2
- exit 4
- fi
- printf '%s\n' "$root"
+ # The OK WORKSPACE root, not the git toplevel: inside the agents-private
+ # monorepo `git rev-parse --show-toplevel` resolves two levels above
+ # public/open-knowledge/, which silently mislocates LOG_DIR/APP_DIR (JSONL
+ # records written outside the subtree; replay hints pointing at paths that
+ # don't exist). Walk up from this library's own location to the nearest
+ # directory carrying bun.lock — correct in both the standalone public repo
+ # and the monorepo, and independent of the caller's cwd.
+ local dir
+ dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ while [[ "$dir" != "/" ]]; do
+ if [[ -f "$dir/bun.lock" ]]; then
+ printf '%s\n' "$dir"
+ return 0
+ fi
+ dir="$(dirname "$dir")"
+ done
+ echo "error: no bun.lock workspace root above ${BASH_SOURCE[0]}" >&2
+ exit 4
}
diff --git a/packages/app/scripts/measure-fuzz.sh b/packages/app/scripts/measure-fuzz.sh
index 926d873b4..7995a78ae 100755
--- a/packages/app/scripts/measure-fuzz.sh
+++ b/packages/app/scripts/measure-fuzz.sh
@@ -176,7 +176,7 @@ START_MS="$(epoch_ms)"
TEST_EXIT=0
(
cd "$APP_DIR"
- bun test "$TEST_FILE" 2>&1
+ bun test --conditions development "$TEST_FILE" 2>&1
) | tee "$OUT_FILE" || TEST_EXIT=$?
END_MS="$(epoch_ms)"
@@ -195,6 +195,12 @@ DURATION_MS=$(( END_MS - START_MS ))
# hook could run): count all seeds as failed conservatively, since we
# cannot confirm any specific seed passed.
+# Optional appended field (newer harness): converged-late count — seeds that
+# exhausted the convergence budget but settled within tolerance. Counted as
+# passes by the harness; recorded here as a perf signal.
+CONVERGED_LATE="$(grep -oE '^\[fuzz\] RESULT [^\n]*convergedLate=[0-9]+' "$OUT_FILE" | grep -oE 'convergedLate=[0-9]+' | tail -1 | cut -d= -f2 || true)"
+CONVERGED_LATE="${CONVERGED_LATE:-0}"
+
FUZZ_RESULT_LINE="$(grep -oE '^\[fuzz\] RESULT seeds=[0-9]+ passed=[0-9]+ failed=[0-9]+ failingSeeds=\[[0-9,]*\]' "$OUT_FILE" | tail -1 || true)"
# 3-way outcome classifier (parallels measure-stress.sh's pass/fail/crash):
@@ -271,6 +277,7 @@ RECORD="$(jq -c -n \
--arg script "deep-fuzz" \
--argjson seedCount "$SEED_COUNT" \
--argjson seedsFailed "$SEEDS_FAILED" \
+ --argjson convergedLate "${CONVERGED_LATE}" \
--argjson rate "$RATE" \
--arg invokedBy "$INVOKED_BY" \
--arg context "$CONTEXT" \
@@ -285,6 +292,7 @@ RECORD="$(jq -c -n \
script: $script,
seedCount: $seedCount,
seedsFailed: $seedsFailed,
+ convergedLate: $convergedLate,
rate: $rate,
invokedBy: $invokedBy,
context: $context,
@@ -320,7 +328,7 @@ if [[ "$SEEDS_FAILED" != "0" ]]; then
echo "──────── failing seed replay commands ────────"
while IFS= read -r seed; do
[[ -z "$seed" ]] && continue
- echo " STRESS_FUZZ_SEED=$seed bun test $TEST_FILE # in $APP_DIR"
+ echo " STRESS_FUZZ_SEED=$seed bun test --conditions development $TEST_FILE # in $APP_DIR"
done <<< "$FAILING_SEEDS_LIST"
echo ""
fi
diff --git a/packages/app/scripts/measure-stress.sh b/packages/app/scripts/measure-stress.sh
index dc43841e7..8b80f0305 100755
--- a/packages/app/scripts/measure-stress.sh
+++ b/packages/app/scripts/measure-stress.sh
@@ -126,7 +126,7 @@ START_MS="$(epoch_ms)"
TEST_EXIT=0
(
cd "$APP_DIR"
- bun test "$TEST_FILE" 2>&1
+ bun test --conditions development "$TEST_FILE" 2>&1
) | tee "$OUT_FILE" || TEST_EXIT=$?
END_MS="$(epoch_ms)"
@@ -255,7 +255,7 @@ echo ""
if [[ "$OUTCOME" == "fail" ]]; then
echo "──────── failure replay command ────────"
- echo " STRESS_SEED=$ACTUAL_SEED bun test $TEST_FILE # in $APP_DIR"
+ echo " STRESS_SEED=$ACTUAL_SEED bun test --conditions development $TEST_FILE # in $APP_DIR"
echo ""
elif [[ "$OUTCOME" == "crash" ]]; then
echo "──────── crash diagnostic ────────"
diff --git a/packages/app/tests/fidelity/invariant-i4.test.ts b/packages/app/tests/fidelity/invariant-i4.test.ts
index 5171a3f72..722ca4215 100644
--- a/packages/app/tests/fidelity/invariant-i4.test.ts
+++ b/packages/app/tests/fidelity/invariant-i4.test.ts
@@ -1,20 +1,9 @@
import { describe, expect, test } from 'bun:test';
import * as fc from 'fast-check';
-import { markdownDoc, paragraphWithFidelityChars } from './arbitraries';
+import { paragraphWithFidelityChars } from './arbitraries';
import { mdRoundTrip, NUM_RUNS, normalize } from './helpers';
describe('I4 — idempotence: two round-trips produce identical output', () => {
- test('document-level idempotence', () => {
- fc.assert(
- fc.property(markdownDoc, (md) => {
- const rt1 = normalize(mdRoundTrip(md));
- const rt2 = normalize(mdRoundTrip(rt1));
- expect(rt2).toBe(rt1);
- }),
- { numRuns: NUM_RUNS, seed: 42 },
- );
- });
-
test('fidelity chars idempotence', () => {
fc.assert(
fc.property(paragraphWithFidelityChars, (md) => {
diff --git a/packages/app/tests/integration/agent-focus-wiring.test.ts b/packages/app/tests/integration/agent-focus-wiring.test.ts
index a8473cf2b..a4df89cb8 100644
--- a/packages/app/tests/integration/agent-focus-wiring.test.ts
+++ b/packages/app/tests/integration/agent-focus-wiring.test.ts
@@ -98,7 +98,7 @@ describe('orphan-hint response shape — L1 integration (US-003)', () => {
timestamp: string;
hints?: Array<{ type: string; parentCandidates: string[]; message: string }>;
}> {
- const res = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ markdown: body, position: 'replace', docName }),
@@ -164,7 +164,7 @@ describe('systemSubscriberCount response field — L1 integration (FR7a)', () =>
subscriberCount?: number;
systemSubscriberCount?: number;
}> {
- const res = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ markdown: body, position: 'replace', docName }),
diff --git a/packages/app/tests/integration/agent-undo.test.ts b/packages/app/tests/integration/agent-undo.test.ts
index 29dfd7e61..80de94f61 100644
--- a/packages/app/tests/integration/agent-undo.test.ts
+++ b/packages/app/tests/integration/agent-undo.test.ts
@@ -19,7 +19,7 @@ async function agentWriteAs(
markdown: string,
docName: string,
): Promise<void> {
- const res = await fetch(`http://localhost:${port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -39,7 +39,7 @@ async function agentUndoFor(
connectionId: string,
scope: 'last' | 'session' = 'last',
): Promise<Response> {
- return fetch(`http://localhost:${port}/api/agent-undo`, {
+ return fetch(`http://127.0.0.1:${port}/api/agent-undo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ docName, connectionId, scope }),
diff --git a/packages/app/tests/integration/agent-write-during-restart.test.ts b/packages/app/tests/integration/agent-write-during-restart.test.ts
index 9cab214f3..f44b4b3ec 100644
--- a/packages/app/tests/integration/agent-write-during-restart.test.ts
+++ b/packages/app/tests/integration/agent-write-during-restart.test.ts
@@ -26,7 +26,7 @@ describe('T6: Agent write during restart', () => {
let server = await createRestartableServer();
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
diff --git a/packages/app/tests/integration/asset-move-rerenders-embeds.test.ts b/packages/app/tests/integration/asset-move-rerenders-embeds.test.ts
index eb2bc66cf..4847d954a 100644
--- a/packages/app/tests/integration/asset-move-rerenders-embeds.test.ts
+++ b/packages/app/tests/integration/asset-move-rerenders-embeds.test.ts
@@ -59,7 +59,7 @@ describe('asset-move embed re-resolution — head-watcher-independent fallback',
});
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
pool.open('test-doc');
@@ -142,7 +142,7 @@ describe('asset-move embed re-resolution — head-watcher-independent fallback',
});
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
pool.open('test-doc');
diff --git a/packages/app/tests/integration/backlinks.test.ts b/packages/app/tests/integration/backlinks.test.ts
index c5c9026d7..400255dc6 100644
--- a/packages/app/tests/integration/backlinks.test.ts
+++ b/packages/app/tests/integration/backlinks.test.ts
@@ -12,7 +12,7 @@ test('backlink endpoints update after persisted agent writes', async () => {
const server = await createTestServer();
try {
- const alpha = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const alpha = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -23,7 +23,7 @@ test('backlink endpoints update after persisted agent writes', async () => {
});
if (!alpha.ok) throw new Error(`alpha write failed: ${alpha.status}`);
- const beta = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const beta = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -35,7 +35,7 @@ test('backlink endpoints update after persisted agent writes', async () => {
if (!beta.ok) throw new Error(`beta write failed: ${beta.status}`);
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/backlinks?docName=beta`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/backlinks?docName=beta`);
const data = (await res.json()) as {
backlinks?: Array<{ source: string; snippet: string | null }>;
};
@@ -61,7 +61,7 @@ test('backlink endpoints update from live client edits before persistence deboun
await pollUntil(
async () => {
- const res = await fetch(`http://localhost:${server.port}/api/backlinks?docName=beta`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/backlinks?docName=beta`);
const data = (await res.json()) as {
backlinks?: Array<{ source: string; snippet: string | null }>;
};
diff --git a/packages/app/tests/integration/branch-switch-live-client.test.ts b/packages/app/tests/integration/branch-switch-live-client.test.ts
index 76baedfb3..7d7375598 100644
--- a/packages/app/tests/integration/branch-switch-live-client.test.ts
+++ b/packages/app/tests/integration/branch-switch-live-client.test.ts
@@ -95,12 +95,12 @@ describe('T5: Branch switch while tab open', () => {
});
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
const systemDoc = new Y.Doc();
const systemProvider = new HocuspocusProvider({
- url: `ws://localhost:${server.port}/collab`,
+ url: `ws://127.0.0.1:${server.port}/collab`,
name: SYSTEM_DOC_NAME,
document: systemDoc,
onStateless: ({ payload }: { payload: string }) => {
diff --git a/packages/app/tests/integration/branch-switched-with-stale-embed-resolution.test.ts b/packages/app/tests/integration/branch-switched-with-stale-embed-resolution.test.ts
index a73a3ac7f..b314f0128 100644
--- a/packages/app/tests/integration/branch-switched-with-stale-embed-resolution.test.ts
+++ b/packages/app/tests/integration/branch-switched-with-stale-embed-resolution.test.ts
@@ -87,7 +87,7 @@ describe('T17: branch switch with `![[photo.png]]` doc — reseed-before-reset',
});
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
pool.open('test-doc');
diff --git a/packages/app/tests/integration/bridge-matrix.test.ts b/packages/app/tests/integration/bridge-matrix.test.ts
index 33b341239..ba6a2af9f 100644
--- a/packages/app/tests/integration/bridge-matrix.test.ts
+++ b/packages/app/tests/integration/bridge-matrix.test.ts
@@ -420,7 +420,7 @@ describe('initial sync and test isolation', () => {
const seeded = '/keep-me-on-reset.md\n';
writeFileSync(okignorePath, seeded, 'utf-8');
- const res = await fetch(`http://localhost:${server.port}/api/test-reset?reset-okignore=false`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/test-reset?reset-okignore=false`, {
method: 'POST',
});
expect(res.ok).toBe(true);
diff --git a/packages/app/tests/integration/bug-c-real-reachability.test.ts b/packages/app/tests/integration/bug-c-real-reachability.test.ts
index bbdc09501..82c034b89 100644
--- a/packages/app/tests/integration/bug-c-real-reachability.test.ts
+++ b/packages/app/tests/integration/bug-c-real-reachability.test.ts
@@ -39,7 +39,7 @@ async function createNoObserverPeer(
const ytext = doc.getText('source');
const fragment = doc.getXmlFragment('default');
const provider = new HocuspocusProvider({
- url: `ws://localhost:${port}/collab`,
+ url: `ws://127.0.0.1:${port}/collab`,
name: docName,
document: doc,
connect: true,
diff --git a/packages/app/tests/integration/cc1-broadcast.test.ts b/packages/app/tests/integration/cc1-broadcast.test.ts
index 070e3c0d2..0951bf4ce 100644
--- a/packages/app/tests/integration/cc1-broadcast.test.ts
+++ b/packages/app/tests/integration/cc1-broadcast.test.ts
@@ -31,7 +31,7 @@ function connectSystemDoc(port: number): {
const doc = new Y.Doc();
const signals: CC1DerivedViewPayload[] = [];
const provider = new HocuspocusProvider({
- url: `ws://localhost:${port}/collab`,
+ url: `ws://127.0.0.1:${port}/collab`,
name: SYSTEM_DOC_NAME,
document: doc,
connect: true,
@@ -93,7 +93,7 @@ describe('CC1 broadcast — L1 integration', () => {
await pollUntil(() => signals.length > 0, 5000, 50);
- const docsRes = await fetch(`http://localhost:${server.port}/api/documents`);
+ const docsRes = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
const docsBody: { documents?: Array<{ docName: string }> } = await docsRes.json();
expect(docsBody.documents?.some((doc) => doc.docName === docName)).toBe(true);
} finally {
@@ -169,14 +169,14 @@ describe('CC1 broadcast — L1 integration', () => {
test('skip surface: no __system__ state in any subsystem', async () => {
expect(existsSync(join(server.contentDir, '__system__.md'))).toBe(false);
- const docsRes = await fetch(`http://localhost:${server.port}/api/documents`);
+ const docsRes = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
const body = (await docsRes.json()) as { documents: Array<{ docName: string }> };
const systemDocs = body.documents.filter((d) => d.docName === '__system__');
expect(systemDocs).toHaveLength(0);
});
test('POST /api/create-page rejects __system__ docName', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/create-page`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/create-page`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: '__system__.md' }),
@@ -203,7 +203,7 @@ describe('CC1 broadcast — L1 integration', () => {
);
const forgedFrame = encoding.toUint8Array(enc);
- const attackerWs = new WebSocket(`ws://localhost:${server.port}/collab/${SYSTEM_DOC_NAME}`);
+ const attackerWs = new WebSocket(`ws://127.0.0.1:${server.port}/collab/${SYSTEM_DOC_NAME}`);
await new Promise<void>((resolve, reject) => {
attackerWs.onopen = () => resolve();
attackerWs.onerror = (e) => reject(new Error(`ws error: ${String(e)}`));
@@ -343,7 +343,7 @@ describe('CC1 broadcast — L1 integration', () => {
const doc = new Y.Doc();
const arrivals: Array<{ seq: number; at: number }> = [];
const provider = new HocuspocusProvider({
- url: `ws://localhost:${server.port}/collab`,
+ url: `ws://127.0.0.1:${server.port}/collab`,
name: SYSTEM_DOC_NAME,
document: doc,
connect: true,
diff --git a/packages/app/tests/integration/classify-final-state.test.ts b/packages/app/tests/integration/classify-final-state.test.ts
new file mode 100644
index 000000000..ca9c428f1
--- /dev/null
+++ b/packages/app/tests/integration/classify-final-state.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, test } from 'bun:test';
+import * as Y from 'yjs';
+import { classifyFinalState, serializeFragment } from './test-harness';
+
+function makeClient(paragraphText: string, ytextBytes: string) {
+ const doc = new Y.Doc();
+ const ytext = doc.getText('source');
+ ytext.insert(0, ytextBytes);
+ const fragment = doc.getXmlFragment('default');
+ const paragraph = new Y.XmlElement('paragraph');
+ const text = new Y.XmlText();
+ text.insert(0, paragraphText);
+ paragraph.insert(0, [text]);
+ fragment.push([paragraph]);
+ return { ytext, fragment };
+}
+
+describe('classifyFinalState', () => {
+ test('diverged peers classify as stalled, never converged-late', () => {
+ const a = makeClient('Alpha.', 'Alpha.\n');
+ const b = makeClient('Alpha.', 'Beta.\n');
+ const result = classifyFinalState([a, b]);
+ expect(result.outcome).toBe('stalled');
+ if (result.outcome === 'stalled') {
+ expect(result.detail).toBe('peers diverged at budget exhaustion');
+ }
+ });
+
+ test('identical peers beyond bridge tolerance classify as stalled', () => {
+ const a = makeClient('Alpha.', 'Entirely different settled bytes.\n');
+ const b = makeClient('Alpha.', 'Entirely different settled bytes.\n');
+ const result = classifyFinalState([a, b]);
+ expect(result.outcome).toBe('stalled');
+ if (result.outcome === 'stalled') {
+ expect(result.detail).toStartWith('bridge invariant beyond tolerance at budget exhaustion');
+ }
+ });
+
+ test('identical, in-tolerance peers classify as converged-late', () => {
+ const a = makeClient('Alpha.', 'Alpha.\n');
+ const b = makeClient('Alpha.', 'Alpha.\n');
+ expect(serializeFragment(a.fragment)).toBe('Alpha.\n');
+ expect(classifyFinalState([a, b])).toEqual({ outcome: 'converged-late' });
+ });
+});
diff --git a/packages/app/tests/integration/client-version-no-regression.test.ts b/packages/app/tests/integration/client-version-no-regression.test.ts
index 941a6a8d2..f11e4f2d5 100644
--- a/packages/app/tests/integration/client-version-no-regression.test.ts
+++ b/packages/app/tests/integration/client-version-no-regression.test.ts
@@ -17,7 +17,7 @@ describe('read-blind server accepts instrumented clients', () => {
});
test('HTTP: /api/server-info with x-ok-client-* headers returns 2xx', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/server-info`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/server-info`, {
headers: clientVersionHeaders({ kind: 'cli', runtimeVersion: '9.9.9-test' }),
});
expect(res.ok).toBe(true);
@@ -28,7 +28,7 @@ describe('read-blind server accepts instrumented clients', () => {
const doc = new Y.Doc();
let authFailed = false;
const provider = new HocuspocusProvider({
- url: `ws://localhost:${server.port}/collab`,
+ url: `ws://127.0.0.1:${server.port}/collab`,
name: `test-${crypto.randomUUID()}`,
document: doc,
token: buildAuthToken(null, null),
diff --git a/packages/app/tests/integration/cold-start-empty-idb.test.ts b/packages/app/tests/integration/cold-start-empty-idb.test.ts
index c1d483ff3..bfca8ec3c 100644
--- a/packages/app/tests/integration/cold-start-empty-idb.test.ts
+++ b/packages/app/tests/integration/cold-start-empty-idb.test.ts
@@ -39,7 +39,7 @@ describe('T13: cold start with empty IDB after server restart', () => {
server = await server.killAndRestartOnSamePort({ downtimeMs: 400 });
cleanups.unshift(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
const serverInstanceId = await seedPoolServerInstanceId(server, pool);
diff --git a/packages/app/tests/integration/config-doc-server-instance-recovery.test.ts b/packages/app/tests/integration/config-doc-server-instance-recovery.test.ts
index 682a7a4ac..40dd72229 100644
--- a/packages/app/tests/integration/config-doc-server-instance-recovery.test.ts
+++ b/packages/app/tests/integration/config-doc-server-instance-recovery.test.ts
@@ -28,7 +28,7 @@ describe('PRD-6881: config-doc server-instance recovery', () => {
const doc = new Y.Doc();
const provider = new HocuspocusProvider({
- url: `ws://localhost:${server.port}/collab`,
+ url: `ws://127.0.0.1:${server.port}/collab`,
name: CONFIG_DOC_NAME_OKIGNORE,
document: doc,
});
@@ -55,7 +55,7 @@ describe('PRD-6881: config-doc server-instance recovery', () => {
const instanceA = server.instance.serverInstanceId;
const doc = new Y.Doc();
const provider = new HocuspocusProvider({
- url: `ws://localhost:${server.port}/collab`,
+ url: `ws://127.0.0.1:${server.port}/collab`,
name: CONFIG_DOC_NAME_OKIGNORE,
document: doc,
token: buildAuthToken(null, instanceA, null),
diff --git a/packages/app/tests/integration/conflict-aware-write-surfaces.test.ts b/packages/app/tests/integration/conflict-aware-write-surfaces.test.ts
index 460ddff41..7946dadf7 100644
--- a/packages/app/tests/integration/conflict-aware-write-surfaces.test.ts
+++ b/packages/app/tests/integration/conflict-aware-write-surfaces.test.ts
@@ -29,7 +29,7 @@ async function setupServerWithDoc(
cleanups.push(() => server.cleanup());
writeFileSync(join(server.contentDir, `${docName}.md`), initial, 'utf-8');
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
@@ -108,7 +108,7 @@ describe('FR1 + FR2: lifecycle swap-in / swap-out (server-observable contract)',
const lifecycleMap = serverDoc.getMap('lifecycle');
expect(lifecycleMap.get('status')).toBeUndefined();
- const preGateRes = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const preGateRes = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -127,7 +127,7 @@ describe('FR1 + FR2: lifecycle swap-in / swap-out (server-observable contract)',
expect(lifecycleMap.get('status')).toBe('conflict');
expect(lifecycleMap.get('reason')).toBe('conflict-markers');
- const inConflictRes = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const inConflictRes = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -151,7 +151,7 @@ describe('FR1 + FR2: lifecycle swap-in / swap-out (server-observable contract)',
expect(serverDoc.getText('source').toString()).toBe(ytextBefore);
- const postGateRes = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const postGateRes = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -179,7 +179,7 @@ describe('FR11: reconciliation conflict path sets lifecycle.status and fires the
cleanups.push(() => server.cleanup());
writeFileSync(join(server.contentDir, `${docName}.md`), baseContent, 'utf-8');
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
@@ -209,7 +209,7 @@ describe('FR11: reconciliation conflict path sets lifecycle.status and fires the
expect(lifecycle.get('status')).toBe('conflict');
expect(lifecycle.get('reason')).toBe('merged-with-markers');
- const res = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -260,7 +260,7 @@ describe('FR12: /api/sync/conflicts + /api/sync/status count parity', () => {
const server = await createTestServer({ contentDir: tmpDir, keepContentDir: true });
cleanups.push(() => server.cleanup());
- const conflictsRes = await fetch(`http://localhost:${server.port}/api/sync/conflicts`);
+ const conflictsRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/conflicts`);
expect(conflictsRes.ok).toBe(true);
const conflictsBody = (await conflictsRes.json()) as {
conflicts: Array<{ file: string }>;
@@ -269,12 +269,12 @@ describe('FR12: /api/sync/conflicts + /api/sync/status count parity', () => {
const files = conflictsBody.conflicts.map((c) => c.file).sort();
expect(files).toEqual([fileA, fileB].sort());
- const statusRes = await fetch(`http://localhost:${server.port}/api/sync/status`);
+ const statusRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/status`);
expect(statusRes.ok).toBe(true);
const statusBody = (await statusRes.json()) as { conflictCount: number };
expect(statusBody.conflictCount).toBe(2);
- const resolveRes = await fetch(`http://localhost:${server.port}/api/sync/resolve-conflict`, {
+ const resolveRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -285,14 +285,14 @@ describe('FR12: /api/sync/conflicts + /api/sync/status count parity', () => {
});
expect(resolveRes.ok).toBe(true);
- const conflictsRes2 = await fetch(`http://localhost:${server.port}/api/sync/conflicts`);
+ const conflictsRes2 = await fetch(`http://127.0.0.1:${server.port}/api/sync/conflicts`);
const conflictsBody2 = (await conflictsRes2.json()) as {
conflicts: Array<{ file: string }>;
};
expect(conflictsBody2.conflicts).toHaveLength(1);
expect(conflictsBody2.conflicts[0]?.file).toBe(fileB);
- const statusRes2 = await fetch(`http://localhost:${server.port}/api/sync/status`);
+ const statusRes2 = await fetch(`http://127.0.0.1:${server.port}/api/sync/status`);
const statusBody2 = (await statusRes2.json()) as { conflictCount: number };
expect(statusBody2.conflictCount).toBe(1);
} finally {
@@ -349,7 +349,7 @@ describe('FR14: lifecycle restore function (in-process; CI-runnable)', () => {
});
expect(restoredEvent).toBeDefined();
- const res = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -430,7 +430,7 @@ describe('on-load lifecycle seed from ConflictStore (runtime race fix)', () => {
cleanups.push(() => server.cleanup());
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
@@ -537,7 +537,7 @@ describeBoot('FR14: boot-time lifecycle restoration from conflicts.json', () =>
});
expect(restoredEvent).toBeDefined();
- const res = await fetch(`http://localhost:${booted.port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -579,7 +579,7 @@ describe('FR16: "Keep mine" dispatched as strategy="content" writes the bytes th
await execFileAsync('git', ['-C', server.contentDir, 'commit', '-m', 'base']);
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
@@ -657,7 +657,7 @@ describe('FR17: Conflicts list HTTP shape (data feed the sidebar section consume
const server = await createTestServer({ contentDir: tmpDir, keepContentDir: true });
cleanups.push(() => server.cleanup());
- const beforeRes = await fetch(`http://localhost:${server.port}/api/sync/conflicts`);
+ const beforeRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/conflicts`);
expect(beforeRes.ok).toBe(true);
const beforeBody = (await beforeRes.json()) as {
conflicts: Array<{ file: string; detectedAt: string }>;
@@ -670,7 +670,7 @@ describe('FR17: Conflicts list HTTP shape (data feed the sidebar section consume
expect(typeof entry.detectedAt).toBe('string');
}
- const resolveRes = await fetch(`http://localhost:${server.port}/api/sync/resolve-conflict`, {
+ const resolveRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/resolve-conflict`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -681,7 +681,7 @@ describe('FR17: Conflicts list HTTP shape (data feed the sidebar section consume
});
expect(resolveRes.ok).toBe(true);
- const afterRes = await fetch(`http://localhost:${server.port}/api/sync/conflicts`);
+ const afterRes = await fetch(`http://127.0.0.1:${server.port}/api/sync/conflicts`);
const afterBody = (await afterRes.json()) as { conflicts: Array<{ file: string }> };
expect(afterBody.conflicts).toHaveLength(1);
expect(afterBody.conflicts[0]?.file).toBe(fileB);
@@ -694,7 +694,7 @@ describe('FR17: Conflicts list HTTP shape (data feed the sidebar section consume
await execFileAsync('git', ['init', '--initial-branch=main', tmpDir2]);
const server2 = await createTestServer({ contentDir: tmpDir2, keepContentDir: true });
cleanups.push(() => server2.cleanup());
- const emptyRes = await fetch(`http://localhost:${server2.port}/api/sync/conflicts`);
+ const emptyRes = await fetch(`http://127.0.0.1:${server2.port}/api/sync/conflicts`);
const emptyBody = (await emptyRes.json()) as { conflicts: Array<{ file: string }> };
expect(emptyBody.conflicts).toHaveLength(0);
diff --git a/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts b/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
index 17afb8f4c..e71ed8fff 100644
--- a/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
+++ b/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
@@ -111,7 +111,7 @@ describe('DU (delete-modify) conflict — foundational contract', () => {
test('GET /api/sync/conflict-content returns kind="delete-modify" when stage 2 is absent', async () => {
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents !== undefined;
@@ -166,7 +166,7 @@ describe('UD (modify-delete) conflict — foundational contract', () => {
test('GET /api/sync/conflict-content returns kind="modify-delete" when stage 3 is absent', async () => {
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
return res?.ok ?? false;
});
@@ -266,7 +266,7 @@ describe('both-modified conflict — backward compatibility', () => {
test('GET /api/sync/conflict-content returns kind="both-modified" when stages 2+3 are present', async () => {
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
return res?.ok ?? false;
});
diff --git a/packages/app/tests/integration/cross-doc-stale-cache.test.ts b/packages/app/tests/integration/cross-doc-stale-cache.test.ts
index 28fe1514b..a93779165 100644
--- a/packages/app/tests/integration/cross-doc-stale-cache.test.ts
+++ b/packages/app/tests/integration/cross-doc-stale-cache.test.ts
@@ -61,7 +61,7 @@ describe('Cross-document stale cache (epoch-scoped IDB)', () => {
writeFileSync(join(server.contentDir, `${DOC_A_NAME}.md`), DOC_A_FIXTURE, 'utf-8');
writeFileSync(join(server.contentDir, `${DOC_B_NAME}.md`), DOC_B_FIXTURE, 'utf-8');
- const firstPool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const firstPool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => firstPool.dispose());
const firstServerId = await seedPoolServerInstanceId(server, firstPool);
@@ -92,7 +92,7 @@ describe('Cross-document stale cache (epoch-scoped IDB)', () => {
);
cleanups.push(() => createSpy.mockRestore());
- const secondPool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const secondPool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => secondPool.dispose());
const secondServerId = await seedPoolServerInstanceId(server, secondPool);
diff --git a/packages/app/tests/integration/disk-ack-missed-frame.test.ts b/packages/app/tests/integration/disk-ack-missed-frame.test.ts
index 53e536c02..d21af6c8e 100644
--- a/packages/app/tests/integration/disk-ack-missed-frame.test.ts
+++ b/packages/app/tests/integration/disk-ack-missed-frame.test.ts
@@ -32,8 +32,8 @@ describe('T15: Missed disk-ack frame recovery via /api/server-info', () => {
});
cleanups.push(() => server.shutdown());
- const baseUrl = `http://localhost:${server.port}`;
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const baseUrl = `http://127.0.0.1:${server.port}`;
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await refreshServerInfo(pool, baseUrl);
diff --git a/packages/app/tests/integration/disk-authority-reconcile.test.ts b/packages/app/tests/integration/disk-authority-reconcile.test.ts
index fbbf276af..bc2248ffc 100644
--- a/packages/app/tests/integration/disk-authority-reconcile.test.ts
+++ b/packages/app/tests/integration/disk-authority-reconcile.test.ts
@@ -23,7 +23,7 @@ afterEach(async () => {
});
async function frontmatterPatch(port: number, docName: string, patch: Record<string, unknown>) {
- return fetch(`http://localhost:${port}/api/frontmatter-patch`, {
+ return fetch(`http://127.0.0.1:${port}/api/frontmatter-patch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ docName, patch }),
@@ -31,7 +31,7 @@ async function frontmatterPatch(port: number, docName: string, patch: Record<str
}
async function renamePath(port: number, fromPath: string, toPath: string) {
- return fetch(`http://localhost:${port}/api/rename-path`, {
+ return fetch(`http://127.0.0.1:${port}/api/rename-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ kind: 'file', fromPath, toPath }),
@@ -50,7 +50,7 @@ describe('PRD-6832 β L1: agent write reconciles a newer out-of-band disk edit',
writeFileSync(filePath, '# V2 NATIVE OUT-OF-BAND EDIT\n\nbody-v2-native\n', 'utf-8');
- const res = await fetch(`http://localhost:${port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -131,7 +131,7 @@ describe('PRD-6832 β L1: agent write reconciles a newer out-of-band disk edit',
writeFileSync(filePath, '# Doc\n\nseed-body\n\ndisk-oob-line\n', 'utf-8');
- const res = await fetch(`http://localhost:${port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ docName, markdown: 'agent-line\n', position: 'append' }),
diff --git a/packages/app/tests/integration/disk-divergence-backstop.test.ts b/packages/app/tests/integration/disk-divergence-backstop.test.ts
index aec274f5b..5d212ee54 100644
--- a/packages/app/tests/integration/disk-divergence-backstop.test.ts
+++ b/packages/app/tests/integration/disk-divergence-backstop.test.ts
@@ -27,7 +27,7 @@ async function writeMd(
markdown: string,
opts: { docName: string; position: 'append' | 'prepend' | 'replace' },
) {
- return fetch(`http://localhost:${port}/api/agent-write-md`, {
+ return fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ markdown, ...opts }),
@@ -38,7 +38,7 @@ async function agentUndoRaw(
port: number,
opts: { docName: string; connectionId: string; scope?: 'last' | 'session' },
) {
- return fetch(`http://localhost:${port}/api/agent-undo`, {
+ return fetch(`http://127.0.0.1:${port}/api/agent-undo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
diff --git a/packages/app/tests/integration/document-list-depth1.test.ts b/packages/app/tests/integration/document-list-depth1.test.ts
index c12868c52..07c893f4d 100644
--- a/packages/app/tests/integration/document-list-depth1.test.ts
+++ b/packages/app/tests/integration/document-list-depth1.test.ts
@@ -23,7 +23,7 @@ afterAll(async () => {
});
const depth1 = (dir?: string): string => {
- const base = `http://localhost:${server.port}/api/documents?showAll=true&depth=1`;
+ const base = `http://127.0.0.1:${server.port}/api/documents?showAll=true&depth=1`;
return dir ? `${base}&dir=${encodeURIComponent(dir)}` : base;
};
@@ -72,7 +72,7 @@ describe('GET /api/documents depth-1 lazy children', () => {
});
test('without depth=1, the recursive walk still returns descendants', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents?showAll=true`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents?showAll=true`);
const body = DocumentListSuccessSchema.parse(await res.json());
const paths = body.documents.map((e) => (e.kind === 'folder' ? e.path : (e.docName ?? e.path)));
expect(paths).toContain('with-kids/grandchild/deep');
diff --git a/packages/app/tests/integration/document-list-showall-cap.test.ts b/packages/app/tests/integration/document-list-showall-cap.test.ts
index dda54845a..4ef274e09 100644
--- a/packages/app/tests/integration/document-list-showall-cap.test.ts
+++ b/packages/app/tests/integration/document-list-showall-cap.test.ts
@@ -23,13 +23,13 @@ afterAll(async () => {
});
async function fetchShowAll() {
- const res = await fetch(`http://localhost:${server.port}/api/documents?showAll=true`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents?showAll=true`);
expect(res.ok).toBe(true);
return DocumentListSuccessSchema.parse(await res.json());
}
async function fetchDefaultRaw(): Promise<Record<string, unknown>> {
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
expect(res.ok).toBe(true);
return (await res.json()) as Record<string, unknown>;
}
diff --git a/packages/app/tests/integration/editor-area-conflict-swap.test.ts b/packages/app/tests/integration/editor-area-conflict-swap.test.ts
index f655bb7ec..b49f4e309 100644
--- a/packages/app/tests/integration/editor-area-conflict-swap.test.ts
+++ b/packages/app/tests/integration/editor-area-conflict-swap.test.ts
@@ -20,7 +20,7 @@ async function setupServerWithDoc(docName: string, initial: string): Promise<Tes
cleanups.push(() => server.cleanup());
writeFileSync(join(server.contentDir, `${docName}.md`), initial, 'utf-8');
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
diff --git a/packages/app/tests/integration/empty-folder-visibility.test.ts b/packages/app/tests/integration/empty-folder-visibility.test.ts
index 622ea8a12..8c5946cdf 100644
--- a/packages/app/tests/integration/empty-folder-visibility.test.ts
+++ b/packages/app/tests/integration/empty-folder-visibility.test.ts
@@ -16,7 +16,7 @@ async function awaitFolderPathsIndexed(
const deadline = Date.now() + timeoutMs;
let lastFolderPaths: string[] = [];
while (Date.now() < deadline) {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (res?.ok) {
const body = DocumentListSuccessSchema.parse(await res.json());
lastFolderPaths = body.documents.filter((e) => e.kind === 'folder').map((e) => e.path ?? '');
@@ -49,7 +49,7 @@ describe('/api/documents empty folder — boot-time', () => {
});
test('returns empty subfolder created before server start', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
expect(res.ok).toBe(true);
const body = DocumentListSuccessSchema.parse(await res.json());
const folders = body.documents.filter((e) => e.kind === 'folder');
@@ -58,7 +58,7 @@ describe('/api/documents empty folder — boot-time', () => {
});
test('returns nested empty folder hierarchy created before server start', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
expect(res.ok).toBe(true);
const body = DocumentListSuccessSchema.parse(await res.json());
const folderPaths = body.documents.filter((e) => e.kind === 'folder').map((e) => e.path);
diff --git a/packages/app/tests/integration/external-edit-stale-client.test.ts b/packages/app/tests/integration/external-edit-stale-client.test.ts
index 4ed1e8ed9..b67c01eb6 100644
--- a/packages/app/tests/integration/external-edit-stale-client.test.ts
+++ b/packages/app/tests/integration/external-edit-stale-client.test.ts
@@ -41,7 +41,7 @@ describe('T9: External disk edit during server restart', () => {
writeFileSync(join(server.contentDir, 'test-doc.md'), CONTENT_A, 'utf-8');
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
diff --git a/packages/app/tests/integration/idle-shutdown-multi-client.test.ts b/packages/app/tests/integration/idle-shutdown-multi-client.test.ts
index 3d7330140..06946c963 100644
--- a/packages/app/tests/integration/idle-shutdown-multi-client.test.ts
+++ b/packages/app/tests/integration/idle-shutdown-multi-client.test.ts
@@ -58,13 +58,13 @@ test('closing spawning editor leaves sibling editor connected; idle-shutdown fir
const yDocA = new Y.Doc();
const yDocB = new Y.Doc();
const providerA = new HocuspocusProvider({
- url: `ws://localhost:${port}/collab`,
+ url: `ws://127.0.0.1:${port}/collab`,
name: docA,
document: yDocA,
connect: true,
});
const providerB = new HocuspocusProvider({
- url: `ws://localhost:${port}/collab`,
+ url: `ws://127.0.0.1:${port}/collab`,
name: docB,
document: yDocB,
connect: true,
diff --git a/packages/app/tests/integration/init-load-byte-stable.test.ts b/packages/app/tests/integration/init-load-byte-stable.test.ts
index 8a9260c1a..5312602d3 100644
--- a/packages/app/tests/integration/init-load-byte-stable.test.ts
+++ b/packages/app/tests/integration/init-load-byte-stable.test.ts
@@ -23,7 +23,7 @@ interface OpenedDoc {
async function openDoc(port: number, docName: string): Promise<OpenedDoc> {
const doc = new Y.Doc();
const provider = new HocuspocusProvider({
- url: `ws://localhost:${port}/collab`,
+ url: `ws://127.0.0.1:${port}/collab`,
name: docName,
document: doc,
connect: true,
diff --git a/packages/app/tests/integration/lazy-continuation-tolerance.test.ts b/packages/app/tests/integration/lazy-continuation-tolerance.test.ts
new file mode 100644
index 000000000..c47104958
--- /dev/null
+++ b/packages/app/tests/integration/lazy-continuation-tolerance.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, test } from 'bun:test';
+import { setTimeout as wait } from 'node:timers/promises';
+import * as Y from 'yjs';
+import {
+ agentWriteMd,
+ assertBridgeInvariant,
+ awaitDocQuiescence,
+ classifyFinalState,
+ createTestClients,
+ createTestServer,
+} from './test-harness';
+
+describe('paragraph lazy-continuation indent — doc settles within tolerance', () => {
+ test('leading-space continuation line converges and the invariant holds', async () => {
+ const server = await createTestServer();
+ const docName = `stall-repro-${Date.now()}`;
+ try {
+ await agentWriteMd(server.port, 'seed paragraph\n', { docName, position: 'replace' });
+ await wait(200);
+ const clients = await createTestClients(server.port, {
+ count: 2,
+ docName,
+ perClientOptions: { skipInvariantWatcher: true },
+ });
+ const [c0, c1] = clients;
+ try {
+ c0.doc.transact(() => {
+ c0.ytext.insert(c0.ytext.length, '\n\npara two\n continuation text');
+ });
+ await awaitDocQuiescence(c0.doc, { timeoutMs: 3000 });
+ await wait(300);
+ await Promise.all(clients.map((c) => awaitDocQuiescence(c.doc, { timeoutMs: 3000 })));
+
+ const paragraph = new Y.XmlElement('paragraph');
+ const t = new Y.XmlText();
+ t.applyDelta([{ insert: 'healer edit' }]);
+ paragraph.insert(0, [t]);
+ c1.fragment.push([paragraph]);
+ await Promise.all(clients.map((c) => awaitDocQuiescence(c.doc, { timeoutMs: 3000 })));
+ await wait(300);
+
+ const outcome = classifyFinalState(clients);
+ expect(outcome.outcome).toBe('converged-late');
+ for (const c of clients) {
+ assertBridgeInvariant(c.ytext, c.fragment);
+ }
+ const finalText = c0.ytext.toString();
+ expect(finalText).toContain('\n continuation text');
+ expect(finalText).toContain('healer edit');
+ expect(finalText.split('continuation text').length - 1).toBe(1);
+ } finally {
+ for (const c of clients) await c.cleanup();
+ }
+ } finally {
+ await server.cleanup();
+ }
+ }, 30_000);
+});
diff --git a/packages/app/tests/integration/link-graph-metadata.test.ts b/packages/app/tests/integration/link-graph-metadata.test.ts
index e7705d6c9..ab0f512ae 100644
--- a/packages/app/tests/integration/link-graph-metadata.test.ts
+++ b/packages/app/tests/integration/link-graph-metadata.test.ts
@@ -54,7 +54,7 @@ afterAll(async () => {
});
async function fetchLinkGraph(): Promise<LinkGraphResponse> {
- const res = await fetch(`http://localhost:${server.port}/api/link-graph`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/link-graph`);
return res.json() as Promise<LinkGraphResponse>;
}
diff --git a/packages/app/tests/integration/managed-rename-crash-recovery.test.ts b/packages/app/tests/integration/managed-rename-crash-recovery.test.ts
index 9663a12c9..43e54a3a5 100644
--- a/packages/app/tests/integration/managed-rename-crash-recovery.test.ts
+++ b/packages/app/tests/integration/managed-rename-crash-recovery.test.ts
@@ -111,7 +111,7 @@ describe('Managed rename — crash recovery via boot-time initAsync (QA-006)', (
expect(existsSync(join(contentDir, 'essays', 'a.md'))).toBe(false);
expect(existsSync(managedRenameJournalPath(contentDir))).toBe(false);
- const res = await fetch(`http://localhost:${server.port}/api/rename-path`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/rename-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ kind: 'folder', fromPath: 'articles', toPath: 'essays' }),
diff --git a/packages/app/tests/integration/managed-rename-loaded-doc.test.ts b/packages/app/tests/integration/managed-rename-loaded-doc.test.ts
index 385ebe33c..30e18aa63 100644
--- a/packages/app/tests/integration/managed-rename-loaded-doc.test.ts
+++ b/packages/app/tests/integration/managed-rename-loaded-doc.test.ts
@@ -48,7 +48,7 @@ describe('Managed rename — loaded-Y.Doc rewrite path (QA-040 / QA-008)', () =>
expect(ytext.toString()).toContain('[[old]]');
expect(ytext.toString()).not.toContain('[[new]]');
- const res = await fetch(`http://localhost:${server.port}/api/rename-path`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/rename-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ kind: 'file', fromPath: 'old', toPath: 'new' }),
diff --git a/packages/app/tests/integration/managed-rename-populated-target.test.ts b/packages/app/tests/integration/managed-rename-populated-target.test.ts
index 299c53c83..7c9aedc8c 100644
--- a/packages/app/tests/integration/managed-rename-populated-target.test.ts
+++ b/packages/app/tests/integration/managed-rename-populated-target.test.ts
@@ -60,7 +60,7 @@ describe('T8: Managed-rename with populated target', () => {
const preText = preDoc.getText('source').toString();
const preClientIdSize = preDoc.store.clients.size;
- const res = await fetch(`http://localhost:${server.port}/api/rename-path`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/rename-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
diff --git a/packages/app/tests/integration/mcp-http.test.ts b/packages/app/tests/integration/mcp-http.test.ts
index 65894e4c2..13396531f 100644
--- a/packages/app/tests/integration/mcp-http.test.ts
+++ b/packages/app/tests/integration/mcp-http.test.ts
@@ -7,7 +7,7 @@ test('POST /mcp serves MCP JSON-RPC over Streamable HTTP', async () => {
const server = await createTestServer();
try {
- const init = await fetch(`http://localhost:${server.port}/mcp`, {
+ const init = await fetch(`http://127.0.0.1:${server.port}/mcp`, {
method: 'POST',
headers: {
accept: 'application/json, text/event-stream',
@@ -36,7 +36,7 @@ test('POST /mcp serves MCP JSON-RPC over Streamable HTTP', async () => {
expect(initBody.result?.serverInfo?.name).toBe('open-knowledge');
expect(initBody.result?.protocolVersion).toBeTruthy();
- const initialized = await fetch(`http://localhost:${server.port}/mcp`, {
+ const initialized = await fetch(`http://127.0.0.1:${server.port}/mcp`, {
method: 'POST',
headers: {
accept: 'application/json, text/event-stream',
@@ -48,7 +48,7 @@ test('POST /mcp serves MCP JSON-RPC over Streamable HTTP', async () => {
});
expect(initialized.status).toBe(202);
- const tools = await fetch(`http://localhost:${server.port}/mcp`, {
+ const tools = await fetch(`http://127.0.0.1:${server.port}/mcp`, {
method: 'POST',
headers: {
accept: 'application/json, text/event-stream',
diff --git a/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts b/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts
index f55f82b7f..7f7010ab0 100644
--- a/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts
+++ b/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts
@@ -70,7 +70,7 @@ describe('MCP move tool — real roundtrip against live OK server (QA-004 / QA-0
const { server: mcp, registrations } = createCapturingServer();
registerMove(mcp, {
- serverUrl: `http://localhost:${server.port}`,
+ serverUrl: `http://127.0.0.1:${server.port}`,
config: BASE_CONFIG,
resolveCwd: async () => server.contentDir,
});
@@ -121,7 +121,7 @@ describe('MCP move tool — real roundtrip against live OK server (QA-004 / QA-0
const { server: mcp, registrations } = createCapturingServer();
registerMove(mcp, {
- serverUrl: `http://localhost:${server.port}`,
+ serverUrl: `http://127.0.0.1:${server.port}`,
config: BASE_CONFIG,
resolveCwd: async () => server.contentDir,
});
diff --git a/packages/app/tests/integration/mcp-session-identity.test.ts b/packages/app/tests/integration/mcp-session-identity.test.ts
index ee73aa2c8..ea45b43e2 100644
--- a/packages/app/tests/integration/mcp-session-identity.test.ts
+++ b/packages/app/tests/integration/mcp-session-identity.test.ts
@@ -14,7 +14,7 @@ interface InitializedSession {
}
async function openMcpSession(port: number, clientName: string): Promise<InitializedSession> {
- const init = await fetch(`http://localhost:${port}/mcp`, {
+ const init = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
accept: 'application/json, text/event-stream',
@@ -37,7 +37,7 @@ async function openMcpSession(port: number, clientName: string): Promise<Initial
const initBody = (await init.json()) as { result?: { protocolVersion?: string } };
const protocolVersion = initBody.result?.protocolVersion ?? MCP_PROTOCOL_VERSION;
- const initialized = await fetch(`http://localhost:${port}/mcp`, {
+ const initialized = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
accept: 'application/json, text/event-stream',
@@ -69,7 +69,7 @@ async function callWriteDocument(
},
rpcId: number,
): Promise<ToolCallResult> {
- const res = await fetch(`http://localhost:${port}/mcp`, {
+ const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
accept: 'application/json, text/event-stream',
@@ -164,11 +164,11 @@ test('two simultaneous Claude MCP sessions land with identical displayName but d
}
} finally {
await client.cleanup();
- await fetch(`http://localhost:${server.port}/mcp`, {
+ await fetch(`http://127.0.0.1:${server.port}/mcp`, {
method: 'DELETE',
headers: { 'mcp-session-id': sessionA.sessionId },
});
- await fetch(`http://localhost:${server.port}/mcp`, {
+ await fetch(`http://127.0.0.1:${server.port}/mcp`, {
method: 'DELETE',
headers: { 'mcp-session-id': sessionB.sessionId },
});
diff --git a/packages/app/tests/integration/mid-drain-restart.test.ts b/packages/app/tests/integration/mid-drain-restart.test.ts
index b20abe098..2ac6dfae0 100644
--- a/packages/app/tests/integration/mid-drain-restart.test.ts
+++ b/packages/app/tests/integration/mid-drain-restart.test.ts
@@ -32,7 +32,7 @@ describe('T11: Mid-drain server restart', () => {
});
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
diff --git a/packages/app/tests/integration/multi-agent-presence.test.ts b/packages/app/tests/integration/multi-agent-presence.test.ts
index dd99ad2ed..9f08140ef 100644
--- a/packages/app/tests/integration/multi-agent-presence.test.ts
+++ b/packages/app/tests/integration/multi-agent-presence.test.ts
@@ -92,7 +92,7 @@ describe('multi-agent presence — Tier 1 regression gate (FR-8)', () => {
const doc = `mp-simple-${crypto.randomUUID().slice(0, 8)}`;
const uuid = `uuid-simple-${crypto.randomUUID().slice(0, 8)}`;
- const res = await fetch(`http://localhost:${server.port}/api/agent-write`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -126,7 +126,7 @@ describe('multi-agent presence — Tier 1 regression gate (FR-8)', () => {
clientName: 'claude-code',
});
- const res = await fetch(`http://localhost:${server.port}/api/metrics/agent-presence`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/metrics/agent-presence`);
expect(res.ok).toBe(true);
const body = (await res.json()) as {
presence: Record<
diff --git a/packages/app/tests/integration/persistence-failure-surfacing-handlers.test.ts b/packages/app/tests/integration/persistence-failure-surfacing-handlers.test.ts
index fb33368a5..0872ea335 100644
--- a/packages/app/tests/integration/persistence-failure-surfacing-handlers.test.ts
+++ b/packages/app/tests/integration/persistence-failure-surfacing-handlers.test.ts
@@ -25,7 +25,7 @@ describe('disk-persistence failure surfacing — edit_document (/api/agent-patch
await agentWriteMd(server.port, '# Doc\n\nFINDME here\n', { docName, position: 'replace' });
process.env.OK_TEST_STORE_FAULT = docName;
- const res = await fetch(`http://localhost:${server.port}/api/agent-patch`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-patch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ find: 'FINDME', replace: 'REPLACED', docName }),
@@ -48,7 +48,7 @@ describe('disk-persistence failure surfacing — edit_document (/api/agent-patch
});
async function frontmatterPatch(port: number, docName: string, patch: Record<string, unknown>) {
- return fetch(`http://localhost:${port}/api/frontmatter-patch`, {
+ return fetch(`http://127.0.0.1:${port}/api/frontmatter-patch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ docName, patch }),
@@ -82,7 +82,7 @@ describe('disk-persistence failure surfacing — edit_frontmatter (/api/frontmat
async function getCheckpointShas(port: number, docName: string): Promise<string[]> {
const r = await fetch(
- `http://localhost:${port}/api/history?docName=${encodeURIComponent(docName)}`,
+ `http://127.0.0.1:${port}/api/history?docName=${encodeURIComponent(docName)}`,
);
if (!r.ok) return [];
const body = (await r.json().catch(() => ({}))) as { entries?: Array<{ sha?: string }> };
@@ -104,7 +104,7 @@ describe('disk-persistence failure surfacing — version rollback (/api/rollback
expect(priorSha).toMatch(/^[0-9a-f]{40}$/i);
process.env.OK_TEST_STORE_FAULT = docName;
- const res = await fetch(`http://localhost:${server.port}/api/rollback`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/rollback`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ docName, commitSha: priorSha }),
diff --git a/packages/app/tests/integration/persistence-failure-surfacing.test.ts b/packages/app/tests/integration/persistence-failure-surfacing.test.ts
index d71e88a05..7eceeacd2 100644
--- a/packages/app/tests/integration/persistence-failure-surfacing.test.ts
+++ b/packages/app/tests/integration/persistence-failure-surfacing.test.ts
@@ -13,7 +13,7 @@ afterEach(async () => {
});
async function writeMd(port: number, docName: string): Promise<Response> {
- return fetch(`http://localhost:${port}/api/agent-write-md`, {
+ return fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ docName, markdown: '# persisted content\n', position: 'replace' }),
diff --git a/packages/app/tests/integration/populated-idb-stale-server.test.ts b/packages/app/tests/integration/populated-idb-stale-server.test.ts
index 22e2d7371..e03afa483 100644
--- a/packages/app/tests/integration/populated-idb-stale-server.test.ts
+++ b/packages/app/tests/integration/populated-idb-stale-server.test.ts
@@ -38,7 +38,7 @@ describe('T14: populated IDB meets stale server instance', () => {
await seedClientPersistenceState('test-doc', [staleBytes], STALE_INSTANCE_ID);
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
pool.setExpectedServerInstanceId(STALE_INSTANCE_ID);
diff --git a/packages/app/tests/integration/provider-pool-buffer-replay.test.ts b/packages/app/tests/integration/provider-pool-buffer-replay.test.ts
index 29a3279de..76a9f9d3e 100644
--- a/packages/app/tests/integration/provider-pool-buffer-replay.test.ts
+++ b/packages/app/tests/integration/provider-pool-buffer-replay.test.ts
@@ -25,7 +25,7 @@ describe('T12: buffer-and-replay across server-instance-mismatch', () => {
let server = await createRestartableServer();
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
@@ -53,7 +53,7 @@ describe('T12: buffer-and-replay across server-instance-mismatch', () => {
let server = await createRestartableServer();
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
diff --git a/packages/app/tests/integration/provider-pool-reconnect.test.ts b/packages/app/tests/integration/provider-pool-reconnect.test.ts
index e4e4f42d4..5e80d35c4 100644
--- a/packages/app/tests/integration/provider-pool-reconnect.test.ts
+++ b/packages/app/tests/integration/provider-pool-reconnect.test.ts
@@ -90,7 +90,7 @@ describe('ProviderPool reconnects', () => {
const docName = 'reload-doc';
writeFileSync(join(server.contentDir, `${docName}.md`), SMALL_FIXTURE, 'utf-8');
- const firstPool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const firstPool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
await seedPoolServerInstanceId(server, firstPool);
await seedAndSyncSingleClient(server, firstPool, docName);
await wait(300);
@@ -106,7 +106,7 @@ describe('ProviderPool reconnects', () => {
expect(server.instance.hocuspocus.documents.has(docName)).toBe(true);
- const secondPool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const secondPool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => secondPool.dispose());
await seedPoolServerInstanceId(server, secondPool);
secondPool.open(docName);
@@ -142,7 +142,7 @@ describe('ProviderPool reconnects', () => {
},
};
- const firstPool = new ProviderPool(3, `ws://localhost:${server.port}/collab`, { storage });
+ const firstPool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`, { storage });
const firstServerId = await seedPoolServerInstanceId(server, firstPool);
await seedAndSyncSingleClient(server, firstPool, docName);
await wait(300);
@@ -159,7 +159,7 @@ describe('ProviderPool reconnects', () => {
server = await server.killAndRestartOnSamePort({ downtimeMs: 500 });
cleanups.unshift(() => server.shutdown());
- const secondPool = new ProviderPool(3, `ws://localhost:${server.port}/collab`, { storage });
+ const secondPool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`, { storage });
cleanups.push(() => secondPool.dispose());
const secondServerId = await seedPoolServerInstanceId(server, secondPool);
expect(secondServerId).not.toBe(firstServerId);
@@ -182,7 +182,7 @@ describe('ProviderPool reconnects', () => {
let server = await createRestartableServer();
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
@@ -216,7 +216,7 @@ describe('ProviderPool reconnects', () => {
let server = await createRestartableServer();
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
@@ -300,7 +300,7 @@ describe('ProviderPool reconnects', () => {
let server = await createRestartableServer();
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
diff --git a/packages/app/tests/integration/removal-phantom-resurrection.test.ts b/packages/app/tests/integration/removal-phantom-resurrection.test.ts
index cd023f5e1..cecefb407 100644
--- a/packages/app/tests/integration/removal-phantom-resurrection.test.ts
+++ b/packages/app/tests/integration/removal-phantom-resurrection.test.ts
@@ -54,7 +54,7 @@ async function renamePath(
fromPath: string,
toPath: string,
): Promise<{ status: number; body: { ok: boolean; renamed?: unknown[] } }> {
- const res = await fetch(`http://localhost:${port}/api/rename-path`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/rename-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ kind: 'file', fromPath, toPath }),
@@ -68,7 +68,7 @@ async function deletePath(
path: string,
kind: 'file' | 'folder' = 'file',
): Promise<{ status: number; body: { ok: boolean; deletedDocNames?: string[] } }> {
- const res = await fetch(`http://localhost:${port}/api/delete-path`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/delete-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ kind, path }),
@@ -81,7 +81,7 @@ async function createPage(
port: number,
path: string,
): Promise<{ status: number; body: { ok: boolean; docName?: string } }> {
- const res = await fetch(`http://localhost:${port}/api/create-page`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/create-page`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path }),
@@ -93,7 +93,7 @@ async function createPage(
async function seedDoc(server: TestServer, docName: string, content = '# seed\n'): Promise<void> {
writeFileSync(join(server.contentDir, `${docName}.md`), content, 'utf-8');
await pollUntilAsync(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
if (!res.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) === true;
@@ -343,7 +343,7 @@ describe('RecentlyRemovedDocs — cache lifecycle', () => {
const doc = new Y.Doc();
const provider = new HocuspocusProvider({
- url: `ws://localhost:${server.port}/collab`,
+ url: `ws://127.0.0.1:${server.port}/collab`,
name: fromName,
document: doc,
connect: true,
@@ -393,7 +393,7 @@ describe('RecentlyRemovedDocs — cache lifecycle', () => {
const doc = new Y.Doc();
const provider = new HocuspocusProvider({
- url: `ws://localhost:${server.port}/collab`,
+ url: `ws://127.0.0.1:${server.port}/collab`,
name: docName,
document: doc,
connect: true,
diff --git a/packages/app/tests/integration/rename-history.test.ts b/packages/app/tests/integration/rename-history.test.ts
index cf801d417..e938377ee 100644
--- a/packages/app/tests/integration/rename-history.test.ts
+++ b/packages/app/tests/integration/rename-history.test.ts
@@ -70,7 +70,7 @@ async function getHistory(
const params = new URLSearchParams({ docName });
if (opts?.branch) params.set('branch', opts.branch);
if (opts?.limit !== undefined) params.set('limit', String(opts.limit));
- const res = await fetch(`http://localhost:${port}/api/history?${params}`);
+ const res = await fetch(`http://127.0.0.1:${port}/api/history?${params}`);
return (await res.json()) as TimelineResponse;
}
@@ -83,7 +83,7 @@ async function getHistoryVersion(
body: { ok: boolean; sha?: string; content?: string; error?: string };
}> {
const params = new URLSearchParams({ docName });
- const res = await fetch(`http://localhost:${port}/api/history/${sha}?${params}`);
+ const res = await fetch(`http://127.0.0.1:${port}/api/history/${sha}?${params}`);
return {
status: res.status,
body: (await res.json()) as { ok: boolean; sha?: string; content?: string; error?: string },
@@ -94,7 +94,7 @@ async function rollback(
port: number,
body: { docName: string; commitSha: string; agentId?: string; agentName?: string },
): Promise<{ status: number; body: RollbackResponse }> {
- const res = await fetch(`http://localhost:${port}/api/rollback`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/rollback`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
@@ -114,7 +114,7 @@ async function renamePath(
summary?: string;
},
): Promise<{ status: number; body: RenameResponse }> {
- const res = await fetch(`http://localhost:${port}/api/rename-path`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/rename-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
@@ -127,7 +127,7 @@ async function deletePath(
port: number,
body: { kind: 'file' | 'folder'; path: string; agentId?: string; agentName?: string },
): Promise<{ status: number }> {
- const res = await fetch(`http://localhost:${port}/api/delete-path`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/delete-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
@@ -139,7 +139,7 @@ async function saveVersion(
port: number,
opts?: { agentId?: string; agentName?: string; message?: string },
): Promise<void> {
- const res = await fetch(`http://localhost:${port}/api/save-version`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/save-version`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -204,7 +204,7 @@ async function awaitWipCommit(
const intervals = [100, 250, 500, 1000];
let attempt = 0;
while (Date.now() < deadline) {
- const flushRes = await fetch(`http://localhost:${server.port}/api/test-flush-git`, {
+ const flushRes = await fetch(`http://127.0.0.1:${server.port}/api/test-flush-git`, {
method: 'POST',
});
if (!flushRes.ok) {
@@ -637,7 +637,7 @@ describe('Timeline rename-history mitigation — integration', () => {
const server = await bootServer();
writeFileSync(join(server.contentDir, 'summary-a.md'), '# A\n', 'utf-8');
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
if (!res.ok) return false;
const data = (await res.json()) as { documents?: DocumentListEntry[] };
return (data.documents ?? []).some((d) => isDocumentListDoc(d) && d.docName === 'summary-a');
@@ -717,7 +717,7 @@ describe('Timeline rename-history mitigation — integration', () => {
const server = await bootServer();
writeFileSync(join(server.contentDir, 'pure-a.md'), '# Pure A\n', 'utf-8');
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
if (!res.ok) return false;
const data = (await res.json()) as { documents?: DocumentListEntry[] };
return (data.documents ?? []).some((d) => isDocumentListDoc(d) && d.docName === 'pure-a');
@@ -750,12 +750,12 @@ describe('Timeline rename-history mitigation — integration', () => {
writeFileSync(join(server.contentDir, 'big', `doc-${i}.md`), `# doc-${i}\n`, 'utf-8');
}
- const rescanRes = await fetch(`http://localhost:${server.port}/api/test-rescan-files`, {
+ const rescanRes = await fetch(`http://127.0.0.1:${server.port}/api/test-rescan-files`, {
method: 'POST',
});
expect(rescanRes.status).toBe(200);
- const docsRes = await fetch(`http://localhost:${server.port}/api/documents`);
+ const docsRes = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
expect(docsRes.status).toBe(200);
const docsData = (await docsRes.json()) as { documents?: DocumentListEntry[] };
const indexedCount = (docsData.documents ?? []).filter(
diff --git a/packages/app/tests/integration/restart-with-embed-doc.test.ts b/packages/app/tests/integration/restart-with-embed-doc.test.ts
index fa83e2a68..221dd54d4 100644
--- a/packages/app/tests/integration/restart-with-embed-doc.test.ts
+++ b/packages/app/tests/integration/restart-with-embed-doc.test.ts
@@ -48,7 +48,7 @@ describe('restart-with-embed-doc: server restart preserves single PM image with
let server = await createRestartableServer({ contentDir });
cleanups.push(() => server.shutdown());
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
diff --git a/packages/app/tests/integration/session-cleanup.test.ts b/packages/app/tests/integration/session-cleanup.test.ts
index ed51334ed..a486accd0 100644
--- a/packages/app/tests/integration/session-cleanup.test.ts
+++ b/packages/app/tests/integration/session-cleanup.test.ts
@@ -17,7 +17,7 @@ afterAll(async () => {
});
function openKeepalive(port: number, connectionId: string): WebSocket {
- const url = `ws://localhost:${port}/collab/keepalive?connectionId=${encodeURIComponent(connectionId)}&pid=${process.pid}`;
+ const url = `ws://127.0.0.1:${port}/collab/keepalive?connectionId=${encodeURIComponent(connectionId)}&pid=${process.pid}`;
return new WebSocket(url);
}
@@ -119,7 +119,7 @@ describe('Keepalive-WS close cleanup (US-011)', () => {
expect(server.instance.sessionManager.hasSession(docName, connectionId)).toBe(true);
- const ws = new WebSocket(`ws://localhost:${server.port}/collab/keepalive?pid=${process.pid}`);
+ const ws = new WebSocket(`ws://127.0.0.1:${server.port}/collab/keepalive?pid=${process.pid}`);
await new Promise<void>((resolve) => {
ws.addEventListener('open', () => {
ws.close();
diff --git a/packages/app/tests/integration/showall-single-flight.test.ts b/packages/app/tests/integration/showall-single-flight.test.ts
index 8e9837a60..b285ac9f6 100644
--- a/packages/app/tests/integration/showall-single-flight.test.ts
+++ b/packages/app/tests/integration/showall-single-flight.test.ts
@@ -15,7 +15,7 @@ const FILES_PER_NESTED_DIR = 40;
let server: TestServer;
function showAllUrl(dir?: string): string {
- const base = `http://localhost:${server.port}/api/documents?showAll=true`;
+ const base = `http://127.0.0.1:${server.port}/api/documents?showAll=true`;
return dir ? `${base}&dir=${encodeURIComponent(dir)}` : base;
}
diff --git a/packages/app/tests/integration/showall-streaming.test.ts b/packages/app/tests/integration/showall-streaming.test.ts
index 9558c7e77..f4914971a 100644
--- a/packages/app/tests/integration/showall-streaming.test.ts
+++ b/packages/app/tests/integration/showall-streaming.test.ts
@@ -10,7 +10,7 @@ const ROOT_FILE_COUNT = 40;
let server: TestServer;
function showAllUrl(dir?: string): string {
- const base = `http://localhost:${server.port}/api/documents?showAll=true`;
+ const base = `http://127.0.0.1:${server.port}/api/documents?showAll=true`;
return dir ? `${base}&dir=${encodeURIComponent(dir)}` : base;
}
diff --git a/packages/app/tests/integration/sidebar-assets.test.ts b/packages/app/tests/integration/sidebar-assets.test.ts
index c0d987485..2231b2384 100644
--- a/packages/app/tests/integration/sidebar-assets.test.ts
+++ b/packages/app/tests/integration/sidebar-assets.test.ts
@@ -46,7 +46,7 @@ afterAll(async () => {
describe('/api/documents sidebar asset rows', () => {
test('returns referenced local assets as non-document rows', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
expect(res.ok).toBe(true);
const body = DocumentListSuccessSchema.parse(await res.json());
diff --git a/packages/app/tests/integration/sidebar-show-all-files.test.ts b/packages/app/tests/integration/sidebar-show-all-files.test.ts
index c6ed3c384..0f4d67850 100644
--- a/packages/app/tests/integration/sidebar-show-all-files.test.ts
+++ b/packages/app/tests/integration/sidebar-show-all-files.test.ts
@@ -57,7 +57,7 @@ afterAll(async () => {
describe('/api/documents?showAll=true', () => {
test("non-bypass request returns today's filtered view (no .gitignored / .okignored / BUILTIN_SKIP_DIRS)", async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
expect(res.ok).toBe(true);
const body = DocumentListSuccessSchema.parse(await res.json());
@@ -74,7 +74,7 @@ describe('/api/documents?showAll=true', () => {
});
test('?showAll=true surfaces .gitignored / .okignored / content-bearing skip-dir markdown but prunes the always-skip floor', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents?showAll=true`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents?showAll=true`);
expect(res.ok).toBe(true);
const body = DocumentListSuccessSchema.parse(await res.json());
@@ -92,7 +92,7 @@ describe('/api/documents?showAll=true', () => {
});
test('?showAll=true surfaces non-md / non-asset files as kind=asset', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents?showAll=true`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents?showAll=true`);
expect(res.ok).toBe(true);
const body = DocumentListSuccessSchema.parse(await res.json());
@@ -121,7 +121,7 @@ describe('/api/documents?showAll=true', () => {
});
test('?showAll=true emits folder entries for content dirs but prunes the always-skip floor (.git / node_modules / .ok)', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents?showAll=true`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents?showAll=true`);
expect(res.ok).toBe(true);
const body = DocumentListSuccessSchema.parse(await res.json());
@@ -140,7 +140,7 @@ describe('/api/documents?showAll=true', () => {
});
test('STOP rule preserved — synthetic system + config docs stay hidden in bypass mode', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents?showAll=true`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents?showAll=true`);
expect(res.ok).toBe(true);
const body = DocumentListSuccessSchema.parse(await res.json());
@@ -164,13 +164,13 @@ describe('/api/documents?showAll=true', () => {
});
test('?showAll=true is per-request only — non-bypass call after bypass call still returns filtered view', async () => {
- const r1 = await fetch(`http://localhost:${server.port}/api/documents?showAll=true`);
+ const r1 = await fetch(`http://127.0.0.1:${server.port}/api/documents?showAll=true`);
const b1 = DocumentListSuccessSchema.parse(await r1.json());
expect(b1.documents.some((e) => e.kind === 'document' && e.docName === 'secrets/api-key')).toBe(
true,
);
- const r2 = await fetch(`http://localhost:${server.port}/api/documents`);
+ const r2 = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
const b2 = DocumentListSuccessSchema.parse(await r2.json());
expect(b2.documents.some((e) => e.kind === 'document' && e.docName === 'secrets/api-key')).toBe(
false,
diff --git a/packages/app/tests/integration/single-file-mode.test.ts b/packages/app/tests/integration/single-file-mode.test.ts
index 1d74930d1..df4486fdc 100644
--- a/packages/app/tests/integration/single-file-mode.test.ts
+++ b/packages/app/tests/integration/single-file-mode.test.ts
@@ -70,7 +70,7 @@ describe('single-file mode — content scope (D3)', () => {
expect(contentFilter.isExcluded('secret.md')).toBe(true);
expect(contentFilter.isExcluded('journal.md')).toBe(true);
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
const json = (await res.json()) as { documents?: Array<{ docName: string }> };
const docNames = (json.documents ?? []).map((d) => d.docName);
expect(docNames).toContain('notes');
@@ -117,7 +117,7 @@ describe('single-file mode — no MCP (FR5)', () => {
singleDocRelPath: 'notes.md',
});
try {
- const res = await fetch(`http://localhost:${server.port}/mcp`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/mcp`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{}',
@@ -294,7 +294,7 @@ describe('single-file mode — content-tree writes refused (G4)', () => {
singleDocRelPath: 'notes.md',
});
try {
- const res = await fetch(`http://localhost:${server.port}/api/folder-config`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/folder-config`, {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ path: '.', frontmatter: { title: 'Nope' } }),
@@ -317,7 +317,7 @@ describe('single-file mode — content-tree writes refused (G4)', () => {
singleDocRelPath: 'notes.md',
});
try {
- const res = await fetch(`http://localhost:${server.port}/api/template`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/template`, {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ folder: '.', name: 'daily', body: '# {{title}}\n' }),
diff --git a/packages/app/tests/integration/stale-idb-doc-reload.test.ts b/packages/app/tests/integration/stale-idb-doc-reload.test.ts
index dbeb48120..02046c4ca 100644
--- a/packages/app/tests/integration/stale-idb-doc-reload.test.ts
+++ b/packages/app/tests/integration/stale-idb-doc-reload.test.ts
@@ -74,7 +74,7 @@ describe('client-persisted state meets a re-seeded doc lineage (same server inst
writeFileSync(filePath, FIXTURE_V1, 'utf-8');
await awaitFileWatcherIndexed(server, docName);
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
const serverInstanceId = await seedPoolServerInstanceId(server, pool);
diff --git a/packages/app/tests/integration/stale-idb-lineage-doors.test.ts b/packages/app/tests/integration/stale-idb-lineage-doors.test.ts
index 69721f025..fc14b3cd6 100644
--- a/packages/app/tests/integration/stale-idb-lineage-doors.test.ts
+++ b/packages/app/tests/integration/stale-idb-lineage-doors.test.ts
@@ -91,7 +91,7 @@ describe('client-persisted state meets a re-seeded doc lineage (deferred-attach
writeFileSync(filePath, FIXTURE_V1, 'utf-8');
await awaitFileWatcherIndexed(server, docName);
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`, {
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`, {
storage: makeStubStorage().stub,
});
cleanups.push(() => pool.dispose());
@@ -171,7 +171,7 @@ describe('client-persisted state meets a re-seeded doc lineage (fresh-pool rejoi
writeFileSync(filePath, FIXTURE_V1, 'utf-8');
await awaitFileWatcherIndexed(server, docName);
- const wsUrl = `ws://localhost:${server.port}/collab`;
+ const wsUrl = `ws://127.0.0.1:${server.port}/collab`;
const { stub: sharedStorage } = makeStubStorage();
const poolA = new ProviderPool(3, wsUrl, { storage: sharedStorage });
diff --git a/packages/app/tests/integration/symlink-alias.test.ts b/packages/app/tests/integration/symlink-alias.test.ts
index 7cff6d481..6292a9f12 100644
--- a/packages/app/tests/integration/symlink-alias.test.ts
+++ b/packages/app/tests/integration/symlink-alias.test.ts
@@ -29,7 +29,7 @@ afterAll(async () => {
describe('QA-009: /api/documents symlink metadata', () => {
test('returns canonical entry with isSymlink=false and alias entry with correct metadata', async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
const body = (await res.json()) as {
documents: Array<{
docName: string;
@@ -69,10 +69,10 @@ describe('QA-010: document read via alias', () => {
await wait(300);
const [viaCan, viaAlias] = await Promise.all([
- fetch(`http://localhost:${server.port}/api/document?docName=target`).then(
+ fetch(`http://127.0.0.1:${server.port}/api/document?docName=target`).then(
(r) => r.json() as Promise<{ docName: string; content: string }>,
),
- fetch(`http://localhost:${server.port}/api/document?docName=foo`).then(
+ fetch(`http://127.0.0.1:${server.port}/api/document?docName=foo`).then(
(r) => r.json() as Promise<{ docName: string; content: string }>,
),
]);
@@ -89,12 +89,12 @@ describe('QA-012: agent-write-md via alias', () => {
await agentWriteMd(server.port, '# Via Alias', { docName: 'foo', position: 'replace' });
await wait(300);
- const res = await fetch(`http://localhost:${server.port}/api/document?docName=target`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/document?docName=target`);
const body = (await res.json()) as { docName: string; content: string };
expect(typeof body.content).toBe('string');
expect(body.content).toContain('Via Alias');
- const aliasRes = await fetch(`http://localhost:${server.port}/api/document?docName=foo`);
+ const aliasRes = await fetch(`http://127.0.0.1:${server.port}/api/document?docName=foo`);
const aliasBody = (await aliasRes.json()) as { docName: string; content: string };
expect(aliasBody.content).toBe(body.content);
});
@@ -102,7 +102,7 @@ describe('QA-012: agent-write-md via alias', () => {
describe('QA-011: agent-write via alias', () => {
test('raw agent-write with alias docName modifies canonical Y.Doc', async () => {
- const writeRes = await fetch(`http://localhost:${server.port}/api/agent-write`, {
+ const writeRes = await fetch(`http://127.0.0.1:${server.port}/api/agent-write`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ docName: 'foo', content: 'agent raw write content' }),
@@ -110,7 +110,7 @@ describe('QA-011: agent-write via alias', () => {
expect(writeRes.ok).toBe(true);
await wait(300);
- const readRes = await fetch(`http://localhost:${server.port}/api/document?docName=target`);
+ const readRes = await fetch(`http://127.0.0.1:${server.port}/api/document?docName=target`);
const body = (await readRes.json()) as { docName: string; content: string };
expect(typeof body.content).toBe('string');
expect(body.content).toContain('agent raw write content');
@@ -129,7 +129,7 @@ describe('QA-013: agent-patch via alias', () => {
expect(result.ok).toBe(true);
await wait(300);
- const readRes = await fetch(`http://localhost:${server.port}/api/document?docName=target`);
+ const readRes = await fetch(`http://127.0.0.1:${server.port}/api/document?docName=target`);
const body = (await readRes.json()) as { docName: string; content: string };
expect(body.content).toContain('new text here');
expect(body.content).not.toContain('old text here');
@@ -142,10 +142,10 @@ describe('QA-002: alias and canonical API reads resolve to same Y.Doc content',
await wait(300);
const [viaCan, viaAlias] = await Promise.all([
- fetch(`http://localhost:${server.port}/api/document?docName=target`).then(
+ fetch(`http://127.0.0.1:${server.port}/api/document?docName=target`).then(
(r) => r.json() as Promise<{ docName: string; content: string }>,
),
- fetch(`http://localhost:${server.port}/api/document?docName=foo`).then(
+ fetch(`http://127.0.0.1:${server.port}/api/document?docName=foo`).then(
(r) => r.json() as Promise<{ docName: string; content: string }>,
),
]);
@@ -158,7 +158,7 @@ describe('QA-002: alias and canonical API reads resolve to same Y.Doc content',
await agentWriteMd(server.port, '# From Canonical', { docName: 'target', position: 'replace' });
await wait(300);
- const viaAlias = await fetch(`http://localhost:${server.port}/api/document?docName=foo`).then(
+ const viaAlias = await fetch(`http://127.0.0.1:${server.port}/api/document?docName=foo`).then(
(r) => r.json() as Promise<{ docName: string; content: string }>,
);
expect(viaAlias.content).toContain('From Canonical');
@@ -189,12 +189,12 @@ describe('QA-015: self-write detection after symlink resolution', () => {
await agentWriteMd(server.port, '# No Echo', { docName: 'foo', position: 'replace' });
await wait(1000);
- const res1 = await fetch(`http://localhost:${server.port}/api/document?docName=target`);
+ const res1 = await fetch(`http://127.0.0.1:${server.port}/api/document?docName=target`);
const body1 = (await res1.json()) as { docName: string; content: string };
await wait(1500);
- const res2 = await fetch(`http://localhost:${server.port}/api/document?docName=target`);
+ const res2 = await fetch(`http://127.0.0.1:${server.port}/api/document?docName=target`);
const body2 = (await res2.json()) as { docName: string; content: string };
expect(body2.content).toBe(body1.content);
});
diff --git a/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts b/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
index 9d0bedbd9..8e8d8a49a 100644
--- a/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
+++ b/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
@@ -23,7 +23,7 @@ async function setupServerWithDoc(docName: string, initial: string): Promise<Tes
cleanups.push(() => server.cleanup());
writeFileSync(join(server.contentDir, `${docName}.md`), initial, 'utf-8');
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
@@ -122,7 +122,7 @@ describe('case "conflicts" reconcile branch -> CRDT lifecycle', () => {
cleanups.push(() => server.cleanup());
writeFileSync(join(server.contentDir, `${docName}.md`), baseContent, 'utf-8');
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === docName) ?? false;
@@ -193,7 +193,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
test('POST /api/agent-write returns 409 doc-in-conflict', async () => {
const { docName, server } = await seedConflictedDoc();
- const res = await fetch(`http://localhost:${server.port}/api/agent-write`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -208,7 +208,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
test('POST /api/agent-write-md returns 409 doc-in-conflict', async () => {
const { docName, server } = await seedConflictedDoc();
- const res = await fetch(`http://localhost:${server.port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -224,7 +224,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
test('POST /api/agent-patch returns 409 doc-in-conflict', async () => {
const { docName, server } = await seedConflictedDoc();
- const res = await fetch(`http://localhost:${server.port}/api/agent-patch`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-patch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -245,7 +245,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
colorSeed: 'u',
});
- const res = await fetch(`http://localhost:${server.port}/api/agent-undo`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/agent-undo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -261,7 +261,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
test('POST /api/rollback returns 409 doc-in-conflict', async () => {
const { docName, server } = await seedConflictedDoc();
- const res = await fetch(`http://localhost:${server.port}/api/rollback`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/rollback`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -274,7 +274,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
test('POST /api/rename-path returns 409 doc-in-conflict when source is conflicted', async () => {
const { docName, server } = await seedConflictedDoc();
- const res = await fetch(`http://localhost:${server.port}/api/rename-path`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/rename-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -288,7 +288,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
test('POST /api/delete-path returns 409 doc-in-conflict when target is conflicted', async () => {
const { docName, server } = await seedConflictedDoc();
- const res = await fetch(`http://localhost:${server.port}/api/delete-path`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/delete-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -318,7 +318,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
});
cleanups.push(() => server.cleanup());
await pollUntil(async () => {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch(() => null);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch(() => null);
if (!res?.ok) return false;
const data = (await res.json()) as { documents?: Array<{ docName: string }> };
return data.documents?.some((d) => d.docName === childDocName) ?? false;
@@ -336,7 +336,7 @@ describe('FR7 + FR9: mutating handlers refuse with RFC 9457 slim 409 during conf
test('POST /api/rename-path (folder) returns 409 when subtree contains a conflicted doc', async () => {
const { folder, childDocName, server } = await seedConflictedDocInFolder();
- const res = await fetch(`http://localhost:${server.port}/api/rename-path`, {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/rename-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -375,7 +375,7 @@ describe('GET /api/sync/conflict-content?source=ytext', () => {
}, 5000);
const ytextRes = await fetch(
- `http://localhost:${server.port}/api/sync/conflict-content?file=${docName}.md&source=ytext`,
+ `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=${docName}.md&source=ytext`,
);
expect(ytextRes.ok).toBe(true);
const ytextBody = (await ytextRes.json()) as {
@@ -390,7 +390,7 @@ describe('GET /api/sync/conflict-content?source=ytext', () => {
expect(ytextBody.lifecycleStatus).toBe('conflict');
const defaultRes = await fetch(
- `http://localhost:${server.port}/api/sync/conflict-content?file=${docName}.md`,
+ `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=${docName}.md`,
);
expect(defaultRes.ok).toBe(true);
const defaultBody = (await defaultRes.json()) as { ours: string };
@@ -421,7 +421,7 @@ describe('GET /api/sync/conflict-content?source=ytext', () => {
}, 5000);
const ytextRes = await fetch(
- `http://localhost:${server.port}/api/sync/conflict-content?file=${docName}.md&source=ytext`,
+ `http://127.0.0.1:${server.port}/api/sync/conflict-content?file=${docName}.md&source=ytext`,
);
expect(ytextRes.ok).toBe(true);
const ytextBody = (await ytextRes.json()) as { ours: string; lifecycleStatus: string | null };
diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.ts
index 31dee4441..5457ff009 100644
--- a/packages/app/tests/integration/test-harness.ts
+++ b/packages/app/tests/integration/test-harness.ts
@@ -54,7 +54,7 @@ export const schema = getSchema(sharedExtensions);
async function getFreePort(): Promise<number> {
return new Promise((resolve) => {
const s = createNetServer();
- s.listen(0, () => {
+ s.listen(0, '127.0.0.1', () => {
const port = (s.address() as AddressInfo).port;
s.close(() => resolve(port));
});
@@ -142,7 +142,7 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P
contentDir,
projectDir: contentDir,
config: ConfigSchema.parse({}),
- getServerUrl: () => `http://localhost:${port}`,
+ getServerUrl: () => `http://127.0.0.1:${port}`,
});
const httpServer = createHttpServer();
@@ -158,7 +158,7 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P
});
await new Promise<void>((resolve) => {
- httpServer.listen(port, () => resolve());
+ httpServer.listen(port, '127.0.0.1', () => resolve());
});
return {
@@ -212,7 +212,7 @@ export async function createTestClient(
let controllableWs: ControllableWebSocket | undefined;
const providerOpts: Record<string, unknown> = {
- url: `ws://localhost:${port}/collab`,
+ url: `ws://127.0.0.1:${port}/collab`,
name: resolvedDocName,
document: doc,
connect: true,
@@ -428,6 +428,34 @@ export function assertBridgeInvariant(ytext: Y.Text, fragment: Y.XmlFragment): v
}
}
+export type FinalStateOutcome =
+ | { outcome: 'converged-late' }
+ | { outcome: 'stalled'; detail: string };
+
+export function classifyFinalState(
+ clients: ReadonlyArray<Pick<TestClient, 'ytext' | 'fragment'>>,
+): FinalStateOutcome {
+ const finalYtexts = clients.map((c) => c.ytext.toString());
+ const finalFragMds = clients.map((c) => serializeFragment(c.fragment));
+ const peersIdentical =
+ finalYtexts.every((t) => t === finalYtexts[0]) &&
+ finalFragMds.every((m) => m === finalFragMds[0]);
+ if (!peersIdentical) {
+ return { outcome: 'stalled', detail: 'peers diverged at budget exhaustion' };
+ }
+ for (const c of clients) {
+ try {
+ assertBridgeInvariant(c.ytext, c.fragment);
+ } catch (err) {
+ return {
+ outcome: 'stalled',
+ detail: `bridge invariant beyond tolerance at budget exhaustion: ${err instanceof Error ? err.message.slice(0, 200) : String(err)}`,
+ };
+ }
+ }
+ return { outcome: 'converged-late' };
+}
+
export function readTestDoc(contentDir: string, docName = 'test-doc'): string {
try {
return readFileSync(join(contentDir, `${docName}.md`), 'utf-8');
@@ -451,7 +479,7 @@ export async function agentWriteMd(
colorSeed?: string;
},
): Promise<void> {
- const res = await fetch(`http://localhost:${port}/api/agent-write-md`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -481,7 +509,7 @@ export async function agentPatch(
replace: string,
docName?: string,
): Promise<{ ok: true } | { ok: false; status: number; error: string }> {
- const res = await fetch(`http://localhost:${port}/api/agent-patch`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-patch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ find, replace, docName }),
@@ -497,7 +525,7 @@ export async function agentUndo(
port: number,
opts: { docName?: string; connectionId: string; scope?: 'last' | 'session' },
): Promise<void> {
- const res = await fetch(`http://localhost:${port}/api/agent-undo`, {
+ const res = await fetch(`http://127.0.0.1:${port}/api/agent-undo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -511,8 +539,8 @@ export async function agentUndo(
export async function testReset(port: number, docName?: string): Promise<void> {
const url = docName
- ? `http://localhost:${port}/api/test-reset?docName=${encodeURIComponent(docName)}`
- : `http://localhost:${port}/api/test-reset`;
+ ? `http://127.0.0.1:${port}/api/test-reset?docName=${encodeURIComponent(docName)}`
+ : `http://127.0.0.1:${port}/api/test-reset`;
const res = await fetch(url, { method: 'POST' });
if (!res.ok) throw new Error(`test-reset failed: ${res.status}`);
}
@@ -541,7 +569,7 @@ export async function awaitFileWatcherIndexed(
let lastBodyPreview = '';
let rescueTriggered = false;
while (Date.now() - start < timeoutMs) {
- const res = await fetch(`http://localhost:${server.port}/api/documents`).catch((err) => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/documents`).catch((err) => {
lastStatus = -1;
lastBodyPreview = `fetch error: ${String(err).slice(0, 80)}`;
return null;
@@ -559,7 +587,7 @@ export async function awaitFileWatcherIndexed(
}
if (!rescueTriggered && Date.now() - start >= rescueAfterMs) {
rescueTriggered = true;
- await fetch(`http://localhost:${server.port}/api/test-rescan-files`, {
+ await fetch(`http://127.0.0.1:${server.port}/api/test-rescan-files`, {
method: 'POST',
}).catch(() => null);
}
@@ -582,7 +610,7 @@ export async function awaitBacklinkIndexed(
let rescueTriggered = false;
while (Date.now() - start < timeoutMs) {
const res = await fetch(
- `http://localhost:${server.port}/api/backlinks?docName=${encodeURIComponent(targetDocName)}`,
+ `http://127.0.0.1:${server.port}/api/backlinks?docName=${encodeURIComponent(targetDocName)}`,
).catch(() => null);
if (res?.ok) {
lastStatus = res.status;
@@ -595,7 +623,7 @@ export async function awaitBacklinkIndexed(
}
if (!rescueTriggered && Date.now() - start >= rescueAfterMs) {
rescueTriggered = true;
- await fetch(`http://localhost:${server.port}/api/test-rescan-backlinks`, {
+ await fetch(`http://127.0.0.1:${server.port}/api/test-rescan-backlinks`, {
method: 'POST',
}).catch(() => null);
}
@@ -1031,8 +1059,8 @@ export function attachSystemDocSubscriber(
pool: ProviderPool,
port: number,
): SystemDocSubscriberHandle {
- const url = `ws://localhost:${port}/collab`;
- const baseUrl = `http://localhost:${port}`;
+ const url = `ws://127.0.0.1:${port}/collab`;
+ const baseUrl = `http://127.0.0.1:${port}`;
const doc = new Y.Doc();
const provider = new HocuspocusProvider({
url,
@@ -1141,7 +1169,7 @@ export async function createMultiClientContext(opts: {
recycleDebounceMs?: number;
}): Promise<MultiClientContext> {
const { ProviderPool } = await import('../../src/editor/provider-pool');
- const wsUrl = `ws://localhost:${opts.server.port}/collab`;
+ const wsUrl = `ws://127.0.0.1:${opts.server.port}/collab`;
const pools: InstanceType<ProviderPoolCtor>[] = [];
for (let i = 0; i < opts.clientCount; i++) {
const pool = new ProviderPool(3, wsUrl, { recycleDebounceMs: opts.recycleDebounceMs });
@@ -1176,7 +1204,7 @@ export async function seedPoolServerInstanceId(
setExpectedServerInstanceId: (id: string | null) => void;
},
): Promise<string> {
- const res = await fetch(`http://localhost:${server.port}/api/server-info`);
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/server-info`);
if (!res.ok) {
throw new Error(`seedPoolServerInstanceId: /api/server-info returned ${res.status}`);
}
diff --git a/packages/app/tests/integration/ytext-source-mode-restart.test.ts b/packages/app/tests/integration/ytext-source-mode-restart.test.ts
index 45ea9b34f..7ebfe4775 100644
--- a/packages/app/tests/integration/ytext-source-mode-restart.test.ts
+++ b/packages/app/tests/integration/ytext-source-mode-restart.test.ts
@@ -43,7 +43,7 @@ describe('T10: Y.Text (source-mode) duplication on restart', () => {
writeFileSync(join(server.contentDir, 'test-doc.md'), FIXTURE, 'utf-8');
- const pool = new ProviderPool(3, `ws://localhost:${server.port}/collab`);
+ const pool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
cleanups.push(() => pool.dispose());
await seedPoolServerInstanceId(server, pool);
diff --git a/packages/app/tests/stress/bridge-convergence.fuzz.test.ts b/packages/app/tests/stress/bridge-convergence.fuzz.test.ts
index 30090ce1c..773be947a 100644
--- a/packages/app/tests/stress/bridge-convergence.fuzz.test.ts
+++ b/packages/app/tests/stress/bridge-convergence.fuzz.test.ts
@@ -27,12 +27,18 @@
* "Convergence failed after 25s" occurs at ~2-4% rate under heavy macOS
* scheduler load with 3 clients + 12 ops + aggressive inter-op pacing.
* This is SPEC §11 "PBT convergence fuzzer flakes on CI under runner load"
- * risk materializing. Seed snapshots written to /tmp/bridge-conv-fuzz-<seed>/
- * on failure enable deterministic replay:
+ * risk materializing. The harness now discriminates at budget exhaustion:
+ * a final state with byte-identical peers AND a holding bridge invariant
+ * classifies as `converged-late` (a PASS, surfaced separately in the
+ * RESULT line as a perf signal) — only peer divergence or a
+ * beyond-tolerance settle fails the seed. Replay-rate triage is therefore
+ * no longer the discriminator for the timeout class (giant fuzz-grown
+ * docs replay as a coin-flip on a loaded machine — neither cleanly
+ * passing nor failing). Seed snapshots written to
+ * /tmp/bridge-conv-fuzz-<seed>/ on failure enable deterministic replay:
* STRESS_FUZZ_SEED=<seed> bun test packages/app/tests/stress/bridge-convergence.fuzz.test.ts
- * If the replay passes, it's infra flakiness; if it fails repeatedly on
- * replay, it's a real bug. Content-preservation violations (oracle d) are
- * deterministic-on-replay — a different signal class from convergence flakes.
+ * Content-preservation violations (oracle d) remain deterministic-on-replay
+ * — a different signal class from convergence timing.
*
* Seed replay: STRESS_FUZZ_SEED=<n> bun test packages/app/tests/stress/bridge-convergence.fuzz.test.ts
* Seed count: BRIDGE_FUZZ_SEEDS=<n> (default: 25; CI PR: 25, nightly: 100)
@@ -56,6 +62,7 @@ import {
agentWriteMd,
assertBridgeInvariant,
awaitDocQuiescence,
+ classifyFinalState,
createItemOriginProbe,
createTestClients,
createTestServer,
@@ -190,7 +197,7 @@ async function applyOp(
clients: TestClient[],
server: TestServer,
docName: string,
-): Promise<void> {
+): Promise<boolean> {
switch (op.kind) {
case 'wysiwyg-type': {
const client = clients[op.clientIdx];
@@ -229,26 +236,34 @@ async function applyOp(
case 'agent-write': {
try {
await agentWriteMd(server.port, `${op.text}\n`, { docName, position: op.position });
- } catch {}
+ } catch {
+ return false;
+ }
break;
}
case 'agent-patch': {
try {
await agentPatch(server.port, op.find, op.replace, docName);
- } catch {}
+ } catch {
+ return false;
+ }
break;
}
case 'agent-undo': {
try {
await agentUndo(server.port, { docName, connectionId: 'claude-1' });
- } catch {}
+ } catch {
+ return false;
+ }
break;
}
case 'external-change': {
+ writeFileSync(join(server.contentDir, `${docName}.md`), op.newContent, 'utf-8');
try {
- writeFileSync(join(server.contentDir, `${docName}.md`), op.newContent, 'utf-8');
applyExternalChange(server.instance.hocuspocus, docName, op.newContent);
- } catch {}
+ } catch {
+ return false;
+ }
break;
}
case 'sync-pause': {
@@ -268,9 +283,18 @@ async function applyOp(
break;
}
}
+ return true;
}
-async function driveToConvergence(clients: TestClient[], timeoutMs = 15000): Promise<boolean> {
+type ConvergenceOutcome =
+ | { outcome: 'converged' }
+ | { outcome: 'converged-late' }
+ | { outcome: 'stalled'; detail: string };
+
+async function driveToConvergence(
+ clients: TestClient[],
+ timeoutMs = 15000,
+): Promise<ConvergenceOutcome> {
const start = Date.now();
await Promise.all(clients.map((c) => awaitDocQuiescence(c.doc, { timeoutMs: 3000 })));
@@ -293,7 +317,7 @@ async function driveToConvergence(clients: TestClient[], timeoutMs = 15000): Pro
break;
}
}
- if (allBridgeOk) return true;
+ if (allBridgeOk) return { outcome: 'converged' };
}
if (attempts < 8) {
@@ -308,7 +332,10 @@ async function driveToConvergence(clients: TestClient[], timeoutMs = 15000): Pro
attempts++;
await wait(200);
}
- return false;
+
+ await Promise.all(clients.map((c) => awaitDocQuiescence(c.doc, { timeoutMs: 3000 })));
+ await wait(250);
+ return classifyFinalState(clients);
}
function writeFuzzSnapshot(
@@ -414,6 +441,7 @@ describe('bridge-convergence fuzzer (FR-17)', () => {
let server: TestServer;
const fuzzPassed: number[] = [];
const fuzzFailed: number[] = [];
+ const fuzzConvergedLate: number[] = [];
beforeAll(async () => {
server = await createTestServer();
@@ -421,7 +449,7 @@ describe('bridge-convergence fuzzer (FR-17)', () => {
afterAll(async () => {
process.stdout.write(
- `[fuzz] RESULT seeds=${fuzzPassed.length + fuzzFailed.length} passed=${fuzzPassed.length} failed=${fuzzFailed.length} failingSeeds=[${fuzzFailed.join(',')}]\n`,
+ `[fuzz] RESULT seeds=${fuzzPassed.length + fuzzFailed.length} passed=${fuzzPassed.length} failed=${fuzzFailed.length} failingSeeds=[${fuzzFailed.join(',')}] convergedLate=${fuzzConvergedLate.length} convergedLateSeeds=[${fuzzConvergedLate.join(',')}]\n`,
);
try {
await server?.cleanup();
@@ -438,293 +466,306 @@ describe('bridge-convergence fuzzer (FR-17)', () => {
? [FIXED_SEED]
: Array.from({ length: SEED_COUNT }, (_, i) => Date.now() + i);
- test.each(seeds)('bridge-convergence seed %d', async (seed) => {
- let setupOk = false;
- let clients: Awaited<ReturnType<typeof createTestClients>> = [] as never;
- const rng = createPRNG(seed);
- const clientCount = 2 + (seed % 2); // 2..3
- const opCount = 12;
- const docName = `fuzz-${seed}`;
-
- try {
- await agentWriteMd(server.port, 'seed paragraph\n', { docName, position: 'replace' });
- await wait(200);
+ test.each(seeds)(
+ 'bridge-convergence seed %d',
+ async (seed) => {
+ let setupOk = false;
+ let clients: Awaited<ReturnType<typeof createTestClients>> = [] as never;
+ const rng = createPRNG(seed);
+ const clientCount = 2 + (seed % 2); // 2..3
+ const opCount = 12;
+ const docName = `fuzz-${seed}`;
- clients = await createTestClients(server.port, {
- count: clientCount,
- docName,
- perClientOptions: { syncControl: true, skipInvariantWatcher: true },
- });
- setupOk = true;
- } catch (err) {
- fuzzFailed.push(seed);
- throw err;
- }
- if (!setupOk) {
- fuzzFailed.push(seed);
- throw new Error(`bridge-convergence fuzz setup invariant violated for seed ${seed}`);
- }
-
- const localFuzzOrigin = Object.freeze({
- source: 'local' as const,
- skipStoreHooks: false,
- context: Object.freeze({
- origin: 'agent-write',
- paired: true as const,
- session_id: `fuzz-probe-${seed}`,
- }),
- });
- if (!isPairedWriteOrigin(localFuzzOrigin)) {
- throw new Error(
- `fuzz: isPairedWriteOrigin(localFuzzOrigin) failed — per-session origin rejected`,
- );
- }
- const agentProbes = clients.map((c) =>
- createItemOriginProbe(c.ytext, { trackedOrigins: [localFuzzOrigin] }),
- );
-
- const livePrefixes = new Set<string>();
- const prefixOf = (marker: string): string => {
- const dashIdx = marker.indexOf('-');
- return dashIdx === -1 ? marker : marker.slice(0, dashIdx + 1);
- };
-
- let expectedBody = 'seed paragraph'; // post-seed, pre-op initial state
- const updateExpectedBody = (op: Op): void => {
- switch (op.kind) {
- case 'wysiwyg-type':
- case 'source-type':
- expectedBody = expectedBody.length > 0 ? `${expectedBody}\n\n${op.marker}` : op.marker;
- break;
- case 'agent-write': {
- switch (op.position) {
- case 'replace':
- expectedBody = op.marker;
- break;
- case 'prepend':
- expectedBody =
- expectedBody.length > 0 ? `${op.marker}\n\n${expectedBody}` : op.marker;
- break;
- case 'append':
- expectedBody =
- expectedBody.trim().length > 0 ? `${expectedBody}\n\n${op.marker}` : op.marker;
- break;
- }
- break;
- }
- case 'agent-patch': {
- const pos = expectedBody.indexOf(op.find);
- if (pos !== -1) {
- expectedBody =
- expectedBody.slice(0, pos) + op.replace + expectedBody.slice(pos + op.find.length);
- }
- break;
- }
- case 'external-change':
- expectedBody = op.newContent.replace(/\n+$/, '');
- break;
- case 'agent-undo':
- expectedBody = '';
- break;
- case 'sync-pause':
- case 'sync-resume':
- case 'wait':
- break;
- }
- };
-
- try {
- const ops = generateOps(rng, clientCount, opCount);
-
- for (const op of ops) {
- await applyOp(op, clients, server, docName);
-
- if (op.kind === 'wysiwyg-type' || op.kind === 'source-type' || op.kind === 'agent-write') {
- livePrefixes.add(prefixOf(op.marker));
- } else if (op.kind === 'external-change') {
- livePrefixes.clear();
- livePrefixes.add(prefixOf(op.marker));
- } else if (op.kind === 'agent-undo') {
- livePrefixes.clear();
- }
+ try {
+ await agentWriteMd(server.port, 'seed paragraph\n', { docName, position: 'replace' });
+ await wait(200);
- updateExpectedBody(op);
+ clients = await createTestClients(server.port, {
+ count: clientCount,
+ docName,
+ perClientOptions: { syncControl: true, skipInvariantWatcher: true },
+ });
+ setupOk = true;
+ } catch (err) {
+ fuzzFailed.push(seed);
+ throw err;
}
-
- for (const c of clients) {
- try {
- c.resumeSync();
- } catch {}
+ if (!setupOk) {
+ fuzzFailed.push(seed);
+ throw new Error(`bridge-convergence fuzz setup invariant violated for seed ${seed}`);
}
- const converged = await driveToConvergence(clients, 60000);
- if (!converged) {
- const states = snapshotClients(clients);
+ const localFuzzOrigin = Object.freeze({
+ source: 'local' as const,
+ skipStoreHooks: false,
+ context: Object.freeze({
+ origin: 'agent-write',
+ paired: true as const,
+ session_id: `fuzz-probe-${seed}`,
+ }),
+ });
+ if (!isPairedWriteOrigin(localFuzzOrigin)) {
throw new Error(
- `Convergence failed after 60s.\n${states.map((s, i) => ` Client ${i}: ytext=${s.ytext.length}ch frag=${s.fragmentMd.length}ch`).join('\n')}`,
+ `fuzz: isPairedWriteOrigin(localFuzzOrigin) failed — per-session origin rejected`,
);
}
+ const agentProbes = clients.map((c) =>
+ createItemOriginProbe(c.ytext, { trackedOrigins: [localFuzzOrigin] }),
+ );
- for (const c of clients) {
- assertBridgeInvariant(c.ytext, c.fragment);
- }
-
- for (const probe of agentProbes) {
- probe.assertOnlyTrackedOrigins();
-
- if (probe.undoStackLength() > 0) {
- probe.recordCapture();
- probe.assertCaptureIntact();
- }
- }
-
- const missingPrefixes: Array<{ clientIdx: number; prefix: string }> = [];
- for (const prefix of livePrefixes) {
- for (let ci = 0; ci < clients.length; ci++) {
- const client = clients[ci];
- if (!client) continue;
- if (!client.ytext.toString().includes(prefix)) {
- missingPrefixes.push({ clientIdx: ci, prefix });
- }
- }
- }
-
- if (missingPrefixes.length > 0) {
- throw new Error(
- `Content preservation violated — ${missingPrefixes.length} missing prefixes ` +
- `(zero tolerance: hybrid diff3+DMP merge must preserve all content).\n` +
- missingPrefixes
- .slice(0, 5)
- .map((m) => ` client ${m.clientIdx} missing prefix '${m.prefix}'`)
- .join('\n') +
- (missingPrefixes.length > 5 ? `\n ...and ${missingPrefixes.length - 5} more` : ''),
- );
- }
+ const livePrefixes = new Set<string>();
+ const prefixOf = (marker: string): string => {
+ const dashIdx = marker.indexOf('-');
+ return dashIdx === -1 ? marker : marker.slice(0, dashIdx + 1);
+ };
- const preMarkerLines = new Map<string, string>(); // prefix → pre-patch line
- const patches: Array<{ find: string; replace: string }> = [];
- for (const op of ops) {
+ let expectedBody = 'seed paragraph'; // post-seed, pre-op initial state
+ const updateExpectedBody = (op: Op): void => {
switch (op.kind) {
case 'wysiwyg-type':
case 'source-type':
- preMarkerLines.set(prefixOf(op.marker), op.marker);
+ expectedBody = expectedBody.length > 0 ? `${expectedBody}\n\n${op.marker}` : op.marker;
break;
- case 'agent-write':
- if (op.position === 'replace') preMarkerLines.clear();
- preMarkerLines.set(prefixOf(op.marker), op.marker);
+ case 'agent-write': {
+ switch (op.position) {
+ case 'replace':
+ expectedBody = op.marker;
+ break;
+ case 'prepend':
+ expectedBody =
+ expectedBody.length > 0 ? `${op.marker}\n\n${expectedBody}` : op.marker;
+ break;
+ case 'append':
+ expectedBody =
+ expectedBody.trim().length > 0 ? `${expectedBody}\n\n${op.marker}` : op.marker;
+ break;
+ }
break;
- case 'agent-patch':
- patches.push({ find: op.find, replace: op.replace });
+ }
+ case 'agent-patch': {
+ const pos = expectedBody.indexOf(op.find);
+ if (pos !== -1) {
+ expectedBody =
+ expectedBody.slice(0, pos) + op.replace + expectedBody.slice(pos + op.find.length);
+ }
break;
+ }
case 'external-change':
- preMarkerLines.clear();
- preMarkerLines.set(prefixOf(op.marker), op.marker);
+ expectedBody = op.newContent.replace(/\n+$/, '');
break;
case 'agent-undo':
- preMarkerLines.clear();
+ expectedBody = '';
+ break;
+ case 'sync-pause':
+ case 'sync-resume':
+ case 'wait':
break;
}
- }
+ };
- if (preMarkerLines.size > 0) {
- const acceptableForPrefix = new Map<string, Set<string>>();
- for (const [prefix, preLine] of preMarkerLines) {
- const accepts = new Set<string>([preLine]);
- for (let iter = 0; iter < patches.length; iter++) {
- const snapshot = [...accepts];
- let grew = false;
- for (const line of snapshot) {
- for (const { find, replace } of patches) {
- if (line.includes(find)) {
- const idx = line.indexOf(find);
- const post = line.slice(0, idx) + replace + line.slice(idx + find.length);
- if (!accepts.has(post)) {
- accepts.add(post);
- grew = true;
- }
- }
- }
- }
- if (!grew) break;
+ try {
+ const ops = generateOps(rng, clientCount, opCount);
+
+ for (const op of ops) {
+ const applied = await applyOp(op, clients, server, docName);
+ if (!applied) continue;
+
+ if (
+ op.kind === 'wysiwyg-type' ||
+ op.kind === 'source-type' ||
+ op.kind === 'agent-write'
+ ) {
+ livePrefixes.add(prefixOf(op.marker));
+ } else if (op.kind === 'external-change') {
+ livePrefixes.clear();
+ livePrefixes.add(prefixOf(op.marker));
+ } else if (op.kind === 'agent-undo') {
+ livePrefixes.clear();
}
- acceptableForPrefix.set(prefix, accepts);
+
+ updateExpectedBody(op);
}
- const chunkGlueRe = /^M\d+-chunked-/;
- const hasChunkedPaste = ops.some((o) => o.kind === 'chunked-source-paste');
-
- const missingContent: Array<{ clientIdx: number; prefix: string }> = [];
- for (let ci = 0; ci < clients.length; ci++) {
- const client = clients[ci];
- if (!client) continue;
- const gotLineList = client.ytext
- .toString()
- .split('\n')
- .map((l) => l.trimEnd());
- const gotLines = new Set(gotLineList);
- for (const [prefix, accepts] of acceptableForPrefix) {
- const matched = [...accepts].some(
- (l) =>
- gotLines.has(l) ||
- (hasChunkedPaste &&
- gotLineList.some(
- (line) => line.startsWith(l) && chunkGlueRe.test(line.slice(l.length)),
- )),
- );
- if (!matched) {
- missingContent.push({ clientIdx: ci, prefix });
+ for (const c of clients) {
+ try {
+ c.resumeSync();
+ } catch {}
+ }
+
+ const convergence = await driveToConvergence(clients, 60000);
+ if (convergence.outcome === 'stalled') {
+ const states = snapshotClients(clients);
+ throw new Error(
+ `Convergence failed after 60s (${convergence.detail}).\n${states.map((s, i) => ` Client ${i}: ytext=${s.ytext.length}ch frag=${s.fragmentMd.length}ch`).join('\n')}`,
+ );
+ }
+ if (convergence.outcome === 'converged-late') {
+ fuzzConvergedLate.push(seed);
+ console.log(`[fuzz] converged-late seed=${seed} (final state within tolerance)`);
+ }
+
+ for (const c of clients) {
+ assertBridgeInvariant(c.ytext, c.fragment);
+ }
+
+ for (const probe of agentProbes) {
+ probe.assertOnlyTrackedOrigins();
+
+ if (probe.undoStackLength() > 0) {
+ probe.recordCapture();
+ probe.assertCaptureIntact();
+ }
+ }
+
+ const missingPrefixes: Array<{ clientIdx: number; prefix: string }> = [];
+ for (const prefix of livePrefixes) {
+ for (let ci = 0; ci < clients.length; ci++) {
+ const client = clients[ci];
+ if (!client) continue;
+ if (!client.ytext.toString().includes(prefix)) {
+ missingPrefixes.push({ clientIdx: ci, prefix });
}
}
}
- if (missingContent.length > 0) {
+ if (missingPrefixes.length > 0) {
throw new Error(
- `Oracle (e) content-set violation — ${missingContent.length} marker prefixes ` +
- `with no acceptable line form (zero tolerance: tail corruption that can't be ` +
- `explained by any applied agent-patch).\n` +
- missingContent
+ `Content preservation violated — ${missingPrefixes.length} missing prefixes ` +
+ `(zero tolerance: hybrid diff3+DMP merge must preserve all content).\n` +
+ missingPrefixes
.slice(0, 5)
- .map(
- (m) =>
- ` client ${m.clientIdx} prefix '${m.prefix}' accepts=${JSON.stringify([...(acceptableForPrefix.get(m.prefix) ?? [])])}`,
- )
+ .map((m) => ` client ${m.clientIdx} missing prefix '${m.prefix}'`)
.join('\n') +
- (missingContent.length > 5 ? `\n ...and ${missingContent.length - 5} more` : ''),
+ (missingPrefixes.length > 5 ? `\n ...and ${missingPrefixes.length - 5} more` : ''),
);
}
- }
- fuzzPassed.push(seed);
- } catch (err) {
- writeFuzzSnapshot(seed, {
- ops: generateOps(createPRNG(seed), clientCount, opCount),
- error: err,
- clientStates: snapshotClients(clients),
- });
- fuzzFailed.push(seed);
- throw err;
- } finally {
- for (const p of agentProbes) {
- try {
- p.cleanup();
- } catch (cleanupErr) {
- console.warn(
- `[bridge-convergence seed ${seed}] agent-probe cleanup failed:`,
- cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
- );
+
+ const preMarkerLines = new Map<string, string>(); // prefix → pre-patch line
+ const patches: Array<{ find: string; replace: string }> = [];
+ for (const op of ops) {
+ switch (op.kind) {
+ case 'wysiwyg-type':
+ case 'source-type':
+ preMarkerLines.set(prefixOf(op.marker), op.marker);
+ break;
+ case 'agent-write':
+ if (op.position === 'replace') preMarkerLines.clear();
+ preMarkerLines.set(prefixOf(op.marker), op.marker);
+ break;
+ case 'agent-patch':
+ patches.push({ find: op.find, replace: op.replace });
+ break;
+ case 'external-change':
+ preMarkerLines.clear();
+ preMarkerLines.set(prefixOf(op.marker), op.marker);
+ break;
+ case 'agent-undo':
+ preMarkerLines.clear();
+ break;
+ }
}
- }
- for (const c of clients) {
- try {
- await c.cleanup();
- } catch (cleanupErr) {
- console.warn(
- `[bridge-convergence seed ${seed}] client cleanup failed:`,
- cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
- );
+
+ if (preMarkerLines.size > 0) {
+ const acceptableForPrefix = new Map<string, Set<string>>();
+ for (const [prefix, preLine] of preMarkerLines) {
+ const accepts = new Set<string>([preLine]);
+ for (let iter = 0; iter < patches.length; iter++) {
+ const snapshot = [...accepts];
+ let grew = false;
+ for (const line of snapshot) {
+ for (const { find, replace } of patches) {
+ if (line.includes(find)) {
+ const idx = line.indexOf(find);
+ const post = line.slice(0, idx) + replace + line.slice(idx + find.length);
+ if (!accepts.has(post)) {
+ accepts.add(post);
+ grew = true;
+ }
+ }
+ }
+ }
+ if (!grew) break;
+ }
+ acceptableForPrefix.set(prefix, accepts);
+ }
+
+ const chunkGlueRe = /^M\d+-chunked-/;
+ const hasChunkedPaste = ops.some((o) => o.kind === 'chunked-source-paste');
+
+ const missingContent: Array<{ clientIdx: number; prefix: string }> = [];
+ for (let ci = 0; ci < clients.length; ci++) {
+ const client = clients[ci];
+ if (!client) continue;
+ const gotLineList = client.ytext
+ .toString()
+ .split('\n')
+ .map((l) => l.trimEnd());
+ const gotLines = new Set(gotLineList);
+ for (const [prefix, accepts] of acceptableForPrefix) {
+ const matched = [...accepts].some(
+ (l) =>
+ gotLines.has(l) ||
+ (hasChunkedPaste &&
+ gotLineList.some(
+ (line) => line.startsWith(l) && chunkGlueRe.test(line.slice(l.length)),
+ )),
+ );
+ if (!matched) {
+ missingContent.push({ clientIdx: ci, prefix });
+ }
+ }
+ }
+
+ if (missingContent.length > 0) {
+ throw new Error(
+ `Oracle (e) content-set violation — ${missingContent.length} marker prefixes ` +
+ `with no acceptable line form (zero tolerance: tail corruption that can't be ` +
+ `explained by any applied agent-patch).\n` +
+ missingContent
+ .slice(0, 5)
+ .map(
+ (m) =>
+ ` client ${m.clientIdx} prefix '${m.prefix}' accepts=${JSON.stringify([...(acceptableForPrefix.get(m.prefix) ?? [])])}`,
+ )
+ .join('\n') +
+ (missingContent.length > 5 ? `\n ...and ${missingContent.length - 5} more` : ''),
+ );
+ }
+ }
+ fuzzPassed.push(seed);
+ } catch (err) {
+ writeFuzzSnapshot(seed, {
+ ops: generateOps(createPRNG(seed), clientCount, opCount),
+ error: err,
+ clientStates: snapshotClients(clients),
+ });
+ fuzzFailed.push(seed);
+ throw err;
+ } finally {
+ for (const p of agentProbes) {
+ try {
+ p.cleanup();
+ } catch (cleanupErr) {
+ console.warn(
+ `[bridge-convergence seed ${seed}] agent-probe cleanup failed:`,
+ cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
+ );
+ }
+ }
+ for (const c of clients) {
+ try {
+ await c.cleanup();
+ } catch (cleanupErr) {
+ console.warn(
+ `[bridge-convergence seed ${seed}] client cleanup failed:`,
+ cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
+ );
+ }
}
}
- }
- }, 120_000);
+ },
+ FIXED_SEED === undefined ? 120_000 : 300_000,
+ );
});
describe('D18 coverage gate', () => {
diff --git a/packages/cli/scripts/aggregate-tolerance-class-fires.ts b/packages/cli/scripts/aggregate-tolerance-class-fires.ts
index 6acabdbd5..f1ed1f6ab 100644
--- a/packages/cli/scripts/aggregate-tolerance-class-fires.ts
+++ b/packages/cli/scripts/aggregate-tolerance-class-fires.ts
@@ -2,14 +2,9 @@
import { readFileSync } from 'node:fs';
-interface FireRecord {
- event: string;
- timestamp: string;
- class: string;
- document: string | null;
- codeUnitPosition: number;
- severity: string;
-}
+import type { ToleranceFireLine } from '@inkeep/open-knowledge-server';
+
+type FireRecord = ToleranceFireLine;
interface ClassStats {
totalFires: number;
@@ -31,6 +26,7 @@ function main(): void {
const raw = readFileSync(logPath, 'utf-8');
const lines = raw.split('\n').filter((l) => l.trim().length > 0);
const records: FireRecord[] = [];
+ let skipped = 0;
for (const line of lines) {
try {
@@ -38,11 +34,23 @@ function main(): void {
if (parsed.event === 'bridge-tolerance-fire') {
records.push(parsed);
}
- } catch {}
+ } catch {
+ skipped += 1;
+ }
+ }
+
+ if (skipped > 0) {
+ console.error(`[aggregate-tolerance] skipped ${skipped} malformed line(s)`);
}
if (records.length === 0) {
- console.log(JSON.stringify({ totalRecords: 0, classes: {}, bySeverity: {} }, null, 2));
+ console.log(
+ JSON.stringify(
+ { totalRecords: 0, skippedLines: skipped, classes: {}, bySeverity: {} },
+ null,
+ 2,
+ ),
+ );
return;
}
@@ -93,6 +101,7 @@ function main(): void {
const report = {
totalRecords: records.length,
+ skippedLines: skipped,
timeRange,
bySeverity: Object.fromEntries(bySeverity),
classes: classStats,
diff --git a/packages/core/src/bridge/normalize.test.ts b/packages/core/src/bridge/normalize.test.ts
index 22970543d..226942bf8 100644
--- a/packages/core/src/bridge/normalize.test.ts
+++ b/packages/core/src/bridge/normalize.test.ts
@@ -512,6 +512,7 @@ describe('detectAppliedToleranceClasses (FR-41)', () => {
'row-no-trailing-pipe',
'list-indent-canonical',
'ordered-list-marker-number',
+ 'paragraph-continuation-indent',
'trailing-whitespace',
'blank-line-collapse',
'trailing-newline',
@@ -551,6 +552,24 @@ describe('detectAppliedToleranceClasses (FR-41)', () => {
expect(detectAppliedToleranceClasses('- foo', '- foo')).not.toContain('list-indent-canonical');
});
+ test('detects paragraph-continuation-indent when a lazy-continuation indent is present', () => {
+ expect(
+ detectAppliedToleranceClasses(
+ 'para line\n continuation text\n',
+ 'para line\ncontinuation text\n',
+ ),
+ ).toContain('paragraph-continuation-indent');
+ });
+
+ test('does not detect paragraph-continuation-indent when no continuation indent is present', () => {
+ expect(
+ detectAppliedToleranceClasses(
+ 'para line\ncontinuation text\n',
+ 'para line\ncontinuation text\n',
+ ),
+ ).not.toContain('paragraph-continuation-indent');
+ });
+
test('detects commonmark-escape when present in either input', () => {
expect(detectAppliedToleranceClasses('init\\_spike', 'init_spike')).toContain(
'commonmark-escape',
@@ -683,6 +702,60 @@ describe('detectAppliedToleranceClasses (FR-41)', () => {
});
});
+describe('paragraph lazy-continuation indent (step 7f)', () => {
+ test('single leading space on a paragraph continuation line is tolerated', () => {
+ expect(normalizeBridge('para two\n continuation text\n')).toBe(
+ normalizeBridge('para two\ncontinuation text\n'),
+ );
+ });
+
+ test('multi-space and tab continuations are tolerated', () => {
+ expect(normalizeBridge('para two\n continuation\n')).toBe(
+ normalizeBridge('para two\ncontinuation\n'),
+ );
+ expect(normalizeBridge('para two\n\tcontinuation\n')).toBe(
+ normalizeBridge('para two\ncontinuation\n'),
+ );
+ });
+
+ test('the observed fuzz construct: continuation born at a chunk boundary', () => {
+ const raw = 'lorem ipsum\n\nM2-foxtrot delta\n dolor sit amet lorem\n';
+ const canonical = 'lorem ipsum\n\nM2-foxtrot delta\ndolor sit amet lorem\n';
+ expect(normalizeBridge(raw)).toBe(normalizeBridge(canonical));
+ });
+
+ test('does NOT fire under a blank line (indented code is engine-preserved)', () => {
+ expect(normalizeBridge('para\n\n indented code\n')).not.toBe(
+ normalizeBridge('para\n\nindented code\n'),
+ );
+ });
+
+ test('does NOT fire inside fenced-code interiors', () => {
+ expect(normalizeBridge('```\ncode\n indented in fence\n```\n')).not.toBe(
+ normalizeBridge('```\ncode\nindented in fence\n```\n'),
+ );
+ });
+
+ test('does NOT fire when de-indenting would mint a setext underline', () => {
+ expect(normalizeBridge('foo\n ---\n')).not.toBe(normalizeBridge('foo\n---\n'));
+ expect(normalizeBridge('foo\n ===\n')).not.toBe(normalizeBridge('foo\n===\n'));
+ });
+
+ test('does NOT fire when the previous line is an ATX heading (no paragraph to continue)', () => {
+ expect(normalizeBridge('# Heading\n indented text\n')).not.toBe(
+ normalizeBridge('# Heading\nindented text\n'),
+ );
+ });
+
+ test('blockquote lazy continuation stays OUT of class (prefix-add, not strip)', () => {
+ expect(normalizeBridge('> a\n b\n')).not.toBe(normalizeBridge('> a\n> b\n'));
+ });
+
+ test('list-marker indents stay owned by step 7c, not stripped as continuations', () => {
+ expect(normalizeBridge('para\n - item\n')).toBe('para\n- item');
+ });
+});
+
describe('fence-opener tracking (CommonMark 4.5: closer must match opener char)', () => {
const FENCED_A = '```ts\n~~~\n| a | b |\n| - | - |\n| 1 | 2\n```\n';
const FENCED_B = '```ts\n~~~\n| a | b |\n| - | - |\n| 1 | 2 |\n```\n';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index fe758e0d1..eb8891d4e 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -50,6 +50,34 @@ function stripTrailingPipe(line: string): string {
return line.slice(0, -1).trimEnd();
}
+const CONTINUATION_BLOCK_START_RE =
+ /^(?:#{1,6}[ \t]|>|(?:[-+*]|\d{1,9}[.)])[ \t]|`{3,}|~{3,}|=+[ \t]*$|-+[ \t]*$|(?:\*[ \t]*){3,}$|(?:_[ \t]*){3,}$)/;
+
+/** Line indices inside fenced-code interiors (opening/closing fence lines
+ * excluded). Same opener-char discipline as `findTableRowLines`: a
+ * mismatched fence char inside an open fence is content. */
+function findFenceInteriorLines(lines: readonly string[]): Set<number> {
+ const interior = new Set<number>();
+ let opener: '`' | '~' | null = null;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i] ?? '';
+ const m = /^(`{3,}|~{3,})/.exec(line.trimStart());
+ if (m?.[1]) {
+ const ch = m[1][0] as '`' | '~';
+ if (opener === null) {
+ opener = ch;
+ continue;
+ }
+ if (opener === ch) {
+ opener = null;
+ continue;
+ }
+ }
+ if (opener !== null) interior.add(i);
+ }
+ return interior;
+}
+
export function normalizeBridge(s: string): string {
const lines = s
.replace(/^/, '')
@@ -62,9 +90,23 @@ export function normalizeBridge(s: string): string {
.replace(/^([#>+-].*|\d+[.)].*|`{3,}.*|~{3,}.*)\n([^\n])/gm, '$1\n\n$2')
.split('\n');
const tableRowLines = findTableRowLines(lines);
+ const fenceInterior = findFenceInteriorLines(lines);
return lines
.map((l, i) => {
const trimmed = l.trimEnd();
+ if (
+ i > 0 &&
+ !fenceInterior.has(i) &&
+ /^[ \t]+\S/.test(trimmed) &&
+ (lines[i - 1] ?? '').trim() !== '' &&
+ !LIST_ITEM_INDENT_RE.test(trimmed) &&
+ !CONTINUATION_BLOCK_START_RE.test(trimmed.trimStart())
+ ) {
+ const prev = (lines[i - 1] ?? '').trimStart();
+ if (!CONTINUATION_BLOCK_START_RE.test(prev) && !prev.startsWith('|')) {
+ return trimmed.replace(/^[ \t]+/, '');
+ }
+ }
if (TABLE_ALIGN_ROW_RE.test(trimmed)) {
const collapsed = trimmed.replace(/\s+/g, '');
return tableRowLines.has(i) &&
@@ -97,6 +139,7 @@ export const BRIDGE_TOLERANCE_CLASSES = [
'row-no-trailing-pipe',
'list-indent-canonical',
'ordered-list-marker-number',
+ 'paragraph-continuation-indent',
'trailing-whitespace',
'blank-line-collapse',
'trailing-newline',
@@ -170,6 +213,11 @@ export function detectAppliedToleranceClasses(left: string, right: string): Brid
classes.push('list-indent-canonical');
}
+ const continuationIndentMultiline = /[^\n]\n[ \t]+(?![-+*>#]|\d+[.)])\S/;
+ if (continuationIndentMultiline.test(leftLf) || continuationIndentMultiline.test(rightLf)) {
+ classes.push('paragraph-continuation-indent');
+ }
+
const canonMarkerLine = (line: string): string =>
line
.replace(/^[ \t]+/, '')
diff --git a/packages/core/src/bridge/tolerance-telemetry.test.ts b/packages/core/src/bridge/tolerance-telemetry.test.ts
index 99f61bef2..7e8923701 100644
--- a/packages/core/src/bridge/tolerance-telemetry.test.ts
+++ b/packages/core/src/bridge/tolerance-telemetry.test.ts
@@ -21,6 +21,7 @@ describe('classifySeverity', () => {
'commonmark-escape',
'leading-newline',
'doc-start-thematic',
+ 'paragraph-continuation-indent',
];
const serializerCaused: BridgeToleranceClass[] = [
'block-separator-collapse',
diff --git a/packages/core/src/bridge/tolerance-telemetry.ts b/packages/core/src/bridge/tolerance-telemetry.ts
index 3fbde92ee..2153c06e4 100644
--- a/packages/core/src/bridge/tolerance-telemetry.ts
+++ b/packages/core/src/bridge/tolerance-telemetry.ts
@@ -18,6 +18,7 @@ const SEVERITY_BY_CLASS = {
crlf: 'parser-caused',
'commonmark-escape': 'parser-caused',
'leading-newline': 'parser-caused',
+ 'paragraph-continuation-indent': 'parser-caused',
'doc-start-thematic': 'parser-caused',
'block-separator-collapse': 'serializer-caused',
'table-align-row-spacing': 'serializer-caused',
diff --git a/packages/core/src/markdown/autolink-void-html-guard.test.ts b/packages/core/src/markdown/autolink-void-html-guard.test.ts
index 66eed34af..aa7d29059 100644
--- a/packages/core/src/markdown/autolink-void-html-guard.test.ts
+++ b/packages/core/src/markdown/autolink-void-html-guard.test.ts
@@ -4,6 +4,7 @@ import { sharedExtensions } from '../extensions/shared.ts';
import { protectFromMdx } from './autolink-void-html-guard.ts';
import { MarkdownManager } from './index.ts';
import { mdastToHtml } from './mdast-to-html.ts';
+import { assertByteStable } from './round-trip-asserts.test-helper.ts';
const mdManager = new MarkdownManager({ extensions: sharedExtensions });
@@ -291,11 +292,7 @@ describe('R23 guard: angle-bracket link destinations', () => {
return out;
}
- function expectByteStable(md: string): void {
- const r1 = roundTrip(md);
- expect(r1).toBe(md);
- expect(roundTrip(r1)).toBe(r1);
- }
+ const expectByteStable = (md: string): void => assertByteStable(roundTrip, md);
test('[link](</my uri>) parses to a link node with the space-bearing url', () => {
const tree = mdManager.parseToMdast('[link](</my uri>)\n');
diff --git a/packages/core/src/markdown/entity-ref-guard.test.ts b/packages/core/src/markdown/entity-ref-guard.test.ts
index 732320661..f4daa3fd5 100644
--- a/packages/core/src/markdown/entity-ref-guard.test.ts
+++ b/packages/core/src/markdown/entity-ref-guard.test.ts
@@ -1,7 +1,12 @@
import { describe, expect, test } from 'bun:test';
import type { Root } from 'mdast';
import { sharedExtensions } from '../extensions/shared.ts';
-import { encodeEntityRefs, protectPattern, restoreEntityRefsPlugin } from './entity-ref-guard.ts';
+import {
+ decodeEntityRefs,
+ encodeEntityRefs,
+ protectPattern,
+ restoreEntityRefsPlugin,
+} from './entity-ref-guard.ts';
import { MarkdownManager } from './index.ts';
describe('protectPattern — length preservation', () => {
@@ -317,6 +322,24 @@ describe('restoreEntityRefsPlugin — mdast walk', () => {
});
});
+describe('decodeEntityRefs — CommonMark §2.5 U+FFFD safety net', () => {
+ test('NUL numeric reference decodes to U+FFFD', () => {
+ expect(decodeEntityRefs('a&#0;b')).toBe('a\uFFFDb');
+ });
+
+ test('surrogate numeric reference decodes to U+FFFD, not a throw', () => {
+ expect(decodeEntityRefs('x&#xD800;y')).toBe('x\uFFFDy');
+ });
+
+ test('out-of-range numeric reference decodes to U+FFFD', () => {
+ expect(decodeEntityRefs('q&#x110000;r')).toBe('q\uFFFDr');
+ });
+
+ test('valid named and numeric refs still decode beside the net', () => {
+ expect(decodeEntityRefs('&quot;&#65;&#x42;')).toBe('"AB');
+ });
+});
+
describe('fenced-code info-string entity refs — real-engine round-trip', () => {
const mgr = new MarkdownManager({ extensions: sharedExtensions });
const roundTrip = (src: string) => mgr.serialize(mgr.parse(src));
diff --git a/packages/core/src/markdown/pipeline.doc-boundary.test.ts b/packages/core/src/markdown/pipeline.doc-boundary.test.ts
index 59ce65552..35ae94e79 100644
--- a/packages/core/src/markdown/pipeline.doc-boundary.test.ts
+++ b/packages/core/src/markdown/pipeline.doc-boundary.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test';
import type { JSONContent } from '@tiptap/core';
import { sharedExtensions } from '../extensions/shared.ts';
import { MarkdownManager } from './index.ts';
+import { assertRoundTripIdempotent } from './round-trip-asserts.test-helper.ts';
const md = new MarkdownManager({ extensions: sharedExtensions });
@@ -9,9 +10,7 @@ function rt(source: string): string {
return md.serialize(md.parse(source));
}
-function expectByteStable(out: string): void {
- expect(rt(out)).toBe(out);
-}
+const expectByteStable = (out: string): void => assertRoundTripIdempotent(rt, out);
describe('indented-code leading-indent capture (tab-expansion)', () => {
test('a tab-indented code line round-trips byte-exact', () => {
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 674e08091..80a52e0c5 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -142,6 +142,11 @@ function splitDocumentHeadBom(source: string): { source: string; hadBom: boolean
: { source, hadBom: false };
}
+const GAP_CAPTURE_MIN_NEWLINES = 3;
+
+const LEADING_BOUNDARY_SHAPE = /^\n+$/;
+const TRAILING_BOUNDARY_SHAPE = /^\n{2,}$/;
+
function captureDocBoundary(
root: MdastRoot,
source: string,
@@ -156,12 +161,12 @@ function captureDocBoundary(
const firstStart = children[0]?.position?.start?.offset;
if (typeof firstStart === 'number' && firstStart > 0) {
const gap = source.slice(0, firstStart);
- if (/^\n+$/.test(gap)) leading = gap;
+ if (LEADING_BOUNDARY_SHAPE.test(gap)) leading = gap;
}
const lastEnd = children[children.length - 1]?.position?.end?.offset;
if (typeof lastEnd === 'number' && lastEnd <= source.length) {
const gap = source.slice(lastEnd);
- if (/^\n{2,}$/.test(gap)) trailing = gap;
+ if (TRAILING_BOUNDARY_SHAPE.test(gap)) trailing = gap;
}
const gaps: Array<number | null> = [];
let anyGap = false;
@@ -171,7 +176,7 @@ function captureDocBoundary(
let blanks: number | null = null;
if (typeof prevEnd === 'number' && typeof nextStart === 'number' && nextStart >= prevEnd) {
const gap = source.slice(prevEnd, nextStart);
- if (/^\n{3,}$/.test(gap)) {
+ if (new RegExp(`^\\n{${GAP_CAPTURE_MIN_NEWLINES},}$`).test(gap)) {
blanks = gap.length - 1;
anyGap = true;
}
@@ -205,12 +210,18 @@ function readDocBoundary(value: unknown): SourceDocBoundary | undefined {
gapBlankLines?: Array<number | null>;
} = {};
if (v.bom === true) out.bom = true;
- if (typeof v.leading === 'string' && /^\n+$/.test(v.leading)) out.leading = v.leading;
- if (typeof v.trailing === 'string' && /^\n{2,}$/.test(v.trailing)) out.trailing = v.trailing;
+ if (typeof v.leading === 'string' && LEADING_BOUNDARY_SHAPE.test(v.leading)) {
+ out.leading = v.leading;
+ }
+ if (typeof v.trailing === 'string' && TRAILING_BOUNDARY_SHAPE.test(v.trailing)) {
+ out.trailing = v.trailing;
+ }
if (
Array.isArray(v.gapBlankLines) &&
v.gapBlankLines.every(
- (g) => g === null || (typeof g === 'number' && Number.isInteger(g) && g >= 2),
+ (g) =>
+ g === null ||
+ (typeof g === 'number' && Number.isInteger(g) && g >= GAP_CAPTURE_MIN_NEWLINES - 1),
)
) {
out.gapBlankLines = v.gapBlankLines as Array<number | null>;
diff --git a/packages/core/src/markdown/round-trip-asserts.test-helper.ts b/packages/core/src/markdown/round-trip-asserts.test-helper.ts
new file mode 100644
index 000000000..e9c80813d
--- /dev/null
+++ b/packages/core/src/markdown/round-trip-asserts.test-helper.ts
@@ -0,0 +1,11 @@
+import { expect } from 'bun:test';
+
+export function assertByteStable(roundTrip: (s: string) => string, source: string): void {
+ const once = roundTrip(source);
+ expect(once).toBe(source);
+ expect(roundTrip(once)).toBe(once);
+}
+
+export function assertRoundTripIdempotent(roundTrip: (s: string) => string, out: string): void {
+ expect(roundTrip(out)).toBe(out);
+}
diff --git a/packages/core/src/markdown/to-markdown-handlers.attention.test.ts b/packages/core/src/markdown/to-markdown-handlers.attention.test.ts
index 837c3e9d6..f2cffd43b 100644
--- a/packages/core/src/markdown/to-markdown-handlers.attention.test.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.attention.test.ts
@@ -3,6 +3,7 @@ import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { sharedExtensions } from '../extensions/shared.ts';
import { MarkdownManager } from './index.ts';
+import { assertRoundTripIdempotent } from './round-trip-asserts.test-helper.ts';
const md = new MarkdownManager({ extensions: sharedExtensions });
@@ -36,9 +37,8 @@ function allNodeTypes(markdown: string): string[] {
return out;
}
-function expectByteStable(out: string): void {
- expect(md.serialize(md.parse(out))).toBe(out);
-}
+const expectByteStable = (out: string): void =>
+ assertRoundTripIdempotent((s) => md.serialize(md.parse(s)), out);
describe('boundary-whitespace attention encode (WYSIWYG-shaped marks)', () => {
test('emphasis with trailing space re-parses as emphasis via char-ref', () => {
diff --git a/packages/core/src/markdown/to-markdown-handlers.inline-math.test.ts b/packages/core/src/markdown/to-markdown-handlers.inline-math.test.ts
index 98b9d2e44..c363ec12b 100644
--- a/packages/core/src/markdown/to-markdown-handlers.inline-math.test.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.inline-math.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test';
import type { JSONContent } from '@tiptap/core';
import { sharedExtensions } from '../extensions/shared.ts';
import { MarkdownManager } from './index.ts';
+import { assertByteStable } from './round-trip-asserts.test-helper.ts';
const md = new MarkdownManager({ extensions: sharedExtensions });
@@ -24,11 +25,8 @@ function countInJson(json: JSONContent, predicate: (n: JSONContent) => boolean):
const isMath = (n: JSONContent) => n.type === 'mathInline';
-function expectByteStable(source: string) {
- const once = md.serialize(md.parse(source));
- expect(once).toBe(source);
- expect(md.serialize(md.parse(once))).toBe(once);
-}
+const expectByteStable = (source: string): void =>
+ assertByteStable((s) => md.serialize(md.parse(s)), source);
function expectReparsesAsMath(emitted: string, formula: string) {
const json = md.parse(emitted);
diff --git a/packages/core/src/markdown/wiki-embed-opaque.test.ts b/packages/core/src/markdown/wiki-embed-opaque.test.ts
index b5c4ef28a..cbca58d56 100644
--- a/packages/core/src/markdown/wiki-embed-opaque.test.ts
+++ b/packages/core/src/markdown/wiki-embed-opaque.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test';
import type { JSONContent } from '@tiptap/core';
import { sharedExtensions } from '../extensions/shared.ts';
import { MarkdownManager } from './index.ts';
+import { assertByteStable } from './round-trip-asserts.test-helper.ts';
const mdManager = new MarkdownManager({ extensions: sharedExtensions });
@@ -9,11 +10,7 @@ function roundTrip(md: string): string {
return mdManager.serialize(mdManager.parse(md));
}
-function expectByteStable(md: string): void {
- const once = roundTrip(md);
- expect(once).toBe(md);
- expect(roundTrip(once)).toBe(once);
-}
+const expectByteStable = (md: string): void => assertByteStable(roundTrip, md);
function findNodes(json: JSONContent, type: string): JSONContent[] {
const out: JSONContent[] = [];
diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json
index 0ab290dda..83fb5bf3c 100644
--- a/packages/core/tsconfig.json
+++ b/packages/core/tsconfig.json
@@ -5,5 +5,5 @@
"allowImportingTsExtensions": true
},
"include": ["src", "*.ts"],
- "exclude": ["node_modules", "dist", "**/*.test.ts"]
+ "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.test-helper.ts"]
}
diff --git a/packages/server/src/boot.test.ts b/packages/server/src/boot.test.ts
index ed00f26dc..dfd189479 100644
--- a/packages/server/src/boot.test.ts
+++ b/packages/server/src/boot.test.ts
@@ -3,12 +3,12 @@ import { describe as _bunDescribe, afterEach, beforeEach, expect, test } from 'b
const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
import { execFile } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { hostname, tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
-import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { emitToleranceFire, OK_DIR } from '@inkeep/open-knowledge-core';
import { context, metrics, trace } from '@opentelemetry/api';
import {
BasicTracerProvider,
@@ -221,6 +221,42 @@ describe('bootServer — runtime state lives at projectDir, not contentDir', ()
});
});
+describe('bootServer — tolerance-telemetry writer wired through the real boot path', () => {
+ test('flag=1 boot produces tolerance-telemetry.jsonl from an emitToleranceFire', async () => {
+ const prevFlag = process.env.OK_BRIDGE_TOLERANCE_TELEMETRY;
+ process.env.OK_BRIDGE_TOLERANCE_TELEMETRY = '1';
+ const projectDir = mkdtempSync(resolve(tmpDir, 'tolerance-telemetry-'));
+ await execFileAsync('git', ['init', '--initial-branch=main', projectDir]);
+ seedOkScaffold(projectDir);
+
+ const booted = await bootServer({
+ config: TEST_CONFIG,
+ projectDir,
+ contentDir: projectDir,
+ port: 0,
+ quiet: true,
+ gitEnabled: false,
+ idleShutdownMs: null,
+ attachUiSibling: false,
+ });
+ try {
+ await booted.ready;
+ emitToleranceFire(['crlf'], 'a\r\n', 'a\n', 'smoke-doc');
+ } finally {
+ await booted.destroy();
+ if (prevFlag === undefined) delete process.env.OK_BRIDGE_TOLERANCE_TELEMETRY;
+ else process.env.OK_BRIDGE_TOLERANCE_TELEMETRY = prevFlag;
+ }
+
+ const logPath = resolve(projectDir, '.ok', 'local', 'tolerance-telemetry.jsonl');
+ expect(existsSync(logPath)).toBe(true);
+ const record = JSON.parse(readFileSync(logPath, 'utf-8').trim().split('\n')[0] ?? '');
+ expect(record.event).toBe('bridge-tolerance-fire');
+ expect(record.class).toBe('crlf');
+ expect(record.document).toBe('smoke-doc');
+ });
+});
+
describe('bootServer — idle-shutdown runs full destroy', () => {
test('after idle-shutdown fires with zero WS clients, httpServer is no longer listening', async () => {
const projectDir = mkdtempSync(resolve(tmpDir, 'idle-full-destroy-'));
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 09bdaceda..9fba97e5b 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -35,6 +35,10 @@ import { MissingOkConfigError } from './missing-ok-config-error.ts';
import { createServer, type ServerInstance, type ServerOptions } from './server-factory.ts';
import { installServerMemoryGauge } from './server-memory-telemetry.ts';
import { initTelemetry, shutdownTelemetry, withSpan } from './telemetry.ts';
+import {
+ initToleranceTelemetryWriter,
+ teardownToleranceTelemetryWriter,
+} from './tolerance-telemetry-writer.ts';
import { acquireUiLock, releaseUiLock, UiLockCollisionError, updateUiLockPort } from './ui-lock.ts';
const LEGACY_RUNTIME_FILENAMES = [
@@ -171,6 +175,7 @@ export async function bootServer(opts: BootServerOptions): Promise<BootedServer>
});
}
initTelemetry({ localSink: localSinkConfig?.telemetry });
+ initToleranceTelemetryWriter(sinkProjectDir);
installServerMemoryGauge();
const { kind: worktreeKind, gitdir: worktreeGitdir } = computeWorktreeAttributes(
@@ -243,6 +248,10 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
process.stderr.write(`${err.message}\n`);
}
await shutdownTelemetry();
+ await Promise.race([
+ teardownToleranceTelemetryWriter(),
+ new Promise<void>((resolve) => setTimeout(resolve, DESTROY_STEP_TIMEOUT_MS)),
+ ]);
throw err;
}
@@ -501,6 +510,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
await runStep('releaseUiLock', async () => releaseUiLock(lockDir));
}
await runStep('shutdownTelemetry', () => shutdownTelemetry());
+ await runStep('teardownToleranceTelemetry', () => teardownToleranceTelemetryWriter());
await runStep('flushLogFileSinks', () => loggerFactory.flushAllFileSinks());
if (errors.length > 0) {
diff --git a/packages/server/src/bridge-watchdog.test.ts b/packages/server/src/bridge-watchdog.test.ts
index 0dbec4a74..297aab0b6 100644
--- a/packages/server/src/bridge-watchdog.test.ts
+++ b/packages/server/src/bridge-watchdog.test.ts
@@ -1,5 +1,9 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { BridgeInvariantViolationError } from '@inkeep/open-knowledge-core';
+import {
+ BridgeInvariantViolationError,
+ setToleranceTelemetryHook,
+ type ToleranceFireRecord,
+} from '@inkeep/open-knowledge-core';
import {
__getSplitBrainRateTupleCountForTests,
__getViolationRateTupleCountForTests,
@@ -669,6 +673,52 @@ describe('bridge-tolerance-applied event (FR-41)', () => {
});
});
+describe('tolerance-telemetry file hook receives the full un-rate-limited list', () => {
+ let fires: ToleranceFireRecord[] = [];
+
+ beforeEach(() => {
+ fires = [];
+ setToleranceTelemetryHook((record) => {
+ fires.push(record);
+ });
+ });
+
+ afterEach(() => {
+ setToleranceTelemetryHook(null);
+ });
+
+ test('hook fires on both calls while console/metric emit once', () => {
+ const originalWarn = console.warn;
+ const warnings: string[] = [];
+ console.warn = (...args: unknown[]) => {
+ warnings.push(args.map(String).join(' '));
+ };
+
+ try {
+ assertBridgeInvariant('# Hello\r\n', '# Hello\n', {
+ site: 'observer-b',
+ docName: 'doc-1',
+ nowMs: 1000,
+ });
+ assertBridgeInvariant('# Hello\r\n', '# Hello\n', {
+ site: 'observer-b',
+ docName: 'doc-1',
+ nowMs: 1500,
+ });
+ } finally {
+ console.warn = originalWarn;
+ }
+
+ expect(fires.filter((f) => f.className === 'crlf')).toHaveLength(2);
+
+ const crlfWarnings = warnings
+ .map((w) => JSON.parse(w))
+ .filter((e) => e.event === 'bridge-tolerance-applied' && e.class === 'crlf');
+ expect(crlfWarnings).toHaveLength(1);
+ expect(getMetrics().bridgeToleranceApplied.crlf).toBe(1);
+ });
+});
+
describe('shouldEmitBridgeToleranceApplied — gate semantics', () => {
test('first call per (site, class) returns true', () => {
expect(shouldEmitBridgeToleranceApplied('observer-b', 'crlf', 1000)).toBe(true);
diff --git a/packages/server/src/bridge-watchdog.ts b/packages/server/src/bridge-watchdog.ts
index 6cf3483b4..ac790af1f 100644
--- a/packages/server/src/bridge-watchdog.ts
+++ b/packages/server/src/bridge-watchdog.ts
@@ -56,12 +56,12 @@ const lastEmitMs = new Map<string, number>();
const MAX_VIOLATION_RATE_TUPLES = 1024;
/** Map<rateKey, last-emit-Unix-ms> for the bridge-tolerance-applied event.
- * rateKey = `${site}::${class}`. Bounded cardinality: 8 classes × 3 sites =
- * 24 entries max globally. Per-(site, class) windows let operators see how
+ * rateKey = `${site}::${class}`. Bounded cardinality: 15 classes × 3 sites =
+ * 45 entries max globally. Per-(site, class) windows let operators see how
* often each site relies on each tolerance class — observer-b CRLF rates
* vs persistence CRLF rates surface separately.
*
- * WARN: same module-level state caveat as `lastEmitMs` above. The 24-entry
+ * WARN: same module-level state caveat as `lastEmitMs` above. The 45-entry
* bound is global; under multi-server-per-process, a single server's
* tolerance event would suppress another server's same-class event in
* the same window. Less concerning than the violation rate-limiter
@@ -239,18 +239,21 @@ export function assertBridgeInvariant(
if (ytextNorm === fragNorm) {
if (ytextSnapshot !== fragmentMdSnapshot) {
const classes = detectAppliedToleranceClasses(ytextSnapshot, fragmentMdSnapshot);
- emitToleranceFire(classes, ytextSnapshot, fragmentMdSnapshot, opts.docName);
- for (const cls of classes) {
- if (shouldEmitBridgeToleranceApplied(opts.site, cls, opts.nowMs)) {
- incrementBridgeToleranceApplied(cls);
- console.warn(
- JSON.stringify({
- event: 'bridge-tolerance-applied',
- site: opts.site,
- class: cls,
- }),
- );
- }
+ const emittedClasses = classes.filter((cls) =>
+ shouldEmitBridgeToleranceApplied(opts.site, cls, opts.nowMs),
+ );
+ if (classes.length > 0) {
+ emitToleranceFire(classes, ytextSnapshot, fragmentMdSnapshot, opts.docName);
+ }
+ for (const cls of emittedClasses) {
+ incrementBridgeToleranceApplied(cls);
+ console.warn(
+ JSON.stringify({
+ event: 'bridge-tolerance-applied',
+ site: opts.site,
+ class: cls,
+ }),
+ );
}
}
return true;
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index a743dfc78..df8bb90ab 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -484,6 +484,7 @@ export {
export {
initToleranceTelemetryWriter,
isToleranceTelemetryEnabled,
+ type ToleranceFireLine,
teardownToleranceTelemetryWriter,
} from './tolerance-telemetry-writer.ts';
export {
diff --git a/packages/server/src/map-driven-observer-a.test.ts b/packages/server/src/map-driven-observer-a.test.ts
index 22604edf9..aa3f63f40 100644
--- a/packages/server/src/map-driven-observer-a.test.ts
+++ b/packages/server/src/map-driven-observer-a.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, spyOn, test } from 'bun:test';
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment } from '@tiptap/y-tiptap';
@@ -7,7 +7,11 @@ import { AGENT_WRITE_ORIGIN } from './agent-sessions.ts';
import { composeAndWriteRawBody } from './bridge-intake.ts';
import { computeMapDrivenBodySplice } from './map-driven-splice.ts';
import { getMetrics } from './metrics.ts';
-import { OBSERVER_SYNC_ORIGIN, setupServerObservers } from './server-observers.ts';
+import {
+ __resetMapDrivenParseErrorWarnForTests,
+ OBSERVER_SYNC_ORIGIN,
+ setupServerObservers,
+} from './server-observers.ts';
const mdManager = new MarkdownManager({ extensions: sharedExtensions });
const schema = getSchema(sharedExtensions);
@@ -336,6 +340,53 @@ describe('map-driven Observer A — default Path A behavior', () => {
expect(reasons).toEqual(['parse-error']);
});
+ test('a sustained parse-error fallback warns once with the error message, then stays counter-only', () => {
+ const raw = '# Heading\n\nFirst.\n\nSecond.\n';
+ const { doc, xmlFragment, ytext } = createTestDoc();
+ const throwingManager = new Proxy(mdManager, {
+ get(target, prop) {
+ if (prop === 'parseToMdast') {
+ return () => {
+ throw new Error('synthetic parser regression');
+ };
+ }
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ __resetMapDrivenParseErrorWarnForTests();
+ const warnSpy = spyOn(console, 'warn');
+ const cleanup = setupServerObservers({
+ doc,
+ xmlFragment,
+ ytext,
+ mdManager: throwingManager,
+ schema,
+ });
+ doc.transact(() => {
+ composeAndWriteRawBody(doc, raw, 'agent');
+ }, AGENT_WRITE_ORIGIN);
+
+ const before = getMetrics();
+ populateFragment(doc, xmlFragment, raw.replace('First.', 'First EDITED.'));
+ populateFragment(doc, xmlFragment, raw.replace('First.', 'First EDITED TWICE.'));
+ const after = getMetrics();
+
+ expect(ytext.toString()).toContain('First EDITED TWICE.');
+ expect(
+ (after.mapDrivenSpliceFallback['parse-error'] ?? 0) -
+ (before.mapDrivenSpliceFallback['parse-error'] ?? 0),
+ ).toBeGreaterThanOrEqual(2);
+ const spliceWarns = warnSpy.mock.calls.filter((args) =>
+ String(args[0]).includes('Map-driven splice'),
+ );
+ expect(spliceWarns).toHaveLength(1);
+ expect(spliceWarns[0]?.[1]).toBe('synthetic parser regression');
+
+ warnSpy.mockRestore();
+ cleanup();
+ });
+
test('an offset-less block reports missing-position through the pure computer', () => {
const reasons: string[] = [];
const splice = computeMapDrivenBodySplice(
diff --git a/packages/server/src/map-driven-splice.ts b/packages/server/src/map-driven-splice.ts
index 5c9d0ce41..0344c335d 100644
--- a/packages/server/src/map-driven-splice.ts
+++ b/packages/server/src/map-driven-splice.ts
@@ -12,7 +12,7 @@ export function computeMapDrivenBodySplice(
oldBody: string,
newPmJson: JSONContent,
mdManager: MarkdownManager,
- onFallback?: (reason: 'parse-error' | 'missing-position') => void,
+ onFallback?: (reason: 'parse-error' | 'missing-position', err?: unknown) => void,
): MapDrivenSplice | null {
let oldChildren: readonly RootContent[];
let newBody: string;
@@ -21,8 +21,8 @@ export function computeMapDrivenBodySplice(
oldChildren = mdManager.parseToMdast(oldBody).children;
newBody = mdManager.serialize(newPmJson);
newChildren = mdManager.parseToMdast(newBody).children;
- } catch {
- onFallback?.('parse-error');
+ } catch (err) {
+ onFallback?.('parse-error', err);
return null;
}
diff --git a/packages/server/src/server-observers.ts b/packages/server/src/server-observers.ts
index 043076f7a..49b57d054 100644
--- a/packages/server/src/server-observers.ts
+++ b/packages/server/src/server-observers.ts
@@ -74,6 +74,23 @@ interface TryComputeMapDrivenSpliceArgs {
readonly docName: string | undefined;
}
+let mapDrivenParseErrorWarned = false;
+
+/** Test-only: re-arm the parse-error warn-once (process-global, so an earlier
+ * suite test exercising the fallback would otherwise consume the single warn). */
+export function __resetMapDrivenParseErrorWarnForTests(): void {
+ mapDrivenParseErrorWarned = false;
+}
+
+function warnOnceMapDrivenParseError(docName: string | undefined, err: unknown): void {
+ if (mapDrivenParseErrorWarned) return;
+ mapDrivenParseErrorWarned = true;
+ console.warn(
+ `[Server Observer A] Map-driven splice parse/serialize threw (doc: ${docName ?? 'unknown'}); drains fall back to the incremental diff (warned once; further failures count in mapDrivenSpliceFallback only):`,
+ err instanceof Error ? err.message : String(err),
+ );
+}
+
function tryComputeMapDrivenSplice(
args: TryComputeMapDrivenSpliceArgs,
): YTextMapDrivenSplice | null {
@@ -93,7 +110,10 @@ function tryComputeMapDrivenSplice(
oldBody,
json as Parameters<typeof computeMapDrivenBodySplice>[1],
mdManager,
- incrementMapDrivenSpliceFallback,
+ (reason, err) => {
+ incrementMapDrivenSpliceFallback(reason);
+ if (reason === 'parse-error') warnOnceMapDrivenParseError(docName, err);
+ },
);
if (!splice) return null;
@@ -133,8 +153,8 @@ export interface SetupServerObserversOpts {
onDispatch?: ObserverDispatchHook;
}
-function settlesSplitBrain(settledText: string, md: string): boolean {
- return settledText !== md && normalizeBridge(settledText) !== normalizeBridge(md);
+function settlesSplitBrain(settledText: string, md: string, normMdPre?: string): boolean {
+ return settledText !== md && normalizeBridge(settledText) !== (normMdPre ?? normalizeBridge(md));
}
export function setupServerObservers(opts: SetupServerObserversOpts): () => void {
@@ -296,7 +316,9 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
const currentText = ytext.toString();
- if (normalizeBridge(currentText) === normalizeBridge(md)) {
+ const normCurrent = normalizeBridge(currentText);
+ const normMd = normalizeBridge(md);
+ if (normCurrent === normMd) {
setActiveSpanAttributes({ 'observer.a.path': 'gated-in-sync' });
recordSettledBaselines(md);
return;
@@ -304,10 +326,11 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
const preMergeBaseline = lastSyncedYTextBytes;
const ytextInSync = currentText === lastSyncedYTextBytes;
- const residualInTolerance =
- lastSyncedYTextBytes === lastSyncedCanonicalMd ||
- normalizeBridge(lastSyncedYTextBytes) === normalizeBridge(lastSyncedCanonicalMd);
- const residualMergeEligible = canonicalWitnessCoherent && !residualInTolerance;
+ const residualMergeEligible =
+ ytextInSync &&
+ canonicalWitnessCoherent &&
+ lastSyncedYTextBytes !== lastSyncedCanonicalMd &&
+ normCurrent !== normalizeBridge(lastSyncedCanonicalMd);
setActiveSpanAttributes({
'observer.a.path': ytextInSync
? residualMergeEligible
@@ -317,6 +340,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
});
const pathBState: { mergedText: string | null } = { mergedText: null };
+ const spliceComputeStart = performance.now();
const mapDrivenSplice =
ytextInSync && residualMergeEligible
? null
@@ -328,7 +352,10 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
docName: opts.docName,
});
if (mapDrivenSplice) {
- setActiveSpanAttributes({ 'observer.a.path': 'map-driven-splice' });
+ setActiveSpanAttributes({
+ 'observer.a.path': 'map-driven-splice',
+ 'observer.a.splice.compute_ms': Math.round(performance.now() - spliceComputeStart),
+ });
}
doc.transact(() => {
@@ -376,7 +403,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
incrementServerObserverFire('a');
recordSettledBaselines(md);
- if (settlesSplitBrain(ytext.toString(), md)) {
+ if (settlesSplitBrain(ytext.toString(), md, normMd)) {
textDirty = true;
recordSplitBrainRederive('post-merge');
}
diff --git a/packages/server/src/share/construct-url.test.ts b/packages/server/src/share/construct-url.test.ts
index f923ad226..04a23a94a 100644
--- a/packages/server/src/share/construct-url.test.ts
+++ b/packages/server/src/share/construct-url.test.ts
@@ -62,7 +62,7 @@ async function bootRig(
hocuspocus.configuration.extensions.push(ext);
const port = await new Promise<number>((resolveListen) => {
- server.listen(0, () => {
+ server.listen(0, '127.0.0.1', () => {
const addr = server.address();
resolveListen(typeof addr === 'object' && addr ? addr.port : 0);
});
@@ -101,7 +101,7 @@ function seedRemoteAndHead(
}
async function postConstructUrl(port: number, body: unknown): Promise<Response> {
- return fetch(`http://localhost:${port}/api/share/construct-url`, {
+ return fetch(`http://127.0.0.1:${port}/api/share/construct-url`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
diff --git a/packages/server/src/tolerance-telemetry-writer.test.ts b/packages/server/src/tolerance-telemetry-writer.test.ts
index 0c878ffa1..15461d95b 100644
--- a/packages/server/src/tolerance-telemetry-writer.test.ts
+++ b/packages/server/src/tolerance-telemetry-writer.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -20,8 +20,8 @@ beforeEach(() => {
delete process.env.OK_BRIDGE_TOLERANCE_TELEMETRY;
});
-afterEach(() => {
- teardownToleranceTelemetryWriter();
+afterEach(async () => {
+ await teardownToleranceTelemetryWriter();
try {
rmSync(tmpProjectDir, { recursive: true, force: true });
} catch {}
@@ -53,12 +53,13 @@ describe('initToleranceTelemetryWriter', () => {
expect(existsSync(logPath)).toBe(false);
});
- test('writes JSONL when flag is ON', () => {
+ test('writes JSONL when flag is ON', async () => {
process.env.OK_BRIDGE_TOLERANCE_TELEMETRY = '1';
initToleranceTelemetryWriter(tmpProjectDir);
emitToleranceFire(['crlf'], 'a\r\n', 'a\n', 'notes/meeting');
+ await teardownToleranceTelemetryWriter();
const logPath = resolve(tmpProjectDir, '.ok', 'local', 'tolerance-telemetry.jsonl');
expect(existsSync(logPath)).toBe(true);
@@ -75,13 +76,14 @@ describe('initToleranceTelemetryWriter', () => {
expect(record.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});
- test('appends multiple fires to same file', () => {
+ test('appends multiple fires to same file', async () => {
process.env.OK_BRIDGE_TOLERANCE_TELEMETRY = '1';
initToleranceTelemetryWriter(tmpProjectDir);
emitToleranceFire(['crlf'], 'a\r\n', 'a\n', 'doc-1');
emitToleranceFire(['bom'], 'hello', 'hello', 'doc-2');
+ await teardownToleranceTelemetryWriter();
const logPath = resolve(tmpProjectDir, '.ok', 'local', 'tolerance-telemetry.jsonl');
const lines = readFileSync(logPath, 'utf-8').trim().split('\n');
expect(lines).toHaveLength(2);
@@ -89,12 +91,13 @@ describe('initToleranceTelemetryWriter', () => {
expect(JSON.parse(lines[1] ?? '').class).toBe('bom');
});
- test('multi-class fire produces one line per class', () => {
+ test('multi-class fire produces one line per class', async () => {
process.env.OK_BRIDGE_TOLERANCE_TELEMETRY = '1';
initToleranceTelemetryWriter(tmpProjectDir);
emitToleranceFire(['bom', 'crlf', 'trailing-whitespace'], 'a \r\n', 'a\n', 'doc');
+ await teardownToleranceTelemetryWriter();
const logPath = resolve(tmpProjectDir, '.ok', 'local', 'tolerance-telemetry.jsonl');
const lines = readFileSync(logPath, 'utf-8').trim().split('\n');
expect(lines).toHaveLength(3);
@@ -103,23 +106,45 @@ describe('initToleranceTelemetryWriter', () => {
expect(classes).toEqual(['bom', 'crlf', 'trailing-whitespace']);
});
- test('null document name serializes as null', () => {
+ test('null document name serializes as null', async () => {
process.env.OK_BRIDGE_TOLERANCE_TELEMETRY = '1';
initToleranceTelemetryWriter(tmpProjectDir);
emitToleranceFire(['trailing-newline'], 'hello\n', 'hello', undefined);
+ await teardownToleranceTelemetryWriter();
const logPath = resolve(tmpProjectDir, '.ok', 'local', 'tolerance-telemetry.jsonl');
const record = JSON.parse(readFileSync(logPath, 'utf-8').trim());
expect(record.document).toBeNull();
});
- test('teardown stops further writes', () => {
+ test('append-failure warning re-arms after teardown (per-boot warn budget)', async () => {
+ process.env.OK_BRIDGE_TOLERANCE_TELEMETRY = '1';
+ const logPath = resolve(tmpProjectDir, '.ok', 'local', 'tolerance-telemetry.jsonl');
+ mkdirSync(logPath, { recursive: true });
+
+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ initToleranceTelemetryWriter(tmpProjectDir);
+ emitToleranceFire(['crlf'], 'a\r\n', 'a\n', 'doc');
+ await teardownToleranceTelemetryWriter();
+ expect(warnSpy.mock.calls.length).toBe(1);
+
+ initToleranceTelemetryWriter(tmpProjectDir);
+ emitToleranceFire(['crlf'], 'b\r\n', 'b\n', 'doc');
+ await teardownToleranceTelemetryWriter();
+ expect(warnSpy.mock.calls.length).toBe(2);
+ } finally {
+ warnSpy.mockRestore();
+ }
+ });
+
+ test('teardown stops further writes', async () => {
process.env.OK_BRIDGE_TOLERANCE_TELEMETRY = '1';
initToleranceTelemetryWriter(tmpProjectDir);
emitToleranceFire(['crlf'], 'a\r', 'a', 'doc');
- teardownToleranceTelemetryWriter();
+ await teardownToleranceTelemetryWriter();
emitToleranceFire(['crlf'], 'b\r', 'b', 'doc');
const logPath = resolve(tmpProjectDir, '.ok', 'local', 'tolerance-telemetry.jsonl');
diff --git a/packages/server/src/tolerance-telemetry-writer.ts b/packages/server/src/tolerance-telemetry-writer.ts
index 69f137759..26835de89 100644
--- a/packages/server/src/tolerance-telemetry-writer.ts
+++ b/packages/server/src/tolerance-telemetry-writer.ts
@@ -1,11 +1,25 @@
-import { appendFileSync, mkdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { setToleranceTelemetryHook, type ToleranceFireRecord } from '@inkeep/open-knowledge-core';
import { getLocalDir } from './config/paths.ts';
+import { RotatingAppender } from './telemetry-file-sink.ts';
const TELEMETRY_FILENAME = 'tolerance-telemetry.jsonl';
+const TELEMETRY_PREV_FILENAME = 'tolerance-telemetry.prev.jsonl';
+const TELEMETRY_MAX_BYTES = 8 * 1024 * 1024;
+
+export interface ToleranceFireLine {
+ event: 'bridge-tolerance-fire';
+ timestamp: string;
+ class: string;
+ document: string | null;
+ codeUnitPosition: number;
+ severity: string;
+}
+
+let appender: RotatingAppender | null = null;
+let appendFailureWarned = false;
export function isToleranceTelemetryEnabled(
env: Record<string, string | undefined> = process.env,
@@ -17,24 +31,36 @@ export function initToleranceTelemetryWriter(projectDir: string): void {
if (!isToleranceTelemetryEnabled()) return;
const localDir = getLocalDir(projectDir);
- mkdirSync(localDir, { recursive: true });
- const logPath = resolve(localDir, TELEMETRY_FILENAME);
+ appender = new RotatingAppender({
+ currentPath: resolve(localDir, TELEMETRY_FILENAME),
+ previousPath: resolve(localDir, TELEMETRY_PREV_FILENAME),
+ maxBytes: TELEMETRY_MAX_BYTES,
+ });
setToleranceTelemetryHook((record: ToleranceFireRecord) => {
- const line = JSON.stringify({
+ const fireLine: ToleranceFireLine = {
event: 'bridge-tolerance-fire',
timestamp: record.timestamp,
class: record.className,
document: record.documentName ?? null,
codeUnitPosition: record.codeUnitPosition,
severity: record.severity,
+ };
+ void appender?.append(`${JSON.stringify(fireLine)}\n`).catch((err: unknown) => {
+ if (!appendFailureWarned) {
+ appendFailureWarned = true;
+ console.warn(
+ '[tolerance-telemetry] append failed; further failures are silent:',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
});
- try {
- appendFileSync(logPath, `${line}\n`);
- } catch {}
});
}
-export function teardownToleranceTelemetryWriter(): void {
+export async function teardownToleranceTelemetryWriter(): Promise<void> {
setToleranceTelemetryHook(null);
+ await appender?.drain();
+ appender = null;
+ appendFailureWarned = false;
}