diff --git a/libs/research/README.md b/libs/research/README.md index e3e62776..c56c99ac 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -267,7 +267,7 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported ### Filesystem Library Cards Adapter - **`createLibraryCardReader({ root, fs })`** (exported from `@stock-bot/research/mcp` alongside `createNodeLibraryCardFs`, `LibraryCardFs`, `LibraryCardDirHandle`, `LibraryCardDirEntry`, `LibraryCardReaderOptions`, `LibraryCardReader`, `LibraryCardError`, and `LibraryCardErrorCode`) implements `Pick` over a configured read-only library root (`/library.yml` and `/cards//.md`) with zero new dependencies. -- **Read-only boundary, fresh reads & symlink safety:** Resolves `root` once at construction, reads `library.yml` and eligible cards fresh on every call (no cache), anchors listings and file reads to opened directory handles (`openDir` / `/proc/self/fd/` in `createNodeLibraryCardFs()`), enforces `O_NOFOLLOW` on every component below the configured root with `fstat` regular-file/directory verification, and fails closed if the runtime cannot enforce that boundary. +- **Read-only boundary, fresh reads & symlink safety:** Resolves `root` once at construction, reads `library.yml` and eligible cards fresh on every call (no cache), requires anchored directory operations (`LibraryCardFs.openDir`, backed by `/proc/self/fd/` in `createNodeLibraryCardFs()`) with no pathname fallback, enforces `O_NOFOLLOW` on every component below the configured root with `fstat` regular-file/directory verification, and fails closed if the adapter or runtime cannot enforce that boundary. - **Exact-ID narrowing & unverified-card assumption:** Returns all eligible cards in manifest section order and code-unit slug order without pre-slicing or truncating text, narrowing only on exact case-sensitive `q.id` (malformed or unknown IDs return an empty frozen array without opening card files) so `createReadKnowledgeTool` owns `query`/`tags` filtering, ranking, truncation, and `limit`. All eligible cards are returned regardless of `verified` status, and callers must bind `root` to a research-visible corpus free of holdout or Vault-only observations. ### Copilot Server diff --git a/libs/research/src/mcp/adapters/library-cards.ts b/libs/research/src/mcp/adapters/library-cards.ts index 6994f173..5a31eac6 100644 --- a/libs/research/src/mcp/adapters/library-cards.ts +++ b/libs/research/src/mcp/adapters/library-cards.ts @@ -14,7 +14,7 @@ import type { KnowledgePort, LibraryCardQuery, LibraryCardRecord } from '../tool const SAFE_IDENT_RE = /^[a-z0-9][a-z0-9-]*$/; const LIBRARY_ID_RE = /^[a-z0-9][a-z0-9_-]*$/; -const SECTION_KEY_SYNTAX_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/; +const PLAIN_YAML_KEY_RE = /^[^?:,[\]{}#&*!|>'"%@`\s][^,[\]{}#\s]*$/; const BLOCK_SCALAR_RE = /^[|>][+-]?$/; /** Error codes thrown by {@link LibraryCardError}. */ @@ -55,7 +55,7 @@ export interface LibraryCardDirHandle { export interface LibraryCardFs { readTextFile(filePath: string): Promise; listDir(dirPath: string): Promise; - openDir?(dirPath: string): Promise; + openDir(dirPath: string): Promise; } /** Factory options for {@link createLibraryCardReader}. */ @@ -124,11 +124,11 @@ function validateFactoryOptions(options: LibraryCardReaderOptions): { fs === null || typeof fs.readTextFile !== 'function' || typeof fs.listDir !== 'function' || - (fs.openDir !== undefined && typeof fs.openDir !== 'function') + typeof fs.openDir !== 'function' ) { throw new LibraryCardError( 'INVALID_FS', - 'Invalid fs: expected a LibraryCardFs implementing readTextFile and listDir.' + 'Invalid fs: expected a LibraryCardFs implementing readTextFile, listDir, and openDir.' ); } @@ -252,7 +252,7 @@ function parseLibraryManifest(content: string): ParsedLibraryManifest { const afterColon = body.slice(colonIdx + 1); if ( rawKey !== sectionKey || - !SECTION_KEY_SYNTAX_RE.test(sectionKey) || + !PLAIN_YAML_KEY_RE.test(sectionKey) || (afterColon.length > 0 && afterColon[0] !== ' ' && afterColon[0] !== '\t') ) { throw invalidLibrary('malformed entry inside "sections" map.'); @@ -481,32 +481,10 @@ function isValidDirHandle(value: unknown): value is LibraryCardDirHandle { ); } -function createPathBackedDirHandle(fs: LibraryCardFs, dirPath: string): LibraryCardDirHandle { - return { - listDir(): Promise { - return fs.listDir(dirPath); - }, - async openSubdir(name: string): Promise { - assertSafeChildName(name); - return createPathBackedDirHandle(fs, path.join(dirPath, name)); - }, - readTextFile(name: string): Promise { - assertSafeChildName(name); - return fs.readTextFile(path.join(dirPath, name)); - }, - async close(): Promise { - // No underlying OS handle to close for path-backed adapters. - }, - }; -} - async function safeOpenRootDir( fs: LibraryCardFs, resolvedRoot: string ): Promise { - if (fs.openDir === undefined) { - return createPathBackedDirHandle(fs, resolvedRoot); - } let handle: unknown; try { handle = await fs.openDir(resolvedRoot); @@ -777,93 +755,12 @@ export function createLibraryCardReader(options: LibraryCardReaderOptions): Libr const manifest = parseLibraryManifest(manifestText); const declaredSections = new Set(manifest.sections); + let target: { readonly sectionId: string; readonly slug: string } | null = null; if (q.id !== undefined) { - const target = parseExactCardId(q.id, manifest.id, declaredSections); + target = parseExactCardId(q.id, manifest.id, declaredSections); if (target === null) { return Object.freeze([]); } - - const rootEntries = await safeListDirHandle( - rootDir, - 'Invalid library.yml: failed to list library root directory.', - false - ); - const hasCardsDir = rootEntries.some( - entry => entry.name === 'cards' && entry.isDirectory && !entry.isFile - ); - if (!hasCardsDir) { - return Object.freeze([]); - } - - const cardsDir = await safeOpenSubdir( - rootDir, - 'cards', - 'Invalid library.yml: failed to open library cards directory.', - true - ); - if (cardsDir === null) { - return Object.freeze([]); - } - - try { - const cardDirEntries = await safeListDirHandle( - cardsDir, - 'Invalid library.yml: failed to list library cards directory.', - true - ); - const hasSectionDir = cardDirEntries.some( - entry => entry.name === target.sectionId && entry.isDirectory && !entry.isFile - ); - if (!hasSectionDir) { - return Object.freeze([]); - } - - const sectionDir = await safeOpenSubdir( - cardsDir, - target.sectionId, - `Invalid library.yml: failed to open section directory "cards/${target.sectionId}".`, - true - ); - if (sectionDir === null) { - return Object.freeze([]); - } - - try { - const sectionEntries = await safeListDirHandle( - sectionDir, - `Invalid library.yml: failed to list section directory "cards/${target.sectionId}".`, - true - ); - const targetFileName = `${target.slug}.md`; - let matchCount = 0; - for (let i = 0; i < sectionEntries.length; i += 1) { - const entry = sectionEntries[i] as LibraryCardDirEntry; - if (entry.isFile && !entry.isDirectory && entry.name === targetFileName) { - matchCount += 1; - } - } - if (matchCount === 0) { - return Object.freeze([]); - } - const relPath = `cards/${target.sectionId}/${target.slug}.md`; - if (matchCount > 1) { - throw invalidCard(relPath, 'duplicate card id.'); - } - - const cardText = await safeReadTextFileFromDir( - sectionDir, - targetFileName, - 'INVALID_CARD', - `Invalid card "${relPath}": failed to read card file.` - ); - const record = parseCardDocument(cardText, manifest.id, target.sectionId, target.slug); - return Object.freeze([record]); - } finally { - await sectionDir.close(); - } - } finally { - await cardsDir.close(); - } } const rootEntries = await safeListDirHandle( @@ -902,11 +799,12 @@ export function createLibraryCardReader(options: LibraryCardReaderOptions): Libr } } + const sectionsToScan = target !== null ? [target.sectionId] : manifest.sections; const cards: LibraryCardRecord[] = []; const seenIds = new Set(); - for (let s = 0; s < manifest.sections.length; s += 1) { - const sectionId = manifest.sections[s] as string; + for (let s = 0; s < sectionsToScan.length; s += 1) { + const sectionId = sectionsToScan[s] as string; if (!presentSectionDirs.has(sectionId)) { continue; } @@ -929,6 +827,7 @@ export function createLibraryCardReader(options: LibraryCardReaderOptions): Libr ); const slugs: string[] = []; + const seenSectionSlugs = new Set(); for (let i = 0; i < sectionEntries.length; i += 1) { const entry = sectionEntries[i] as LibraryCardDirEntry; if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) { @@ -938,6 +837,13 @@ export function createLibraryCardReader(options: LibraryCardReaderOptions): Libr if (!SAFE_IDENT_RE.test(slug)) { continue; } + if (target !== null && slug !== target.slug) { + continue; + } + if (seenSectionSlugs.has(slug)) { + throw invalidCard(`cards/${sectionId}/${slug}.md`, 'duplicate card id.'); + } + seenSectionSlugs.add(slug); slugs.push(slug); } diff --git a/libs/research/test/mcp-library-cards.test.ts b/libs/research/test/mcp-library-cards.test.ts index e9ca8828..fb173c01 100644 --- a/libs/research/test/mcp-library-cards.test.ts +++ b/libs/research/test/mcp-library-cards.test.ts @@ -110,30 +110,84 @@ function createFakeLibraryFs(init?: { } } + const readFileByPath = async (filePath: string): Promise => { + readPaths.push(filePath); + const forcedErr = readErrors.get(filePath); + if (forcedErr !== undefined) { + throw forcedErr; + } + const text = files.get(filePath); + if (text === undefined) { + throw makeEnoent(filePath); + } + return text; + }; + + const listDirByPath = async (dirPath: string): Promise => { + listPaths.push(dirPath); + const forcedErr = listErrors.get(dirPath); + if (forcedErr !== undefined) { + throw forcedErr; + } + const entries = dirs.get(dirPath); + if (entries === undefined) { + throw makeEnoent(dirPath); + } + return [...entries]; + }; + + const createAnchoredFakeDirHandle = (dirPath: string): LibraryCardDirHandle => { + let closed = false; + const assertOpen = (): void => { + if (closed) { + throw new Error(`Directory handle already closed: ${dirPath}`); + } + }; + const assertChildName = (name: string): void => { + if ( + name.length === 0 || + name === '.' || + name === '..' || + name.includes('/') || + name.includes('\\') || + name.includes('\0') + ) { + throw new Error(`Invalid child name: ${name}`); + } + }; + return { + async listDir(): Promise { + assertOpen(); + return listDirByPath(dirPath); + }, + async openSubdir(name: string): Promise { + assertOpen(); + assertChildName(name); + const childPath = path.join(dirPath, name); + if (!dirs.has(childPath)) { + throw makeEnoent(childPath); + } + return createAnchoredFakeDirHandle(childPath); + }, + async readTextFile(name: string): Promise { + assertOpen(); + assertChildName(name); + return readFileByPath(path.join(dirPath, name)); + }, + async close(): Promise { + closed = true; + }, + }; + }; + const fs: LibraryCardFs = { - async readTextFile(filePath: string): Promise { - readPaths.push(filePath); - const forcedErr = readErrors.get(filePath); - if (forcedErr !== undefined) { - throw forcedErr; - } - const text = files.get(filePath); - if (text === undefined) { - throw makeEnoent(filePath); - } - return text; - }, - async listDir(dirPath: string): Promise { - listPaths.push(dirPath); - const forcedErr = listErrors.get(dirPath); - if (forcedErr !== undefined) { - throw forcedErr; - } - const entries = dirs.get(dirPath); - if (entries === undefined) { + readTextFile: readFileByPath, + listDir: listDirByPath, + async openDir(dirPath: string): Promise { + if (dirPath !== VIRTUAL_ROOT && !dirs.has(dirPath)) { throw makeEnoent(dirPath); } - return [...entries]; + return createAnchoredFakeDirHandle(dirPath); }, }; @@ -282,6 +336,8 @@ describe('MCP library-cards filesystem adapter', () => { 'library.yml': `id: quant sections: alphas: Alphas + -draft: Draft notes + .archived: Archived notes Bad_Section: Invalid section name empty-section: Declared section with no directory `, @@ -291,6 +347,7 @@ sections: 'cards/alphas/UpperCase.md': MOMENTUM_CARD, 'cards/alphas/symlink-card.md': MOMENTUM_CARD, 'cards/undeclared/secret.md': MOMENTUM_CARD, + 'cards/-draft/valid-card.md': MOMENTUM_CARD, 'cards/Bad_Section/valid-card.md': MOMENTUM_CARD, }, dirs: { @@ -301,6 +358,7 @@ sections: cards: [ { name: 'alphas', isFile: false, isDirectory: true }, { name: 'undeclared', isFile: false, isDirectory: true }, + { name: '-draft', isFile: false, isDirectory: true }, { name: 'Bad_Section', isFile: false, isDirectory: true }, { name: 'symlink-section', isFile: false, isDirectory: false }, ], @@ -352,6 +410,19 @@ sections: }), 'INVALID_FS' ); + // A two-method wrapper omitting anchored openDir must fail closed at construction. + const nodeFs = createNodeLibraryCardFs(); + await expectLibraryCardError( + () => + createLibraryCardReader({ + root: VIRTUAL_ROOT, + fs: { + readTextFile: p => nodeFs.readTextFile(p), + listDir: p => nodeFs.listDir(p), + } as unknown as LibraryCardFs, + }), + 'INVALID_FS' + ); // Zero I/O happened during invalid option checks. expect(fake.readPaths).toHaveLength(0); @@ -750,9 +821,7 @@ LEAKED_SIBLING_CONTENT readTextFile: p => baseNodeFs.readTextFile(p), listDir: p => baseNodeFs.listDir(p), async openDir(dirPath: string): Promise { - const rootHandle = await (baseNodeFs.openDir as NonNullable)( - dirPath - ); + const rootHandle = await baseNodeFs.openDir(dirPath); return { listDir: () => rootHandle.listDir(), readTextFile: name => rootHandle.readTextFile(name), @@ -799,9 +868,7 @@ LEAKED_SIBLING_CONTENT readTextFile: p => baseNodeFs.readTextFile(p), listDir: p => baseNodeFs.listDir(p), async openDir(dirPath: string): Promise { - const rootHandle = await (baseNodeFs.openDir as NonNullable)( - dirPath - ); + const rootHandle = await baseNodeFs.openDir(dirPath); return { listDir: () => rootHandle.listDir(), readTextFile: name => rootHandle.readTextFile(name),