Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Prevent seed docs presence leaks (PRD-9706) (#7252)
Nick Gomezd702bff203ca
diff --git a/packages/app/tests/stress/_helpers/fixtures.ts b/packages/app/tests/stress/_helpers/fixtures.tsindex d1c8dc253..f45adf12c 100644--- a/packages/app/tests/stress/_helpers/fixtures.ts+++ b/packages/app/tests/stress/_helpers/fixtures.ts@@ -56,15 +56,21 @@ export function isConcurrentOverwriteRefusal(error: unknown): boolean {}async function problemError(res: Response, message: string): Promise<ProblemError> {- let body: { type?: unknown } | null = null;+ let body: { type?: unknown; title?: unknown; detail?: unknown } | null = null;let parseFailure: unknown;try {- body = (await res.json()) as { type?: unknown };+ body = (await res.json()) as { type?: unknown; title?: unknown; detail?: unknown };} catch (error) {parseFailure = error;}+ const problem = [body?.type, body?.title, body?.detail].filter(+ (part): part is string => typeof part === 'string' && part.length > 0,+ );+ const fullMessage = problem.length > 0 ? `${message} (${problem.join('; ')})` : message;const err: ProblemError =- parseFailure === undefined ? new Error(message) : new Error(message, { cause: parseFailure });+ parseFailure === undefined+ ? new Error(fullMessage)+ : new Error(fullMessage, { cause: parseFailure });err.status = res.status;if (typeof body?.type === 'string') err.type = body.type;return err;@@ -690,6 +696,13 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({throw err;}}+ async function postTestReset(+ query: { scope: 'document'; docName?: string } | { scope: 'presence' },+ ): Promise<void> {+ const search = new URLSearchParams(query).toString();+ const res = await post(`/api/test-reset?${search}`);+ if (!res.ok) throw await problemError(res, `test-reset?${search} failed: ${res.status}`);+ }const helpers: ApiHelpers = {async createPage(path: string): Promise<void> {const res = await post('/api/create-page', { path });@@ -722,12 +735,7 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({}},async testReset(docName?: string): Promise<void> {- const res = await post(- docName ? `/api/test-reset?docName=${encodeURIComponent(docName)}` : '/api/test-reset',- );- if (!res.ok) {- throw new Error(`test-reset failed${docName ? ` for ${docName}` : ''}: ${res.status}`);- }+ await postTestReset({ scope: 'document', ...(docName !== undefined ? { docName } : {}) });},async seedDocs(docs: Array<{ name: string; markdown: string }>): Promise<void> {await resetContentToFixtureBaseline(baseURL, workerServer.contentDir);@@ -737,6 +745,7 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({await helpers.createPage(/\.(md|mdx)$/i.test(d.name) ? d.name : `${d.name}.md`);}for (const d of docs) await helpers.replaceDoc(docNameOf(d.name), d.markdown);+ await postTestReset({ scope: 'presence' });await waitForSeededPagesSettled(baseURL,docs.map((d) => docNameOf(d.name)),diff --git a/packages/app/tests/stress/multi-agent-presence.e2e.ts b/packages/app/tests/stress/multi-agent-presence.e2e.tsindex 95d5d556f..b0d485d52 100644--- a/packages/app/tests/stress/multi-agent-presence.e2e.ts+++ b/packages/app/tests/stress/multi-agent-presence.e2e.ts@@ -1,3 +1,5 @@+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';import { CONCURRENT_REPLACE_WINDOW_MS } from '@inkeep/open-knowledge-server';import {expect,@@ -11,6 +13,35 @@ function agentId(label: string): string {}test.describe('multi-agent presence — sectioned PresenceBar (FR-9)', () => {+ test('seeding docs publishes no unrequested agent presence', async ({ api, baseURL }) => {+ await api.seedDocs([{ name: 'seed-presence-contract', markdown: '# seeded' }]);++ const response = await fetch(`${baseURL}/api/metrics/agent-presence`);+ expect(response.ok).toBe(true);+ expect(await response.json()).toEqual({ presence: {} });+ });++ test('seeding docs keeps the project config the caller wrote before seeding', async ({+ api,+ workerServer,+ }) => {+ const configDir = join(workerServer.contentDir, '.ok');+ const configPath = join(configDir, 'config.yml');+ const originalConfig = existsSync(configPath) ? readFileSync(configPath) : null;+ const callerConfig = 'contentRules:\n markdownlint:\n enabled: true\n';+ mkdirSync(configDir, { recursive: true });+ writeFileSync(configPath, callerConfig, 'utf-8');+ try {+ await api.seedDocs([{ name: 'seed-config-contract', markdown: '# seeded' }]);++ expect(existsSync(configPath)).toBe(true);+ expect(readFileSync(configPath, 'utf-8')).toBe(callerConfig);+ } finally {+ if (originalConfig !== null) writeFileSync(configPath, originalConfig);+ else rmSync(configPath, { force: true });+ }+ });+test('two distinct agents on the same doc render as two badges (bug-bash repro)', async ({page,api,diff --git a/packages/server/src/http/test-routes.test.ts b/packages/server/src/http/test-routes.test.tsindex 27331690c..0ecab6d65 100644--- a/packages/server/src/http/test-routes.test.ts+++ b/packages/server/src/http/test-routes.test.ts@@ -1,8 +1,10 @@-import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import type { Hocuspocus } from '@hocuspocus/server';+import type { Document, Hocuspocus } from '@hocuspocus/server';+import { type AgentPresenceEntry, SYSTEM_DOC_NAME } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test } from 'vitest';+import { AgentPresenceBroadcaster } from '../agent-presence.ts';import type { AgentSessionManager } from '../agent-sessions.ts';import { makeCaptureRes, makeSyntheticReq } from '../composition-rig.test-helper.ts';import type { ConflictAuthority } from '../conflict-authority.ts';@@ -141,8 +143,147 @@ describe('POST /api/test-reset scope', () => {expect(captured.status).toBe(400);expect(JSON.parse(captured.body)).toMatchObject({type: 'urn:ok:error:invalid-request',- title: 'scope must be one of document, server.',+ title: 'scope must be one of document, server, presence.',});expect(readFileSync(join(contentDir, 'test-doc.md'), 'utf-8')).toBe('kept\n');});});++function presenceEntry(displayName: string): AgentPresenceEntry {+ return {+ displayName,+ icon: 'claude',+ color: '#D97757',+ currentDoc: 'seeded.md',+ mode: 'writing',+ ts: Date.now(),+ };+}++function presenceResetRig() {+ const contentDir = contentDirWithTestDoc('kept\n');+ mkdirSync(join(contentDir, '.ok'), { recursive: true });+ writeFileSync(+ join(contentDir, '.ok', 'config.yml'),+ 'contentRules:\n markdownlint:\n enabled: true\n',+ 'utf-8',+ );+ writeFileSync(join(contentDir, '.okignore'), 'kept-by-caller/\n', 'utf-8');++ let awarenessState: Record<string, unknown> | null = null;+ const awareness = {+ getLocalState: () => awarenessState,+ setLocalState: (next: Record<string, unknown> | null) => {+ awarenessState = next;+ },+ };+ const documents = new Map<string, Document>([+ [SYSTEM_DOC_NAME, { name: SYSTEM_DOC_NAME, awareness } as unknown as Document],+ ['test-doc', { name: 'test-doc', getConnections: () => [{}] } as unknown as Document],+ ['seeded', { name: 'seeded', getConnections: () => [{}] } as unknown as Document],+ ]);+ const closedConnections: Array<string | undefined> = [];+ const closedSessions: Array<string | undefined> = [];+ const unloadedDocuments: string[] = [];+ let settingsResets = 0;+ const hocuspocus = {+ documents,+ debouncer: { isDebounced: () => false, executeNow: async () => {} },+ closeConnections: (docName?: string) => {+ closedConnections.push(docName);+ },+ unloadDocument: async (document: Document) => {+ unloadedDocuments.push(document.name);+ },+ } as unknown as Hocuspocus;+ const agentPresence = new AgentPresenceBroadcaster(hocuspocus);+ agentPresence.setPresence('claude-1', presenceEntry('Claude'));+ agentPresence.setPresence('agent-seeded', presenceEntry('Seeded agent'));++ const group = buildGroup({+ contentDir,+ agentPresence,+ hocuspocus,+ resetSettingsForTest: () => {+ settingsResets++;+ },+ forceUnloadDocument: async (document: Document) => {+ unloadedDocuments.push(document.name);+ },+ sessionManager: {+ closeAll: async (docName?: string) => {+ closedSessions.push(docName);+ },+ liveSessionCount: 1,+ } as unknown as AgentSessionManager,+ durabilityState: {+ deleteReconciledBase: () => {},+ listStaleExternalWrites: () => [],+ } as unknown as TestRouteDeps['durabilityState'],+ conflicts: { dissolveReconcile: () => {} } as unknown as ConflictAuthority,+ });++ return {+ group,+ contentDir,+ agentPresence,+ documents,+ closedConnections,+ closedSessions,+ unloadedDocuments,+ settingsResets: () => settingsResets,+ };+}++describe('POST /api/test-reset scope=presence', () => {+ test('clears every agent presence and leaves sessions, connections, loaded documents, settings and files as the caller left them', async () => {+ const rig = presenceResetRig();+ expect(Object.keys(rig.agentPresence.getPresenceMap()).sort()).toEqual([+ 'agent-seeded',+ 'claude-1',+ ]);++ const captured = await postTestReset(rig.group, '?scope=presence');++ expect(captured.status).toBe(200);+ expect(rig.agentPresence.getPresenceMap()).toEqual({});+ expect(rig.closedSessions).toEqual([]);+ expect(rig.closedConnections).toEqual([]);+ expect(rig.unloadedDocuments).toEqual([]);+ expect([...rig.documents.keys()].sort()).toEqual(+ [SYSTEM_DOC_NAME, 'seeded', 'test-doc'].sort(),+ );+ expect(rig.settingsResets()).toBe(0);+ expect(readFileSync(join(rig.contentDir, 'test-doc.md'), 'utf-8')).toBe('kept\n');+ expect(readFileSync(join(rig.contentDir, '.ok', 'config.yml'), 'utf-8')).toBe(+ 'contentRules:\n markdownlint:\n enabled: true\n',+ );+ expect(readFileSync(join(rig.contentDir, '.okignore'), 'utf-8')).toBe('kept-by-caller/\n');+ });++ test.each([+ ['docName', 'docName=seeded'],+ ['reset-okignore', 'reset-okignore=false'],+ ])(+ 'a presence-scope reset naming %s is refused before anything is reset',+ async (parameter, query) => {+ const rig = presenceResetRig();++ const captured = await postTestReset(rig.group, `?scope=presence&${query}`);++ expect(captured.status).toBe(400);+ expect(JSON.parse(captured.body)).toMatchObject({+ type: 'urn:ok:error:invalid-request',+ title: `${parameter} cannot be combined with scope=presence: a presence-scope reset clears agent presence only.`,+ });+ expect(Object.keys(rig.agentPresence.getPresenceMap()).sort()).toEqual([+ 'agent-seeded',+ 'claude-1',+ ]);+ expect(rig.closedSessions).toEqual([]);+ expect(rig.closedConnections).toEqual([]);+ expect(rig.unloadedDocuments).toEqual([]);+ expect(readFileSync(join(rig.contentDir, 'test-doc.md'), 'utf-8')).toBe('kept\n');+ },+ );+});diff --git a/packages/server/src/http/test-routes.ts b/packages/server/src/http/test-routes.tsindex 89267b530..e8b00303b 100644--- a/packages/server/src/http/test-routes.ts+++ b/packages/server/src/http/test-routes.ts@@ -26,7 +26,8 @@ import { getRequestId } from './request-id.ts';import { withValidation } from './request-validation.ts';import { successResponse } from './success-response.ts';-const TEST_RESET_SCOPES = ['document', 'server'] as const;+const TEST_RESET_SCOPES = ['document', 'server', 'presence'] as const;+const PRESENCE_RESET_REFUSED_PARAMS = ['docName', 'reset-okignore'] as const;type TestResetScope = (typeof TEST_RESET_SCOPES)[number];interface TestServerResetResidue {@@ -99,14 +100,18 @@ export function createTestRoutes(deps: TestRouteDeps): ApiRouteGroup {return isSystemDoc(docName) || isConfigDoc(docName);}+ function clearAgentPresence(): void {+ for (const agentId of Object.keys(agentPresence?.getPresenceMap() ?? {})) {+ agentPresence?.clearPresence(agentId);+ }+ }+async function resetLoadedState(keep: string): Promise<void> {for (const docName of hocuspocus.documents.keys()) {if (docName === keep || isServerStateDoc(docName)) continue;await unloadDocumentForTest(docName);}- for (const agentId of Object.keys(agentPresence?.getPresenceMap() ?? {})) {- agentPresence?.clearPresence(agentId);- }+ clearAgentPresence();for (const [docName] of recentlyRemovedDocs?.entries() ?? []) {recentlyRemovedDocs?.delete(docName);}@@ -148,6 +153,24 @@ export function createTestRoutes(deps: TestRouteDeps): ApiRouteGroup {);return;}+ if (scope === 'presence') {+ const refusedParam = PRESENCE_RESET_REFUSED_PARAMS.find((param) =>+ url.searchParams.has(param),+ );+ if (refusedParam !== undefined) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ `${refusedParam} cannot be combined with scope=presence: a presence-scope reset clears agent presence only.`,+ { handler: 'test-reset' },+ );+ return;+ }+ clearAgentPresence();+ successResponse(res, 200, TestResetSuccessSchema, { scope }, { handler: 'test-reset' });+ return;+ }if (scope === 'server' && url.searchParams.has('reset-okignore')) {errorResponse(res,