Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Require every Open Knowledge test to assert what it checks (#5132)

Nick Gomez6afc01610516
diff --git a/knip.config.ts b/knip.config.ts
index 3b68578af..37d9ce912 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -62,8 +62,7 @@ export default {
'packages/app/src/lib/perf/mark.ts': ['types'],
'packages/app/src/editor/typing-burst-detector.ts': ['exports', 'types'],
'packages/server/src/bridge-intake.ts': ['types'],
- 'packages/core/src/schemas/api.type-tests.ts': ['files'],
- 'packages/core/src/git-pathspec.type-tests.ts': ['files'],
+ '**/*.type-tests.ts': ['files'],
'packages/server/src/http/request-validation.ts': ['exports', 'types'],
'packages/server/src/http/error-response.ts': ['exports'],
'packages/app/src/editor/http-client.ts': ['types'],
@@ -146,11 +145,15 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: ['yjs'],
+ ignoreDependencies: [
+ 'yjs',
+ ],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/src/components/ActivityPanelDiffView.dom.test.tsx b/packages/app/src/components/ActivityPanelDiffView.dom.test.tsx
index 67ca5adc2..cd092728f 100644
--- a/packages/app/src/components/ActivityPanelDiffView.dom.test.tsx
+++ b/packages/app/src/components/ActivityPanelDiffView.dom.test.tsx
@@ -84,7 +84,10 @@ describe('ActivityPanelDiffView — shadow root contract', () => {
cacheKey="doc@v1"
/>,
);
- await pierreShadow(container);
+ const shadow = await pierreShadow(container);
+ expect(shadow.textContent).toContain('!!!');
+ expect(shadow.textContent).toContain('@@@');
+ expect(shadow.textContent).toContain('different content');
});
test('renders with overflow:wrap — data-overflow attribute present in shadow root', async () => {
diff --git a/packages/app/src/editor/extensions/code-block-languages.test.ts b/packages/app/src/editor/extensions/code-block-languages.test.ts
index 62a26538d..de8f762c2 100644
--- a/packages/app/src/editor/extensions/code-block-languages.test.ts
+++ b/packages/app/src/editor/extensions/code-block-languages.test.ts
@@ -68,29 +68,33 @@ describe('CODE_BLOCK_LANGUAGES table invariants', () => {
test('no alias collides with another entry`s canonical value', () => {
const canonicals = new Set(CODE_BLOCK_LANGUAGES.map((l) => l.value));
+ const collisions: string[] = [];
for (const lang of CODE_BLOCK_LANGUAGES) {
for (const alias of lang.aliases ?? []) {
if (alias === lang.value) continue;
if (canonicals.has(alias)) {
- throw new Error(
+ collisions.push(
`Alias collision: "${alias}" listed as alias of "${lang.value}" but is canonical for another entry`,
);
}
}
}
+ expect(collisions, collisions.join('\n')).toEqual([]);
});
test('no duplicate aliases across entries', () => {
const seen = new Map<string, string>();
+ const duplicates: string[] = [];
for (const lang of CODE_BLOCK_LANGUAGES) {
for (const alias of lang.aliases ?? []) {
const prior = seen.get(alias);
if (prior && prior !== lang.value) {
- throw new Error(`Alias "${alias}" listed under both "${prior}" and "${lang.value}"`);
+ duplicates.push(`Alias "${alias}" listed under both "${prior}" and "${lang.value}"`);
}
seen.set(alias, lang.value);
}
}
+ expect(duplicates, duplicates.join('\n')).toEqual([]);
});
test('first entry is plaintext (the canonical "no highlighting" option)', () => {
diff --git a/packages/app/src/editor/source-polish/view-plugin.test.ts b/packages/app/src/editor/source-polish/view-plugin.test.ts
index 887316091..feda62329 100644
--- a/packages/app/src/editor/source-polish/view-plugin.test.ts
+++ b/packages/app/src/editor/source-polish/view-plugin.test.ts
@@ -85,9 +85,7 @@ describe('source-polish view-plugin — buildDecorationsForRanges', () => {
const doc = '~~ padded ~~';
const decos = collect(doc);
const delRanges = markRangesWithClass(decos, 'cm-del');
- if (delRanges.length > 0) {
- expect(doc.slice(delRanges[0].from, delRanges[0].to)).toBe(' padded ');
- }
+ expect(delRanges).toEqual([]);
});
});
diff --git a/packages/app/src/lib/perf/hdr-histogram.test.ts b/packages/app/src/lib/perf/hdr-histogram.test.ts
index ff30386f6..0acfdd870 100644
--- a/packages/app/src/lib/perf/hdr-histogram.test.ts
+++ b/packages/app/src/lib/perf/hdr-histogram.test.ts
@@ -111,11 +111,10 @@ describe('Histogram', () => {
const got = snap[r];
const allowed = Math.max(1, oracle * tolerance);
const error = Math.abs(got - oracle);
- if (error > allowed) {
- throw new Error(
- `${distroName} n=${n} ${r}: got=${got}, oracle=${oracle}, error=${error}, allowed=${allowed.toFixed(2)}`,
- );
- }
+ expect(
+ error,
+ `${distroName} n=${n} ${r}: got=${got}, oracle=${oracle}, error=${error}, allowed=${allowed.toFixed(2)}`,
+ ).toBeLessThanOrEqual(allowed);
}
}
}
diff --git a/packages/app/src/lib/perf/scheduler-polyfill-shim.test.ts b/packages/app/src/lib/perf/scheduler-polyfill-shim.test.ts
index e73a5a91f..2289f23f0 100644
--- a/packages/app/src/lib/perf/scheduler-polyfill-shim.test.ts
+++ b/packages/app/src/lib/perf/scheduler-polyfill-shim.test.ts
@@ -28,6 +28,6 @@ describe('scheduler-polyfill-shim install side-effect', () => {
});
test('scheduler.yield() resolves under the test runner event loop', async () => {
- await scheduler.yield();
+ await expect(scheduler.yield()).resolves.toBeUndefined();
});
});
diff --git a/packages/app/src/lib/tab-session-restore-recovery-notice.dom.test.tsx b/packages/app/src/lib/tab-session-restore-recovery-notice.dom.test.tsx
index d4cbde59f..9e5bfb2b9 100644
--- a/packages/app/src/lib/tab-session-restore-recovery-notice.dom.test.tsx
+++ b/packages/app/src/lib/tab-session-restore-recovery-notice.dom.test.tsx
@@ -16,7 +16,7 @@ describe('showTabSessionRestoreRecoveryNotice', () => {
showTabSessionRestoreRecoveryNotice();
- await screen.findByText(NOTICE_TEXT);
+ expect((await screen.findByText(NOTICE_TEXT)).textContent).toMatch(NOTICE_TEXT);
});
test('does not veil the app it just recovered', async () => {
diff --git a/packages/app/tests/conversion/conversion-fidelity.test.ts b/packages/app/tests/conversion/conversion-fidelity.test.ts
index 9a9f8b305..50d96330b 100644
--- a/packages/app/tests/conversion/conversion-fidelity.test.ts
+++ b/packages/app/tests/conversion/conversion-fidelity.test.ts
@@ -156,7 +156,7 @@ const CONSTRUCTS: Array<{ name: string; input: string; stable?: boolean; note?:
describe('markdown round-trip: serialize(parse(md))', () => {
for (const { name, input, stable } of CONSTRUCTS) {
- test.concurrent(name, () => {
+ test.concurrent(name, ({ expect }) => {
const output = stripTrailingWhitespace(mdRoundTrip(input));
const normalized = stripTrailingWhitespace(input);
@@ -164,6 +164,9 @@ describe('markdown round-trip: serialize(parse(md))', () => {
expect(output).toBe(normalized);
} else {
const tokens = normalized.match(/[\w&<>]+/g) ?? [];
+ if (tokens.length === 0) {
+ expect(mdManager.parse(output)).toEqual(mdManager.parse(input));
+ }
for (const token of tokens) {
expect(output).toContain(token);
}
@@ -174,11 +177,14 @@ describe('markdown round-trip: serialize(parse(md))', () => {
describe('tree round-trip: pmJSON → updateYFragment → yXmlFragmentToProsemirrorJSON → serialize', () => {
for (const { name, input } of CONSTRUCTS) {
- test.concurrent(name, () => {
+ test.concurrent(name, ({ expect }) => {
const output = stripTrailingWhitespace(treeRoundTrip(input));
const normalized = stripTrailingWhitespace(input);
const tokens = normalized.match(/[\w&<>]+/g) ?? [];
+ if (tokens.length === 0) {
+ expect(mdManager.parse(output)).toEqual(mdManager.parse(input));
+ }
for (const token of tokens) {
expect(output).toContain(token);
}
@@ -284,7 +290,7 @@ const MARKED_INLINE_LEAF: Array<{ name: string; input: string; expected: string
describe('marked inline leaf nodes: byte-exact through chains 1 and 2', () => {
for (const { name, input, expected } of MARKED_INLINE_LEAF) {
- test.concurrent(name, () => {
+ test.concurrent(name, ({ expect }) => {
expect(mdRoundTrip(input)).toBe(expected);
expect(treeRoundTrip(input)).toBe(expected);
});
@@ -347,6 +353,10 @@ describe('disk round-trip: XmlFragment → persistence → disk → onLoadDocume
() => tokens.every((t) => readTestDoc(server.contentDir).includes(t)),
5000,
);
+ } else {
+ await expect
+ .poll(() => mdManager.parse(readTestDoc(server.contentDir)), { timeout: 5000 })
+ .toEqual(json);
}
const diskContent = readTestDoc(server.contentDir);
@@ -366,6 +376,10 @@ describe('disk round-trip: XmlFragment → persistence → disk → onLoadDocume
const tokens = stripTrailingWhitespace(input).match(/[\w&<>]+/g) ?? [];
if (tokens.length > 0) {
await pollUntil(() => tokens.every((t) => client2.ytext.toString().includes(t)), 5000);
+ } else {
+ await expect
+ .poll(() => mdManager.parse(client2.ytext.toString()), { timeout: 5000 })
+ .toEqual(mdManager.parse(input));
}
for (const token of tokens) {
diff --git a/packages/app/tests/integration/backlinks.test.ts b/packages/app/tests/integration/backlinks.test.ts
index 1506beaa3..070dcd2ed 100644
--- a/packages/app/tests/integration/backlinks.test.ts
+++ b/packages/app/tests/integration/backlinks.test.ts
@@ -1,6 +1,6 @@
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { test } from 'vitest';
+import { expect, test } from 'vitest';
import {
awaitBacklinkIndexed,
createTestClient,
@@ -34,18 +34,20 @@ 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://127.0.0.1:${server.port}/api/backlinks?docName=beta`);
- const data = (await res.json()) as {
- backlinks?: Array<{ source: string; snippet: string | null }>;
- };
- return (
- Array.isArray(data.backlinks) &&
- data.backlinks.some(
- (entry) => entry.source === 'alpha' && entry.snippet === 'Links to beta.',
- )
- );
- });
+ await expect(
+ pollUntil(async () => {
+ 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 }>;
+ };
+ return (
+ Array.isArray(data.backlinks) &&
+ data.backlinks.some(
+ (entry) => entry.source === 'alpha' && entry.snippet === 'Links to beta.',
+ )
+ );
+ }),
+ ).resolves.toBeUndefined();
} finally {
await server.cleanup();
}
@@ -59,29 +61,30 @@ test('backlink endpoints update from live client edits before persistence deboun
try {
client.ytext.insert(0, '# Alpha\n\nLinks to [[beta]].\n');
- await pollUntil(
- async () => {
- 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 }>;
- };
- return (
- Array.isArray(data.backlinks) &&
- data.backlinks.some(
- (entry) => entry.source === 'alpha' && entry.snippet === 'Links to beta.',
- )
- );
- },
- 900,
- 50,
- );
+ await expect(
+ pollUntil(
+ async () => {
+ 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 }>;
+ };
+ return (
+ Array.isArray(data.backlinks) &&
+ data.backlinks.some(
+ (entry) => entry.source === 'alpha' && entry.snippet === 'Links to beta.',
+ )
+ );
+ },
+ 900,
+ 50,
+ ),
+ ).resolves.toBeUndefined();
const elapsedMs = Date.now() - startedAt;
- if (elapsedMs >= 1500) {
- throw new Error(
- `backlinks only updated after ${elapsedMs}ms, expected before store debounce`,
- );
- }
+ expect(
+ elapsedMs,
+ `backlinks only updated after ${elapsedMs}ms, expected before store debounce`,
+ ).toBeLessThan(1500);
} finally {
await client.cleanup();
await server.cleanup();
@@ -102,7 +105,7 @@ test(
'utf-8',
);
- await awaitBacklinkIndexed(server, 'beta', 'gamma');
+ await expect(awaitBacklinkIndexed(server, 'beta', 'gamma')).resolves.toBeUndefined();
} finally {
await server.cleanup();
}
diff --git a/packages/app/tests/integration/bridge-convergence-regression.test.ts b/packages/app/tests/integration/bridge-convergence-regression.test.ts
index 728eaa9e0..2cd482d21 100644
--- a/packages/app/tests/integration/bridge-convergence-regression.test.ts
+++ b/packages/app/tests/integration/bridge-convergence-regression.test.ts
@@ -101,7 +101,7 @@ describe('Bridge convergence regression', () => {
await wait(2000);
- assertBridgeInvariant(client.ytext, client.fragment);
+ expect(() => assertBridgeInvariant(client.ytext, client.fragment)).not.toThrow();
} finally {
await client.cleanup();
}
diff --git a/packages/app/tests/integration/bridge-matrix.test.ts b/packages/app/tests/integration/bridge-matrix.test.ts
index 298222006..b5b0c37b8 100644
--- a/packages/app/tests/integration/bridge-matrix.test.ts
+++ b/packages/app/tests/integration/bridge-matrix.test.ts
@@ -96,7 +96,9 @@ describe('smoke', () => {
});
describe('wysiwyg-keyboard-typing: WYSIWYG writes', () => {
- test.concurrent('wysiwyg-keyboard-typing→Y.Text: local XmlFragment edit propagates to Y.Text via Observer A', async () => {
+ test.concurrent('wysiwyg-keyboard-typing→Y.Text: local XmlFragment edit propagates to Y.Text via Observer A', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
applyMarkdownToFragment(client, '# WYSIWYG Heading\n\nSome paragraph content.');
@@ -109,7 +111,9 @@ describe('wysiwyg-keyboard-typing: WYSIWYG writes', () => {
}
});
- test.concurrent('wysiwyg-keyboard-typing→Disk: local XmlFragment edit persists to .md file', async () => {
+ test.concurrent('wysiwyg-keyboard-typing→Disk: local XmlFragment edit persists to .md file', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
applyMarkdownToFragment(client, '# Disk Test\n\nThis should persist.');
@@ -128,7 +132,9 @@ describe('wysiwyg-keyboard-typing: WYSIWYG writes', () => {
});
describe('source-codemirror-typing: source mode writes', () => {
- test.concurrent('source-codemirror-typing→XmlFragment: local Y.Text edit propagates to XmlFragment via Observer B', async () => {
+ test.concurrent('source-codemirror-typing→XmlFragment: local Y.Text edit propagates to XmlFragment via Observer B', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
client.doc.transact(() => {
@@ -144,7 +150,9 @@ describe('source-codemirror-typing: source mode writes', () => {
}
});
- test.concurrent('source-codemirror-typing→Disk: local Y.Text edit persists to .md file', async () => {
+ test.concurrent('source-codemirror-typing→Disk: local Y.Text edit persists to .md file', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
client.doc.transact(() => {
@@ -164,7 +172,9 @@ describe('source-codemirror-typing: source mode writes', () => {
});
describe('agent-api-write: agent writes', () => {
- test.concurrent('agent-api-write→Y.Text: agent-write-md propagates to client Y.Text', async () => {
+ test.concurrent('agent-api-write→Y.Text: agent-write-md propagates to client Y.Text', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
await agentWriteMd(server.port, '# Agent Heading\n\nAgent wrote this.', {
@@ -179,7 +189,9 @@ describe('agent-api-write: agent writes', () => {
}
});
- test.concurrent('agent-api-write→XmlFragment: agent-write-md propagates to client XmlFragment', async () => {
+ test.concurrent('agent-api-write→XmlFragment: agent-write-md propagates to client XmlFragment', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
await agentWriteMd(server.port, '# Agent Fragment\n\nVisible in WYSIWYG.', {
@@ -195,7 +207,9 @@ describe('agent-api-write: agent writes', () => {
}
});
- test.concurrent('agent-api-write→Disk: agent-write-md persists to .md file', async () => {
+ test.concurrent('agent-api-write→Disk: agent-write-md persists to .md file', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
await agentWriteMd(server.port, '# Agent Disk\n\nPersisted by agent.', {
@@ -214,7 +228,9 @@ describe('agent-api-write: agent writes', () => {
}
});
- test.concurrent('agent-api-write-patch→Y.Text: agent-patch replaces target span in Y.Text', async () => {
+ test.concurrent('agent-api-write-patch→Y.Text: agent-patch replaces target span in Y.Text', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
await agentWriteMd(server.port, '# Header\n\nOriginal body text.', {
@@ -238,7 +254,9 @@ describe('agent-api-write: agent writes', () => {
}
});
- test.concurrent('agent-api-write-patch→XmlFragment: agent-patch propagates to XmlFragment', async () => {
+ test.concurrent('agent-api-write-patch→XmlFragment: agent-patch propagates to XmlFragment', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
await agentWriteMd(server.port, '# Title\n\nFoo bar baz qux.', { docName: client.docName });
@@ -256,7 +274,9 @@ describe('agent-api-write: agent writes', () => {
}
});
- test.concurrent('agent-api-write-patch: agent-patch with unknown find text returns 404 without mutating', async () => {
+ test.concurrent('agent-api-write-patch: agent-patch with unknown find text returns 404 without mutating', async ({
+ expect,
+ }) => {
const client = await createTestClient(server.port);
try {
await agentWriteMd(server.port, '# Seed\n\nUntouched content.', {
diff --git a/packages/app/tests/integration/bridge-watchdog-multi-peer-drain.test.ts b/packages/app/tests/integration/bridge-watchdog-multi-peer-drain.test.ts
index 516c88021..73f267995 100644
--- a/packages/app/tests/integration/bridge-watchdog-multi-peer-drain.test.ts
+++ b/packages/app/tests/integration/bridge-watchdog-multi-peer-drain.test.ts
@@ -116,7 +116,9 @@ describe('FR-31 bridge watchdog — multi-peer drain', () => {
});
try {
await pollUntil(() => watcher.ytext.toString().includes('WD-RECOVER-WYSIWYG'), 5000);
- await assertAllConverged([driver, watcher], { timeout: 5000 });
+ await expect(
+ assertAllConverged([driver, watcher], { timeout: 5000 }),
+ ).resolves.toBeUndefined();
} finally {
await watcher.cleanup();
}
diff --git a/packages/app/tests/integration/bug-a-mechanism-isolation.test.ts b/packages/app/tests/integration/bug-a-mechanism-isolation.test.ts
index be9105f51..d08a20fad 100644
--- a/packages/app/tests/integration/bug-a-mechanism-isolation.test.ts
+++ b/packages/app/tests/integration/bug-a-mechanism-isolation.test.ts
@@ -173,10 +173,10 @@ describe('Bug-A mechanism isolation: server stomp via syncTextToFragment', () =>
console.log(`\nFinal data loss (user content missing at T3): ${anyFinalLoss}`);
console.log('=============================================\n');
- expect(true).toBe(true);
+ expect(anyFinalLoss).toBe(false);
});
test('teardown', async () => {
- await server.cleanup();
+ await expect(server.cleanup()).resolves.toBeUndefined();
});
});
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index 8a60e5826..a28cc2b18 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts b/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts
index f78217246..731638739 100644
--- a/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts
+++ b/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts
@@ -47,6 +47,10 @@ async function assertConverged(clients: TestClient[], markers: string[]): Promis
await wait(500);
for (const c of clients) {
+ for (const marker of markers) {
+ expect(c.ytext.toString()).toContain(marker);
+ expect(serializeFragment(c.fragment)).toContain(marker);
+ }
assertBridgeInvariant(c.ytext, c.fragment);
}
diff --git a/packages/app/tests/integration/c5-agent-plus-source.test.ts b/packages/app/tests/integration/c5-agent-plus-source.test.ts
index 7b29fb916..7e1c695b5 100644
--- a/packages/app/tests/integration/c5-agent-plus-source.test.ts
+++ b/packages/app/tests/integration/c5-agent-plus-source.test.ts
@@ -38,6 +38,10 @@ async function assertConverged(clients: TestClient[], markers: string[]): Promis
await wait(500);
for (const c of clients) {
+ for (const marker of markers) {
+ expect(c.ytext.toString()).toContain(marker);
+ expect(serializeFragment(c.fragment)).toContain(marker);
+ }
assertBridgeInvariant(c.ytext, c.fragment);
}
diff --git a/packages/app/tests/integration/c6-mode-switch-mid-debounce.test.ts b/packages/app/tests/integration/c6-mode-switch-mid-debounce.test.ts
index 703991635..2afe225df 100644
--- a/packages/app/tests/integration/c6-mode-switch-mid-debounce.test.ts
+++ b/packages/app/tests/integration/c6-mode-switch-mid-debounce.test.ts
@@ -47,6 +47,10 @@ async function assertConverged(clients: TestClient[], markers: string[]): Promis
await wait(500);
for (const c of clients) {
+ for (const marker of markers) {
+ expect(c.ytext.toString()).toContain(marker);
+ expect(serializeFragment(c.fragment)).toContain(marker);
+ }
assertBridgeInvariant(c.ytext, c.fragment);
}
diff --git a/packages/app/tests/integration/c7-disconnect-reconnect-burst.test.ts b/packages/app/tests/integration/c7-disconnect-reconnect-burst.test.ts
index 7081f9b48..897e0d560 100644
--- a/packages/app/tests/integration/c7-disconnect-reconnect-burst.test.ts
+++ b/packages/app/tests/integration/c7-disconnect-reconnect-burst.test.ts
@@ -47,6 +47,10 @@ async function assertConverged(clients: TestClient[], markers: string[]): Promis
await wait(500);
for (const c of clients) {
+ for (const marker of markers) {
+ expect(c.ytext.toString()).toContain(marker);
+ expect(serializeFragment(c.fragment)).toContain(marker);
+ }
assertBridgeInvariant(c.ytext, c.fragment);
}
diff --git a/packages/app/tests/integration/c9-join-mid-debounce.test.ts b/packages/app/tests/integration/c9-join-mid-debounce.test.ts
index 9378f17c6..ac999e027 100644
--- a/packages/app/tests/integration/c9-join-mid-debounce.test.ts
+++ b/packages/app/tests/integration/c9-join-mid-debounce.test.ts
@@ -46,6 +46,10 @@ async function assertConverged(clients: TestClient[], markers: string[]): Promis
await wait(500);
for (const c of clients) {
+ for (const marker of markers) {
+ expect(c.ytext.toString()).toContain(marker);
+ expect(serializeFragment(c.fragment)).toContain(marker);
+ }
assertBridgeInvariant(c.ytext, c.fragment);
}
diff --git a/packages/app/tests/integration/cc1-broadcast.test.ts b/packages/app/tests/integration/cc1-broadcast.test.ts
index d6a9f07c8..b08c86dcb 100644
--- a/packages/app/tests/integration/cc1-broadcast.test.ts
+++ b/packages/app/tests/integration/cc1-broadcast.test.ts
@@ -184,17 +184,22 @@ describe('CC1 broadcast — L1 integration', () => {
50,
'a files signal caused after the empty-file write',
);
-
- await pollUntil(
- async () => {
- const docsRes = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
- const docsBody: { documents?: Array<{ docName: string }> } = await docsRes.json();
- return docsBody.documents?.some((doc) => doc.docName === docName) === true;
- },
- 5000,
- 50,
- 'the empty file to appear in documents',
+ expect(signals.some((signal) => signal.ch === 'files' && signal.seq > filesBefore)).toBe(
+ true,
);
+
+ await expect(
+ pollUntil(
+ async () => {
+ const docsRes = await fetch(`http://127.0.0.1:${server.port}/api/documents`);
+ const docsBody: { documents?: Array<{ docName: string }> } = await docsRes.json();
+ return docsBody.documents?.some((doc) => doc.docName === docName) === true;
+ },
+ 5000,
+ 50,
+ 'the empty file to appear in documents',
+ ),
+ ).resolves.toBeUndefined();
} finally {
destroy();
}
diff --git a/packages/app/tests/integration/composition-sweep-index.test.ts b/packages/app/tests/integration/composition-sweep-index.test.ts
index e3c4a12d5..1f522d66d 100644
--- a/packages/app/tests/integration/composition-sweep-index.test.ts
+++ b/packages/app/tests/integration/composition-sweep-index.test.ts
@@ -175,7 +175,11 @@ function stripCommentLines(text: string): string {
}
function resolveCompositionTest(pkgRelPath: string, title: string): ResolvedCompositionTest {
- const src = stripCommentLines(readFileSync(resolve(PACKAGES, pkgRelPath), 'utf-8'));
+ return resolveCompositionTestSource(readFileSync(resolve(PACKAGES, pkgRelPath), 'utf-8'), title);
+}
+
+function resolveCompositionTestSource(source: string, title: string): ResolvedCompositionTest {
+ const src = stripCommentLines(source);
const decl = /(?<![.\w])(?:test|it)((?:\.\w+)*)\s*\(\s*(['"`])([\s\S]*?)\2/g;
const declarations: Array<{ modifiers: string; title: string; end: number }> = [];
for (const m of src.matchAll(decl)) {
@@ -260,15 +264,17 @@ describe('composition sweep index (H13)', () => {
declared: true,
disabled: true,
});
- expect(
- resolveCompositionTest(self, 'planted assertion-free composition fixture'),
- ).toMatchObject({ declared: true, disabled: false, assertions: 0 });
});
test.skip('planted disabled composition fixture', () => {
expect(true).toBe(true);
});
test('planted assertion-free composition fixture', () => {
- return;
+ const source = 'test("assertion-free", () => {});';
+ expect(resolveCompositionTestSource(source, 'assertion-free')).toEqual({
+ declared: true,
+ disabled: false,
+ assertions: 0,
+ });
});
});
diff --git a/packages/app/tests/integration/e2e-stop-rules.test.ts b/packages/app/tests/integration/e2e-stop-rules.test.ts
index a47103747..956de79ff 100644
--- a/packages/app/tests/integration/e2e-stop-rules.test.ts
+++ b/packages/app/tests/integration/e2e-stop-rules.test.ts
@@ -525,71 +525,64 @@ describe('E2E STOP rule — zero allowlist', () => {
test('no page.waitForTimeout( in tests/{stress,visual,a11y}/*.e2e.ts (AC-3)', () => {
const violations = collectMatches(e2eFiles, (line) => line.includes('page.waitForTimeout('));
- if (violations.length > 0) {
- throw new Error(
- `page.waitForTimeout( pattern found — replace with condition-based wait per D-Q1:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `page.waitForTimeout( pattern found — replace with condition-based wait per D-Q1:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test("no waitUntil: 'networkidle' in tests/{stress,visual,a11y}/*.e2e.ts (AC-4)", () => {
const violations = collectMatches(e2eFiles, (line) =>
/waitUntil:\s*['"]networkidle['"]/.test(line),
);
- if (violations.length > 0) {
- throw new Error(
- `waitUntil: 'networkidle' pattern found — use 'domcontentloaded' + waitForActiveProviderSynced instead:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `waitUntil: 'networkidle' pattern found — use 'domcontentloaded' + waitForActiveProviderSynced instead:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no new Promise + setTimeout busy-wait in tests/{stress,visual,a11y}/*.e2e.ts (D-Q14)', () => {
const pattern = /new Promise\(\s*(\w+)\s*=>\s*setTimeout\(\s*\1\s*,/;
const violations = collectMatches(e2eFiles, (line) => pattern.test(line));
- if (violations.length > 0) {
- throw new Error(
- `\`new Promise(r => setTimeout(r, N))\` busy-wait found — use a condition-based wait:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `\`new Promise(r => setTimeout(r, N))\` busy-wait found — use a condition-based wait:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no page.pause( in tests/{stress,visual,a11y}/*.e2e.ts (D-Q14)', () => {
const violations = collectMatches(e2eFiles, (line) => line.includes('page.pause('));
- if (violations.length > 0) {
- throw new Error(
- `page.pause( found — debugger pauses must not land in committed E2E tests:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `page.pause( found — debugger pauses must not land in committed E2E tests:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test("no test.skip(browserName === 'webkit') in tests/{stress,visual,a11y}/*.e2e.ts (AC-5 ratchet)", () => {
const pattern = /test\.skip\(\s*browserName\s*===\s*['"]webkit['"]/;
const violations = collectMatches(e2eFiles, (line) => pattern.test(line));
- if (violations.length > 0) {
- throw new Error(
- `webkit-skip pattern reintroduced — chromium-only CI ratchet (D-Q10):\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `webkit-skip pattern reintroduced — chromium-only CI ratchet (D-Q10):\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test("no keyboard.press('Meta+X') — use ControlOrMeta+X for cross-platform CI (D-Q10)", () => {
const pattern = /keyboard\.press\(\s*['"`]Meta\+[A-Za-z][A-Za-z]*['"`]/;
const violations = collectMatches(e2eFiles, (line) => pattern.test(line));
- if (violations.length > 0) {
- throw new Error(
- `keyboard.press('Meta+X') — replace with 'ControlOrMeta+X' so CI (Linux chromium) maps to Ctrl+X:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `keyboard.press('Meta+X') — replace with 'ControlOrMeta+X' so CI (Linux chromium) maps to Ctrl+X:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no inner-file helper imports — must use barrel ./_helpers (D-Q11)', () => {
const innerImport = /from\s+['"]\.\.?(?:\/[^'"]*)?\/_helpers\/[a-zA-Z][\w-]*['"]/;
const violations = collectMatches(e2eFiles, (line) => innerImport.test(line));
- if (violations.length > 0) {
- throw new Error(
- `Inner-file helper import found — import from the barrel ('./_helpers') only:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Inner-file helper import found — import from the barrel ('./_helpers') only:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no ungated window.__ writes outside dev-gate allowlist (US-006/US-026)', () => {
@@ -610,22 +603,20 @@ describe('E2E STOP rule — zero allowlist', () => {
violations.push(` ${file.path}:${i + 1} ${line.trim()}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `Ungated window.__ write outside the dev-gate allowlist — wrap in if (import.meta.env.DEV) and add to dev-gate-allowlist.ts:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Ungated window.__ write outside the dev-gate allowlist — wrap in if (import.meta.env.DEV) and add to dev-gate-allowlist.ts:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no static value import of the DEV ACP thread harness', () => {
const violations = collectMatches(listAppSrcTsFiles(), (line) =>
isStaticDevHarnessImport(line),
);
- if (violations.length > 0) {
- throw new Error(
- `Static import of dev-thread-harness in app source — it must be reached only through the DEV-gated dynamic import:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Static import of dev-thread-harness in app source — it must be reached only through the DEV-gated dynamic import:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no editor.mount( / editor.unmount( in V2 cache surfaces (precedent §25(a), SPEC US-001 Phase 1.0)', () => {
@@ -657,11 +648,10 @@ describe('E2E STOP rule — zero allowlist', () => {
violations.push(` ${relative(REPO_ROOT, abs)}:${i + 1} ${trimmed}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `editor.mount()/unmount() call found in a V2-cache surface — use raw editor.editorView.dom reparent instead per precedent §25(a):\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `editor.mount()/unmount() call found in a V2-cache surface — use raw editor.editorView.dom reparent instead per precedent §25(a):\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no waitForFunction(fn, { timeout/polling }) — options must be 3rd arg (precedent §20(j))', () => {
@@ -702,11 +692,10 @@ describe('E2E STOP rule — zero allowlist', () => {
violations.push(` ${file.path}:${i + 1} ${line.trim()}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `waitForFunction(fn, { timeout/polling }) pattern — options as 2nd arg is bound to \`arg\` and silently ignored. Pass \`null\` as 2nd arg: \`waitForFunction(fn, null, { timeout: N })\`. See AGENTS.md §20(j):\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `waitForFunction(fn, { timeout/polling }) pattern — options as 2nd arg is bound to \`arg\` and silently ignored. Pass \`null\` as 2nd arg: \`waitForFunction(fn, null, { timeout: N })\`. See AGENTS.md §20(j):\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('e2e files that spawn a dev server must isolate shared mutable state (vite cache + i18n compile)', () => {
@@ -718,11 +707,10 @@ describe('E2E STOP rule — zero allowlist', () => {
);
}
}
- if (violations.length > 0) {
- throw new Error(
- `dev-server spawn without shared-state isolation — pass OK_TEST_VITE_CACHE_DIR (via prepareViteCacheDir from ./_helpers, removeAllDuringTeardown in teardown) and OK_TEST_SKIP_I18N_COMPILE: '1' in the spawn env. A line reported as unconfirmed rather than missing is one this guard could not settle: either it cannot read the spawn's env at all, so inline the env object at the call, or the key is absent from the env object's own properties while a spread may carry it, so declare the key at the call instead of leaving it to the spread, or the key is declared but a spread that follows it may replace it, so move the declaration after the last spread:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `dev-server spawn without shared-state isolation — pass OK_TEST_VITE_CACHE_DIR (via prepareViteCacheDir from ./_helpers, removeAllDuringTeardown in teardown) and OK_TEST_SKIP_I18N_COMPILE: '1' in the spawn env. A line reported as unconfirmed rather than missing is one this guard could not settle: either it cannot read the spawn's env at all, so inline the env object at the call, or the key is absent from the env object's own properties while a spread may carry it, so declare the key at the call instead of leaving it to the spread, or the key is declared but a spread that follows it may replace it, so move the declaration after the last spread:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('the spawn-isolation rule resolves a dev-server spawn in exactly the pinned sites', () => {
@@ -1192,11 +1180,10 @@ describe('E2E STOP rule — zero allowlist', () => {
violations.push(` ${file.path}:${i + 1} ${line.trim()}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `window.__activeEditor must be published only by DocumentContext.tsx — additional writers collide with the getter-only accessor and throw TypeError on doc open in DEV. Delete the direct write and read through window.__activeEditor (the getter already resolves via the active-editor.ts registry, which TiptapEditor already populates via registerEditor/unregisterEditor):\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `window.__activeEditor must be published only by DocumentContext.tsx — additional writers collide with the getter-only accessor and throw TypeError on doc open in DEV. Delete the direct write and read through window.__activeEditor (the getter already resolves via the active-editor.ts registry, which TiptapEditor already populates via registerEditor/unregisterEditor):\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('selection-halo CSS rules use plugin-state propagation, not `:has()` (Precedent #34)', () => {
@@ -1222,11 +1209,10 @@ describe('E2E STOP rule — zero allowlist', () => {
}
}
- if (violations.length > 0) {
- throw new Error(
- `Selection-halo CSS rules must not use \`:has()\` — precedent #34 requires innermost-wins via plugin-state propagation (\`data-has-child-selected\`). Move the cascade logic into SelectionStatePlugin's apply function and let JsxComponentView emit the attribute:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Selection-halo CSS rules must not use \`:has()\` — precedent #34 requires innermost-wins via plugin-state propagation (\`data-has-child-selected\`). Move the cascade logic into SelectionStatePlugin's apply function and let JsxComponentView emit the attribute:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('selection-halo transition uses `var(--ease-out-strong)`, not bare `ease-out` (round-2 review fix)', () => {
@@ -1259,20 +1245,18 @@ describe('E2E STOP rule — zero allowlist', () => {
}
}
- if (violations.length > 0) {
- throw new Error(
- `Selection-halo transition uses bare \`ease-out\` — use \`var(--ease-out-strong)\` for consistency with the repo's 7 other transitions (round-2 review fix, commit 4e9d96a5):\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Selection-halo transition uses bare \`ease-out\` — use \`var(--ease-out-strong)\` for consistency with the repo's 7 other transitions (round-2 review fix, commit 4e9d96a5):\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no remote placeholder-image hosts in tests/{stress,visual,a11y} (PRD-8532)', () => {
const violations = collectMatches(e2eTsFiles, isRemoteImageHost);
- if (violations.length > 0) {
- throw new Error(
- `Remote placeholder-image host found — write a local fixture under tests/stress/_fixtures and wait with waitForImageDecoded (from the ./_helpers barrel) instead:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Remote placeholder-image host found — write a local fixture under tests/stress/_fixtures and wait with waitForImageDecoded (from the ./_helpers barrel) instead:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('remote-image-host rule fires on planted hosts and not on adjacent negatives', () => {
@@ -1311,8 +1295,6 @@ describe('E2E STOP rule — zero allowlist', () => {
'src/locales/<locale>/messages.json and Vite full-page-reloads running tests mid-evaluate.',
);
}
- if (errors.length > 0) {
- throw new Error(`${errors.join('\n')}\nFound predev:\n ${predev}`);
- }
+ expect(errors, `${errors.join('\n')}\nFound predev:\n ${predev}`).toEqual([]);
});
});
diff --git a/packages/app/tests/integration/empty-folder-visibility.test.ts b/packages/app/tests/integration/empty-folder-visibility.test.ts
index 90e4f1277..6b754e99b 100644
--- a/packages/app/tests/integration/empty-folder-visibility.test.ts
+++ b/packages/app/tests/integration/empty-folder-visibility.test.ts
@@ -22,16 +22,17 @@ async function awaitFolderPathsIndexed(
const body = DocumentListSuccessSchema.parse(await res.json());
lastFolderPaths = body.documents.filter((e) => e.kind === 'folder').map((e) => e.path ?? '');
if (expectedFolderPaths.every((path) => lastFolderPaths.includes(path))) {
- return;
+ break;
}
}
await wait(50);
}
- throw new Error(
+ expect(
+ lastFolderPaths,
`folder paths not indexed within ${timeoutMs}ms: expected=${expectedFolderPaths.join(
',',
)}; last=${lastFolderPaths.join(',')}`,
- );
+ ).toEqual(expect.arrayContaining(expectedFolderPaths));
}
describe('/api/documents empty folder — boot-time', () => {
diff --git a/packages/app/tests/integration/hook-timeout-stop-rules.test.ts b/packages/app/tests/integration/hook-timeout-stop-rules.test.ts
index 3c41cdd2c..895eb4d5c 100644
--- a/packages/app/tests/integration/hook-timeout-stop-rules.test.ts
+++ b/packages/app/tests/integration/hook-timeout-stop-rules.test.ts
@@ -77,17 +77,16 @@ describe('hook-timeout STOP rule — beforeAll must carry an explicit timeout',
}
}
}
- if (violations.length > 0) {
- throw new Error(
- `${violations.length} beforeAll site(s) without an explicit timeout argument. ` +
- `Hooks without one ride the invocation's budget — direct ` +
- `flag-less runs and the test:conversion script can kill slow boots ` +
- `and surface a misleading 'server.cleanup' TypeError from afterAll. ` +
- `Add a second argument, preferably the shared constant: ` +
- `\`beforeAll(async () => { ... }, HARNESS_BOOT_TIMEOUT_MS);\` ` +
- `(a numeric literal like \`}, 30_000);\` is also accepted):\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `${violations.length} beforeAll site(s) without an explicit timeout argument. ` +
+ `Hooks without one ride the invocation's budget — direct ` +
+ `flag-less runs and the test:conversion script can kill slow boots ` +
+ `and surface a misleading 'server.cleanup' TypeError from afterAll. ` +
+ `Add a second argument, preferably the shared constant: ` +
+ `\`beforeAll(async () => { ... }, HARNESS_BOOT_TIMEOUT_MS);\` ` +
+ `(a numeric literal like \`}, 30_000);\` is also accepted):\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('real-corpus negative controls: already-protected sites are classified compliant', () => {
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 6fcdc23f2..4fc2c11f9 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 40b5cdfd6..9f2f6feb6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 93666af70..2a085742b 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/link-graph-metadata.test.ts b/packages/app/tests/integration/link-graph-metadata.test.ts
index b24f376d2..217a617d2 100644
--- a/packages/app/tests/integration/link-graph-metadata.test.ts
+++ b/packages/app/tests/integration/link-graph-metadata.test.ts
@@ -27,7 +27,7 @@ beforeAll(async () => {
writeFileSync(
join(contentDir, 'hub.md'),
- '---\ntitle: Hub Page\ncluster: retrieval\ncategory: concept\ntags: [search, vectors]\n---\n\n# Hub\n\nLinks to [[spoke-a]] and [[spoke-b]].\n',
+ '---\ntitle: Hub Page\ncluster: retrieval\ncategory: concept\ntags: [search, vectors]\n---\n\n# Hub\n\nLinks to [[spoke-a]] and [[spoke-b]], plus [Example](https://example.com/reference).\n',
'utf-8',
);
writeFileSync(
@@ -101,6 +101,7 @@ describe('/api/link-graph metadata enrichment', () => {
const data = await fetchLinkGraph();
const externals = data.nodes.filter((n) => n.kind === 'external');
+ expect(externals.map((node) => node.url)).toEqual(['https://example.com/reference']);
for (const ext of externals) {
expect(ext.cluster).toBeUndefined();
expect(ext.category).toBeUndefined();
diff --git a/packages/app/tests/integration/loopback-bind-discipline.test.ts b/packages/app/tests/integration/loopback-bind-discipline.test.ts
index 5a0e58313..ef4f61881 100644
--- a/packages/app/tests/integration/loopback-bind-discipline.test.ts
+++ b/packages/app/tests/integration/loopback-bind-discipline.test.ts
@@ -95,14 +95,13 @@ describe('loopback bind discipline (app test sources)', () => {
violations.push(` ${file.path}:${v.line} ${v.text}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `Hostless rig bind found — a bare listen(0) binds the IPv6 wildcard '::', whose loopback-specific ` +
- `port slots stay silently bindable by foreign processes; their listeners then intercept this rig's ` +
- `localhost dials (the rotating integration-suite flake). Bind a loopback-specific host ` +
- `(e.g. listen(0, '127.0.0.1', cb)) and dial the literal from server.address():\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Hostless rig bind found — a bare listen(0) binds the IPv6 wildcard '::', whose loopback-specific ` +
+ `port slots stay silently bindable by foreign processes; their listeners then intercept this rig's ` +
+ `localhost dials (the rotating integration-suite flake). Bind a loopback-specific host ` +
+ `(e.g. listen(0, '127.0.0.1', cb)) and dial the literal from server.address():\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no interpolated-port localhost dial URLs', () => {
@@ -112,14 +111,13 @@ describe('loopback bind discipline (app test sources)', () => {
violations.push(` ${file.path}:${v.line} ${v.text}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `Ambiguous-name rig dial found — 'localhost' resolves '::1'-first, exactly the loopback-specific slot ` +
- `a foreign process can hold while the rig sits on a wildcard (or single-family) bind. Dial the ` +
- `literal address the rig actually bound (a harness-advertised base URL, or ` +
- `http://127.0.0.1:\${port}):\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Ambiguous-name rig dial found — 'localhost' resolves '::1'-first, exactly the loopback-specific slot ` +
+ `a foreign process can hold while the rig sits on a wildcard (or single-family) bind. Dial the ` +
+ `literal address the rig actually bound (a harness-advertised base URL, or ` +
+ `http://127.0.0.1:\${port}):\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('listen predicate fires on planted violations and not on adjacent negatives', () => {
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 867598d34..878d5196b 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/provider-pool-transport-drop.test.ts b/packages/app/tests/integration/provider-pool-transport-drop.test.ts
index 06525fc18..6c9856769 100644
--- a/packages/app/tests/integration/provider-pool-transport-drop.test.ts
+++ b/packages/app/tests/integration/provider-pool-transport-drop.test.ts
@@ -89,7 +89,7 @@ describe('ProviderPool transport drop recovery', () => {
for (let i = 0; i < 30; i += 1) {
writeFileSync(join(server.contentDir, `churn-${i}.md`), `# churn ${i}\n`, 'utf-8');
}
- dropTransport(server, docName);
+ expect(dropTransport(server, docName)).toBeGreaterThan(0);
for (let i = 30; i < 60; i += 1) {
writeFileSync(join(server.contentDir, `churn-${i}.md`), `# churn ${i}\n`, 'utf-8');
}
@@ -108,6 +108,9 @@ describe('ProviderPool transport drop recovery', () => {
20_000,
100,
);
+ expect(pool.getActive()?.provider.document.getText('source').toString()).toContain(
+ 'CHURN-DROP MARKER',
+ );
}, 60_000);
test('two consecutive drops in quick succession still recover', async () => {
@@ -120,8 +123,10 @@ describe('ProviderPool transport drop recovery', () => {
await seedPoolServerInstanceId(server, pool);
await openSynced(server, pool, docName);
- dropTransport(server, docName);
- await pollUntil(() => dropTransport(server, docName) > 0, 10_000, 100);
+ expect(dropTransport(server, docName)).toBeGreaterThan(0);
+ await expect(
+ pollUntil(() => dropTransport(server, docName) > 0, 10_000, 100),
+ ).resolves.toBeUndefined();
await pollUntil(() => pool.getActive()?.provider.isSynced === true, 20_000, 100);
writeFileSync(
@@ -137,5 +142,8 @@ describe('ProviderPool transport drop recovery', () => {
15_000,
100,
);
+ expect(pool.getActive()?.provider.document.getText('source').toString()).toContain(
+ 'SECOND-DROP MARKER',
+ );
}, 60_000);
});
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 0970ac12f..4ada3cf26 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index b632185e1..cbe2b705f 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,3 +1,4 @@
+
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index c530ce4ba..89bc9b4d9 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/skills-in-place-list.test.ts b/packages/app/tests/integration/skills-in-place-list.test.ts
index 277a5d979..e515b20fc 100644
--- a/packages/app/tests/integration/skills-in-place-list.test.ts
+++ b/packages/app/tests/integration/skills-in-place-list.test.ts
@@ -124,12 +124,14 @@ describe('in-place skills in /api/skills + /api/skills/installed', () => {
chokidarServer = await createTestServer({ contentDir: gContent });
const cBase = `http://127.0.0.1:${chokidarServer.port}`;
writeSkill(gContent, '.codex/skills/first-ever', '# First');
- await pollUntil(async () => {
- const res = await fetch(`${cBase}/api/skills?scope=project`);
- if (!res.ok) return false;
- const body = (await res.json()) as { skills?: Array<{ name: string }> };
- return (body.skills ?? []).some((s) => s.name === 'first-ever');
- }, 20000);
+ await expect(
+ pollUntil(async () => {
+ const res = await fetch(`${cBase}/api/skills?scope=project`);
+ if (!res.ok) return false;
+ const body = (await res.json()) as { skills?: Array<{ name: string }> };
+ return (body.skills ?? []).some((s) => s.name === 'first-ever');
+ }, 20000),
+ ).resolves.toBeUndefined();
} finally {
delete process.env.OK_FILE_WATCHER_BACKEND;
await chokidarServer?.cleanup();
@@ -139,12 +141,14 @@ describe('in-place skills in /api/skills + /api/skills/installed', () => {
test('a skill created AFTER boot is admitted as content via the live re-scan', async () => {
writeSkill(contentDir, '.claude/skills/live-added', '# Born after boot');
- await pollUntil(async () => {
- const res = await fetch(`${base()}/api/documents`);
- if (!res.ok) return false;
- const body = (await res.json()) as { documents?: Array<{ docName: string }> };
- return (body.documents ?? []).some((d) => d.docName === '.claude/skills/live-added/SKILL');
- }, 15000);
+ await expect(
+ pollUntil(async () => {
+ const res = await fetch(`${base()}/api/documents`);
+ if (!res.ok) return false;
+ const body = (await res.json()) as { documents?: Array<{ docName: string }> };
+ return (body.documents ?? []).some((d) => d.docName === '.claude/skills/live-added/SKILL');
+ }, 15000),
+ ).resolves.toBeUndefined();
});
test('a PRE-EXISTING same-hash copy re-syncs when the canonical is edited (auto-pairing)', async () => {
@@ -153,6 +157,7 @@ describe('in-place skills in /api/skills + /api/skills/installed', () => {
const { readFileSync: rf, writeFileSync: wf } = await import('node:fs');
wf(canonicalMd, rf(canonicalMd, 'utf-8').replace('# Same', '# Same EDITED'));
await pollUntil(() => rf(copyMd, 'utf-8').includes('# Same EDITED'), 15000);
+ expect(rf(copyMd, 'utf-8')).toContain('# Same EDITED');
});
test('in-place canonicals do not double-list as detected installed skills', async () => {
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index d3767adc9..a78aeb0e4 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,3 +1,4 @@
+
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index b076f955c..e7cc69c3f 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 7935e35f8..9ddcd0730 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/meta/e2e-ci-membership.test.ts b/packages/app/tests/meta/e2e-ci-membership.test.ts
index b2338a5ac..ab669bb29 100644
--- a/packages/app/tests/meta/e2e-ci-membership.test.ts
+++ b/packages/app/tests/meta/e2e-ci-membership.test.ts
@@ -77,49 +77,45 @@ describe('test:e2e membership meta-guard', () => {
test('every tests/stress/*.e2e.ts is in the test:e2e enumeration or the exclusion ledger', () => {
const { onDisk, enumerated, ledgered } = loadRealSets();
const { unlisted } = computeMembershipViolations(onDisk, enumerated, ledgered);
- if (unlisted.length > 0) {
- throw new Error(
- `CI-invisible stress e2e file(s) — ${LEDGER_HINT}:\n${unlisted
- .map((f) => ` tests/stress/${f}`)
- .join('\n')}`,
- );
- }
+ expect(
+ unlisted,
+ `CI-invisible stress e2e file(s) — ${LEDGER_HINT}:\n${unlisted
+ .map((f) => ` tests/stress/${f}`)
+ .join('\n')}`,
+ ).toEqual([]);
});
test('no file is in BOTH the test:e2e enumeration and the exclusion ledger', () => {
const { onDisk, enumerated, ledgered } = loadRealSets();
const { dual } = computeMembershipViolations(onDisk, enumerated, ledgered);
- if (dual.length > 0) {
- throw new Error(
- `File(s) present in both the test:e2e enumeration and the ledger — a promoted file must have its ledger entry deleted:\n${dual
- .map((f) => ` tests/stress/${f}`)
- .join('\n')}`,
- );
- }
+ expect(
+ dual,
+ `File(s) present in both the test:e2e enumeration and the ledger — a promoted file must have its ledger entry deleted:\n${dual
+ .map((f) => ` tests/stress/${f}`)
+ .join('\n')}`,
+ ).toEqual([]);
});
test('every ledger entry points at a file that still exists', () => {
const { onDisk, enumerated, ledgered } = loadRealSets();
const { staleLedger } = computeMembershipViolations(onDisk, enumerated, ledgered);
- if (staleLedger.length > 0) {
- throw new Error(
- `Stale ledger entr(ies) — the file no longer exists; delete the entry from e2e-ci-ledger.ts:\n${staleLedger
- .map((f) => ` ${f}`)
- .join('\n')}`,
- );
- }
+ expect(
+ staleLedger,
+ `Stale ledger entr(ies) — the file no longer exists; delete the entry from e2e-ci-ledger.ts:\n${staleLedger
+ .map((f) => ` ${f}`)
+ .join('\n')}`,
+ ).toEqual([]);
});
test('every enumerated test:e2e file still exists', () => {
const { onDisk, enumerated, ledgered } = loadRealSets();
const { staleEnumeration } = computeMembershipViolations(onDisk, enumerated, ledgered);
- if (staleEnumeration.length > 0) {
- throw new Error(
- `Stale test:e2e entr(ies) — the file no longer exists on disk. Playwright file args are filters, so a stale entry silently matches nothing; remove it from the script:\n${staleEnumeration
- .map((f) => ` tests/stress/${f}`)
- .join('\n')}`,
- );
- }
+ expect(
+ staleEnumeration,
+ `Stale test:e2e entr(ies) — the file no longer exists on disk. Playwright file args are filters, so a stale entry silently matches nothing; remove it from the script:\n${staleEnumeration
+ .map((f) => ` tests/stress/${f}`)
+ .join('\n')}`,
+ ).toEqual([]);
});
test('ledger entries are unique and carry non-empty reason + evidence', () => {
@@ -131,9 +127,7 @@ describe('test:e2e membership meta-guard', () => {
if (entry.reason.trim() === '') problems.push(` empty reason: ${entry.file}`);
if (entry.evidence.trim() === '') problems.push(` empty evidence: ${entry.file}`);
}
- if (problems.length > 0) {
- throw new Error(`Ledger hygiene violation(s):\n${problems.join('\n')}`);
- }
+ expect(problems, `Ledger hygiene violation(s):\n${problems.join('\n')}`).toEqual([]);
});
test('membership predicate fires on planted violations and not on adjacent negatives', () => {
diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.ts
index 5995e1966..6748214f5 100644
--- a/packages/cli/src/commands/start.test.ts
+++ b/packages/cli/src/commands/start.test.ts
@@ -428,7 +428,7 @@ describe('bootStartServer (integration)', () => {
skipAutoInit: true,
});
await booted.destroy();
- await booted.destroy();
+ await expect(booted.destroy()).resolves.toBeUndefined();
booted = null;
});
diff --git a/packages/cli/src/integrations/registry-apply.test.ts b/packages/cli/src/integrations/registry-apply.test.ts
index 51df87698..6e9303a0f 100644
--- a/packages/cli/src/integrations/registry-apply.test.ts
+++ b/packages/cli/src/integrations/registry-apply.test.ts
@@ -234,8 +234,10 @@ describe('a user-global MCP artifact', () => {
it('reports no surface for an agent whose config is project-only', async () => {
const report = await run([{ satisfierId: 'pi/mcp/user/config-entry', desired: 'present' }]);
- const action = actionFor(report, 'pi/mcp/user/config-entry');
- if (action !== undefined) expect(action.action).not.toBe('failed');
+ expect(report.actions).toEqual([]);
+ expect(report.conflicts).toMatchObject([
+ { kind: 'unknown-satisfier', satisfierIds: ['pi/mcp/user/config-entry'] },
+ ]);
});
});
diff --git a/packages/cli/src/loopback-bind-discipline.test.ts b/packages/cli/src/loopback-bind-discipline.test.ts
index 5ca7e1014..693463d74 100644
--- a/packages/cli/src/loopback-bind-discipline.test.ts
+++ b/packages/cli/src/loopback-bind-discipline.test.ts
@@ -93,14 +93,13 @@ describe('loopback bind discipline (cli test sources)', () => {
violations.push(` ${file.path}:${v.line} ${v.text}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `Hostless rig bind found — a bare listen(0) binds the IPv6 wildcard '::', whose loopback-specific ` +
- `port slots stay silently bindable by foreign processes; their listeners then intercept this rig's ` +
- `localhost dials (the rotating integration-suite flake). Bind a loopback-specific host ` +
- `(e.g. listen(0, '127.0.0.1', cb)) and dial the literal from server.address():\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Hostless rig bind found — a bare listen(0) binds the IPv6 wildcard '::', whose loopback-specific ` +
+ `port slots stay silently bindable by foreign processes; their listeners then intercept this rig's ` +
+ `localhost dials (the rotating integration-suite flake). Bind a loopback-specific host ` +
+ `(e.g. listen(0, '127.0.0.1', cb)) and dial the literal from server.address():\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no interpolated-port localhost dial URLs', () => {
@@ -110,14 +109,13 @@ describe('loopback bind discipline (cli test sources)', () => {
violations.push(` ${file.path}:${v.line} ${v.text}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `Ambiguous-name rig dial found — 'localhost' resolves '::1'-first, exactly the loopback-specific slot ` +
- `a foreign process can hold while the rig sits on a wildcard (or single-family) bind. Dial the ` +
- `literal address the rig actually bound (a rig-advertised base URL, or ` +
- `http://127.0.0.1:\${port}):\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Ambiguous-name rig dial found — 'localhost' resolves '::1'-first, exactly the loopback-specific slot ` +
+ `a foreign process can hold while the rig sits on a wildcard (or single-family) bind. Dial the ` +
+ `literal address the rig actually bound (a rig-advertised base URL, or ` +
+ `http://127.0.0.1:\${port}):\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('listen predicate fires on planted violations and not on adjacent negatives', () => {
diff --git a/packages/cli/src/tsdown-bundle-coverage.test.ts b/packages/cli/src/tsdown-bundle-coverage.test.ts
index 3fadd56ed..541ce3088 100644
--- a/packages/cli/src/tsdown-bundle-coverage.test.ts
+++ b/packages/cli/src/tsdown-bundle-coverage.test.ts
@@ -37,9 +37,8 @@ describe('tsdown alwaysBundle covers every cli runtime dep', () => {
expect(alwaysBundleBlock.length).toBeGreaterThan(0);
});
- for (const dep of declaredDeps) {
+ for (const dep of declaredDeps.filter((name) => !neverBundleNames.includes(name))) {
test(`alwaysBundle covers '${dep}'`, () => {
- if (neverBundleNames.includes(dep)) return;
const escaped = dep.replace(/[\\^$*+?.()|[\]{}-]/g, '\\$&').replace(/\//g, '\\\\?/');
const pattern = new RegExp(`\\^${escaped}\\(`);
expect(
diff --git a/packages/core/src/acp/codex-legacy-notice.test.ts b/packages/core/src/acp/codex-legacy-notice.test.ts
index aa52e5906..9340d260e 100644
--- a/packages/core/src/acp/codex-legacy-notice.test.ts
+++ b/packages/core/src/acp/codex-legacy-notice.test.ts
@@ -180,7 +180,7 @@ describe('isCodexLegacyWarningUpdate — properties', () => {
update as SessionUpdate,
agent as CodexLegacyAgentIdentity,
);
- return typeof verdict === 'boolean';
+ expect(typeof verdict).toBe('boolean');
}),
{ numRuns: PBT_NUM_RUNS },
);
@@ -195,7 +195,7 @@ describe('isCodexLegacyWarningUpdate — properties', () => {
(prefix, body, terminated) => {
const text = `${prefix}${body}${terminated ? TERMINATOR : ''}`;
const verdict = isCodexLegacyWarningUpdate(candidateFrom(text), CODEX);
- return verdict === text.endsWith(TERMINATOR);
+ expect(verdict).toBe(text.endsWith(TERMINATOR));
},
),
{ numRuns: PBT_NUM_RUNS },
@@ -207,7 +207,7 @@ describe('isCodexLegacyWarningUpdate — properties', () => {
fc.property(fc.string(), (body) => {
const text = `${body}${TERMINATOR}`;
fc.pre(!text.startsWith(WARNING_PREFIX) && !text.startsWith(CONFIG_WARNING_PREFIX));
- return isCodexLegacyWarningUpdate(candidateFrom(text), CODEX) === false;
+ expect(isCodexLegacyWarningUpdate(candidateFrom(text), CODEX)).toBe(false);
}),
{ numRuns: PBT_NUM_RUNS },
);
@@ -223,7 +223,8 @@ describe('isCodexLegacyWarningUpdate — properties', () => {
isCodexLegacyWarningUpdate(update, agent);
- return JSON.stringify(update) === updateBefore && JSON.stringify(agent) === agentBefore;
+ expect(JSON.stringify(update)).toBe(updateBefore);
+ expect(JSON.stringify(agent)).toBe(agentBefore);
}),
{ numRuns: PBT_NUM_RUNS },
);
@@ -271,9 +272,11 @@ describe('isCodexLegacyWarningUpdate — properties', () => {
fc.constantFrom(...HEADS),
fc.constantFrom(...TAILS),
fc.string(),
- (head, tail, body) =>
- isCodexLegacyWarningUpdate(candidateFrom(`${head}${body}${tail}`), CODEX) ===
- isCodexLegacyWarningUpdate(candidateFrom(`${head}${tail}`), CODEX),
+ (head, tail, body) => {
+ expect(isCodexLegacyWarningUpdate(candidateFrom(`${head}${body}${tail}`), CODEX)).toBe(
+ isCodexLegacyWarningUpdate(candidateFrom(`${head}${tail}`), CODEX),
+ );
+ },
),
{ numRuns: PBT_NUM_RUNS },
);
diff --git a/packages/core/src/agent-registry/readiness.test.ts b/packages/core/src/agent-registry/readiness.test.ts
index 04854dea7..8835f143b 100644
--- a/packages/core/src/agent-registry/readiness.test.ts
+++ b/packages/core/src/agent-registry/readiness.test.ts
@@ -451,12 +451,27 @@ describe('capability grants', () => {
it('lists only ids the capability table declares', () => {
const declared = CAPABILITY_RECORDS.map((record) => record.id);
+ const observed = new Set<string>();
+ const satisfied: SatisfierProbe = { state: 'satisfied', strictness: EXACT };
for (const agent of Object.values(AGENT_REGISTRY)) {
+ const probes = snapshot(
+ Object.fromEntries(agent.satisfiers.map((satisfier) => [satisfier.id, satisfied])),
+ );
for (const mode of AGENT_MODES) {
- for (const id of assessReadiness({ agentId: agent.id, mode }).grantedCapabilities) {
- expect(declared).toContain(id);
+ expect(
+ assessReadiness({ agentId: agent.id, mode }).grantedCapabilities,
+ `${agent.id}/${mode}: no probe authorizes a capability`,
+ ).toEqual([]);
+ const granted = assessReadiness({ agentId: agent.id, mode, probes }).grantedCapabilities;
+ expect(
+ granted.filter((id) => !declared.includes(id)),
+ `${agent.id}/${mode}: every granted capability is declared`,
+ ).toEqual([]);
+ for (const id of granted) {
+ observed.add(id);
}
}
}
+ expect([...observed].sort()).toEqual([...declared].sort());
});
});
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/constants/preview-embed-starters.test.ts b/packages/core/src/constants/preview-embed-starters.test.ts
index 373593183..7a1f3868f 100644
--- a/packages/core/src/constants/preview-embed-starters.test.ts
+++ b/packages/core/src/constants/preview-embed-starters.test.ts
@@ -10,15 +10,16 @@ describe('PREVIEW_EMBED_STARTERS — SVG paint-attribute hygiene (PRD-6760)', ()
for (const starter of PREVIEW_EMBED_STARTERS) {
test(`${starter.id} — no var() in SVG paint-accepting presentation attributes`, () => {
const svgBlocks = starter.html.match(SVG_BLOCK_RE) ?? [];
+ const violations: string[] = [];
for (const svg of svgBlocks) {
const match = svg.match(PAINT_ATTR_RE);
- expect(
- match,
- match
- ? `${starter.id}: ${match[0]} — route through style="${match[1]}: var(...)" instead`
- : undefined,
- ).toBeNull();
+ if (match) {
+ violations.push(
+ `${starter.id}: ${match[0]} — route through style="${match[1]}: var(...)" instead`,
+ );
+ }
}
+ expect(violations).toEqual([]);
});
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index fc267cbea..fb0ba5a7c 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/schema-invariant.test.ts b/packages/core/src/schema-invariant.test.ts
index 71bc7a76e..fa1d4f7b5 100644
--- a/packages/core/src/schema-invariant.test.ts
+++ b/packages/core/src/schema-invariant.test.ts
@@ -165,18 +165,20 @@ describe('R10: schema add-only invariant', () => {
});
test('no attrs removed from existing node types (outside allowed narrowings)', () => {
+ const violations: string[] = [];
for (const [nodeType, expected] of Object.entries(snapshot.nodes)) {
const actual = current.nodes[nodeType];
if (!actual) continue;
for (const attrName of Object.keys(expected.attrs)) {
if (actual.attrs[attrName] !== undefined) continue;
if (isAllowedNarrowing(nodeType, 'attr-removed', attrName)) continue;
- throw new Error(
+ violations.push(
`Schema NARROWED — attr '${attrName}' removed from node type '${nodeType}'. ` +
'This violates precedent #9 unless registered in ALLOWED_NARROWINGS with spec evidence.',
);
}
}
+ expect(violations, violations.join('\n')).toEqual([]);
});
test('all attrs have default values', () => {
@@ -188,6 +190,7 @@ describe('R10: schema add-only invariant', () => {
});
test('content expressions not narrowed (superset check)', () => {
+ const violations: string[] = [];
for (const [nodeType, expected] of Object.entries(snapshot.nodes)) {
const actual = current.nodes[nodeType];
if (!actual) continue;
@@ -195,7 +198,7 @@ describe('R10: schema add-only invariant', () => {
if (expected.content !== '' && isAllowedNarrowing(nodeType, 'content')) {
continue;
}
- throw new Error(
+ violations.push(
`Schema content expression changed on node type '${nodeType}': ` +
`'${expected.content}' → '${actual.content}'. ` +
'This requires an ALLOWED_NARROWINGS entry with kind:"content" + ' +
@@ -204,6 +207,7 @@ describe('R10: schema add-only invariant', () => {
'Y.Item data loss on downstream peers.',
);
}
+ expect(violations, violations.join('\n')).toEqual([]);
});
test('sharedExtensions ordering unchanged', () => {
@@ -256,25 +260,17 @@ describe('R10: schema add-only invariant', () => {
test('snapshot matches current schema (regenerate if additive-only changes)', () => {
const currentJson = JSON.stringify(current, null, 2);
const snapshotJson = JSON.stringify(snapshot, null, 2);
- if (currentJson !== snapshotJson) {
- const newNodes = Object.keys(current.nodes).filter((n) => !(n in snapshot.nodes));
- const missingNodes = Object.keys(snapshot.nodes).filter((n) => !(n in current.nodes));
- if (missingNodes.length > 0) {
- throw new Error(
- `Schema NARROWED — removed node types: ${missingNodes.join(', ')}. This is forbidden by R10.`,
- );
- }
- if (newNodes.length > 0) {
- throw new Error(
- `Schema snapshot outdated — new node types: ${newNodes.join(', ')}. ` +
- 'Regenerate schema-snapshot.json and verify the diff is additive-only.',
- );
- }
- throw new Error(
- 'Schema snapshot mismatch. Regenerate schema-snapshot.json and verify the diff is additive-only. ' +
- 'If removing or renaming attrs/types, STOP — this violates R10 (y-prosemirror data loss).',
- );
- }
+ const newNodes = Object.keys(current.nodes).filter((n) => !(n in snapshot.nodes));
+ const missingNodes = Object.keys(snapshot.nodes).filter((n) => !(n in current.nodes));
+ const message =
+ missingNodes.length > 0
+ ? `Schema NARROWED — removed node types: ${missingNodes.join(', ')}. This is forbidden by R10.`
+ : newNodes.length > 0
+ ? `Schema snapshot outdated — new node types: ${newNodes.join(', ')}. ` +
+ 'Regenerate schema-snapshot.json and verify the diff is additive-only.'
+ : 'Schema snapshot mismatch. Regenerate schema-snapshot.json and verify the diff is additive-only. ' +
+ 'If removing or renaming attrs/types, STOP — this violates R10 (y-prosemirror data loss).';
+ expect(currentJson, message).toBe(snapshotJson);
});
});
diff --git a/packages/desktop/src/main/agent-registry-apply.test.ts b/packages/desktop/src/main/agent-registry-apply.test.ts
index 0ea20f5b6..e28e9429a 100644
--- a/packages/desktop/src/main/agent-registry-apply.test.ts
+++ b/packages/desktop/src/main/agent-registry-apply.test.ts
@@ -14,9 +14,14 @@ import type { HostSnapshot, SurfaceState } from '@inkeep/open-knowledge-core';
import type { IpcMainInvokeEvent } from 'electron';
import { describe, expect, test, vi } from 'vitest';
import { EDITOR_TARGETS } from '../../../cli/src/commands/editors.ts';
+import { classifyExistingMcpEntry, writeEditorMcpConfig } from '../../../cli/src/commands/init.ts';
import { removeOwnMcpEntry } from '../../../cli/src/commands/mcp-config-removal.ts';
import { ensurePiBridge } from '../../../cli/src/commands/pi-acp-bridge.ts';
import { collectCliHostSnapshot } from '../../../cli/src/integrations/registry-probes.ts';
+import {
+ removeProjectSkill,
+ writeProjectSkill,
+} from '../../../cli/src/integrations/write-project-skill.ts';
import type {
AgentIntegrationsApplyRequest,
AgentIntegrationsApplyResult,
@@ -27,6 +32,7 @@ import {
applyIntents,
createAgentIntegrationsApplyDelegate,
} from './agent-registry-apply.ts';
+import { checkAndRepairProjectMcpOnProjectOpen } from './project-mcp-reclaim.ts';
const PROJECT = '/proj';
const EVENT = { sender: { id: 1 } } as unknown as IpcMainInvokeEvent;
@@ -198,6 +204,81 @@ function piFixture() {
return { root, projectDir, home, bridgePath, trustPath, surfaces };
}
+function projectSkillFixture() {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-desktop-project-skill-reopen-')));
+ const projectDir = join(root, 'project');
+ const home = join(root, 'home');
+ mkdirSync(projectDir);
+ mkdirSync(home);
+ const skillPaths = {
+ claude: join(projectDir, '.claude', 'skills', 'open-knowledge', 'SKILL.md'),
+ codex: join(projectDir, '.codex', 'skills', 'open-knowledge', 'SKILL.md'),
+ };
+ const surfaces = makeSurfaces();
+ surfaces.project.projectConfigPath = (id, cwd) =>
+ EDITOR_TARGETS[id].projectConfigPath?.(cwd) ?? null;
+ surfaces.project.writeProjectMcpConfig = ({ id, projectDir: cwd, projectPath }) => {
+ const result = writeEditorMcpConfig(
+ EDITOR_TARGETS[id],
+ cwd,
+ { mode: 'published', skipAvailabilityCheck: true, replaceEntry: true },
+ home,
+ projectPath,
+ );
+ if (result.action === 'written' || result.action === 'overwritten') return result;
+ if (result.action === 'declined') return { action: 'declined', reason: result.declineReason };
+ return { action: 'failed', error: result.error };
+ };
+ surfaces.project.writeProjectSkill = (id, cwd) =>
+ writeProjectSkill(EDITOR_TARGETS[id], cwd, { home });
+ surfaces.project.removeProjectSkill = (id, cwd) => removeProjectSkill(EDITOR_TARGETS[id], cwd);
+
+ async function reopen() {
+ return checkAndRepairProjectMcpOnProjectOpen({
+ projectDir,
+ executablePath: '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge',
+ isPackaged: true,
+ platform: 'darwin',
+ env: {},
+ logger: { event: vi.fn() },
+ cli: {
+ editorTargets: EDITOR_TARGETS,
+ allEditorIds: ['claude', 'codex'],
+ classifyExistingProjectMcpConfig: (id, cwd, path) =>
+ classifyExistingMcpEntry(EDITOR_TARGETS[id], cwd, home, path),
+ writeProjectMcpConfig: ({ editorId, projectDir: cwd, projectPath, pruneOnly }) => {
+ const result = writeEditorMcpConfig(
+ EDITOR_TARGETS[editorId],
+ cwd,
+ {
+ mode: 'published',
+ skipAvailabilityCheck: true,
+ ...(pruneOnly === true ? { pruneOnly: true } : {}),
+ },
+ home,
+ projectPath,
+ );
+ if (result.action === 'failed') return { action: 'failed', error: result.error };
+ if (result.action === 'declined') {
+ return { action: 'declined', reason: result.declineReason };
+ }
+ return { action: result.action === 'skipped-flag' ? 'unchanged' : 'overwritten' };
+ },
+ },
+ });
+ }
+
+ return {
+ root,
+ projectDir,
+ home,
+ surfaces,
+ skillPaths,
+ reopen,
+ snapshot: () => collectCliHostSnapshot({ cwd: projectDir, home }),
+ };
+}
+
describe('applyIntents on the desktop host', () => {
test('a project MCP intent runs the project MCP writer', async () => {
const surfaces = makeSurfaces();
@@ -528,32 +609,137 @@ describe('applyIntents on the desktop host', () => {
expect(surfaces.calls.userSkillDecisions).toEqual([]);
});
- test('a unanimous project-skill batch records the decision the reclaim reads', async () => {
- const surfaces = makeSurfaces();
+ test('a unanimous project-skill OFF batch stays OFF after the project-open sweep', async () => {
+ const fixture = projectSkillFixture();
+ try {
+ const installed = await applyIntents(
+ {
+ intents: [
+ want(CLAUDE_PROJECT_MCP),
+ want(CODEX_PROJECT_MCP),
+ want(CLAUDE_PROJECT_SKILL),
+ want(CODEX_PROJECT_SKILL),
+ ],
+ },
+ fixture,
+ );
+ expect(installed.report.actions.every((action) => action.action === 'written')).toBe(true);
+ expect(existsSync(fixture.skillPaths.claude)).toBe(true);
+ expect(existsSync(fixture.skillPaths.codex)).toBe(true);
- await apply(surfaces, [drop(CLAUDE_PROJECT_SKILL), drop(CODEX_PROJECT_SKILL)], {
- [CLAUDE_PROJECT_SKILL]: 'satisfied',
- [CODEX_PROJECT_SKILL]: 'satisfied',
- [CLAUDE_PROJECT_MCP]: 'satisfied',
- [CODEX_PROJECT_MCP]: 'satisfied',
- });
+ const removed = await applyIntents(
+ { intents: [drop(CLAUDE_PROJECT_SKILL), drop(CODEX_PROJECT_SKILL)] },
+ fixture,
+ );
+ expect(actionFor(removed.report, CLAUDE_PROJECT_SKILL)?.action).toBe('removed');
+ expect(actionFor(removed.report, CODEX_PROJECT_SKILL)?.action).toBe('removed');
+ expect(existsSync(dirname(fixture.skillPaths.claude))).toBe(false);
+ expect(existsSync(dirname(fixture.skillPaths.codex))).toBe(false);
+
+ expect(await fixture.reopen()).toMatchObject({
+ status: 'done',
+ perEditor: [
+ { editor: 'claude', status: 'healthy-current' },
+ { editor: 'codex', status: 'healthy-current' },
+ ],
+ });
+ expect(existsSync(dirname(fixture.skillPaths.claude))).toBe(false);
+ expect(existsSync(dirname(fixture.skillPaths.codex))).toBe(false);
+ const after = await fixture.snapshot();
+ expect(after.probes.satisfiers[CLAUDE_PROJECT_SKILL]?.state).toBe('absent');
+ expect(after.probes.satisfiers[CODEX_PROJECT_SKILL]?.state).toBe('absent');
+ expect(after.probes.satisfiers[CLAUDE_PROJECT_MCP]?.state).toBe('satisfied');
+ expect(after.probes.satisfiers[CODEX_PROJECT_MCP]?.state).toBe('satisfied');
+ } finally {
+ rmSync(fixture.root, { recursive: true, force: true });
+ }
});
- test('a batch that disagrees about the project skill records no decision', async () => {
- const surfaces = makeSurfaces();
+ test('a disagreeing project-skill batch keeps each choice after the project-open sweep', async () => {
+ const fixture = projectSkillFixture();
+ try {
+ await applyIntents(
+ {
+ intents: [want(CLAUDE_PROJECT_MCP), want(CODEX_PROJECT_MCP), want(CODEX_PROJECT_SKILL)],
+ },
+ fixture,
+ );
+ expect(existsSync(fixture.skillPaths.claude)).toBe(false);
+ expect(existsSync(fixture.skillPaths.codex)).toBe(true);
- await apply(surfaces, [want(CLAUDE_PROJECT_SKILL), drop(CODEX_PROJECT_SKILL)], {
- [CLAUDE_PROJECT_SKILL]: 'absent',
- [CODEX_PROJECT_SKILL]: 'satisfied',
- [CLAUDE_PROJECT_MCP]: 'satisfied',
- [CODEX_PROJECT_MCP]: 'satisfied',
- });
- });
+ const changed = await applyIntents(
+ { intents: [want(CLAUDE_PROJECT_SKILL), drop(CODEX_PROJECT_SKILL)] },
+ fixture,
+ );
+ expect(actionFor(changed.report, CLAUDE_PROJECT_SKILL)?.action).toBe('written');
+ expect(actionFor(changed.report, CODEX_PROJECT_SKILL)?.action).toBe('removed');
+ const claudeSkill = readFileSync(fixture.skillPaths.claude, 'utf8');
+ expect(existsSync(dirname(fixture.skillPaths.codex))).toBe(false);
+ writeFileSync(
+ join(fixture.projectDir, '.mcp.json'),
+ JSON.stringify({
+ mcpServers: {
+ 'open-knowledge': {
+ command: '/bin/sh',
+ args: ['-l', '-c', '# ok-mcp-v1\nexit 127'],
+ },
+ },
+ }),
+ );
- test('a batch with no project-skill row leaves the recorded decision alone', async () => {
- const surfaces = makeSurfaces();
+ expect(await fixture.reopen()).toMatchObject({
+ status: 'done',
+ perEditor: [
+ { editor: 'claude', status: 'reclaimed' },
+ { editor: 'codex', status: 'healthy-current' },
+ ],
+ });
+ expect(readFileSync(fixture.skillPaths.claude, 'utf8')).toBe(claudeSkill);
+ expect(existsSync(dirname(fixture.skillPaths.codex))).toBe(false);
+ const after = await fixture.snapshot();
+ expect(after.probes.satisfiers[CLAUDE_PROJECT_SKILL]?.state).toBe('satisfied');
+ expect(after.probes.satisfiers[CODEX_PROJECT_SKILL]?.state).toBe('absent');
+ expect(after.probes.satisfiers[CLAUDE_PROJECT_MCP]?.state).toBe('satisfied');
+ expect(after.probes.satisfiers[CODEX_PROJECT_MCP]?.state).toBe('satisfied');
+ } finally {
+ rmSync(fixture.root, { recursive: true, force: true });
+ }
+ });
- await apply(surfaces, [want(CLAUDE_PROJECT_MCP)], { [CLAUDE_PROJECT_MCP]: 'absent' });
+ test('a batch with no project-skill row preserves skill presence after the project-open sweep', async () => {
+ const fixture = projectSkillFixture();
+ try {
+ await applyIntents(
+ { intents: [want(CODEX_PROJECT_MCP), want(CODEX_PROJECT_SKILL)] },
+ fixture,
+ );
+ expect(existsSync(fixture.skillPaths.claude)).toBe(false);
+ const codexSkill = readFileSync(fixture.skillPaths.codex, 'utf8');
+
+ const changed = await applyIntents({ intents: [want(CLAUDE_PROJECT_MCP)] }, fixture);
+ expect(changed.report.actions).toMatchObject([
+ { satisfierId: CLAUDE_PROJECT_MCP, action: 'written' },
+ ]);
+ expect(existsSync(dirname(fixture.skillPaths.claude))).toBe(false);
+ expect(readFileSync(fixture.skillPaths.codex, 'utf8')).toBe(codexSkill);
+
+ expect(await fixture.reopen()).toMatchObject({
+ status: 'done',
+ perEditor: [
+ { editor: 'claude', status: 'healthy-current' },
+ { editor: 'codex', status: 'healthy-current' },
+ ],
+ });
+ expect(existsSync(dirname(fixture.skillPaths.claude))).toBe(false);
+ expect(readFileSync(fixture.skillPaths.codex, 'utf8')).toBe(codexSkill);
+ const after = await fixture.snapshot();
+ expect(after.probes.satisfiers[CLAUDE_PROJECT_SKILL]?.state).toBe('absent');
+ expect(after.probes.satisfiers[CODEX_PROJECT_SKILL]?.state).toBe('satisfied');
+ expect(after.probes.satisfiers[CLAUDE_PROJECT_MCP]?.state).toBe('satisfied');
+ expect(after.probes.satisfiers[CODEX_PROJECT_MCP]?.state).toBe('satisfied');
+ } finally {
+ rmSync(fixture.root, { recursive: true, force: true });
+ }
});
test('re-running the same Save touches nothing the second time', async () => {
diff --git a/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts b/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts
index e4ee2df0b..58216d8ee 100644
--- a/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts
@@ -203,10 +203,12 @@ describe("desktopLaunchOptions — a packaged launch bounds its detached server'
describe('no smoke file references __dirname without defining it', () => {
const SMOKE_DIR = join(dirname(fileURLToPath(import.meta.url)), '..');
+ const files = readdirSync(SMOKE_DIR)
+ .filter((file) => file.endsWith('.e2e.ts'))
+ .map((file) => ({ file, src: readFileSync(join(SMOKE_DIR, file), 'utf8') }))
+ .filter(({ src }) => src.includes('__dirname'));
- it.each(readdirSync(SMOKE_DIR).filter((f) => f.endsWith('.e2e.ts')))('%s', (file) => {
- const src = readFileSync(join(SMOKE_DIR, file), 'utf8');
- if (!src.includes('__dirname')) return;
+ it.each(files)('$file', ({ file, src }) => {
expect(src, `${file} uses __dirname without defining it`).toMatch(/const __dirname\s*=/);
});
});
diff --git a/packages/desktop/tests/utility/pty-readiness.test.ts b/packages/desktop/tests/utility/pty-readiness.test.ts
index 6184ca8bd..7568101e9 100644
--- a/packages/desktop/tests/utility/pty-readiness.test.ts
+++ b/packages/desktop/tests/utility/pty-readiness.test.ts
@@ -438,6 +438,7 @@ describe('driving a real host through a shell that starts slowly', () => {
intervalMs: 5,
stallMs: 2_000,
});
+ expect(io.read()).toContain('HARNESS_42_DONE');
} finally {
host.killActive();
}
diff --git a/packages/server/src/acp/managed-runtime-flow.integration.test.ts b/packages/server/src/acp/managed-runtime-flow.integration.test.ts
index 88dd7df40..f8478c3ad 100644
--- a/packages/server/src/acp/managed-runtime-flow.integration.test.ts
+++ b/packages/server/src/acp/managed-runtime-flow.integration.test.ts
@@ -368,6 +368,7 @@ describe('managed-runtime consent + download flow', () => {
await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });
await waitFor(() => !existsSync(staleDir), 3_000, 'stale runtime staging cleanup');
+ expect(existsSync(staleDir)).toBe(false);
});
test('grant → download → install', async () => {
diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.ts
index 9885bde5b..b7d5c1c42 100644
--- a/packages/server/src/acp/thread-manager.integration.test.ts
+++ b/packages/server/src/acp/thread-manager.integration.test.ts
@@ -649,6 +649,7 @@ describe('AcpThreadManager (real subprocess)', () => {
10_000,
'thread force-closed',
);
+ expect(manager.listThreads().filter((t) => t.archived !== true)).toEqual([]);
}, 45_000);
test('unknown agents and capacity are refused cleanly', async () => {
@@ -4037,6 +4038,10 @@ describe('AcpThreadManager prompt queueing', () => {
5_000,
'the file read cleared the stall',
);
+ expect(
+ infoLog.mock.calls.some((call) => call[1] === '[acp-threads] turn resumed after stall'),
+ ).toBe(true);
+ expect(manager.getInfo(info.threadId)?.stalledSince).toBeUndefined();
await waitUntil(() => !internals(manager).turnActive(info.threadId), 20_000, 'turn ended');
await manager.closeThread(info.threadId);
@@ -4168,6 +4173,7 @@ describe.skipIf(process.platform === 'win32')('login-shell PATH fallback', () =>
const info = await manager.createThread({ agent: { source: 'custom', id: 'shell-agent' } });
await manager.subscribe(info.threadId, 0, () => {});
await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');
+ expect(manager.getInfo(info.threadId)?.status).toBe('ready');
}, 30_000);
test('a command missing from the login shell too still fails with the install hint', async () => {
diff --git a/packages/server/src/bash/path-honesty-contract.test.ts b/packages/server/src/bash/path-honesty-contract.test.ts
index c420cceed..31dd65ed8 100644
--- a/packages/server/src/bash/path-honesty-contract.test.ts
+++ b/packages/server/src/bash/path-honesty-contract.test.ts
@@ -86,12 +86,15 @@ const COMMANDS = [
describe('exec never reports a path that does not exist', () => {
test.each(COMMANDS)('%s', async (command) => {
const root = await corpus();
- for (const path of await reported(root, command)) {
- expect(
- () => statSync(resolve(root, path)),
- `${command} reported a nonexistent path: ${path}`,
- ).not.toThrow();
- }
+ const nonexistentPaths = (await reported(root, command)).flatMap((path) => {
+ try {
+ statSync(resolve(root, path));
+ return [];
+ } catch (error) {
+ return [{ path, error }];
+ }
+ });
+ expect(nonexistentPaths, `${command} reported nonexistent paths`).toEqual([]);
});
test('the assertion can fail, so a passing run means something', async () => {
diff --git a/packages/server/src/composition-precedence.test.ts b/packages/server/src/composition-precedence.test.ts
index 6fe3f6b7a..f99d57604 100644
--- a/packages/server/src/composition-precedence.test.ts
+++ b/packages/server/src/composition-precedence.test.ts
@@ -81,10 +81,11 @@ describe('route dispatch and precedence — normal mode (no React shell)', () =>
test('a live /collab WebSocket connects through the composed upgrade path', async () => {
const ws = new WebSocket(`ws://127.0.0.1:${normal.port}/collab`);
- await new Promise<void>((resolvePromise, reject) => {
- ws.on('open', () => resolvePromise());
- ws.on('error', reject);
+ const outcome = await new Promise<'open' | Error>((resolvePromise) => {
+ ws.on('open', () => resolvePromise('open'));
+ ws.on('error', resolvePromise);
});
+ expect(outcome).toBe('open');
ws.close();
await new Promise<void>((resolvePromise) => ws.on('close', () => resolvePromise()));
});
diff --git a/packages/server/src/config-file-watcher.test.ts b/packages/server/src/config-file-watcher.test.ts
index dcb2aee3a..5a8cb236c 100644
--- a/packages/server/src/config-file-watcher.test.ts
+++ b/packages/server/src/config-file-watcher.test.ts
@@ -139,8 +139,8 @@ describe('startConfigFileWatcher', () => {
test('cleanup function returned is idempotent', async () => {
const cleanup = await startConfigFileWatcher(fx.absPath, () => {});
- await cleanup();
- await cleanup();
+ await expect(cleanup()).resolves.toBeUndefined();
+ await expect(cleanup()).resolves.toBeUndefined();
});
test('handler exceptions are caught and do not crash the watcher', async () => {
@@ -316,8 +316,8 @@ describe('startMultiPathConfigFileWatcher', () => {
test('cleanup function is idempotent', async () => {
const cleanup = await startMultiPathConfigFileWatcher([multiFx.pathA, multiFx.pathB], () => {});
- await cleanup();
- await cleanup();
+ await expect(cleanup()).resolves.toBeUndefined();
+ await expect(cleanup()).resolves.toBeUndefined();
});
test('does not fire onChange for sibling files in the same dir that are not in the watched set', async () => {
diff --git a/packages/server/src/conflict-authority.test.ts b/packages/server/src/conflict-authority.test.ts
index 78e66898e..6b5c28be5 100644
--- a/packages/server/src/conflict-authority.test.ts
+++ b/packages/server/src/conflict-authority.test.ts
@@ -1036,12 +1036,6 @@ describe('ConflictAuthority working-tree resolve against a real repo', () => {
expect(rig.authority.count()).toBe(0);
expect(await headSha()).toBe(before);
});
-
- test('the union type refuses a working-tree raise with no pinned blob', () => {
- const { authority } = makeAuthority();
- // @ts-expect-error a working-tree conflict without theirsSha is not constructible
- authority.raise({ kind: 'working-tree', file: 'a.md' });
- });
});
const MARKERED = [
diff --git a/packages/server/src/conflict-authority.type-tests.ts b/packages/server/src/conflict-authority.type-tests.ts
new file mode 100644
index 000000000..7aa8af488
--- /dev/null
+++ b/packages/server/src/conflict-authority.type-tests.ts
@@ -0,0 +1,6 @@
+import type { ConflictAuthority } from './conflict-authority.ts';
+
+declare const authority: ConflictAuthority;
+
+// @ts-expect-error a working-tree conflict without theirsSha is not constructible
+authority.raise({ kind: 'working-tree', file: 'a.md' });
diff --git a/packages/server/src/console-discipline.test.ts b/packages/server/src/console-discipline.test.ts
index 51ec07fa7..2d764391c 100644
--- a/packages/server/src/console-discipline.test.ts
+++ b/packages/server/src/console-discipline.test.ts
@@ -107,16 +107,15 @@ describe('console discipline (server sources)', () => {
violations.push(` ${file.path}:${v.line} ${v.text}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `Raw console.* call found in packages/server/src — console output never reaches the pino file sink ` +
- `(.ok/local/logs/server-current.jsonl) that bug-report bundles collect, and the packaged desktop app ` +
- `runs the server detached with no persistent stdio. Use getLogger(name) from './logger.ts' ` +
- `(warn/error still reach the terminal through the console stream). The only sanctioned console shapes ` +
- `are the structured telemetry-event channel (console.<level>(JSON.stringify({ event: ... }))) and the ` +
- `FILE_ALLOWLIST bootstrap/stdio surfaces in console-discipline.test.ts:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Raw console.* call found in packages/server/src — console output never reaches the pino file sink ` +
+ `(.ok/local/logs/server-current.jsonl) that bug-report bundles collect, and the packaged desktop app ` +
+ `runs the server detached with no persistent stdio. Use getLogger(name) from './logger.ts' ` +
+ `(warn/error still reach the terminal through the console stream). The only sanctioned console shapes ` +
+ `are the structured telemetry-event channel (console.<level>(JSON.stringify({ event: ... }))) and the ` +
+ `FILE_ALLOWLIST bootstrap/stdio surfaces in console-discipline.test.ts:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('predicate fires on planted violations and not on adjacent negatives', () => {
diff --git a/packages/server/src/derived-document-index-boundary.test.ts b/packages/server/src/derived-document-index-boundary.test.ts
deleted file mode 100644
index 868d9a03e..000000000
--- a/packages/server/src/derived-document-index-boundary.test.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { describe, expectTypeOf, test } from 'vitest';
-import type { ApiExtensionOptions } from './api-extension.ts';
-import type {
- DerivedDocumentIndexApiPort,
- DerivedDocumentIndexLivePort,
- DerivedDocumentIndexPersistencePort,
-} from './derived-document-index.ts';
-import type { LiveDerivedIndexOptions } from './live-derived-index.ts';
-import type { PersistenceOptions } from './persistence.ts';
-import type { ServerOptions } from './server-factory.ts';
-
-type RawIndexMember =
- | 'backlinkIndex'
- | 'tagIndex'
- | 'updateDocumentFromMarkdown'
- | 'deleteDocument'
- | 'renameDocument'
- | 'saveToDisk'
- | 'loadFromDisk'
- | 'rebuildFromDisk'
- | 'reconcileWithDisk'
- | 'ingestGlobalSkillBundles'
- | 'init'
- | 'close'
- | 'switchBranch';
-
-type ConsumerOptionKey =
- | keyof ApiExtensionOptions
- | keyof LiveDerivedIndexOptions
- | keyof PersistenceOptions;
-
-type ConsumerPortKey =
- | keyof DerivedDocumentIndexApiPort
- | keyof DerivedDocumentIndexLivePort
- | keyof DerivedDocumentIndexPersistencePort;
-
-describe('derived document index ownership boundary', () => {
- test('runtime consumers accept only their coordinator ports', () => {
- expectTypeOf<ApiExtensionOptions['derivedDocumentIndex']>().toEqualTypeOf<
- DerivedDocumentIndexApiPort | undefined
- >();
- expectTypeOf<
- LiveDerivedIndexOptions['derivedDocumentIndex']
- >().toEqualTypeOf<DerivedDocumentIndexLivePort>();
- expectTypeOf<PersistenceOptions['derivedDocumentIndex']>().toEqualTypeOf<
- DerivedDocumentIndexPersistencePort | undefined
- >();
- });
-
- test('consumer options and ports do not expose raw relationship indexes', () => {
- expectTypeOf<Extract<ConsumerOptionKey, RawIndexMember>>().toEqualTypeOf<never>();
- expectTypeOf<Extract<ConsumerPortKey, RawIndexMember>>().toEqualTypeOf<never>();
- });
-
- test('server composition owns coordinator construction', () => {
- expectTypeOf<
- Extract<keyof ServerOptions, 'backlinkIndex' | 'tagIndex' | 'derivedDocumentIndex'>
- >().toEqualTypeOf<never>();
- });
-});
diff --git a/packages/server/src/derived-document-index-boundary.type-tests.ts b/packages/server/src/derived-document-index-boundary.type-tests.ts
new file mode 100644
index 000000000..2e10599e5
--- /dev/null
+++ b/packages/server/src/derived-document-index-boundary.type-tests.ts
@@ -0,0 +1,52 @@
+import { expectTypeOf } from 'vitest';
+import type { ApiExtensionOptions } from './api-extension.ts';
+import type {
+ DerivedDocumentIndexApiPort,
+ DerivedDocumentIndexLivePort,
+ DerivedDocumentIndexPersistencePort,
+} from './derived-document-index.ts';
+import type { LiveDerivedIndexOptions } from './live-derived-index.ts';
+import type { PersistenceOptions } from './persistence.ts';
+import type { ServerOptions } from './server-factory.ts';
+
+type RawIndexMember =
+ | 'backlinkIndex'
+ | 'tagIndex'
+ | 'updateDocumentFromMarkdown'
+ | 'deleteDocument'
+ | 'renameDocument'
+ | 'saveToDisk'
+ | 'loadFromDisk'
+ | 'rebuildFromDisk'
+ | 'reconcileWithDisk'
+ | 'ingestGlobalSkillBundles'
+ | 'init'
+ | 'close'
+ | 'switchBranch';
+
+type ConsumerOptionKey =
+ | keyof ApiExtensionOptions
+ | keyof LiveDerivedIndexOptions
+ | keyof PersistenceOptions;
+
+type ConsumerPortKey =
+ | keyof DerivedDocumentIndexApiPort
+ | keyof DerivedDocumentIndexLivePort
+ | keyof DerivedDocumentIndexPersistencePort;
+
+expectTypeOf<ApiExtensionOptions['derivedDocumentIndex']>().toEqualTypeOf<
+ DerivedDocumentIndexApiPort | undefined
+>();
+expectTypeOf<
+ LiveDerivedIndexOptions['derivedDocumentIndex']
+>().toEqualTypeOf<DerivedDocumentIndexLivePort>();
+expectTypeOf<PersistenceOptions['derivedDocumentIndex']>().toEqualTypeOf<
+ DerivedDocumentIndexPersistencePort | undefined
+>();
+
+expectTypeOf<Extract<ConsumerOptionKey, RawIndexMember>>().toEqualTypeOf<never>();
+expectTypeOf<Extract<ConsumerPortKey, RawIndexMember>>().toEqualTypeOf<never>();
+
+expectTypeOf<
+ Extract<keyof ServerOptions, 'backlinkIndex' | 'tagIndex' | 'derivedDocumentIndex'>
+>().toEqualTypeOf<never>();
diff --git a/packages/server/src/error-log-discipline.uncached.test.ts b/packages/server/src/error-log-discipline.uncached.test.ts
index 37611303a..351329d84 100644
--- a/packages/server/src/error-log-discipline.uncached.test.ts
+++ b/packages/server/src/error-log-discipline.uncached.test.ts
@@ -120,9 +120,7 @@ describe('error-log payload discipline (server + cli + desktop main)', () => {
test('every FILE_ALLOWLIST entry still exists on disk', () => {
const paths = new Set(files.map((f) => f.path));
- for (const allowed of FILE_ALLOWLIST.keys()) {
- expect(paths.has(allowed)).toBe(true);
- }
+ expect([...FILE_ALLOWLIST.keys()].filter((allowed) => !paths.has(allowed))).toEqual([]);
});
test('error/warn logger calls pass the raw error under err, not a string copy', () => {
@@ -133,16 +131,15 @@ describe('error-log payload discipline (server + cli + desktop main)', () => {
violations.push(` ${file.path}:${v.line} ${v.text}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `String-coerced error field found in an error/warn log call. Pass the RAW error under ` +
- `the \`err\` key (\`log.warn({ err }, '...')\`) — the pino serializers capture ` +
- `name/message/stack; \`err.message\` / \`String(err)\` discard the stack the JSONL ` +
- `bundle needs. For a site where a string copy is genuinely intended, suffix the line ` +
- `with \`// ${MARKER} <why>\` or add a FILE_ALLOWLIST entry in ` +
- `error-log-discipline.uncached.test.ts:\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `String-coerced error field found in an error/warn log call. Pass the RAW error under ` +
+ `the \`err\` key (\`log.warn({ err }, '...')\`) — the pino serializers capture ` +
+ `name/message/stack; \`err.message\` / \`String(err)\` discard the stack the JSONL ` +
+ `bundle needs. For a site where a string copy is genuinely intended, suffix the line ` +
+ `with \`// ${MARKER} <why>\` or add a FILE_ALLOWLIST entry in ` +
+ `error-log-discipline.uncached.test.ts:\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('predicate fires on planted violations and not on adjacent negatives', () => {
diff --git a/packages/server/src/file-watcher-chokidar-fallback.test.ts b/packages/server/src/file-watcher-chokidar-fallback.test.ts
index ea13bd2ed..5f8eb78a7 100644
--- a/packages/server/src/file-watcher-chokidar-fallback.test.ts
+++ b/packages/server/src/file-watcher-chokidar-fallback.test.ts
@@ -103,6 +103,10 @@ describe('chokidar backend — live subfolder watching (forceBackend)', () => {
() => events.some((e) => e.kind === 'update' && e.docName === 'sub/note'),
{ timeoutMs: 15_000, pollMs: 40 },
);
+ expect(events).toContainEqual(expect.objectContaining({ kind: 'update', docName: 'root' }));
+ expect(events).toContainEqual(
+ expect.objectContaining({ kind: 'update', docName: 'sub/note' }),
+ );
} finally {
await handle.unsubscribe();
}
@@ -130,6 +134,14 @@ describe('chokidar backend — live subfolder watching (forceBackend)', () => {
),
{ timeoutMs: 15_000, pollMs: 40 },
);
+ expect(events).toContainEqual(
+ expect.objectContaining({ kind: 'folder-create', relativePath: 'fresh' }),
+ );
+ expect(
+ events.some(
+ (e) => (e.kind === 'create' || e.kind === 'update') && e.docName === 'fresh/child',
+ ),
+ ).toBe(true);
} finally {
await handle.unsubscribe();
}
@@ -197,6 +209,13 @@ describe('chokidar backend — templates-as-content watching (forceBackend)', ()
},
{ timeoutMs: 6_000, pollMs: 40 },
);
+ expect(
+ events.some(
+ (e) =>
+ (e.kind === 'create' || e.kind === 'update') &&
+ e.docName === 'notes/.ok/templates/standup',
+ ),
+ ).toBe(true);
} finally {
await handle.unsubscribe();
}
@@ -218,6 +237,9 @@ describe('chokidar backend — templates-as-content watching (forceBackend)', ()
() => events.some((e) => e.kind === 'conflict' && e.docName === '.ok/templates/daily'),
{ timeoutMs: 6_000, pollMs: 40 },
);
+ expect(events).toContainEqual(
+ expect.objectContaining({ kind: 'conflict', docName: '.ok/templates/daily' }),
+ );
} finally {
await handle.unsubscribe();
}
diff --git a/packages/server/src/file-watcher-chokidar-readiness.test.ts b/packages/server/src/file-watcher-chokidar-readiness.test.ts
index b75f74053..c627572af 100644
--- a/packages/server/src/file-watcher-chokidar-readiness.test.ts
+++ b/packages/server/src/file-watcher-chokidar-readiness.test.ts
@@ -11,7 +11,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
import { syncBuiltinESMExports } from 'node:module';
import { tmpdir } from 'node:os';
import { join, relative, resolve } from 'node:path';
-import { afterEach, beforeEach, describe, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createContentFilter } from './content-filter.ts';
import { type DiskEvent, lastKnownHash, startWatcher, writeTracker } from './file-watcher.ts';
import { waitWithinTestBudget } from './wait-within-test-budget.test-helper.ts';
@@ -186,6 +186,7 @@ async function expectDiskEventForCreationAfterStart(
() => events.some(site.matches),
{ timeoutMs: DELIVERY_LIVENESS_BOUND_MS, pollMs: DELIVERY_POLL_MS },
);
+ expect(events.some(site.matches), site.expected).toBe(true);
} finally {
await handle.unsubscribe();
}
diff --git a/packages/server/src/health-routes.test.ts b/packages/server/src/health-routes.test.ts
index 68efb1250..efecfb87a 100644
--- a/packages/server/src/health-routes.test.ts
+++ b/packages/server/src/health-routes.test.ts
@@ -98,7 +98,7 @@ describe('/readyz', () => {
expect(res.status).toBe(200);
});
- test('destroy() flips readiness to draining before the listener closes', async () => {
+ test('destroy() flips readiness to draining before the listener closes', async (ctx) => {
const tmp = await mkdtemp(resolve(tmpdir(), 'ok-readyz-drain-'));
try {
const draining = await bootCompositionRig(tmp);
@@ -117,11 +117,11 @@ describe('/readyz', () => {
}
await destroyed;
- if (probe !== 'refused') {
- expect(probe.status).toBe(503);
- expect(probe.body?.ready).toBe(false);
- expect(probe.body?.status).toBe('draining');
- }
+ ctx.skip(
+ probe === 'refused',
+ 'the listener closed before the probe connected, so this run could not observe the draining window',
+ );
+ expect(probe).toMatchObject({ status: 503, body: { ready: false, status: 'draining' } });
} finally {
await rm(tmp, { recursive: true, force: true });
}
diff --git a/packages/server/src/loopback-bind-discipline.test.ts b/packages/server/src/loopback-bind-discipline.test.ts
index ab6695a21..95f2a8689 100644
--- a/packages/server/src/loopback-bind-discipline.test.ts
+++ b/packages/server/src/loopback-bind-discipline.test.ts
@@ -93,14 +93,13 @@ describe('loopback bind discipline (server test sources)', () => {
violations.push(` ${file.path}:${v.line} ${v.text}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `Hostless rig bind found — a bare listen(0) binds the IPv6 wildcard '::', whose loopback-specific ` +
- `port slots stay silently bindable by foreign processes; their listeners then intercept this rig's ` +
- `localhost dials (the rotating share/git-context flake). Bind a loopback-specific host ` +
- `(e.g. listen(0, '127.0.0.1', cb)) and dial the literal from server.address():\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Hostless rig bind found — a bare listen(0) binds the IPv6 wildcard '::', whose loopback-specific ` +
+ `port slots stay silently bindable by foreign processes; their listeners then intercept this rig's ` +
+ `localhost dials (the rotating share/git-context flake). Bind a loopback-specific host ` +
+ `(e.g. listen(0, '127.0.0.1', cb)) and dial the literal from server.address():\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('no interpolated-port localhost dial URLs', () => {
@@ -110,13 +109,12 @@ describe('loopback bind discipline (server test sources)', () => {
violations.push(` ${file.path}:${v.line} ${v.text}`);
}
}
- if (violations.length > 0) {
- throw new Error(
- `Ambiguous-name rig dial found — 'localhost' resolves '::1'-first, exactly the loopback-specific slot ` +
- `a foreign process can hold while the rig sits on a wildcard (or single-family) bind. Dial the ` +
- `literal address the rig actually bound (e.g. http://127.0.0.1:\${port}):\n${violations.join('\n')}`,
- );
- }
+ expect(
+ violations,
+ `Ambiguous-name rig dial found — 'localhost' resolves '::1'-first, exactly the loopback-specific slot ` +
+ `a foreign process can hold while the rig sits on a wildcard (or single-family) bind. Dial the ` +
+ `literal address the rig actually bound (e.g. http://127.0.0.1:\${port}):\n${violations.join('\n')}`,
+ ).toEqual([]);
});
test('listen predicate fires on planted violations and not on adjacent negatives', () => {
diff --git a/packages/server/src/managed-artifact-watcher.test.ts b/packages/server/src/managed-artifact-watcher.test.ts
index 4e20c0270..bc3096e5d 100644
--- a/packages/server/src/managed-artifact-watcher.test.ts
+++ b/packages/server/src/managed-artifact-watcher.test.ts
@@ -37,6 +37,7 @@ describe('startManagedArtifactWatcher', () => {
() => seen.some(([p, c]) => p === leaf && c === 'v1'),
{ timeoutMs: 20_000, pollMs: 50 },
);
+ expect(seen).toContainEqual([leaf, 'v1']);
}, 25_000);
test('fires onUnlink (not onChange) when a SKILL.md is deleted', async () => {
diff --git a/packages/server/src/mcp/tools/exec.test.ts b/packages/server/src/mcp/tools/exec.test.ts
index 5ee180f9b..b42a34a65 100644
--- a/packages/server/src/mcp/tools/exec.test.ts
+++ b/packages/server/src/mcp/tools/exec.test.ts
@@ -734,11 +734,7 @@ describe('exec — per-row route-only previewUrl (FR-2.2)', () => {
)) as ExecResult;
const s = structured(result);
- for (const entry of s.enrichedPaths) {
- expect(entry.path.startsWith('../')).toBe(false);
- expect(entry.path).not.toBe('..');
- expect(entry.path.startsWith('/')).toBe(false);
- }
+ expect(s.enrichedPaths).toEqual([]);
});
test('mcp-tool-path-traversal: `cat /etc/passwd.md`-style absolute path is dropped from enrichedPaths', async () => {
@@ -749,10 +745,7 @@ describe('exec — per-row route-only previewUrl (FR-2.2)', () => {
)) as ExecResult;
const s = structured(result);
- for (const entry of s.enrichedPaths) {
- expect(entry.path.startsWith('/')).toBe(false);
- expect(entry.path.startsWith('../')).toBe(false);
- }
+ expect(s.enrichedPaths).toEqual([]);
});
test('FR13: nested .ok/ paths are filtered from enrichedPaths (not surfaced as listings)', async () => {
diff --git a/packages/server/src/paired-write-enforcement.test.ts b/packages/server/src/paired-write-enforcement.test.ts
index 7d1ff7050..a6191afc8 100644
--- a/packages/server/src/paired-write-enforcement.test.ts
+++ b/packages/server/src/paired-write-enforcement.test.ts
@@ -175,11 +175,10 @@ describe('paired-write enforcement', () => {
}
}
}
- if (failures.length > 0) {
- throw new Error(
- `Found ${failures.length} unrecognized transact origin(s):\n ${failures.join('\n ')}`,
- );
- }
+ expect(
+ failures,
+ `Found ${failures.length} unrecognized transact origin(s):\n ${failures.join('\n ')}`,
+ ).toEqual([]);
});
test('paired-write origins route through a sanctioned primitive', () => {
@@ -217,12 +216,11 @@ describe('paired-write enforcement', () => {
}
}
}
- if (failures.length > 0) {
- throw new Error(
- `Found ${failures.length} paired-write transact site(s) bypassing sanctioned primitives:\n ` +
- failures.join('\n '),
- );
- }
+ expect(
+ failures,
+ `Found ${failures.length} paired-write transact site(s) bypassing sanctioned primitives:\n ` +
+ failures.join('\n '),
+ ).toEqual([]);
});
test('all three sanctioned primitives are exported from bridge-intake.ts', () => {
diff --git a/packages/server/src/paired-write-origin.test.ts b/packages/server/src/paired-write-origin.type-tests.ts
similarity index 82%
rename from packages/server/src/paired-write-origin.test.ts
rename to packages/server/src/paired-write-origin.type-tests.ts
index e2c9d189b..bcb7ff0a2 100644
--- a/packages/server/src/paired-write-origin.test.ts
+++ b/packages/server/src/paired-write-origin.type-tests.ts
@@ -1,8 +1,3 @@
-/**
- * Compile-time type assertions for `PairedWriteOrigin` (bridge-correctness precedent #1 extension).
- */
-
-import { describe, test } from 'vitest';
import type { AGENT_WRITE_ORIGIN } from './agent-sessions.ts';
import type { MANAGED_RENAME_ORIGIN, ROLLBACK_ORIGIN } from './api-extension.ts';
import type { FILE_WATCHER_ORIGIN } from './external-change.ts';
@@ -23,19 +18,15 @@ void _managedRenameIsPaired;
const _missingPairedFlag = {
source: 'local' as const,
skipStoreHooks: false,
- // @ts-expect-error — `context.paired: true` is required by PairedWriteOrigin
context: { origin: 'forgot-the-marker' },
+ // @ts-expect-error — `context.paired: true` is required by PairedWriteOrigin
} as const satisfies PairedWriteOrigin;
void _missingPairedFlag;
const _pairedFalseRejected = {
source: 'local' as const,
skipStoreHooks: false,
- // @ts-expect-error — `paired: false` violates `paired: true`
context: { origin: 'wrong-value', paired: false },
+ // @ts-expect-error — `paired: false` violates `paired: true`
} as const satisfies PairedWriteOrigin;
void _pairedFalseRejected;
-
-describe('PairedWriteOrigin (compile-time assertions)', () => {
- test('all four paired origins carry the type-level brand', () => {});
-});
diff --git a/packages/server/src/polled-watcher-contract.test.ts b/packages/server/src/polled-watcher-contract.test.ts
index 2bd4eccc8..9808e5974 100644
--- a/packages/server/src/polled-watcher-contract.test.ts
+++ b/packages/server/src/polled-watcher-contract.test.ts
@@ -612,6 +612,7 @@ describe('startManagedArtifactWatcher when a SKILL.md or its skill directory goe
`onUnlink to report ${leaf('demo')} once its skill directory was deleted, which drops it from the listing`,
(reports) => unlinked(reports, leaf('demo')),
);
+ expect(unlinked(run.reports(), leaf('demo'))).toBe(true);
});
});
@@ -651,6 +652,7 @@ describe.skipIf(process.platform === 'win32' || process.geteuid?.() === 0)(
`onChange to report the edit of ${target} made once its directory was readable, after a start that met it unreadable`,
(reports) => delivered(reports, target, READABLE_AGAIN),
);
+ expect(delivered(run.reports(), target, READABLE_AGAIN)).toBe(true);
},
);
},
diff --git a/packages/server/src/principal.test.ts b/packages/server/src/principal.test.ts
index 8047456d6..600d07402 100644
--- a/packages/server/src/principal.test.ts
+++ b/packages/server/src/principal.test.ts
@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { loadPrincipal } from './principal.ts';
let tmpDir: string;
@@ -13,6 +13,7 @@ beforeEach(async () => {
});
afterEach(async () => {
+ vi.unstubAllEnvs();
await rm(tmpDir, { recursive: true, force: true });
});
@@ -78,9 +79,16 @@ describe('loadPrincipal — display field refresh', () => {
});
test('synthesized email has principal-<shortId>@openknowledge.local shape', async () => {
- const principal = await loadPrincipal(tmpDir);
- if (principal.source === 'synthesized') {
- expect(principal.display_email).toMatch(/@openknowledge\.local$/);
+ for (const key of Object.keys(process.env)) {
+ if (key.startsWith('GIT_')) vi.stubEnv(key, undefined);
}
+ const emptyGitConfig = resolve(tmpDir, 'empty.gitconfig');
+ writeFileSync(emptyGitConfig, '');
+ vi.stubEnv('GIT_CONFIG_GLOBAL', emptyGitConfig);
+ vi.stubEnv('GIT_CONFIG_NOSYSTEM', '1');
+
+ const principal = await loadPrincipal(tmpDir);
+ expect(principal.source).toBe('synthesized');
+ expect(principal.display_email).toMatch(/^principal-[0-9a-f]{8}@openknowledge\.local$/);
});
});
diff --git a/packages/server/src/process-lock.test.ts b/packages/server/src/process-lock.test.ts
index d37c69116..34bc931d2 100644
--- a/packages/server/src/process-lock.test.ts
+++ b/packages/server/src/process-lock.test.ts
@@ -572,7 +572,8 @@ describe('releaseProcessLock', () => {
});
test('no-op if lock does not exist', () => {
- releaseProcessLock({ lockName: LOCK_NAME, lockDir });
+ expect(() => releaseProcessLock({ lockName: LOCK_NAME, lockDir })).not.toThrow();
+ expect(existsSync(lockPath)).toBe(false);
});
test('refuses to remove a lock owned by a different pid', () => {
diff --git a/packages/server/src/seed/starter.test.ts b/packages/server/src/seed/starter.test.ts
index 9ff56dd6f..2fda8c4e5 100644
--- a/packages/server/src/seed/starter.test.ts
+++ b/packages/server/src/seed/starter.test.ts
@@ -300,17 +300,23 @@ describe('STARTER_PACKS — all packs structural validation', () => {
test('every rootFile body uses only v1 substitution tokens', () => {
const ALLOWED = new Set(['date', 'user']);
+ const unknownTokens: string[] = [];
for (const pack of Object.values(STARTER_PACKS)) {
for (const [filename, body] of Object.entries(pack.rootFiles ?? {})) {
const tokens = [...body.matchAll(/\{\{([^{}\n]+?)\}\}/g)].map((m) => (m[1] ?? '').trim());
for (const token of tokens) {
- expect(
- ALLOWED.has(token),
- `Pack "${pack.id}" rootFile "${filename}" uses unknown token "{{${token}}}" — only {{date}} and {{user}} are allowed in v1.`,
- ).toBe(true);
+ if (!ALLOWED.has(token)) {
+ unknownTokens.push(
+ `Pack "${pack.id}" rootFile "${filename}" uses unknown token "{{${token}}}"`,
+ );
+ }
}
}
}
+ expect(
+ unknownTokens,
+ `Only {{date}} and {{user}} are allowed in v1.\n${unknownTokens.join('\n')}`,
+ ).toEqual([]);
});
test('every rootFile key is a safe relative path (forward-slash nesting allowed, no escape)', () => {
diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.ts
index ff0e52cc6..2729487e4 100644
--- a/packages/server/src/server-factory.test.ts
+++ b/packages/server/src/server-factory.test.ts
@@ -1648,24 +1648,6 @@ describe('createServer() degraded signal', () => {
_resetDocExtensionsForTests();
}
});
-
- test('degraded is readonly — push and reassignment are compile-time errors', async () => {
- const contentDir = mkdtempSync(resolve(testProjectDir, 'content-'));
- const srv: ServerInstance = createServer({
- contentDir,
- projectDir: testProjectDir,
- quiet: true,
- });
-
- // @ts-expect-error — readonly array: push is not allowed
- srv.degraded.push('test');
-
- // @ts-expect-error — readonly field: reassignment is not allowed
- srv.degraded = [];
-
- await srv.ready;
- await srv.destroy();
- });
});
describe('createServer() — config-doc admission (US-005)', () => {
@@ -3106,9 +3088,11 @@ describe('createServer() — config-doc admission guard', () => {
try {
await server.ready;
const guard = getConfigDocAdmissionGuard(server);
- await guard.onAuthenticate(
- makePayload({ documentName: 'some-user-doc', peer: undefined, host: null }),
- );
+ await expect(
+ guard.onAuthenticate(
+ makePayload({ documentName: 'some-user-doc', peer: undefined, host: null }),
+ ),
+ ).resolves.toBeUndefined();
} finally {
await server.destroy();
}
@@ -3119,13 +3103,15 @@ describe('createServer() — config-doc admission guard', () => {
try {
await server.ready;
const guard = getConfigDocAdmissionGuard(server);
- await guard.onAuthenticate(
- makePayload({
- documentName: '__config__/project',
- peer: '127.0.0.1',
- host: 'localhost:5173',
- }),
- );
+ await expect(
+ guard.onAuthenticate(
+ makePayload({
+ documentName: '__config__/project',
+ peer: '127.0.0.1',
+ host: 'localhost:5173',
+ }),
+ ),
+ ).resolves.toBeUndefined();
} finally {
await server.destroy();
}
@@ -3136,9 +3122,11 @@ describe('createServer() — config-doc admission guard', () => {
try {
await server.ready;
const guard = getConfigDocAdmissionGuard(server);
- await guard.onAuthenticate(
- makePayload({ documentName: '__user__/config.yml', peer: '::1', host: '[::1]:5173' }),
- );
+ await expect(
+ guard.onAuthenticate(
+ makePayload({ documentName: '__user__/config.yml', peer: '::1', host: '[::1]:5173' }),
+ ),
+ ).resolves.toBeUndefined();
} finally {
await server.destroy();
}
@@ -3288,9 +3276,11 @@ describe('createServer() — config-doc admission guard', () => {
try {
await server.ready;
const guard = getConfigDocAdmissionGuard(server);
- await guard.onAuthenticate(
- makePayload({ documentName: '__config__/project', peer: undefined, host: 'localhost' }),
- );
+ await expect(
+ guard.onAuthenticate(
+ makePayload({ documentName: '__config__/project', peer: undefined, host: 'localhost' }),
+ ),
+ ).resolves.toBeUndefined();
} finally {
await server.destroy();
}
@@ -3325,15 +3315,17 @@ describe('createServer() — config-doc admission guard', () => {
try {
await server.ready;
const guard = getConfigDocAdmissionGuard(server);
- await guard.onAuthenticate({
- token: undefined,
- documentName: '__config__/project',
- context: {},
- request: {
- socket: { remoteAddress: '127.0.0.1' },
- headers: { host: 'localhost:5173' },
- },
- } as unknown as Parameters<typeof guard.onAuthenticate>[0]);
+ await expect(
+ guard.onAuthenticate({
+ token: undefined,
+ documentName: '__config__/project',
+ context: {},
+ request: {
+ socket: { remoteAddress: '127.0.0.1' },
+ headers: { host: 'localhost:5173' },
+ },
+ } as unknown as Parameters<typeof guard.onAuthenticate>[0]),
+ ).resolves.toBeUndefined();
} finally {
await server.destroy();
}
diff --git a/packages/server/src/server-factory.type-tests.ts b/packages/server/src/server-factory.type-tests.ts
new file mode 100644
index 000000000..72bc275f5
--- /dev/null
+++ b/packages/server/src/server-factory.type-tests.ts
@@ -0,0 +1,9 @@
+import type { ServerInstance } from './server-factory.ts';
+
+declare const server: ServerInstance;
+
+// @ts-expect-error — readonly array: push is not allowed
+server.degraded.push('test');
+
+// @ts-expect-error — readonly field: reassignment is not allowed
+server.degraded = [];
diff --git a/packages/server/src/server-lock.test.ts b/packages/server/src/server-lock.test.ts
index aca571bc7..baf10a09c 100644
--- a/packages/server/src/server-lock.test.ts
+++ b/packages/server/src/server-lock.test.ts
@@ -257,7 +257,8 @@ describe('releaseServerLock', () => {
});
test('no-op if lock does not exist', () => {
- releaseServerLock(lockDir);
+ expect(() => releaseServerLock(lockDir)).not.toThrow();
+ expect(existsSync(lockPath)).toBe(false);
});
test('refuses to remove a lock owned by a different pid', () => {
diff --git a/packages/server/src/shadow-lock.test.ts b/packages/server/src/shadow-lock.test.ts
index f9d123142..50e5adda9 100644
--- a/packages/server/src/shadow-lock.test.ts
+++ b/packages/server/src/shadow-lock.test.ts
@@ -124,6 +124,7 @@ describe('releaseLock', () => {
const shadowDir = resolve(tmpDir, 'shadow');
mkdirSync(shadowDir, { recursive: true });
- releaseLock(shadowDir);
+ expect(() => releaseLock(shadowDir)).not.toThrow();
+ expect(existsSync(resolve(shadowDir, 'lock'))).toBe(false);
});
});
diff --git a/packages/server/src/shadow-repo.test.ts b/packages/server/src/shadow-repo.test.ts
index e4877d16b..23b16d672 100644
--- a/packages/server/src/shadow-repo.test.ts
+++ b/packages/server/src/shadow-repo.test.ts
@@ -99,7 +99,14 @@ describe('initShadowRepo', () => {
await git.raw('config', 'user.name', 'Test');
await git.raw('config', 'user.email', '[email protected]');
+ const gitignorePath = resolve(projectRoot, '.gitignore');
await initShadowRepo(projectRoot);
+ expect(existsSync(gitignorePath)).toBe(false);
+
+ const gitignore = 'node_modules/\n.env\n';
+ writeFileSync(gitignorePath, gitignore);
+ await initShadowRepo(projectRoot);
+ expect(readFileSync(gitignorePath, 'utf-8')).toBe(gitignore);
});
test('is idempotent — second call does not error', async () => {
diff --git a/packages/server/src/sync-handshake-span-extension.test.ts b/packages/server/src/sync-handshake-span-extension.test.ts
index 0443d50b8..3b478e256 100644
--- a/packages/server/src/sync-handshake-span-extension.test.ts
+++ b/packages/server/src/sync-handshake-span-extension.test.ts
@@ -218,9 +218,15 @@ describe('sync.handshake span — OTel SDK fault isolation', () => {
} as any;
trace.setGlobalTracerProvider(faultyProvider);
- const extension = createSyncHandshakeSpanExtension();
- await extension.afterLoadDocument?.(makePayload({ documentName: 'README', mountId: UUID_A }));
- trace.disable();
- setupExporter();
+ try {
+ const extension = createSyncHandshakeSpanExtension();
+ expect(extension.afterLoadDocument).toBeTypeOf('function');
+ await expect(
+ extension.afterLoadDocument?.(makePayload({ documentName: 'README', mountId: UUID_A })),
+ ).resolves.toBeUndefined();
+ } finally {
+ trace.disable();
+ setupExporter();
+ }
});
});
diff --git a/packages/server/src/telemetry.test.ts b/packages/server/src/telemetry.test.ts
index f09f0819d..4c86b6ed2 100644
--- a/packages/server/src/telemetry.test.ts
+++ b/packages/server/src/telemetry.test.ts
@@ -269,7 +269,7 @@ describe('Telemetry', () => {
describe('shutdownTelemetry', () => {
it('is idempotent — calling twice does not throw', async () => {
await shutdownTelemetry();
- await shutdownTelemetry();
+ await expect(shutdownTelemetry()).resolves.toBeUndefined();
});
it('completes after enabled-push init without throwing', async () => {
@@ -280,12 +280,12 @@ describe('Telemetry', () => {
} finally {
process.env.OTEL_SDK_DISABLED = saved;
}
- await shutdownTelemetry();
+ await expect(shutdownTelemetry()).resolves.toBeUndefined();
});
it('completes after file-sink-only init without throwing', async () => {
initTelemetry({ localSink: makeLocalSinkOpts(tmp) });
- await shutdownTelemetry();
+ await expect(shutdownTelemetry()).resolves.toBeUndefined();
});
it('completes after both-pipelines init without throwing', async () => {
@@ -296,7 +296,7 @@ describe('Telemetry', () => {
} finally {
process.env.OTEL_SDK_DISABLED = saved;
}
- await shutdownTelemetry();
+ await expect(shutdownTelemetry()).resolves.toBeUndefined();
});
it('clears its timeout timer on fast-path resolve (no event-loop hold)', async () => {
diff --git a/test-support/fixtures/no-net-connect/no-net-connect.fixture.ts b/test-support/fixtures/no-net-connect/no-net-connect.fixture.ts
index e451d29bf..11516947b 100644
--- a/test-support/fixtures/no-net-connect/no-net-connect.fixture.ts
+++ b/test-support/fixtures/no-net-connect/no-net-connect.fixture.ts
@@ -29,7 +29,8 @@ if (process.env.OK_FIXTURE_COLLECTION_BLOCK === '1') {
}
test('swallowed undeclared forbidden fetch fails', async () => {
- await captureBlockedRequest('undeclared.invalid');
+ const error = await captureBlockedRequest('undeclared.invalid');
+ expect(error).toBeInstanceOf(NetConnectBlockedError);
});
test('declared exact hostname block passes', async () => {
@@ -39,7 +40,7 @@ test('declared exact hostname block passes', async () => {
});
test('unused hostname expectation fails', () => {
- expectBlockedNetworkRequest('unused.invalid');
+ expect(() => expectBlockedNetworkRequest('unused.invalid')).not.toThrow();
});
test('mismatched hostname expectation fails', async () => {
@@ -104,26 +105,43 @@ describe('suite hook declarations cannot authorize sibling suite blocks', () =>
});
describe('a block that lands after its scope drained is reported, not enforced', () => {
+ let resolveOrphan: (outcome: unknown) => void;
+ let resolveLateDeclaration: (outcome: unknown) => void;
+ const orphanOutcome = new Promise<unknown>((resolve) => {
+ resolveOrphan = resolve;
+ });
+ const lateDeclarationOutcome = new Promise<unknown>((resolve) => {
+ resolveLateDeclaration = resolve;
+ });
+
test('schedules a forbidden fetch that lands after it returns', () => {
- setTimeout(() => {
- void fetch('https://orphan.invalid/resource').catch(() => {});
- }, 10);
+ expect(() => {
+ setTimeout(() => {
+ void fetch('https://orphan.invalid/resource').then(resolveOrphan, resolveOrphan);
+ }, 10);
+ }).not.toThrow();
});
test('schedules a late declaration that cannot re-open its scope', () => {
- setTimeout(() => {
- expectBlockedNetworkRequest('late-declaration.invalid');
- void fetch('https://late-declaration.invalid/resource').catch(() => {});
- }, 10);
+ expect(() => {
+ setTimeout(() => {
+ expectBlockedNetworkRequest('late-declaration.invalid');
+ void fetch('https://late-declaration.invalid/resource').then(
+ resolveLateDeclaration,
+ resolveLateDeclaration,
+ );
+ }, 10);
+ }).not.toThrow();
});
test('a later test gives the orphan time to land', async () => {
- await new Promise((resolve) => setTimeout(resolve, 250));
+ await expect(orphanOutcome).resolves.toBeInstanceOf(NetConnectBlockedError);
+ await expect(lateDeclarationOutcome).resolves.toBeInstanceOf(NetConnectBlockedError);
});
});
test('unrelated console error passes', () => {
- console.error('fixture diagnostic unrelated to network blocking');
+ expect(() => console.error('fixture diagnostic unrelated to network blocking')).not.toThrow();
});
describe('concurrent siblings isolate exact hostname expectations', () => {
@@ -136,7 +154,7 @@ describe('concurrent siblings isolate exact hostname expectations', () => {
releaseBeta = resolve;
});
- test.concurrent('alpha request', async () => {
+ test.concurrent('alpha request', async ({ expect }) => {
expectBlockedNetworkRequest('alpha.invalid');
releaseAlpha?.();
await betaDeclared;
@@ -144,7 +162,7 @@ describe('concurrent siblings isolate exact hostname expectations', () => {
expect(error).toBeInstanceOf(NetConnectBlockedError);
});
- test.concurrent('beta request', async () => {
+ test.concurrent('beta request', async ({ expect }) => {
await alphaDeclared;
expectBlockedNetworkRequest('beta.invalid');
releaseBeta?.();
@@ -171,19 +189,19 @@ describe('concurrent unexpected block stays with its owning test', () => {
releaseInnocentDone = resolve;
});
- test.concurrent('offender swallows its unexpected block', async () => {
+ test.concurrent('offender swallows its unexpected block', async ({ expect }) => {
releaseOffenderStarted?.();
await innocentReady;
- await captureBlockedRequest('concurrent-offender.invalid');
+ const error = await captureBlockedRequest('concurrent-offender.invalid');
releaseOffenderBlocked?.();
await innocentDone;
+ expect(error).toBeInstanceOf(NetConnectBlockedError);
});
- test.concurrent('innocent sibling passes', async () => {
+ test.concurrent('innocent sibling passes', async ({ expect }) => {
await offenderStarted;
releaseInnocentReady?.();
- await offenderBlocked;
- expect(true).toBe(true);
+ await expect(offenderBlocked).resolves.toBeUndefined();
releaseInnocentDone?.();
});
});
diff --git a/test-support/vitest.base.ts b/test-support/vitest.base.ts
index bf2d6f825..461e4afcc 100644
--- a/test-support/vitest.base.ts
+++ b/test-support/vitest.base.ts
@@ -40,6 +40,7 @@ export const okVitestBase = {
testTimeout: 30_000,
hookTimeout: 30_000,
env: { DO_NOT_TRACK: '1' },
+ expect: { requireAssertions: true },
tags: [
{
name: 'known-bug',