diff --git a/cli/src/commands/brain-sources.ts b/cli/src/commands/brain-sources.ts deleted file mode 100644 index 7e6a7c1872..0000000000 --- a/cli/src/commands/brain-sources.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { apiFetch, CliError, EXIT } from '../api.js'; -import { resolveConfig } from '../config.js'; -import { printJson, type OutputMode } from '../output.js'; -export async function runBrainSources(mode: OutputMode, rest: string[]): Promise { - const [action = 'list', ...args] = rest; - if (!['list', 'add', 'remove'].includes(action)) throw new CliError('invalid_args', 'Use o8 brain sources list|add |remove .', EXIT.INVALID_ARGS); - const body: Record = { action }; - if (action === 'remove') body.id = args[0]; - if (action === 'add') { - body.path = args.shift(); - for (let i = 0; i < args.length; i += 2) { - const flag = args[i]; const value = args[i + 1]; - if (!value || !['--name', '--include', '--exclude'].includes(flag)) throw new CliError('invalid_args', 'Use --name, --include or --exclude with a value.', EXIT.INVALID_ARGS); - body[flag.slice(2)] = flag === '--name' ? value : value.split(',').map(p => p.trim()).filter(Boolean); - } - } - if (action !== 'list' && !body[action === 'add' ? 'path' : 'id']) throw new CliError('invalid_args', 'A folder or source ID is required.', EXIT.INVALID_ARGS); - const result = await apiFetch<{ sources: Array<{ id: string; name: string; path: string; state: string; facts: number }> }>(resolveConfig(), '/api/cortex/sources', action === 'list' ? {} : { method: 'POST', body }); - if (mode.human) for (const source of result.data?.sources ?? []) process.stdout.write(`${source.id} ${source.name} ${source.path} ${source.state} ${source.facts} facts\n`); - else printJson({ schema: 'o8/brain.sources/v1', ...result.data }); - return 0; -} diff --git a/cli/src/index.ts b/cli/src/index.ts index 481a7d746a..fe0f67560e 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -2,7 +2,6 @@ import { runIntegrationQueue } from './commands/integration-queue.js'; import { runPacketPolicy } from './commands/packet/policy.js'; import { runHeavy } from './commands/run-heavy.js'; import { runPrStack } from './commands/pr-stack.js'; -import { runBrainSources } from './commands/brain-sources.js'; import { runThreads } from './commands/threads.js'; import { runWorkspaceCleanup } from './commands/workspace-cleanup.js'; import { runNext } from './commands/next.js'; @@ -271,7 +270,6 @@ commands: broadcast automation-say|focus|post|token post from an automation, set focus, post narration, or manage spectator bearers msg send|inbox send a bounded agent message (--reply-to ID, --close) or read this session's inbox presence list|join list live sessions or register an explicit external name - brain sources manage read-only markdown knowledge folders cortex observe propose a worker observation for the orchestrator lane touches active lanes touching a path or packet diff worker spawn create + dispatch one governed worker from any Git repo (--title --body [--repo path] [--runtime id] [--model m] [--effort adaptive|low|medium|high|max|xhigh|ultra] [--caller label] [--read-only]) @@ -448,9 +446,6 @@ async function dispatch(args: ParsedArgs): Promise { return runMsg(args.mode, secondary, args.rest); case 'presence': return runPresence(args.mode, secondary, args.rest); - case 'brain': - if (secondary === 'sources') return runBrainSources(args.mode, args.rest); - throw unknownSubcommandError('brain', secondary); case 'cortex': { if (secondary === 'observe') return runCortexObserve(args.mode, args.rest); throw unknownSubcommandError('cortex', secondary); diff --git a/crates/o8d/route-templates.json b/crates/o8d/route-templates.json index 8101709b63..3f494d1dfe 100644 --- a/crates/o8d/route-templates.json +++ b/crates/o8d/route-templates.json @@ -38,7 +38,6 @@ "/api/cortex/proposals", "/api/cortex/recent-outcomes", "/api/cortex/reingest", - "/api/cortex/sources", "/api/devices/agent", "/api/github/webhook", "/api/lanes", diff --git a/docs/internals/next-settings-parity.md b/docs/internals/next-settings-parity.md index b4046d3b5b..2f969d1a18 100644 --- a/docs/internals/next-settings-parity.md +++ b/docs/internals/next-settings-parity.md @@ -119,7 +119,6 @@ the existing operator-defaults route unless another owner is named. | Indexing / Repositories | Every repository index status; Refresh docs; Retry | missing | present: repository status, per-repository refresh receipt, retry after error | | Indexing / Engineering Brain | Saved instructions; Recorded task outcomes; Knowledge storage | missing | partial: instruction/outcome totals present; knowledge storage details remain | | Indexing / Conversation history | Choose ZIP/JSON conversation export; Import conversation history; local profile/topic/unfinished-project summary | missing | skipped: account-export/profile ingestion review | -| Indexing / Knowledge sources | Folder; include patterns; exclude patterns; add/refresh/remove source and facts | missing | missing: source ingestion/redaction behavior skipped | | MCP / Clients | Claude Desktop, Claude Code, Hermes Agent, OpenClaw status; Install/Update/Remove | missing | skipped: writes authenticated client configuration | | MCP / External servers | Add command/URL/JSON; candidate edit/add; manual name/transport/command/args/env/URL; enable; worker/Symon injection; test; remove | missing | skipped: arbitrary environment, credentials and network endpoints | | MCP / ChatGPT task review | Held task; exact requirements; approve/deny review | missing | skipped: authorization | diff --git a/docs/operations/cli-agent-experience-audit.md b/docs/operations/cli-agent-experience-audit.md index 5b3561d678..0a3857c79a 100644 --- a/docs/operations/cli-agent-experience-audit.md +++ b/docs/operations/cli-agent-experience-audit.md @@ -105,7 +105,6 @@ Live native actions and destructive commands were not exercised. | `o8 broadcast --help` | 0 | missing | missing | missing | | `o8 msg --help` | 0 | missing | missing | missing | | `o8 presence --help` | 0 | missing | missing | missing | -| `o8 brain sources --help` | 0 | missing | missing | missing | | `o8 cortex observe --help` | 0 | missing | missing | missing | | `o8 lane touches --help` | 0 | missing | missing | missing | | `o8 artifact create --help` | 0 | missing | missing | missing | diff --git a/docs/operations/mcp-agent-experience-audit.md b/docs/operations/mcp-agent-experience-audit.md index a1ddbbbda8..2731824939 100644 --- a/docs/operations/mcp-agent-experience-audit.md +++ b/docs/operations/mcp-agent-experience-audit.md @@ -127,7 +127,6 @@ records discovery coverage, not a successful execution of every action. | `o8_packet_transcript` | packetId | none | limit | none | yes | | `steer_packet` | packetId, message | none | none explicit | none | missing | | `o8_operator_defaults` | none declared | 18 enum-bearing settings | includeReceipts, includeAuth, includeDetails, broadcastCommentaryIntervalMinutes, broadcastCommentaryMinNewEvents, broadcastCommentaryMaxPerHour, broadcastVoice, broadcastVoiceLullMinutes, meteredPacketCostCapUsd, meteredPacketInputTokenCap, uiLoopMaxIterations, uiLoopMaxMinutes, uiLoopMaxDiffBytes, uiLoopMaxDiffFiles, uiLoopPreviewTimeoutMs, defaultDispatchRuntime, defaultDispatchModel, requireApproval | none | yes | -| `cortex_knowledge_sources` | action | action | none explicit | action, path, name, id, include, exclude | missing | | `cortex_propose_observation` | packetId, kind, text | kind, scope | scope | none | missing | | `cortex_ask` | question | none | projectId, bypassCache, terse | none | missing | | `o8_feature_list` | repoPath | status | none explicit | status, limit | missing | diff --git a/scripts/server-bundle-budget.json b/scripts/server-bundle-budget.json index e60271be5c..0df8212090 100644 --- a/scripts/server-bundle-budget.json +++ b/scripts/server-bundle-budget.json @@ -854,8 +854,6 @@ "shared:entry:src/lib/cortex/directive-merges.ts": 2187, "shared:entry:src/lib/cortex/forget.ts": 7103, "shared:entry:src/lib/cortex/indexer/doc-watcher.ts": 9257, - "shared:entry:src/lib/cortex/knowledge/index.ts": 3194, - "shared:entry:src/lib/cortex/knowledge/sources-route.ts": 5094, "shared:entry:src/lib/cortex/qa/ask.ts": 3054, "shared:entry:src/lib/cortex/qa/llm/byok-keys.ts": 688, "shared:entry:src/lib/cortex/qa/llm/inference-route.ts": 1840, diff --git a/src/app/api/cortex/sources/route.ts b/src/app/api/cortex/sources/route.ts deleted file mode 100644 index 5131864b3b..0000000000 --- a/src/app/api/cortex/sources/route.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ownedByNativeTransport } from '@/lib/ws-server/native-owner'; -import type { NextRequest } from 'next/server'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; -const unavailable = () => Response.json({ error: 'Native owner unavailable.' }, { status: 503 }); -export const GET = ownedByNativeTransport(async request => (await import('@/lib/cortex/knowledge/sources-route')).GET(request as NextRequest), unavailable); -export const POST = ownedByNativeTransport(async request => (await import('@/lib/cortex/knowledge/sources-route')).POST(request as NextRequest), unavailable); diff --git a/src/lib/cortex/indexer/doc-watcher.ts b/src/lib/cortex/indexer/doc-watcher.ts index 24cb150712..25ca8ce20a 100644 --- a/src/lib/cortex/indexer/doc-watcher.ts +++ b/src/lib/cortex/indexer/doc-watcher.ts @@ -1,4 +1,3 @@ -import { ensureKnowledgeSourceWatcher, stopKnowledgeSourceWatcher } from '@/lib/cortex/knowledge'; import { chunkMarkdown } from './markdown-chunks'; /** * Doc-watcher — incremental re-distillation on file change (#964). @@ -452,7 +451,5 @@ function startRepoDocWatcher(): () => void { } export function startDocWatcher(): () => void { - ensureKnowledgeSourceWatcher(); - const stopDocs = startRepoDocWatcher(); - return () => { stopKnowledgeSourceWatcher(); stopDocs(); }; + return startRepoDocWatcher(); } diff --git a/src/lib/cortex/knowledge/answer-validity.ts b/src/lib/cortex/knowledge/answer-validity.ts deleted file mode 100644 index 8b0537e491..0000000000 --- a/src/lib/cortex/knowledge/answer-validity.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { readMemoryRevision } from '@/lib/cortex/memory-revision'; -import type { TypedRow } from '@/lib/cortex/qa/types'; -export class KnowledgeSourcesChangedError extends Error { - constructor() { super('Knowledge sources changed while answering. Ask again.'); this.name = 'KnowledgeSourcesChangedError'; } -} -export function assertKnowledgeAnswerCurrent(rows: TypedRow[], revision: string) { - if (rows.some(row => row.fields.sourceKind === 'knowledge') && revision !== readMemoryRevision()) throw new KnowledgeSourcesChangedError(); -} diff --git a/src/lib/cortex/knowledge/index.ts b/src/lib/cortex/knowledge/index.ts deleted file mode 100644 index 5b7cda507b..0000000000 --- a/src/lib/cortex/knowledge/index.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { createHash, randomUUID } from 'node:crypto'; -import { watch } from 'node:fs'; -import path from 'node:path'; -import { getSqlite } from '@/lib/db'; -import { ensureKnowledgeChunksSchema } from '@/lib/db/v83-runtime-tables-migration'; -import { distillDocChunkBatch } from '@/lib/cortex/indexer/doc-distill'; -import { chunkMarkdown } from '@/lib/cortex/indexer/markdown-chunks'; -import { advanceMemoryRevision } from '@/lib/cortex/memory-revision'; -import { invalidateAnswerCache } from '@/lib/cortex/qa/ask'; -import type { KnowledgeSource } from '@/lib/operator/knowledge-source-defaults'; -import { getOperatorDefaultsTomlPath } from '@/lib/settings/operator-defaults-store'; -import { configuredKnowledgeSources } from './sources'; -import { readNotes, secretChunk } from './read-notes'; -import { recurring } from '@/lib/background-work/ledger'; - -const generations = new Map(); -const status = new Map(); -let work: Promise = Promise.resolve(); -let lifecycle = 0; -let watcherStop: (() => void) | undefined; -export function ensureKnowledgeSourceWatcher() { if (process.env.O8_DISABLE_DOC_WATCH !== '1') watcherStop ??= startKnowledgeSourceWatcher(); } -export function stopKnowledgeSourceWatcher() { watcherStop?.(); watcherStop = undefined; } -function tables() { - const db = getSqlite(); - ensureKnowledgeChunksSchema(db); - return db; -} -function changedMemory() { advanceMemoryRevision(getSqlite()); invalidateAnswerCache(); } -export function invalidateKnowledgeSource(id: string) { generations.set(id, (generations.get(id) ?? 0) + 1); } -export function forgetKnowledgeSource(id: string): void { - invalidateKnowledgeSource(id); - const db = tables(); - db.transaction(() => { - db.prepare("DELETE FROM facts WHERE source_kind = 'knowledge' AND source_id IN (SELECT source_id FROM knowledge_chunks WHERE source = ?)").run(id); - db.prepare('DELETE FROM knowledge_chunks WHERE source = ?').run(id); - changedMemory(); - })(); - status.delete(id); -} -export function knowledgeSourceState(source: KnowledgeSource) { - const db = tables(); - const row = db.prepare("SELECT count(*) AS count FROM facts WHERE source_kind = 'knowledge' AND source_id IN (SELECT source_id FROM knowledge_chunks WHERE source = ?)").get(source.id) as { count: number }; - return { ...source, ...(status.get(source.id) ?? { state: 'ready' as const }), facts: row.count }; -} -export function knowledgeProvenance(sourceId: string) { - const row = tables().prepare('SELECT source, relative_path, title, wiki_links FROM knowledge_chunks WHERE source_id = ?').get(sourceId) as { source: string; relative_path: string; title: string; wiki_links: string } | undefined; - const source = row && configuredKnowledgeSources().find(s => s.id === row.source); - if (!source || !row) return null; - return { title: row.title, sourceName: source.name, sourcePath: path.join(source.path, row.relative_path), wikiLinks: JSON.parse(row.wiki_links) as string[] }; -} -async function indexSource(source: KnowledgeSource): Promise { - const generation = generations.get(source.id) ?? 0; - const current = () => (generations.get(source.id) ?? 0) === generation - && configuredKnowledgeSources().some(s => JSON.stringify(s) === JSON.stringify(source)); - if (!current()) return; - status.set(source.id, { state: 'indexing' }); - try { - const { notes } = readNotes(source); const db = tables(); const retained = new Set(); - for (const note of notes) { - if (!current()) return; - const chunks = chunkMarkdown(note.body); - const safe = chunks.filter(chunk => !secretChunk(chunk.text) && !chunk.headingPath.some(secretChunk) && !secretChunk(note.relativePath) && !secretChunk(source.name)); - const ids = safe.map(c => `knowledge:${source.id}:${encodeURIComponent(note.relativePath)}:${c.chunkIdx}`); - ids.forEach(id => retained.add(id)); - const title = secretChunk(note.title) ? 'Notes' : note.title; - const links = JSON.stringify(note.wikiLinks.filter(link => !secretChunk(link))); - const metadataChanged = (db.prepare('SELECT title, wiki_links FROM knowledge_chunks WHERE source = ? AND relative_path = ? LIMIT 1').get(source.id, note.relativePath) as { title: string; wiki_links: string } | undefined); - const old = db.prepare('SELECT source_id FROM knowledge_chunks WHERE source = ? AND relative_path = ?').all(source.id, note.relativePath) as Array<{ source_id: string }>; - // Deletions and newly sensitive chunks stop being retrievable before any inference. - db.transaction(() => { for (const row of old) if (!ids.includes(row.source_id)) { - db.prepare("DELETE FROM facts WHERE source_kind = 'knowledge' AND source_id = ?").run(row.source_id); - db.prepare('DELETE FROM knowledge_chunks WHERE source_id = ?').run(row.source_id); - changedMemory(); - } })(); - const pending = safe.map((chunk, i) => ({ ...chunk, id: ids[i], hash: createHash('sha256').update(JSON.stringify([source.name, note.relativePath, chunk.headingPath, chunk.text])).digest('hex') })); - const changed = pending.filter(chunk => (db.prepare('SELECT text_hash FROM knowledge_chunks WHERE source_id = ?').get(chunk.id) as { text_hash: string } | undefined)?.text_hash !== chunk.hash); - const result = changed.length ? await distillDocChunkBatch({ chunks: changed.map(c => ({ id: c.id, repoName: source.name, - relPath: note.relativePath, headingPath: c.headingPath, text: c.text })), timeoutMs: 240_000 }) : { factsByChunkId: new Map() }; - if (!current()) return; - db.transaction(() => { - for (const chunk of pending) { - if (changed.some(c => c.id === chunk.id)) { - db.prepare("DELETE FROM facts WHERE source_kind = 'knowledge' AND source_id = ?").run(chunk.id); - for (const fact of result.factsByChunkId.get(chunk.id) ?? []) { - if (fact.confidence < 0.6 || !Number.isFinite(fact.confidence) || !fact.source_excerpt || !chunk.text.includes(fact.source_excerpt) - || secretChunk(fact.content) || secretChunk(fact.source_excerpt)) continue; - db.prepare(`INSERT INTO facts (id, kind, content, source_kind, source_id, source_excerpt, repo_path, confidence, fingerprint, extracted_by, source_authority) - VALUES (?, ?, ?, 'knowledge', ?, ?, NULL, ?, ?, 'doc-distiller', 0.85) ON CONFLICT(fingerprint) DO NOTHING`).run(randomUUID(), fact.kind, fact.content, chunk.id, fact.source_excerpt, - fact.confidence, createHash('sha256').update(chunk.id + '\n' + fact.content).digest('hex')); - } - } - db.prepare(`INSERT INTO knowledge_chunks (source_id, source, relative_path, title, wiki_links, text_hash) VALUES (?, ?, ?, ?, ?, ?) - ON CONFLICT(source_id) DO UPDATE SET title=excluded.title, wiki_links=excluded.wiki_links, text_hash=excluded.text_hash`) - .run(chunk.id, source.id, note.relativePath, title, links, chunk.hash); - } - if (changed.length || metadataChanged?.title !== title || metadataChanged?.wiki_links !== links) changedMemory(); - })(); - } - if (!current()) return; - db.transaction(() => { - for (const row of db.prepare('SELECT source_id FROM knowledge_chunks WHERE source = ?').all(source.id) as Array<{ source_id: string }>) { - if (retained.has(row.source_id)) continue; - db.prepare("DELETE FROM facts WHERE source_kind = 'knowledge' AND source_id = ?").run(row.source_id); - db.prepare('DELETE FROM knowledge_chunks WHERE source_id = ?').run(row.source_id); changedMemory(); - } - })(); - status.set(source.id, { state: 'ready' }); - } catch { if (current()) status.set(source.id, { state: 'error', error: 'This folder could not be indexed. Check its path, patterns and connected Brain runtime, then retry.' }); } -} -export function indexKnowledgeSources(): Promise { - configuredKnowledgeSources().forEach(s => status.set(s.id, { state: 'indexing' })); - const epoch = lifecycle; - work = work.catch(() => {}).then(async () => { - if (epoch !== lifecycle) return; - const sources = configuredKnowledgeSources(); - const db = tables(); - for (const row of db.prepare('SELECT DISTINCT source FROM knowledge_chunks').all() as Array<{ source: string }>) { - if (!sources.some(s => s.id === row.source)) forgetKnowledgeSource(row.source); - } - for (const source of sources) await indexSource(source); - }); - return work; -} -/** Same server lifecycle as the repository doc watcher; all handles read source folders only. */ -export function startKnowledgeSourceWatcher(): () => void { - let stopped = false; let timer: ReturnType | undefined; - let handles: ReturnType[] = []; - const queue = () => { if (stopped) return; if (timer) clearTimeout(timer); timer = setTimeout(() => { void synchronize(); }, 2_000); }; - const synchronize = async () => { - if (stopped) return; - handles.forEach(h => h.close()); handles = []; - const sources = configuredKnowledgeSources(); - for (const source of sources) { - try { for (const dir of readNotes(source).directories) { const h = watch(dir, queue); h.on('error', queue); h.unref(); handles.push(h); } } catch { /* Index status reports unreadable sources. */ } - } - const settings = getOperatorDefaultsTomlPath(); - try { const h = watch(path.dirname(settings), (_event, name) => { if (name?.toString() === path.basename(settings)) queue(); }); h.on('error', queue); h.unref(); handles.push(h); } catch { /* The add route also starts an index job. */ } - await indexKnowledgeSources(); - }; - const rescan = recurring('knowledge-rescan', queue, 60_000); rescan.unref(); - void synchronize(); - return () => { clearInterval(rescan); stop(); }; - function stop() { stopped = true; lifecycle += 1; if (timer) clearTimeout(timer); handles.forEach(h => h.close()); configuredKnowledgeSources().forEach(s => invalidateKnowledgeSource(s.id)); } -} diff --git a/src/lib/cortex/knowledge/read-notes.ts b/src/lib/cortex/knowledge/read-notes.ts deleted file mode 100644 index 42dbce337f..0000000000 --- a/src/lib/cortex/knowledge/read-notes.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readdirSync, realpathSync } from 'node:fs'; -import path from 'node:path'; -import { redactSecrets } from '@/lib/telemetry/scrub'; -import { redactBroadcastText } from '@/lib/broadcast/redaction'; -import type { KnowledgeSource } from '@/lib/operator/knowledge-source-defaults'; -import { canonicalSource, containsPath } from './sources'; - -export interface Note { relativePath: string; title: string; wikiLinks: string[]; body: string } -export function secretChunk(text: string): boolean { - return redactSecrets(text) !== text || redactBroadcastText(text) !== text - || /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----|\b(?:gh[pousr]_|github_pat_|sk-(?:ant-|proj-|or-)?)[A-Za-z0-9_-]{16,}/.test(text); -} -function matches(pattern: string, relative: string): boolean { - const parts = pattern.split('/'); - let expression = '^'; - parts.forEach((segment, index) => { - if (segment === '**') expression += index === parts.length - 1 ? '.*' : '(?:[^/]+/)*'; - else { - expression += [...segment].map(c => c === '*' ? '[^/]*' : c === '?' ? '[^/]' : c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join(''); - if (index < parts.length - 1) expression += '/'; - } - }); - return new RegExp(expression + '$').test(relative); -} -function safeRead(root: string, file: string): string | null { - let fd: number | undefined; - try { - const rootStat = lstatSync(root, { bigint: true }); - let current = root; - for (const part of path.relative(root, file).split(path.sep)) { - current = path.join(current, part); - if (lstatSync(current).isSymbolicLink()) return null; - } - const before = lstatSync(file, { bigint: true }); - if (!before.isFile() || before.size > BigInt(128 * 1024) || !containsPath(root, realpathSync(file))) return null; - fd = openSync(file, constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0)); - const opened = fstatSync(fd, { bigint: true }); - const afterRoot = lstatSync(root, { bigint: true }); - if (!opened.isFile() || before.ino !== opened.ino || before.dev !== opened.dev || opened.size > BigInt(128 * 1024) - || rootStat.ino !== afterRoot.ino || rootStat.dev !== afterRoot.dev || realpathSync(root) !== root || !containsPath(root, realpathSync(file))) return null; - const body = readFileSync(fd, 'utf8'); - const after = fstatSync(fd, { bigint: true }); - if (after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || body.length > 128 * 1024) return null; - return body; - } catch { return null; } finally { if (fd !== undefined) closeSync(fd); } -} -export function readNotes(source: KnowledgeSource): { notes: Note[]; directories: string[] } { - canonicalSource(source); - const directories: string[] = []; const notes: Note[] = []; const pending = [source.path]; - let entriesSeen = 0; let bytesRead = 0; - while (pending.length) { - const dir = pending.pop()!; - if (lstatSync(dir).isSymbolicLink() || !containsPath(source.path, realpathSync(dir))) continue; - directories.push(dir); - for (const item of readdirSync(dir, { withFileTypes: true })) { - if (++entriesSeen > 10_000) throw new Error('Knowledge folder exceeds the 10,000-entry limit. Narrow its patterns or choose a smaller folder.'); - if (item.name.startsWith('.')) continue; - const file = path.join(dir, item.name); const rel = path.relative(source.path, file).split(path.sep).join('/'); - if (source.exclude.some(p => matches(p, rel) || rel.startsWith(p.replace(/\/\*\*$/, '') + '/'))) continue; - if (item.isSymbolicLink()) continue; - if (item.isDirectory()) { pending.push(file); continue; } - if (!item.isFile() || !/\.md$/i.test(item.name) || !source.include.some(p => matches(p, rel))) continue; - const body = safeRead(source.path, file); if (body === null) continue; - bytesRead += Buffer.byteLength(body); - if (bytesRead > 32 * 1024 * 1024) throw new Error('Knowledge folder exceeds the 32 MiB text limit. Narrow its patterns.'); - const front = body.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); - const title = front?.[1].match(/^title:\s*["']?([^\r\n"']+)/m)?.[1].trim() || body.match(/^#\s+(.+)$/m)?.[1].trim() || item.name.replace(/\.md$/i, ''); - const wikiLinks = [...new Set([...body.matchAll(/\[\[([^\]\r\n]{1,240})\]\]/g)].map(m => m[1]))].slice(0,100); - notes.push({ relativePath: rel, title: title.slice(0,240), wikiLinks, body }); - } - } - return { notes, directories }; -} diff --git a/src/lib/cortex/knowledge/reconcile.ts b/src/lib/cortex/knowledge/reconcile.ts deleted file mode 100644 index 312dfa3c00..0000000000 --- a/src/lib/cortex/knowledge/reconcile.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { nativeHttpTransportEnabled } from '@/lib/ws-server/api-front-door-config'; -import { isNativeCortexReader } from '@/lib/cortex/owner-process'; -import { getWsBase } from '@/lib/panel/api-port'; -import { getOrCreateWsToken } from '@/lib/ws-auth'; -import type { KnowledgeSource } from '@/lib/operator/knowledge-source-defaults'; -/** Every settings writer uses the same removal/cancellation and answer-cache boundary. */ -export async function reconcileKnowledgeSources(before: KnowledgeSource[], after: KnowledgeSource[]) { - if (JSON.stringify(before) === JSON.stringify(after)) return; - if (nativeHttpTransportEnabled() && !isNativeCortexReader()) { - // Window-bearing settings transactions stay in Next. Only WS reconciles their index. - // Best effort: the settings are already saved, so an unreachable index owner must not - // fail the save or roll back its window change. WS reindexes on its next reconcile. - try { - const response = await fetch(`${getWsBase().replace(/^ws:/, 'http:')}/api/cortex/sources`, { - method: 'POST', headers: { authorization: `Bearer ${getOrCreateWsToken()}`, 'content-type': 'application/json' }, - body: JSON.stringify({ action: 'reconcile', before }), redirect: 'manual', cache: 'no-store', - signal: AbortSignal.timeout(5_000), - }); - await response.body?.cancel(); - if (!response.ok) console.warn('[knowledge] Knowledge source reconciliation was not accepted by its owner.'); - } catch { - console.warn('[knowledge] Knowledge source owner unavailable; reconciliation deferred.'); - } - return; - } - const { ensureKnowledgeSourceWatcher, forgetKnowledgeSource, indexKnowledgeSources } = await import('./index'); - for (const source of before) { - if (!after.some(next => JSON.stringify(next) === JSON.stringify(source))) forgetKnowledgeSource(source.id); - } - ensureKnowledgeSourceWatcher(); - void indexKnowledgeSources(); -} diff --git a/src/lib/cortex/knowledge/sources-route.ts b/src/lib/cortex/knowledge/sources-route.ts deleted file mode 100644 index 07460056df..0000000000 --- a/src/lib/cortex/knowledge/sources-route.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import path from 'node:path'; -import { NextResponse, type NextRequest } from 'next/server'; -import { resolveRequestPrincipalContext } from '@/lib/auth/principal'; -import { getOperatorDefaults, updateOperatorDefaults } from '@/lib/operator/defaults'; -import { reconcileKnowledgeSources } from '@/lib/cortex/knowledge/reconcile'; -import { withStoragePressurePolicyLock } from '@/lib/orchestrator/storage-pressure-policy-lock'; -import { parseKnowledgeSources } from '@/lib/operator/knowledge-source-defaults'; -import { configuredKnowledgeSources } from '@/lib/cortex/knowledge/sources'; -import { ensureKnowledgeSourceWatcher, forgetKnowledgeSource, indexKnowledgeSources, invalidateKnowledgeSource, knowledgeSourceState } from '@/lib/cortex/knowledge'; - -const reply = (data: unknown, status = 200) => NextResponse.json(data, { status, headers: { 'Cache-Control': 'no-store' } }); -function denied(request: Request) { - return resolveRequestPrincipalContext(request).role !== 'operator' ? reply({ error: 'Knowledge sources require an operator credential.' }, 403) : null; -} -export async function GET(request: NextRequest) { - const refusal = denied(request); if (refusal) return refusal; - return reply({ sources: configuredKnowledgeSources().map(knowledgeSourceState) }); -} -let mutations: Promise = Promise.resolve(); -export async function POST(request: NextRequest) { - const refusal = denied(request); if (refusal) return refusal; - const body = await request.json().catch(() => null) as Record | null; - // A Next window transaction already holds the cross-process settings lock. - // Its reconciliation must not queue behind a source writer waiting for that lock. - if (body?.action === 'reconcile') { - try { - await reconcileKnowledgeSources(parseKnowledgeSources(body.before), configuredKnowledgeSources()); - return reply({ ok: true }); - } catch { return reply({ error: 'Knowledge sources could not be reconciled.' }, 400); } - } - const operation = mutations.catch(() => {}).then(() => withStoragePressurePolicyLock(async () => { - if (!body || !['add', 'remove', 'refresh'].includes(String(body.action))) return reply({ error: 'Choose add, remove or refresh.' }, 400); - try { - const { values } = await getOperatorDefaults(); - if (body.action === 'add') { - if (typeof body.path !== 'string' || !body.path.trim()) return reply({ error: 'A folder path is required.' }, 400); - const source = { id: randomUUID(), path: body.path, name: typeof body.name === 'string' && body.name.trim() ? body.name.trim() : path.basename(body.path), - include: body.include ?? ['**/*.md'], exclude: body.exclude ?? [] }; - await updateOperatorDefaults({ knowledgeSources: [...values.knowledgeSources, source] as typeof values.knowledgeSources }); - } else if (body.action === 'remove') { - if (typeof body.id !== 'string' || !values.knowledgeSources.some(s => s.id === body.id)) return reply({ error: 'Knowledge source not found.' }, 404); - invalidateKnowledgeSource(body.id); - await updateOperatorDefaults({ knowledgeSources: values.knowledgeSources.filter(s => s.id !== body.id) }); - forgetKnowledgeSource(body.id); - } - ensureKnowledgeSourceWatcher(); - void indexKnowledgeSources(); - return reply({ sources: configuredKnowledgeSources().map(knowledgeSourceState) }); - } catch (error) { return reply({ error: error instanceof Error ? error.message : 'Knowledge source could not be updated.' }, 400); } - })); - mutations = operation; - return operation; -} diff --git a/src/lib/cortex/knowledge/sources.ts b/src/lib/cortex/knowledge/sources.ts index 554783113f..0bf3967eb7 100644 --- a/src/lib/cortex/knowledge/sources.ts +++ b/src/lib/cortex/knowledge/sources.ts @@ -6,11 +6,11 @@ import { loadOperatorDefaultsFilesSync } from '@/lib/settings/operator-defaults- import { parseKnowledgeSources, type KnowledgeSource } from '@/lib/operator/knowledge-source-defaults'; import { gitWriteRoots } from './git-write-roots'; -export function configuredKnowledgeSources(): KnowledgeSource[] { +function configuredKnowledgeSources(): KnowledgeSource[] { const values = loadOperatorDefaultsFilesSync(raw => JSON.parse(raw)); try { return parseKnowledgeSources(values.knowledgeSources ?? []); } catch { return []; } } -export function containsPath(root: string, candidate: string) { +function containsPath(root: string, candidate: string) { const rel = path.relative(root, candidate); return rel === '' || (!rel.startsWith(`..${path.sep}`) && rel !== '..' && !path.isAbsolute(rel)); } diff --git a/src/lib/cortex/qa/ask.ts b/src/lib/cortex/qa/ask.ts index 58dedc31f6..9ab5d8a140 100644 --- a/src/lib/cortex/qa/ask.ts +++ b/src/lib/cortex/qa/ask.ts @@ -1,4 +1,3 @@ -import { assertKnowledgeAnswerCurrent } from '@/lib/cortex/knowledge/answer-validity'; /** * Cortex Q&A public API (epic #915 sub-2). * @@ -409,9 +408,7 @@ async function runAskCortexUncached( let answer = ''; const citations: Citation[] = []; - const assertKnowledgeCurrent = () => assertKnowledgeAnswerCurrent(topRows, memoryRevision); const emit: SseEmit = (name, payload) => { - assertKnowledgeCurrent(); if (name === 'token') { answer += (payload as { text: string }).text ?? ''; } else if (name === 'citation') { @@ -444,8 +441,7 @@ async function runAskCortexUncached( } } catch (error) { if (error instanceof ManagedBrainUnavailableError) { - assertKnowledgeCurrent(); - throw new ManagedBrainUnavailableError( + throw new ManagedBrainUnavailableError( topRows.map(row => ({ ...row.citation, title: rowDisplayTitle(row) })), topRows.length, ); @@ -453,7 +449,6 @@ async function runAskCortexUncached( throw error; } - assertKnowledgeCurrent(); const result: AskCortexResult = { answer: answer.trim(), citations, @@ -587,9 +582,7 @@ export async function runAskPipeline( let cachedAnswer = ''; const cachedCitations: Citation[] = []; - const assertKnowledgeCurrent = () => assertKnowledgeAnswerCurrent(topRows, memoryRevision); const trackingEmit: SseEmit = (name, payload) => { - assertKnowledgeCurrent(); if (name === 'token') { cachedAnswer += (payload as { text: string }).text ?? ''; } else if (name === 'citation') { @@ -621,7 +614,6 @@ export async function runAskPipeline( await composeClassB(question, repoPath, topRows, trackingEmit, options); } - assertKnowledgeCurrent(); // Store in cache for follow-up identical questions. if (cachedAnswer.trim() && memoryRevision === readMemoryRevision()) { setCache(key, { diff --git a/src/lib/cortex/qa/citations.ts b/src/lib/cortex/qa/citations.ts index 4bdcb29cd7..03532aad42 100644 --- a/src/lib/cortex/qa/citations.ts +++ b/src/lib/cortex/qa/citations.ts @@ -92,7 +92,7 @@ export function rowDisplayTitle(row: TypedRow): string { title = pick('title', 'relPath'); break; case 'fact': - title = fields?.sourceKind === 'knowledge' ? `${pick('sourceName')} · ${pick('title')}` : pick('content').split('\n')[0] ?? ''; + title = pick('content').split('\n')[0] ?? ''; break; case 'project': title = pick('name'); diff --git a/src/lib/cortex/qa/compose-class-b.test.ts b/src/lib/cortex/qa/compose-class-b.test.ts index b385676634..e7792d3ee9 100644 --- a/src/lib/cortex/qa/compose-class-b.test.ts +++ b/src/lib/cortex/qa/compose-class-b.test.ts @@ -21,8 +21,6 @@ vi.mock('@/lib/operator/brain-routing', () => ({ })); vi.mock('@/lib/operator/role-routing-ledger', () => ({ recordRoleRoutingReceiptSafely: vi.fn() })); -import { KnowledgeSourcesChangedError } from '@/lib/cortex/knowledge/answer-validity'; -import { composeClassA } from '@/lib/cortex/qa/compose-class-a'; import { composeClassB } from '@/lib/cortex/qa/compose-class-b'; import { callCodex } from '@/lib/cortex/qa/llm/codex-adapter'; import { callOpenRouter } from '@/lib/cortex/qa/llm/openrouter-adapter'; @@ -111,18 +109,5 @@ describe('Class B Brain subscription routing', () => { text: 'Managed answer. [CITATION:directive-subscription-routing]', }); }); - it.each(['codex', 'sonnet', 'eval'])('never starts a fallback after knowledge revocation in the %s composer', async tier => { - const refusal = new KnowledgeSourcesChangedError(); - vi.mocked(resolveBrainUseClaudeCliSync).mockReturnValue(tier !== 'codex'); - const result = { tier: 'cli' as const, text: 'An answer. [D-subscription-routing]', tokens: tokens('An answer. [D-subscription-routing]') }; - vi.mocked(callSonnet).mockResolvedValue(result); - vi.stubEnv('O8_EVAL_MODE', tier === 'eval' ? '1' : '0'); - try { - await expect(composeClassB('How is this routed?', '/repo/o8', [row], () => { throw refusal; }, { terse: true })).rejects.toBe(refusal); - expect(composeClassA).not.toHaveBeenCalled(); - expect(callCodex).toHaveBeenCalledTimes(tier === 'codex' ? 1 : 0); - expect(callSonnet).toHaveBeenCalledTimes(tier === 'codex' ? 0 : 1); - } finally { vi.unstubAllEnvs(); } - }); }); diff --git a/src/lib/cortex/qa/compose-class-b.ts b/src/lib/cortex/qa/compose-class-b.ts index 19cf908f1a..1337a4d980 100644 --- a/src/lib/cortex/qa/compose-class-b.ts +++ b/src/lib/cortex/qa/compose-class-b.ts @@ -1,4 +1,3 @@ -import { KnowledgeSourcesChangedError } from '@/lib/cortex/knowledge/answer-validity'; import 'server-only'; import { composeConnectedBrain } from './compose-connected'; @@ -128,7 +127,6 @@ export async function composeClassB( emit('done', {}); } catch (err) { - if (err instanceof KnowledgeSourcesChangedError) throw err; noteBrainQuotaError(err, 'anthropic'); flushBrainQuotaAlerts(emit); const message = err instanceof Error ? err.message : 'composer-B error'; @@ -177,7 +175,6 @@ async function composeClassBViaManaged( } emit('done', {}); } catch (err) { - if (err instanceof KnowledgeSourcesChangedError) throw err; console.warn('[qa][composer-B] managed inference failed:', err instanceof Error ? err.message : err); recordManagedBrainReceipt(repoPath, 'failed', 'Managed inference was unavailable or its allowance was reached.'); throw new ManagedBrainUnavailableError(); @@ -248,7 +245,6 @@ async function composeClassBViaCodex( } emit('done', {}); } catch (err) { - if (err instanceof KnowledgeSourcesChangedError) throw err; noteBrainQuotaError(err, 'openai'); flushBrainQuotaAlerts(emit); console.warn('[qa][composer-B] Codex CLI failed:', err instanceof Error ? err.message : err); @@ -333,7 +329,6 @@ async function composeClassBViaSonnetAdapter( emit('done', {}); } catch (err) { - if (err instanceof KnowledgeSourcesChangedError) throw err; noteBrainQuotaError(err, 'anthropic'); flushBrainQuotaAlerts(emit); const message = err instanceof Error ? err.message : 'composer-B-eval error'; diff --git a/src/lib/cortex/qa/compose-connected.ts b/src/lib/cortex/qa/compose-connected.ts index 933e6847d8..c859fbf9f5 100644 --- a/src/lib/cortex/qa/compose-connected.ts +++ b/src/lib/cortex/qa/compose-connected.ts @@ -1,4 +1,3 @@ -import { KnowledgeSourcesChangedError } from '@/lib/cortex/knowledge/answer-validity'; import 'server-only'; import { currentComposerBrainRoute } from '@/lib/operator/composer-brain-context'; @@ -31,7 +30,6 @@ export async function composeConnectedBrain(question: string, repoPath: string | for (const row of verifiedRows) emit('citation', { kind: row.citation.kind, rowId: `${row.citation.kind}-${row.citation.rowId}`, table: row.citation.table, title: rowDisplayTitle(row), excerpt: row.citation.excerpt, url: row.citation.url, sourcePath: row.citation.sourcePath }); receipt('selected'); emit('done', {}); return true; } catch (error) { - if (error instanceof KnowledgeSourcesChangedError) throw error; receipt('failed'); throw new Error(`The connected ${route.runtime === 'codex' ? 'Codex' : 'Claude'} runtime could not answer. Check its connection and try again.`, { cause: error }); } diff --git a/src/lib/cortex/qa/retrievers/facts.ts b/src/lib/cortex/qa/retrievers/facts.ts index 6df7ed5d31..d7e9fcf330 100644 --- a/src/lib/cortex/qa/retrievers/facts.ts +++ b/src/lib/cortex/qa/retrievers/facts.ts @@ -1,4 +1,3 @@ -import { knowledgeProvenance } from '@/lib/cortex/knowledge'; /** * Facts retriever — Engineering Brain Indexer surface (#915 north star #1). * @@ -150,7 +149,7 @@ function factsFtsSearch( snippet(facts_fts, -1, '«', '»', '…', 8) AS excerpt FROM facts_fts WHERE facts_fts MATCH ? - AND EXISTS (SELECT 1 FROM facts f WHERE f.id = facts_fts.fact_id + AND EXISTS (SELECT 1 FROM facts f WHERE f.id = facts_fts.fact_id AND f.source_kind != 'knowledge' AND (f.source_kind != 'outcome' OR EXISTS ( SELECT 1 FROM session_outcomes so WHERE ('outcome:' || so.id = f.source_id OR so.id = f.source_id) AND so.project_id IS ?))) @@ -302,8 +301,7 @@ export async function retrieveFacts(input: RetrieverInput): Promise): P } } -export const CORTEX_HANDLERS = { cortex_ask: handleAsk, cortex_propose_observation: handleProposeObservation, cortex_knowledge_sources: handleKnowledgeSources }; +export const CORTEX_HANDLERS = { cortex_ask: handleAsk, cortex_propose_observation: handleProposeObservation }; diff --git a/src/lib/mcp/operator-handlers/knowledge-sources.ts b/src/lib/mcp/operator-handlers/knowledge-sources.ts deleted file mode 100644 index 21a079454b..0000000000 --- a/src/lib/mcp/operator-handlers/knowledge-sources.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { apiFetch, jsonResult, type McpTool } from './shared'; -export const KNOWLEDGE_SOURCE_TOOLS: McpTool[] = [{ - name: 'cortex_knowledge_sources', - description: 'List, add or remove operator-approved read-only markdown knowledge folders. Sources never become dispatch targets. Credential-shaped chunks are skipped before distillation. Removing a source deletes its derived facts, not its files.', - inputSchema: { type: 'object', properties: { - action: { type: 'string', enum: ['list', 'add', 'remove'] }, path: { type: 'string' }, name: { type: 'string' }, id: { type: 'string' }, - include: { type: 'array', items: { type: 'string' } }, exclude: { type: 'array', items: { type: 'string' } }, - }, required: ['action'], additionalProperties: false }, -}]; -export async function handleKnowledgeSources(args: Record) { - if (!['list', 'add', 'remove'].includes(String(args.action))) throw new Error('Choose list, add or remove.'); - return jsonResult(await apiFetch('/api/cortex/sources', args.action === 'list' ? {} : { method: 'POST', body: JSON.stringify(args) })); -} diff --git a/src/lib/operator/defaults.ts b/src/lib/operator/defaults.ts index acc894e92f..4d0ba5950f 100644 --- a/src/lib/operator/defaults.ts +++ b/src/lib/operator/defaults.ts @@ -1,5 +1,4 @@ import * as conversationDefaults from './conversation-defaults'; -import { reconcileKnowledgeSources } from '@/lib/cortex/knowledge/reconcile'; import { parseKnowledgeSources, type KnowledgeSourceDefaults } from './knowledge-source-defaults'; import { parseOperatorDefaultsToml } from '@/lib/settings/toml'; import { validateKnowledgeSourceRoots } from '@/lib/cortex/knowledge/sources'; @@ -1091,12 +1090,7 @@ async function updateOperatorDefaultsOnce(update: Partial, exp } export async function updateOperatorDefaults(update: Partial, expectedRevision?: string): Promise { - const apply = async () => { - const before = getOperatorDefaultsSync().values.knowledgeSources; - const result = await updateOperatorDefaultsOnce(update, expectedRevision); - await reconcileKnowledgeSources(before, result.values.knowledgeSources); - return result; - }; + const apply = () => updateOperatorDefaultsOnce(update, expectedRevision); return expectedRevision ? withOperatorDefaultsWriteLock(apply) : withOperatorDefaultsUpdateRetry(apply); } @@ -1104,12 +1098,7 @@ export async function applyOperatorDefaultsToml(raw: string, expectedRevision: s return withOperatorDefaultsWriteLock(async () => { const knowledge = parseOperatorDefaultsToml(raw).knowledgeSources; if (knowledge !== undefined) validateKnowledgeSourceRoots(knowledge); - const before = getOperatorDefaultsSync().values.knowledgeSources; - return applyOperatorDefaultsTomlFile(raw, expectedRevision, OPERATOR_DEFAULTS_FALLBACK, async () => { - const result = await getOperatorDefaults(); - await reconcileKnowledgeSources(before, result.values.knowledgeSources); - return result; - }); + return applyOperatorDefaultsTomlFile(raw, expectedRevision, OPERATOR_DEFAULTS_FALLBACK, getOperatorDefaults); }); } diff --git a/src/lib/ws-server/native-http-registry.ts b/src/lib/ws-server/native-http-registry.ts index 7ffaee196e..66ae00aabb 100644 --- a/src/lib/ws-server/native-http-registry.ts +++ b/src/lib/ws-server/native-http-registry.ts @@ -468,7 +468,6 @@ export const nativeSurfaceRoutes: Record = { route('/api/runtime/capabilities', 'GET', () => import('@/app/api/runtime/capabilities/route')), route('/api/worktrees/retention-usage', 'GET', () => import('@/app/api/worktrees/retention-usage/route')), route('/api/runtime/capacity', 'GET', () => import('@/app/api/runtime/capacity/route')), - route('/api/cortex/sources', 'GET POST', () => import('@/lib/cortex/knowledge/sources-route')), // Move the plan controls and inference together: OAuth attempts (including // their loopback listeners) and in-flight cancellation share one WS service. route('/api/panel/models/chatgpt', 'GET POST DELETE', () => import('@/app/api/panel/models/chatgpt/route')), diff --git a/tests/integration-weights.json b/tests/integration-weights.json index 0d46b8a293..466f304bbf 100644 --- a/tests/integration-weights.json +++ b/tests/integration-weights.json @@ -446,7 +446,6 @@ "tests/knowledge-source-direct-writers-real-path.test.ts": 7, "tests/knowledge-source-metadata-inodes-real-path.test.ts": 8, "tests/knowledge-source-write-boundaries-real-path.test.ts": 11, - "tests/knowledge-sources-real-path.test.ts": 12, "tests/lane-branch-binding-diff.test.ts": 6, "tests/lane-completion-presentation-real-path.test.ts": 3, "tests/lane-confined-verification-real-path.test.ts": 4, diff --git a/tests/knowledge-source-direct-writers-real-path.test.ts b/tests/knowledge-source-direct-writers-real-path.test.ts index 0234320e24..f5451c125a 100644 --- a/tests/knowledge-source-direct-writers-real-path.test.ts +++ b/tests/knowledge-source-direct-writers-real-path.test.ts @@ -14,7 +14,6 @@ const f = vi.hoisted(() => { return { root, launched: vi.fn(), spawned: vi.fn(), failGitProbe: false, gitCalls: 0 }; }); vi.mock('@/lib/skeleton/autoscan', () => ({ triggerScan: vi.fn() })); -vi.mock('@/lib/cortex/knowledge/reconcile', () => ({ reconcileKnowledgeSources: async () => {} })); vi.mock('@/lib/runtime/actions', async original => ({ ...await original(), launchRuntimeSurface: async (input: { cwd: string }) => { f.launched(input); writeFileSync(path.join(input.cwd, 'note.md'), 'runtime wrote'); @@ -222,11 +221,9 @@ it.each(['refs/heads', 'logs/refs/heads'])('refuses source admission when a regi const note = path.join(vault, 'note.md'); writeFileSync(note, '# Retained admission canary\n'); const target = path.join(writable, '.git', storage); renameSync(target, `${target}-retained`); symlinkSync(vault, target, 'dir'); await addRepo(writable); - const sourceApi = await import('@/app/api/cortex/sources/route'); const retained = readFileSync(note); - const response = await sourceApi.POST(req('/api/cortex/sources', { action: 'add', path: vault })); - expect.soft(readFileSync(note)).toEqual(retained); - expect(response.status, await response.text()).toBe(400); + await expect(protect(vault)).rejects.toThrow(/separate from registered repositories/); + expect(readFileSync(note)).toEqual(retained); }); it.each(['refs/heads', 'logs/refs/heads'])('allows Git %s symlinks whose physical storage remains separate from knowledge sources', async storage => { diff --git a/tests/knowledge-sources-real-path.test.ts b/tests/knowledge-sources-real-path.test.ts deleted file mode 100644 index c01bacd665..0000000000 --- a/tests/knowledge-sources-real-path.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, unlinkSync } from 'node:fs'; -import path from 'node:path'; -import { NextRequest } from 'next/server'; -import { afterAll, afterEach, beforeEach, expect, it, vi } from 'vitest'; -import type { DistillBatchInput } from '@/lib/cortex/indexer/doc-distill'; -import type { TypedRow } from '@/lib/cortex/qa/types'; -import { buildCliBundle } from './fixtures/cli-bundle'; -const fixture = await vi.hoisted(async () => { - const fs = await import('node:fs'); const os = await import('node:os'); const path = await import('node:path'); - const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'o8-knowledge-'))); - const data = path.join(root, 'data'); fs.mkdirSync(data); - process.env.CORTEX_IDE_DATA_DIR = data; process.env.O8_DATA_DIR = data; process.env.O8_HYBRID_SCORER = '0'; - return { root, data, distill: vi.fn(), compose: vi.fn(), sendLead: vi.fn(async () => {}) }; -}); -vi.mock('@/lib/lane/orchestrator-send-entry', () => ({ sendOrchestratorBackendTurn: fixture.sendLead })); -vi.mock('@/lib/cortex/indexer/doc-distill', () => ({ distillDocChunkBatch: fixture.distill })); -vi.mock('@/lib/cortex/qa/classifier', () => ({ classifyQuestion: async () => ({ class: 'A', bm25Variants: ['Apricot'] }) })); -vi.mock('@/lib/cortex/qa/composer', async original => ({ ...await original(), - composeClassA: async (_question: string, _repo: unknown, rows: TypedRow[], emit: (name: string, value: unknown) => void) => { - await fixture.compose(rows); - emit('token', { text: rows.map(row => row.fields.content).join('\n') }); - rows.forEach(row => emit('citation', { ...row.citation, rowId: `${row.citation.kind}-${row.citation.rowId}` })); - }, -})); -vi.mock('@/lib/cortex/qa/llm/haiku-adapter', () => ({ prewarmHaiku: vi.fn() })); -vi.mock('@/lib/cortex/qa/llm/sonnet-adapter', () => ({ prewarmSonnetCli: vi.fn() })); -const { handleOperatorMcpMessage } = await import('@/lib/mcp/operator-mcp-host'); -const sourcesApi = await import('@/app/api/cortex/sources/route'); -const answerApi = await import('@/app/api/cortex/ask/answer/route'); -const { getOperatorDefaults, getOperatorDefaultsSync, updateOperatorDefaults } = await import('@/lib/operator/defaults'); -const { getOrCreateWsToken } = await import('@/lib/ws-auth'); -const { indexKnowledgeSources, stopKnowledgeSourceWatcher } = await import('@/lib/cortex/knowledge'); -const { retrieveFacts } = await import('@/lib/cortex/qa/retrievers/facts'); -const { getSqlite, closeDb } = await import('@/lib/db'); -const token = getOrCreateWsToken(); -const text = (name: string) => `${name} is the orchard policy. ${'This is a sufficiently detailed local note for the documentation chunker. '.repeat(4)}`; -function request(body?: unknown, auth = true, endpoint = '/api/cortex/sources') { - return new NextRequest(`http://localhost${endpoint}`, { method: body ? 'POST' : 'GET', headers: auth ? { authorization: `Bearer ${token}`, 'Content-Type': 'application/json' } : {}, ...(body ? { body: JSON.stringify(body) } : {}) }); -} -async function add(folder: string, extra = {}) { - const response = await sourcesApi.POST(request({ action: 'add', path: folder, ...extra })); - expect(response.status, await response.clone().text()).toBe(200); - await indexKnowledgeSources(); - return (await response.json()).sources.at(-1) as { id: string; path: string }; -} -const facts = () => getSqlite().prepare("SELECT content, source_excerpt FROM facts WHERE source_kind = 'knowledge'").all(); -let folder: string; -beforeEach(async () => { - stopKnowledgeSourceWatcher(); - for (const source of (await getOperatorDefaults()).values.knowledgeSources) await sourcesApi.POST(request({ action: 'remove', id: source.id })); - stopKnowledgeSourceWatcher(); - folder = path.join(fixture.root, crypto.randomUUID()); mkdirSync(folder); - fixture.distill.mockReset().mockImplementation(async ({ chunks }: DistillBatchInput) => ({ factsByChunkId: new Map(chunks.map(chunk => [chunk.id, - [{ kind: 'decision', content: chunk.text.includes('Bronze') ? 'Bronze is the orchard policy.' : 'Apricot is the orchard policy.', source_excerpt: chunk.text.slice(0, 160), confidence: 0.9 }]])), estTokens: 1 })); - fixture.compose.mockClear(); - vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => { - const req = new NextRequest(url, init ? { ...init, signal: init.signal ?? undefined } : undefined); - if (req.nextUrl.pathname === '/api/cortex/sources') return init?.method === 'POST' ? sourcesApi.POST(req) : sourcesApi.GET(req); - if (req.nextUrl.pathname === '/api/cortex/ask/answer') return answerApi.POST(req); - throw new Error('Unexpected outbound request'); - })); -}); -afterEach(() => { stopKnowledgeSourceWatcher(); vi.unstubAllGlobals(); }); -afterAll(async () => { stopKnowledgeSourceWatcher(); await indexKnowledgeSources(); closeDb(); rmSync(fixture.root, { recursive: true, force: true }); }); -it('exposes read-only knowledge-source management through the real operator MCP catalog', async () => { - const response = await handleOperatorMcpMessage({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, 'full'); - expect((response?.result as { tools: Array<{ name: string }> }).tools.map(tool => tool.name)).toContain('cortex_knowledge_sources'); -}); -it('refuses unauthenticated source reads and mutations', async () => { - expect((await sourcesApi.GET(request(undefined, false))).status).toBe(403); - expect((await sourcesApi.POST(request({ action: 'add', path: folder }, false))).status).toBe(403); - expect((await getOperatorDefaults()).values.knowledgeSources).toEqual([]); -}); -it('registers the exact literal notes folder without trimming significant whitespace', async () => { - const literal = `${folder} `; mkdirSync(literal); - writeFileSync(path.join(literal, 'plan.md'), text('Apricot')); - writeFileSync(path.join(folder, 'plan.md'), text('Bronze')); - const registered = await add(literal); - expect(registered.path).toBe(literal); - expect(getOperatorDefaultsSync().values.knowledgeSources[0].path).toBe(literal); - expect(JSON.stringify(facts())).toContain('Apricot'); - expect(JSON.stringify(facts())).not.toContain('Bronze'); - expect(readdirSync(literal)).toEqual(['plan.md']); -}); -it.each(['repository', 'source'] as const)('refuses a case alias of an existing %s during source registration', async owner => { - const registry = await import('@/lib/repos/registry'); - const registered = owner === 'repository' ? await registry.addRepo(folder) : null; - if (owner === 'source') await add(folder); - const alias = path.join(path.dirname(folder), path.basename(folder).toUpperCase()); - const insensitive = existsSync(alias) && statSync(alias).ino === statSync(folder).ino; - if (!insensitive) mkdirSync(alias); - try { - const response = await sourcesApi.POST(request({ action: 'add', path: alias })); - expect(response.status, await response.clone().text()).toBe(insensitive ? 400 : 200); - expect((await getOperatorDefaults()).values.knowledgeSources).toHaveLength(owner === 'source' ? (insensitive ? 1 : 2) : (insensitive ? 0 : 1)); - } finally { if (registered) await registry.removeRepo(registered.id); } -}); -it('indexes safe markdown through MCP, persists defaults, and answers cortex_ask with note citations without writing the source', async () => { - const body = `---\ntitle: Orchard handbook\n---\n# Orchard\n## Policy\n${text('Apricot')} [[Related decision]]\n## Credentials\n${text('Secret')}\napi_key: sk-proj-${'x'.repeat(40)}\n## api_key: sk-proj-${'y'.repeat(40)}\n${text('Heading secret')}\n`; - writeFileSync(path.join(folder, 'plan.md'), body); - const response = await handleOperatorMcpMessage({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'cortex_knowledge_sources', arguments: { action: 'add', path: folder } } }, 'full'); - expect((response?.result as { isError?: boolean }).isError).not.toBe(true); - await indexKnowledgeSources(); - expect(fixture.distill).toHaveBeenCalled(); - expect(JSON.stringify(fixture.distill.mock.calls)).not.toContain('sk-proj-'); - expect(JSON.stringify(facts())).toContain('Apricot'); expect(JSON.stringify(facts())).not.toContain('Secret'); - expect(getOperatorDefaultsSync().values.knowledgeSources[0].path).toBe(folder); - const settings = readFileSync(path.join(fixture.data, 'settings.toml'), 'utf8'); expect(settings).toContain('knowledge_sources'); - const answer = await handleOperatorMcpMessage({ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'cortex_ask', arguments: { question: 'Apricot', bypassCache: true } } }, 'full'); - const payload = JSON.parse((answer?.result as { content: Array<{ text: string }> }).content[0].text); - expect(payload.answer).toContain('Apricot'); - expect(payload.citations).toEqual(expect.arrayContaining([expect.objectContaining({ sourcePath: path.join(folder, 'plan.md'), title: 'Orchard handbook' })])); - const rows = await retrieveFacts({ question: 'Apricot' }); - expect(rows.rows[0].fields.wikiLinks).toContain('Related decision'); - expect(readdirSync(folder)).toEqual(['plan.md']); expect(readFileSync(path.join(folder, 'plan.md'), 'utf8')).toBe(body); -}); -it('skips hidden/excluded notes and linked files/directories that escape the configured source', async () => { - const outside = path.join(fixture.root, 'outside.md'); writeFileSync(outside, text('Outside')); - writeFileSync(path.join(folder, 'good.md'), text('Apricot')); writeFileSync(path.join(folder, '.hidden.md'), text('Hidden')); - mkdirSync(path.join(folder, 'archive')); writeFileSync(path.join(folder, 'archive', 'old.md'), text('Archive')); - symlinkSync(outside, path.join(folder, 'linked.md')); symlinkSync(path.dirname(outside), path.join(folder, 'linked-directory'), 'dir'); - await add(folder, { exclude: ['archive/**'] }); - const sent = fixture.distill.mock.calls.flatMap(([input]) => (input as DistillBatchInput).chunks.map(c => c.relPath)); - expect(sent).toEqual(['good.md']); -}); -it('distills only changed chunks, removes deleted facts and keeps citation metadata', async () => { - const file = path.join(folder, 'plan.md'); writeFileSync(file, `# Notes\n## First\n${text('Apricot')}\n## Second\n${text('Bronze')}`); - const source = await add(folder); fixture.distill.mockClear(); - writeFileSync(file, `# Notes\n## First\n${text('Apricot')}\n## Second\n${text('Bronze')} The policy changed.`); - await indexKnowledgeSources(); - expect(fixture.distill.mock.calls).toHaveLength(1); expect(fixture.distill.mock.calls[0][0].chunks).toHaveLength(1); - const response = await sourcesApi.POST(request({ action: 'remove', id: source.id })); expect(response.status).toBe(200); - expect(facts()).toEqual([]); expect((await retrieveFacts({ question: 'Apricot' })).rows).toEqual([]); - expect(readFileSync(file, 'utf8')).toContain('The policy changed'); -}); -it('does not resurrect facts when a source is removed during pending distillation', async () => { - writeFileSync(path.join(folder, 'plan.md'), text('Apricot')); - let finish!: (value: unknown) => void; let entered!: () => void; - const started = new Promise(resolve => { entered = resolve; }); - let pending!: DistillBatchInput; - fixture.distill.mockImplementationOnce(async (input: DistillBatchInput) => { pending = input; entered(); return new Promise(resolve => { finish = resolve; }); }); - const response = await sourcesApi.POST(request({ action: 'add', path: folder })); const source = (await response.json()).sources[0]; - await started; - expect((await sourcesApi.POST(request({ action: 'remove', id: source.id }))).status).toBe(200); - finish({ factsByChunkId: new Map(pending.chunks.map(chunk => [chunk.id, [{ kind: 'decision', content: 'Apricot must not return.', source_excerpt: chunk.text.slice(0, 160), confidence: 0.9 }]])), estTokens: 1 }); await indexKnowledgeSources(); expect(facts()).toEqual([]); -}); -it('blocks registration and direct worker/worktree dispatch into a knowledge folder', async () => { - writeFileSync(path.join(folder, 'plan.md'), text('Apricot')); await add(folder); - const { WorktreeManager } = await import('@/lib/worktree/manager'); - await expect(new WorktreeManager(folder).create({ agentType: 'codex', taskName: 'test' })).rejects.toThrow('read-only'); - const { addRepo, listRepos } = await import('@/lib/repos/registry'); - expect(await listRepos()).toEqual([]); await expect(addRepo(folder)).rejects.toThrow('read-only'); - await expect(addRepo(path.dirname(folder))).rejects.toThrow('read-only'); - const { launchRuntimeSurface } = await import('@/lib/runtime/actions'); - await expect(launchRuntimeSurface({ runtime: 'codex', prompt: 'change', cwd: folder })).rejects.toThrow('read-only'); - await expect(launchRuntimeSurface({ runtime: 'codex', prompt: 'change', cwd: path.dirname(folder) })).rejects.toThrow('read-only'); - const { dispatch } = await import('@/lib/lane/commands'); - expect(await dispatch({ verb: 'open_lane', repoPath: folder, branch: 'work', runtime: 'codex', label: 'test' })).toMatchObject({ ok: false, note: expect.stringContaining('read-only') }); - expect(readdirSync(folder)).toEqual(['plan.md']); -}); - -it('observes filesystem edits and deletions through the running source watcher', async () => { - const file = path.join(folder, 'plan.md'); writeFileSync(file, text('Apricot')); - await add(folder); fixture.distill.mockClear(); - writeFileSync(file, text('Bronze')); - await vi.waitFor(() => expect(JSON.stringify(facts())).toContain('Bronze'), { timeout: 8_000, interval: 50 }); - expect(fixture.distill).toHaveBeenCalledTimes(1); - unlinkSync(file); - await vi.waitFor(() => expect(facts()).toEqual([]), { timeout: 8_000, interval: 50 }); -}, 20_000); -it('rejects linked roots and invalid patterns before persisting sources or starting inference', async () => { - const linked = path.join(fixture.root, crypto.randomUUID()); symlinkSync(folder, linked, 'dir'); - expect((await sourcesApi.POST(request({ action: 'add', path: linked }))).status).toBe(400); - expect((await sourcesApi.POST(request({ action: 'add', path: folder, include: ['../*.md'] }))).status).toBe(400); - expect(getOperatorDefaultsSync().values.knowledgeSources).toEqual([]); expect(fixture.distill).not.toHaveBeenCalled(); -}); -it('runs the built CLI source commands against the real authenticated API', async () => { - const { spawn } = await import('node:child_process'); const { createServer } = await import('node:http'); - const bundle = path.join(fixture.root, 'cli.mjs'); - await buildCliBundle(bundle, 'test'); - const server = createServer(async (req, res) => { - try { - let body = ''; for await (const part of req) body += part; - const request = new NextRequest(`http://localhost${req.url}`, { method: req.method, headers: { authorization: String(req.headers.authorization ?? ''), 'Content-Type': 'application/json' }, ...(body ? { body } : {}) }); - const response = req.method === 'POST' ? await sourcesApi.POST(request) : await sourcesApi.GET(request); - res.writeHead(response.status, { 'Content-Type': 'application/json' }); res.end(await response.text()); - } catch { res.writeHead(500); res.end('{}'); } - }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address() as { port: number }; - const run = (args: string[]) => new Promise((resolve, reject) => { - const child = spawn(process.execPath, [bundle, 'brain', 'sources', ...args], { env: { ...process.env, O8_WORKER_TOKEN: '', O8_API_PORT: String(address.port), O8_API_TOKEN: token }, stdio: ['ignore', 'pipe', 'pipe'] }); - let stdout = ''; let stderr = ''; child.stdout.on('data', part => { stdout += part; }); child.stderr.on('data', part => { stderr += part; }); - child.on('error', reject); child.on('exit', code => code === 0 ? resolve(stdout) : reject(new Error(`CLI exit ${code}: ${stderr}`))); - }); - try { - const added = JSON.parse(await run(['add', folder, '--name', 'CLI notes', '--exclude', 'archive/**'])); - expect(added.sources[0]).toMatchObject({ name: 'CLI notes', path: folder, exclude: ['archive/**'] }); - expect(JSON.parse(await run(['list'])).sources).toHaveLength(1); - expect(JSON.parse(await run(['remove', added.sources[0].id])).sources).toEqual([]); - expect(getOperatorDefaultsSync().values.knowledgeSources).toEqual([]); - } finally { await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); } -}, 20_000); - -it('reconciles direct defaults and full TOML removal immediately, including cached answers', async () => { - writeFileSync(path.join(folder, 'plan.md'), text('Apricot')); await add(folder); - const { askCortex } = await import('@/lib/cortex/qa/ask'); - expect((await askCortex('Apricot', undefined)).answer).toContain('Apricot'); - const { applyOperatorDefaultsToml, getOperatorDefaultsTomlState } = await import('@/lib/operator/defaults'); - await updateOperatorDefaults({ knowledgeSources: [] }); - expect(facts()).toEqual([]); expect((await askCortex('Apricot', undefined)).answer).not.toContain('Apricot'); - await add(folder); expect(facts().length).toBeGreaterThan(0); - const state = await getOperatorDefaultsTomlState(); - await applyOperatorDefaultsToml('[brain]\n', state.revision); - expect(facts()).toEqual([]); expect((await askCortex('Apricot', undefined)).answer).not.toContain('Apricot'); -}); -it('protects source additions and implicit TOML removal at the shared defaults API', async () => { - writeFileSync(path.join(folder, 'plan.md'), text('Apricot')); await add(folder); - const defaultsApi = await import('@/app/api/panel/operator-defaults/route'); - expect((await defaultsApi.POST(request({ knowledgeSources: [] }, false))).status).toBe(403); - expect((await defaultsApi.POST(request({ settingsToml: '[brain]\n', settingsTomlRevision: 'fixture' }, false))).status).toBe(403); - expect(getOperatorDefaultsSync().values.knowledgeSources).toHaveLength(1); expect(facts().length).toBeGreaterThan(0); -}); -it('re-distills heading-only edits and removes a previously indexed chunk if its heading becomes sensitive', async () => { - const file = path.join(folder, 'plan.md'); writeFileSync(file, `## Initial\n${text('Apricot')}`); - await add(folder); fixture.distill.mockClear(); - writeFileSync(file, `## Changed meaning\n${text('Apricot')}`); await indexKnowledgeSources(); - expect(fixture.distill).toHaveBeenCalledTimes(1); expect(fixture.distill.mock.calls[0][0].chunks[0].headingPath).toContain('Changed meaning'); - fixture.distill.mockClear(); writeFileSync(file, `## api_key: sk-proj-${'z'.repeat(40)}\n${text('Apricot')}`); - await indexKnowledgeSources(); expect(fixture.distill).not.toHaveBeenCalled(); expect(facts()).toEqual([]); -}); - -it.each(['answer', 'stream'])('refuses an in-flight %s after its source is removed', async mode => { - writeFileSync(path.join(folder, 'plan.md'), text('Apricot')); const source = await add(folder); - let entered!: () => void; let finish!: () => void; - const started = new Promise(resolve => { entered = resolve; }); - fixture.compose.mockImplementationOnce(async () => { entered(); await new Promise(resolve => { finish = resolve; }); }); - const { askCortex, runAskPipeline } = await import('@/lib/cortex/qa/ask'); - const emitted: unknown[] = []; - const pending = mode === 'answer' ? askCortex('Apricot', undefined, { bypassCache: true }) - : runAskPipeline('Apricot', undefined, (name, payload) => { if (name === 'token' || name === 'citation') emitted.push(payload); }, true); - await started; - expect((await sourcesApi.POST(request({ action: 'remove', id: source.id }))).status).toBe(200); - const refusal = expect(pending).rejects.toThrow('Knowledge sources changed'); finish(); await refusal; - expect(emitted).toEqual([]); -}); - -it('reads persisted source settings in a fresh process after restart', async () => { - const source = await add(folder, { name: 'Restart notes' }); - const { spawn } = await import('node:child_process'); - const output = await new Promise((resolve, reject) => { - const child = spawn(process.execPath, ['--import', 'tsx', '--conditions=react-server', '--input-type=module', '-e', - "const module = await import('./src/lib/operator/defaults.ts'); const { getOperatorDefaultsSync } = module.default ?? module; process.stdout.write(JSON.stringify(getOperatorDefaultsSync().values.knowledgeSources));"], { cwd: process.cwd(), env: process.env, stdio: ['ignore', 'pipe', 'pipe'] }); - let stdout = ''; let stderr = ''; child.stdout.on('data', part => { stdout += part; }); child.stderr.on('data', part => { stderr += part; }); - child.on('error', reject); child.on('exit', code => code === 0 ? resolve(stdout) : reject(new Error(`Restart exit ${code}: ${stderr}`))); - }); - expect(JSON.parse(output)).toEqual([expect.objectContaining({ id: source.id, path: folder, name: 'Restart notes' })]); -}, 20_000); - - -it('refuses lead admission into an unlisted Git knowledge vault before recording or launching a writable turn', async () => { - const { execFileSync } = await import('node:child_process'); - execFileSync('git', ['init', folder], { stdio: 'ignore' }); - await add(folder); - const { POST: leadPost } = await import('@/app/api/orchestrator/lead/route'); - const { listRepos } = await import('@/lib/repos/registry'); - expect(await listRepos()).toEqual([]); - const alias = path.join(fixture.root, `alias-${crypto.randomUUID()}`); symlinkSync(folder, alias, 'dir'); - const child = path.join(folder, 'nested'); mkdirSync(child); - const before = getSqlite().prepare('SELECT count(*) AS n FROM orchestrator_leads').get(); - const turnsBefore = getSqlite().prepare('SELECT count(*) AS n FROM orchestrator_lead_turns').get(); - fixture.sendLead.mockClear(); - for (const repoPath of [folder, child, alias]) { - const response = await leadPost(request({ action: 'start', repoPath, backend: 'codex', model: 'gpt-5.6-sol', effort: 'high', idempotencyKey: crypto.randomUUID(), - brief: { objective: 'Inspect knowledge', scope: ['notes'], doneTests: ['Read only'], nonGoals: [], budgets: [], escalationCriteria: ['Any write'] } }, true, '/api/orchestrator/lead')); - if (response.status === 202) { - const accepted = await response.clone().json(); - await leadPost(request({ action: 'stop', leadId: accepted.lead.id }, true, '/api/orchestrator/lead')); - await new Promise(resolve => setTimeout(resolve, 0)); - } - expect(response.status, await response.clone().text()).toBe(400); - expect((await response.json()).error).toMatchObject({ code: 'invalid_lead_repo', message: expect.stringContaining('read-only') }); - } - expect(getSqlite().prepare('SELECT count(*) AS n FROM orchestrator_leads').get()).toEqual(before); - expect(getSqlite().prepare('SELECT count(*) AS n FROM orchestrator_lead_turns').get()).toEqual(turnsBefore); - expect(fixture.sendLead).not.toHaveBeenCalled(); - expect(await listRepos()).toEqual([]); -}); diff --git a/tests/o8d-knowledge-owner-real-path.test.ts b/tests/o8d-knowledge-owner-real-path.test.ts index 53bbb700f8..fcf0d4e3bc 100644 --- a/tests/o8d-knowledge-owner-real-path.test.ts +++ b/tests/o8d-knowledge-owner-real-path.test.ts @@ -1,17 +1,14 @@ import { createHash } from 'node:crypto'; -import { mkdtempSync, realpathSync, rmdirSync, writeFileSync } from 'node:fs'; +import { writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { tmpdir } from 'node:os'; import { NextRequest } from 'next/server'; import { afterAll, beforeAll, expect, it, vi } from 'vitest'; import { startParityReference } from './fixtures/ws-parity-server'; -// A forwarded Next request must never import either local stateful implementation. -vi.mock('@/lib/cortex/knowledge/sources-route', () => { throw new Error('Next loaded the knowledge owner'); }); +// A forwarded Next request must never import the local stateful implementation. vi.mock('@/app/api/panel/operator-defaults/handler', () => { throw new Error('Next loaded the settings owner'); }); let server: Awaited>; let origin: string; -let folder: string; const device = 'knowledge-owner-device'; const worker = 'knowledge-owner-worker'; const forged = { 'x-forwarded-for': '127.0.0.1', 'x-real-ip': '127.0.0.1', 'x-o8-client-addr': '127.0.0.1', 'x-o8-relay-forward': '1' }; @@ -29,14 +26,14 @@ beforeAll(async () => { writeFileSync(join(server.directory, 'mobile-device-tokens'), createHash('sha256').update(device).digest('hex')); writeFileSync(join(server.directory, 'worker-token'), worker); }, 120_000); -afterAll(async () => { vi.unstubAllEnvs(); if (folder) rmdirSync(folder); await server?.stop(); }); +afterAll(async () => { vi.unstubAllEnvs(); await server?.stop(); }); it('keeps source admission operator-only and the existing settings device grant', async () => { - for (const path of ['/api/cortex/sources', '/api/panel/operator-defaults?include=values']) { + for (const path of ['/api/panel/operator-defaults?include=values']) { for (const method of ['GET', 'POST']) { for (const [token, status] of [['', 401], ['wrong-token', 401], [device, 403], [worker, 403]] as const) { // Settings grants device reads; its knowledge-source writes require the operator. - if (path.includes('operator-defaults') && (token === device && method === 'GET')) continue; + if (token === device && method === 'GET') continue; const response = await fetch(request(path, method, token, method === 'POST' ? { knowledgeSources: [] } : undefined)); expect(response.status, `${method} ${path} ${token}`).toBe(status); } @@ -44,29 +41,4 @@ it('keeps source admission operator-only and the existing settings device grant' } expect((await fetch(request('/api/panel/operator-defaults?include=values', 'GET', device))).status).toBe(200); expect((await fetch(request('/api/panel/operator-defaults', 'POST', worker, { knowledgeSources: [] }))).status).toBe(403); - expect((await fetch(request('/api/cortex/sources'))).status).toBe(200); -}); - -it('shares reconciliation and listing through the WS owner without loading a local Next copy', async () => { - const sources = await import('@/app/api/cortex/sources/route'); - const settings = await import('@/app/api/panel/operator-defaults/route'); - folder = realpathSync(mkdtempSync(join(tmpdir(), 'o8-owner-notes-'))); - const added = await sources.POST(request('/api/cortex/sources', 'POST', server.token, { action: 'add', path: folder })); - expect(added.status, await added.clone().text()).toBe(200); - const source = (await added.json()).sources[0]; - expect(source).toMatchObject({ path: folder, facts: 0 }); - const values = await settings.GET(request('/api/panel/operator-defaults?include=values')); - expect(values.status).toBe(200); - const data = await values.json(); - expect(data.values.knowledgeSources).toContainEqual(expect.objectContaining({ id: source.id })); - rmdirSync(folder); - const refresh = await sources.POST(request('/api/cortex/sources', 'POST', server.token, { action: 'refresh' })); - expect(refresh.status).toBe(200); - await expect.poll(async () => (await (await sources.GET(request('/api/cortex/sources'))).json()).sources[0].state).toBe('error'); - expect((await (await fetch(request('/api/cortex/sources'))).json()).sources[0].state).toBe('error'); - folder = ''; - const removed = await settings.POST(request('/api/panel/operator-defaults?include=native', 'POST', server.token, { knowledgeSources: [], settingsTomlRevision: data.settingsToml.revision })); - expect(removed.status, await removed.clone().text()).toBe(200); - const listed = await sources.GET(request('/api/cortex/sources')); - expect(await listed.json()).toEqual({ sources: [] }); }); diff --git a/tests/o8d-native-route-inventory-real-path.test.ts b/tests/o8d-native-route-inventory-real-path.test.ts index 2e32dcb46a..5cdda1c6a3 100644 --- a/tests/o8d-native-route-inventory-real-path.test.ts +++ b/tests/o8d-native-route-inventory-real-path.test.ts @@ -251,7 +251,6 @@ const DYNAMIC_NEXT_CALLS = ['src/lib/ws-server/next-fetch.ts: buildNextUrl(pathn * hid here (#5768). A new module of this kind shows up as a change to this list. */ const API_BASE_CLIENTS = [ - 'src/lib/cortex/knowledge/reconcile.ts', 'src/lib/hooks/claude-code-pretool-hook.ts', 'src/lib/operator/settings-window-owner.ts', 'src/lib/orchestrator/http/reload.ts', diff --git a/tests/o8d-settings-window-owner-real-path.test.ts b/tests/o8d-settings-window-owner-real-path.test.ts index 291b233829..84b19a0117 100644 --- a/tests/o8d-settings-window-owner-real-path.test.ts +++ b/tests/o8d-settings-window-owner-real-path.test.ts @@ -9,7 +9,6 @@ import { afterAll, beforeAll, expect, it, vi } from 'vitest'; import { startParityReference } from './fixtures/ws-parity-server'; const fixture = vi.hoisted(() => ({ spawn: vi.fn(), auth: vi.fn(), invalidate: vi.fn(), entitlement: vi.fn() })); -vi.mock('@/lib/cortex/knowledge/index', () => { throw new Error('Next loaded the knowledge index'); }); vi.mock('@/lib/runtimes/shared/auth-detect', async original => ({ ...await original(), getRuntimeAuthSnapshot: fixture.auth, invalidateRuntimeAuthCache: fixture.invalidate })); vi.mock('@/lib/entitlement/store', async original => { const originalStore = await original(); fixture.entitlement.mockImplementation(originalStore.getEntitlementSync); return { ...originalStore, getEntitlementSync: fixture.entitlement }; }); vi.mock('@/lib/providers/child-process', async original => ({ ...await original(), spawn: fixture.spawn })); @@ -108,7 +107,7 @@ it('keeps structured and TOML window changes and rollback in Next with native tr expect(loop.status).toBe(503); }); -it('keeps knowledge state in WS and reads shared receipts, entitlements and runtime refresh there', async () => { +it('saves knowledge sources and reads shared receipts, entitlements and runtime refresh in WS', async () => { const { recordRoleRoutingReceipt } = await import('@/lib/operator/role-routing-ledger'); const receipt = recordRoleRoutingReceipt({ role: 'brain', requested: { backend: null, runtime: null, model: null, effort: null, label: 'Fixture' }, sources: { backend: 'default', runtime: 'default', model: 'default', effort: 'default' }, reason: 'Window owner fixture', status: 'selected' }); @@ -118,8 +117,7 @@ it('keeps knowledge state in WS and reads shared receipts, entitlements and runt const source = { id: crypto.randomUUID(), path: folder, name: 'Fixture notes', include: ['**/*.md'], exclude: [] }; const saved = await call({ experimentalNext: false, knowledgeSources: [source], settingsTomlRevision: before.settingsToml.revision }); expect(saved.status, await saved.clone().text()).toBe(200); - const sources = await fetch(`${origin}/api/cortex/sources`, { headers: { authorization: `Bearer ${server.token}` } }); - expect((await sources.json()).sources).toContainEqual(expect.objectContaining({ id: source.id })); + expect((await (await call()).json()).values.knowledgeSources).toContainEqual(expect.objectContaining({ id: source.id })); fixture.auth.mockClear(); fixture.invalidate.mockClear(); fixture.entitlement.mockClear(); writeFileSync(join(directory, 'entitlement.json'), JSON.stringify({ plan: 'free' })); const free = await (await call(undefined, '/api/panel/operator-defaults?refresh=runtime')).json(); @@ -136,47 +134,10 @@ it('keeps knowledge state in WS and reads shared receipts, entitlements and runt } finally { rmdirSync(folder); } }); -it('orders concurrent source writes behind a Next window save without blocking its WS reconciliation', async () => { - const folders = [0, 1].map(() => realpathSync(mkdtempSync(join(tmpdir(), 'o8-window-concurrent-notes-')))); - const before = await (await call()).json(); - const source = { id: crypto.randomUUID(), path: folders[0], name: 'First', include: ['**/*.md'], exclude: [] }; - const originalFetch = globalThis.fetch; - let entered = false; - let release!: () => void; - const held = new Promise(resolve => { release = resolve; }); - vi.stubGlobal('fetch', async (input: Parameters[0], init?: RequestInit) => { - if (typeof input === 'string' && input.endsWith('/api/cortex/sources') && typeof init?.body === 'string' - && JSON.parse(init.body).action === 'reconcile') { entered = true; await held; } - return originalFetch(input, init); - }); - try { - const saved = call({ experimentalNext: false, knowledgeSources: [source], settingsTomlRevision: before.settingsToml.revision }); - await expect.poll(() => entered).toBe(true); - let addSettled = false; - const added = originalFetch(`${origin}/api/cortex/sources`, { method: 'POST', - headers: { authorization: `Bearer ${server.token}`, 'content-type': 'application/json' }, - body: JSON.stringify({ action: 'add', path: folders[1] }), signal: AbortSignal.timeout(5_000), - }).then(response => { addSettled = true; return response; }); - await new Promise(resolve => setTimeout(resolve, 50)); - expect(addSettled).toBe(false); - release(); - const responses = await Promise.all([saved, added]); - expect(responses.map(response => response.status)).toEqual([200, 200]); - const sources = await (await originalFetch(`${origin}/api/cortex/sources`, { headers: { authorization: `Bearer ${server.token}` } })).json(); - expect(sources.sources.map((entry: { path: string }) => entry.path).sort()).toEqual([...folders].sort()); - } finally { release(); vi.unstubAllGlobals(); folders.forEach(folder => rmdirSync(folder)); } -}); - -it('serves the plain settings save from Next and keeps it when index reconciliation fails', async () => { +it('serves the plain settings save from Next', async () => { const dummy = join(directory, 'stub-window'); vi.stubEnv('O8_NEXT_BIN', dummy); const folder = realpathSync(mkdtempSync(join(tmpdir(), 'o8-window-plain-notes-'))); - const originalFetch = globalThis.fetch; - vi.stubGlobal('fetch', async (input: Parameters[0], init?: RequestInit) => { - if (typeof input === 'string' && input.endsWith('/api/cortex/sources') && typeof init?.body === 'string' - && JSON.parse(init.body).action === 'reconcile') return new Response('{}', { status: 503 }); - return originalFetch(input, init); - }); try { const spawned = fixture.spawn.mock.calls.length; const before = await (await call()).json(); @@ -198,7 +159,7 @@ it('serves the plain settings save from Next and keeps it when index reconciliat expect(disabled.status).toBe(200); expect(runtime.__o8NativeWindow?.child).toBeUndefined(); expect(existsSync(join(directory, 'ws-window-actions'))).toBe(false); - } finally { vi.unstubAllGlobals(); rmdirSync(folder); } + } finally { rmdirSync(folder); } }); it('answers native settings reads when the window owner is not running', async () => { diff --git a/tests/test-classification.json b/tests/test-classification.json index 786fe89a5b..ccbd4c7ea8 100644 --- a/tests/test-classification.json +++ b/tests/test-classification.json @@ -3743,16 +3743,6 @@ "real-path" ] }, - { - "path": "tests/knowledge-sources-real-path.test.ts", - "reasons": [ - "child-process", - "git-cli", - "network-listener", - "real-path", - "worktree-api" - ] - }, { "path": "tests/lane-branch-binding-diff.test.ts", "reasons": [