From 8ee307678fb4585ef2d0fe82dbac17121a56e8f8 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:18:11 -0500 Subject: [PATCH 1/4] =?UTF-8?q?T-163:=20M2.1m=20=E2=80=94=20Filesystem=20l?= =?UTF-8?q?ibrary=20adapter=20for=20the=20MCP=20copilot=20`read=5Fknowledg?= =?UTF-8?q?e`=20tool:=20`KnowledgePort.listLibraryCards`=20over=20`library?= =?UTF-8?q?.yml`=20+=20`cards/
/*.md`=20in=20`libs/research/src/mc?= =?UTF-8?q?p/adapters/library-cards.ts`=20(injected=20read-only=20fs=20por?= =?UTF-8?q?t,=20strict=20front-matter=20parser,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 6 + .../src/mcp/adapters/library-cards.ts | 708 ++++++++++++++++++ libs/research/src/mcp/index.ts | 1 + libs/research/test/mcp-library-cards.test.ts | 705 +++++++++++++++++ 4 files changed, 1420 insertions(+) create mode 100644 libs/research/src/mcp/adapters/library-cards.ts create mode 100644 libs/research/test/mcp-library-cards.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index cf49f406..bdad396f 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -264,6 +264,12 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`delistedAt` derivation:** Projects `delistedAt` as `listing.listed_to` (`YYYY-MM-DD`) when `delist_reason IS NOT NULL AND delist_reason <> 'active'`, else `null`. When `q.includeDelisted === false`, rows with non-null `delistedAt <= cutoff` are filtered out while future delistings (`delistedAt > cutoff`) remain eligible as of the cutoff. - **Port matching vs. MCP ranking:** The adapter matches on resolved as-of ticker (`ILIKE`), `listing.ticker_root` (`ILIKE`, gated by `NOT root_is_future`), `instrument.canonical_name` (`ILIKE`), or case-insensitive exact `instrument.primary_isin`, ignores `q.limit`, and returns all candidates ordered by `listing_id ASC`. When composed with `createSearchSymbolsTool`, the MCP tool applies Vault clamping/masking, ranks by exact ticker > ticker prefix > company name substring (tie-breaking by `listingId ASC`), and truncates to `limit` — so callers needing ticker-substring, root-only, or exact-ISIN lookups should call the port directly, while MCP tool callers should query by ticker or company name. +### Filesystem Library Cards Adapter + +- **`createLibraryCardReader({ root, fs })`** (exported from `@stock-bot/research/mcp` alongside `createNodeLibraryCardFs`, `LibraryCardFs`, `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), discovers `cards/` and declared section directories via parent listings so symbolic links are never followed, and opens text files read-only with `O_NOFOLLOW` + regular-file verification in `createNodeLibraryCardFs()`. +- **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 - **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions. diff --git a/libs/research/src/mcp/adapters/library-cards.ts b/libs/research/src/mcp/adapters/library-cards.ts new file mode 100644 index 00000000..a2798e97 --- /dev/null +++ b/libs/research/src/mcp/adapters/library-cards.ts @@ -0,0 +1,708 @@ +/** + * Read-only filesystem adapter for the MCP copilot `read_knowledge` tool, + * implementing {@link KnowledgePort.listLibraryCards} over `/library.yml` + * and `/cards//.md`. + * + * Filesystem access is injected via {@link LibraryCardFs} for hermetic testing, + * with {@link createNodeLibraryCardFs} provided for Node/Bun composition. + */ + +import { constants as fsConstants } from 'node:fs'; +import { open, readdir } from 'node:fs/promises'; +import path from 'node:path'; +import type { KnowledgePort, LibraryCardQuery, LibraryCardRecord } from '../tools/read-knowledge'; + +const SAFE_IDENT_RE = /^[a-z0-9][a-z0-9-]*$/; +const LIBRARY_ID_RE = /^[a-z0-9][a-z0-9_-]*$/; +const BLOCK_SCALAR_RE = /^[|>][+-]?$/; + +/** Error codes thrown by {@link LibraryCardError}. */ +export type LibraryCardErrorCode = + | 'INVALID_FS' + | 'INVALID_ROOT' + | 'INVALID_LIBRARY' + | 'INVALID_CARD'; + +/** Typed validation and I/O error thrown by the library card filesystem adapter. */ +export class LibraryCardError extends RangeError { + readonly code: LibraryCardErrorCode; + + constructor(code: LibraryCardErrorCode, message: string) { + super(message); + this.name = 'LibraryCardError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Directory entry metadata returned by {@link LibraryCardFs.listDir}. */ +export interface LibraryCardDirEntry { + readonly name: string; + readonly isFile: boolean; + readonly isDirectory: boolean; +} + +/** Minimal read-only filesystem port injected into {@link createLibraryCardReader}. */ +export interface LibraryCardFs { + readTextFile(filePath: string): Promise; + listDir(dirPath: string): Promise; +} + +/** Factory options for {@link createLibraryCardReader}. */ +export interface LibraryCardReaderOptions { + readonly root: string; + readonly fs: LibraryCardFs; +} + +/** Library-card subset of {@link KnowledgePort}. */ +export type LibraryCardReader = Pick; + +interface ParsedLibraryManifest { + readonly id: string; + readonly sections: readonly string[]; +} + +type FrontMatterValue = string | readonly string[]; + +function compareCodeUnits(a: string, b: string): number { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; +} + +function isEnoentError(err: unknown): boolean { + return ( + typeof err === 'object' && + err !== null && + (err as { readonly code?: unknown }).code === 'ENOENT' + ); +} + +function invalidLibrary(reason: string): LibraryCardError { + return new LibraryCardError('INVALID_LIBRARY', `Invalid library.yml: ${reason}`); +} + +function invalidCard(relPath: string, reason: string): LibraryCardError { + return new LibraryCardError('INVALID_CARD', `Invalid card "${relPath}": ${reason}`); +} + +function validateFactoryOptions(options: LibraryCardReaderOptions): { + readonly resolvedRoot: string; + readonly fs: LibraryCardFs; +} { + if (typeof options !== 'object' || options === null) { + throw new LibraryCardError( + 'INVALID_ROOT', + 'Invalid options: expected an object with root and fs.' + ); + } + + const { root, fs } = options; + if (typeof root !== 'string' || root.trim().length === 0 || root.includes('\0')) { + throw new LibraryCardError( + 'INVALID_ROOT', + 'Invalid root: expected a non-empty filesystem path without null bytes.' + ); + } + + if ( + typeof fs !== 'object' || + fs === null || + typeof fs.readTextFile !== 'function' || + typeof fs.listDir !== 'function' + ) { + throw new LibraryCardError( + 'INVALID_FS', + 'Invalid fs: expected a LibraryCardFs implementing readTextFile and listDir.' + ); + } + + return { + resolvedRoot: path.resolve(root), + fs, + }; +} + +function parseLibraryScalar(rawValue: string): string { + if (rawValue.length === 0) { + throw invalidLibrary('"id" must not be empty.'); + } + if (rawValue.startsWith("'")) { + throw invalidLibrary('single-quoted "id" values are not supported.'); + } + if (rawValue.startsWith('"')) { + let parsed: unknown; + try { + parsed = JSON.parse(rawValue); + } catch { + throw invalidLibrary('invalid double-quoted "id" value.'); + } + if (typeof parsed !== 'string') { + throw invalidLibrary('invalid double-quoted "id" value.'); + } + return parsed; + } + if (rawValue.startsWith('[') || rawValue.startsWith('{') || BLOCK_SCALAR_RE.test(rawValue)) { + throw invalidLibrary('"id" must be a scalar string.'); + } + return rawValue; +} + +function parseLibraryManifest(content: string): ParsedLibraryManifest { + const lines = content.split(/\r?\n/); + + let libraryId: string | undefined; + let sawSections = false; + let sectionsIndent: number | null = null; + let currentTopLevelKey: string | null = null; + const seenSectionKeys = new Set(); + const validSections: string[] = []; + + for (let i = 0; i < lines.length; i += 1) { + const line = lines[i] as string; + const trimmed = line.trim(); + if (trimmed.length === 0 || trimmed.startsWith('#')) { + continue; + } + + let indent = 0; + while (indent < line.length && line[indent] === ' ') { + indent += 1; + } + if (line[indent] === '\t') { + throw invalidLibrary('tab indentation is not supported.'); + } + + if (indent === 0) { + const colonIdx = line.indexOf(':'); + if (colonIdx <= 0) { + throw invalidLibrary('malformed top-level entry.'); + } + const key = line.slice(0, colonIdx).trim(); + const rawValue = line.slice(colonIdx + 1).trim(); + if (key.length === 0 || /\s/.test(key)) { + throw invalidLibrary('invalid top-level key.'); + } + + currentTopLevelKey = key; + + if (key === 'id') { + if (libraryId !== undefined) { + throw invalidLibrary('duplicate "id" declaration.'); + } + const parsedId = parseLibraryScalar(rawValue); + if (!LIBRARY_ID_RE.test(parsedId)) { + throw invalidLibrary('"id" must match ^[a-z0-9][a-z0-9_-]*$.'); + } + libraryId = parsedId; + } else if (key === 'sections') { + if (sawSections) { + throw invalidLibrary('duplicate "sections" declaration.'); + } + if (rawValue.length > 0) { + throw invalidLibrary('"sections" must be an indented map.'); + } + sawSections = true; + sectionsIndent = null; + } + continue; + } + + if (currentTopLevelKey === null) { + throw invalidLibrary('indented entry before any top-level declaration.'); + } + if (currentTopLevelKey === 'id') { + throw invalidLibrary('"id" must be a single-line scalar.'); + } + if (currentTopLevelKey !== 'sections') { + continue; + } + + if (sectionsIndent === null) { + sectionsIndent = indent; + } else if (indent !== sectionsIndent) { + throw invalidLibrary('inconsistent indentation inside "sections" map.'); + } + + const body = line.slice(indent); + const colonIdx = body.indexOf(':'); + if (colonIdx <= 0) { + throw invalidLibrary('malformed entry inside "sections" map.'); + } + const sectionKey = body.slice(0, colonIdx).trim(); + const sectionTitle = body.slice(colonIdx + 1).trim(); + if (sectionKey.length === 0 || sectionTitle.length === 0) { + throw invalidLibrary('empty key or title inside "sections" map.'); + } + if (seenSectionKeys.has(sectionKey)) { + throw invalidLibrary('duplicate key inside "sections" map.'); + } + seenSectionKeys.add(sectionKey); + + if (SAFE_IDENT_RE.test(sectionKey)) { + validSections.push(sectionKey); + } + } + + if (libraryId === undefined) { + throw invalidLibrary('missing "id" declaration.'); + } + if (!sawSections || seenSectionKeys.size === 0) { + throw invalidLibrary('missing or empty "sections" map.'); + } + + return { + id: libraryId, + sections: validSections, + }; +} + +function parseFrontMatterValue(rawValue: string, relPath: string): FrontMatterValue { + if (rawValue.length === 0) { + throw invalidCard(relPath, 'empty or multiline front-matter value.'); + } + if (BLOCK_SCALAR_RE.test(rawValue)) { + throw invalidCard(relPath, 'multiline front-matter values are not supported.'); + } + if (rawValue.startsWith("'")) { + throw invalidCard(relPath, 'single-quoted front-matter values are not supported.'); + } + if (rawValue.startsWith('{')) { + throw invalidCard(relPath, 'object front-matter values are not supported.'); + } + + if (rawValue.startsWith('"')) { + let parsed: unknown; + try { + parsed = JSON.parse(rawValue); + } catch { + throw invalidCard(relPath, 'invalid double-quoted front-matter string.'); + } + if (typeof parsed !== 'string') { + throw invalidCard(relPath, 'invalid double-quoted front-matter string.'); + } + return parsed; + } + + if (rawValue.startsWith('[')) { + let parsed: unknown; + try { + parsed = JSON.parse(rawValue); + } catch { + throw invalidCard(relPath, 'invalid front-matter array.'); + } + if (!Array.isArray(parsed)) { + throw invalidCard(relPath, 'invalid front-matter array.'); + } + const items: string[] = []; + for (let i = 0; i < parsed.length; i += 1) { + const entry: unknown = parsed[i]; + if (typeof entry !== 'string') { + throw invalidCard(relPath, 'front-matter array entries must be strings.'); + } + items.push(entry); + } + return items; + } + + return rawValue; +} + +function parseCardDocument( + content: string, + libraryId: string, + sectionId: string, + slug: string +): LibraryCardRecord { + const relPath = `cards/${sectionId}/${slug}.md`; + const lines = content.split(/\r?\n/); + + if (lines[0] !== '---') { + throw invalidCard(relPath, 'missing opening front-matter delimiter.'); + } + + let closingIndex = -1; + for (let i = 1; i < lines.length; i += 1) { + if (lines[i] === '---') { + closingIndex = i; + break; + } + } + if (closingIndex === -1) { + throw invalidCard(relPath, 'missing closing front-matter delimiter.'); + } + + const fields = new Map(); + for (let i = 1; i < closingIndex; i += 1) { + const line = lines[i] as string; + const trimmed = line.trim(); + if (trimmed.length === 0 || trimmed.startsWith('#')) { + continue; + } + if (line[0] === ' ' || line[0] === '\t') { + throw invalidCard(relPath, 'multiline or indented front-matter values are not supported.'); + } + + const colonIdx = line.indexOf(':'); + if (colonIdx <= 0) { + throw invalidCard(relPath, 'malformed front-matter entry.'); + } + const key = line.slice(0, colonIdx).trim(); + if (key.length === 0 || /\s/.test(key)) { + throw invalidCard(relPath, 'invalid front-matter key.'); + } + if (fields.has(key)) { + throw invalidCard(relPath, 'duplicate front-matter key.'); + } + + const rawValue = line.slice(colonIdx + 1).trim(); + fields.set(key, parseFrontMatterValue(rawValue, relPath)); + } + + const rawTitle = fields.get('title'); + if (typeof rawTitle !== 'string' || rawTitle.trim().length === 0) { + throw invalidCard(relPath, 'missing or empty "title".'); + } + + const rawSummary = fields.get('summary'); + if (typeof rawSummary !== 'string' || rawSummary.trim().length === 0) { + throw invalidCard(relPath, 'missing or empty "summary".'); + } + + const rawMatches = fields.get('matches'); + if (rawMatches !== undefined && !Array.isArray(rawMatches)) { + throw invalidCard(relPath, '"matches" must be an array of strings.'); + } + + const tags: string[] = []; + const seenTags = new Set(); + const addTag = (raw: string): void => { + const normalized = raw.trim().toLowerCase(); + if (normalized.length > 0 && !seenTags.has(normalized)) { + seenTags.add(normalized); + tags.push(normalized); + } + }; + + addTag(sectionId); + if (rawMatches !== undefined) { + for (let i = 0; i < rawMatches.length; i += 1) { + addTag(rawMatches[i] as string); + } + } + + const body = lines + .slice(closingIndex + 1) + .join('\n') + .trim(); + + return Object.freeze({ + id: `${libraryId}:${sectionId}/${slug}`, + title: rawTitle, + tags: Object.freeze(tags), + summary: rawSummary, + body, + }); +} + +function parseExactCardId( + id: string, + libraryId: string, + declaredSections: ReadonlySet +): { readonly sectionId: string; readonly slug: string } | null { + const prefix = `${libraryId}:`; + if (!id.startsWith(prefix)) { + return null; + } + const rest = id.slice(prefix.length); + const slashIdx = rest.indexOf('/'); + if (slashIdx <= 0 || rest.indexOf('/', slashIdx + 1) !== -1) { + return null; + } + const sectionId = rest.slice(0, slashIdx); + const slug = rest.slice(slashIdx + 1); + if (!SAFE_IDENT_RE.test(sectionId) || !SAFE_IDENT_RE.test(slug)) { + return null; + } + if (!declaredSections.has(sectionId)) { + return null; + } + return { sectionId, slug }; +} + +async function safeReadTextFile( + fs: LibraryCardFs, + filePath: string, + errorCode: 'INVALID_LIBRARY' | 'INVALID_CARD', + errorMessage: string +): Promise { + let content: unknown; + try { + content = await fs.readTextFile(filePath); + } catch { + throw new LibraryCardError(errorCode, errorMessage); + } + if (typeof content !== 'string') { + throw new LibraryCardError(errorCode, errorMessage); + } + return content; +} + +async function safeListDir( + fs: LibraryCardFs, + dirPath: string, + errorMessage: string, + allowMissing: boolean +): Promise { + let rawEntries: unknown; + try { + rawEntries = await fs.listDir(dirPath); + } catch (err) { + if (allowMissing && isEnoentError(err)) { + return []; + } + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + + if (!Array.isArray(rawEntries)) { + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + + const entries: LibraryCardDirEntry[] = []; + for (let i = 0; i < rawEntries.length; i += 1) { + const entry: unknown = rawEntries[i]; + if ( + typeof entry !== 'object' || + entry === null || + typeof (entry as { readonly name?: unknown }).name !== 'string' || + typeof (entry as { readonly isFile?: unknown }).isFile !== 'boolean' || + typeof (entry as { readonly isDirectory?: unknown }).isDirectory !== 'boolean' + ) { + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + entries.push(entry as LibraryCardDirEntry); + } + + return entries; +} + +/** + * Creates a read-only {@link LibraryCardFs} backed by `node:fs/promises`. + * + * Opens text files read-only with `O_NOFOLLOW` (where supported) and confirms + * they are regular files before reading, and reports directory entry types + * without following symbolic links. + */ +export function createNodeLibraryCardFs(): LibraryCardFs { + const noFollowFlag = typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0; + const openFlags = fsConstants.O_RDONLY | noFollowFlag; + + return { + async readTextFile(filePath: string): Promise { + const handle = await open(filePath, openFlags); + try { + const stats = await handle.stat(); + if (!stats.isFile()) { + throw new Error('Target path is not a regular file.'); + } + return await handle.readFile({ encoding: 'utf8' }); + } finally { + await handle.close(); + } + }, + + async listDir(dirPath: string): Promise { + const dirents = await readdir(dirPath, { withFileTypes: true }); + const entries: LibraryCardDirEntry[] = []; + for (let i = 0; i < dirents.length; i += 1) { + const dirent = dirents[i]; + if (dirent !== undefined) { + entries.push({ + name: dirent.name, + isFile: dirent.isFile(), + isDirectory: dirent.isDirectory(), + }); + } + } + return entries; + }, + }; +} + +/** + * Creates a read-only filesystem reader implementing + * {@link KnowledgePort.listLibraryCards} over `/library.yml` and + * `/cards//.md`. + * + * Reads fresh from the injected {@link LibraryCardFs} on every call, narrows + * only by exact case-sensitive `q.id` (leaving `q.query`, `q.tags`, ranking, + * truncation, and `limit` to `createReadKnowledgeTool`), and returns all + * eligible cards regardless of `verified` status. + */ +export function createLibraryCardReader(options: LibraryCardReaderOptions): LibraryCardReader { + const { resolvedRoot, fs } = validateFactoryOptions(options); + const manifestPath = path.join(resolvedRoot, 'library.yml'); + const cardsDirPath = path.join(resolvedRoot, 'cards'); + + return { + async listLibraryCards(q: LibraryCardQuery): Promise { + const manifestText = await safeReadTextFile( + fs, + manifestPath, + 'INVALID_LIBRARY', + 'Invalid library.yml: failed to read manifest.' + ); + const manifest = parseLibraryManifest(manifestText); + const declaredSections = new Set(manifest.sections); + + if (q.id !== undefined) { + const target = parseExactCardId(q.id, manifest.id, declaredSections); + if (target === null) { + return Object.freeze([]); + } + + const rootEntries = await safeListDir( + fs, + resolvedRoot, + '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 cardDirEntries = await safeListDir( + fs, + cardsDirPath, + '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 sectionDirPath = path.join(cardsDirPath, target.sectionId); + const sectionEntries = await safeListDir( + fs, + sectionDirPath, + `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 safeReadTextFile( + fs, + path.join(sectionDirPath, 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]); + } + + const rootEntries = await safeListDir( + fs, + resolvedRoot, + '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 cardDirEntries = await safeListDir( + fs, + cardsDirPath, + 'Invalid library.yml: failed to list library cards directory.', + true + ); + const presentSectionDirs = new Set(); + for (let i = 0; i < cardDirEntries.length; i += 1) { + const entry = cardDirEntries[i] as LibraryCardDirEntry; + if (entry.isDirectory && !entry.isFile && SAFE_IDENT_RE.test(entry.name)) { + presentSectionDirs.add(entry.name); + } + } + + const cards: LibraryCardRecord[] = []; + const seenIds = new Set(); + + for (let s = 0; s < manifest.sections.length; s += 1) { + const sectionId = manifest.sections[s] as string; + if (!presentSectionDirs.has(sectionId)) { + continue; + } + + const sectionDirPath = path.join(cardsDirPath, sectionId); + const sectionEntries = await safeListDir( + fs, + sectionDirPath, + `Invalid library.yml: failed to list section directory "cards/${sectionId}".`, + true + ); + + const slugs: string[] = []; + for (let i = 0; i < sectionEntries.length; i += 1) { + const entry = sectionEntries[i] as LibraryCardDirEntry; + if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) { + continue; + } + const slug = entry.name.slice(0, -3); + if (!SAFE_IDENT_RE.test(slug)) { + continue; + } + slugs.push(slug); + } + + slugs.sort(compareCodeUnits); + + for (let i = 0; i < slugs.length; i += 1) { + const slug = slugs[i] as string; + const relPath = `cards/${sectionId}/${slug}.md`; + const canonicalId = `${manifest.id}:${sectionId}/${slug}`; + if (seenIds.has(canonicalId)) { + throw invalidCard(relPath, 'duplicate card id.'); + } + seenIds.add(canonicalId); + + const cardText = await safeReadTextFile( + fs, + path.join(sectionDirPath, `${slug}.md`), + 'INVALID_CARD', + `Invalid card "${relPath}": failed to read card file.` + ); + cards.push(parseCardDocument(cardText, manifest.id, sectionId, slug)); + } + } + + return Object.freeze(cards); + }, + }; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index e598bcfa..afe3358e 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,3 +1,4 @@ +export * from './adapters/library-cards'; export * from './adapters/postgres-symbol-search'; export * from './adapters/postgres-trial-ref'; export * from './copilot-server'; diff --git a/libs/research/test/mcp-library-cards.test.ts b/libs/research/test/mcp-library-cards.test.ts new file mode 100644 index 00000000..04edcc91 --- /dev/null +++ b/libs/research/test/mcp-library-cards.test.ts @@ -0,0 +1,705 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { + type KnowledgePort, + type LibraryCardDirEntry, + LibraryCardError, + type LibraryCardFs, + READ_KNOWLEDGE_MAX_TEXT_LENGTH, + type ReadKnowledgeResultPayload, + createLibraryCardReader, + createMcpServer, + createNodeLibraryCardFs, + createReadKnowledgeTool, +} from '../src/mcp/index'; + +const VIRTUAL_ROOT = '/virtual/quant-library'; + +const PIOTROSKI_CARD = `--- +verified: false +checked: 2026-03-15 +title: "Piotroski F-Score: Value, Quality (1976–2000)" +summary: "Nine-signal accounting screen: profitability, leverage, and operating efficiency." +excerpt: "Separates winners from value traps among high book-to-market equities." +matches: [" Value ", "Fundamental", "alphas", "value", "Quality"] +related: ["quant:alphas/novy-marx-gross-profitability"] +sources: ["https://doi.org/10.2307/2672906", "https://example.com/papers/f-score?year=2000&mode=full"] +confidence: high +topic: fundamental-value +--- + +# Piotroski F-Score + +Nine binary fundamental signals evaluated strictly point-in-time. +`; + +const MOMENTUM_CARD = `--- +verified: true +checked: 2026-03-10 +title: "Cross-Sectional Momentum (12-1)" +summary: "Twelve-month return skipping the most recent month." +--- + +Skipping the last month mitigates short-term reversal. +`; + +const LIVE_OPS_CARD = `--- +verified: false +checked: 2026-03-12 +title: "IBKR Margin & FX Rebalance Checklist" +summary: "Pre-trade checks for USD/CAD margin accounts." +matches: ["execution", "IBKR"] +--- + +Verify buying power and currency conversion buffers before routing. +`; + +const STANDARD_MANIFEST = `# Quant methodology library +id: quant +name: "Quant Research Library" +shelves: + - id: core + title: "Core reading" + nested: + ignored: true +sections: + live-ops: Live operations & execution + alphas: Signal & alpha research +`; + +interface FakeFsState { + readonly files: Map; + readonly dirs: Map; + readonly readPaths: string[]; + readonly listPaths: string[]; + readonly readErrors: Map; + readonly listErrors: Map; + readonly fs: LibraryCardFs; +} + +function makeEnoent(targetPath: string): NodeJS.ErrnoException { + const err = new Error(`ENOENT: no such file or directory, open '${targetPath}'`) as NodeJS.ErrnoException; + err.code = 'ENOENT'; + return err; +} + +function createFakeLibraryFs(init?: { + readonly files?: Readonly>; + readonly dirs?: Readonly>; +}): FakeFsState { + const files = new Map(); + const dirs = new Map(); + const readPaths: string[] = []; + const listPaths: string[] = []; + const readErrors = new Map(); + const listErrors = new Map(); + + if (init?.files !== undefined) { + for (const [relOrAbs, text] of Object.entries(init.files)) { + const full = path.isAbsolute(relOrAbs) ? relOrAbs : path.join(VIRTUAL_ROOT, relOrAbs); + files.set(full, text); + } + } + if (init?.dirs !== undefined) { + for (const [relOrAbs, entries] of Object.entries(init.dirs)) { + const full = relOrAbs === '' ? VIRTUAL_ROOT : path.isAbsolute(relOrAbs) ? relOrAbs : path.join(VIRTUAL_ROOT, relOrAbs); + dirs.set(full, [...entries]); + } + } + + 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) { + throw makeEnoent(dirPath); + } + return [...entries]; + }, + }; + + return { files, dirs, readPaths, listPaths, readErrors, listErrors, fs }; +} + +function createStandardFakeFs(): FakeFsState { + return createFakeLibraryFs({ + files: { + 'library.yml': STANDARD_MANIFEST, + 'cards/live-ops/ibkr-margin.md': LIVE_OPS_CARD, + 'cards/alphas/piotroski-f-score.md': PIOTROSKI_CARD, + 'cards/alphas/a-momentum.md': MOMENTUM_CARD, + }, + dirs: { + '': [ + { name: 'library.yml', isFile: true, isDirectory: false }, + { name: '_topics.yml', isFile: true, isDirectory: false }, + { name: 'rules', isFile: false, isDirectory: true }, + { name: 'cards', isFile: false, isDirectory: true }, + ], + cards: [ + { name: 'alphas', isFile: false, isDirectory: true }, + { name: 'live-ops', isFile: false, isDirectory: true }, + ], + 'cards/live-ops': [{ name: 'ibkr-margin.md', isFile: true, isDirectory: false }], + // Deliberately unsorted listing to verify code-unit slug sorting. + 'cards/alphas': [ + { name: 'piotroski-f-score.md', isFile: true, isDirectory: false }, + { name: 'a-momentum.md', isFile: true, isDirectory: false }, + ], + }, + }); +} + +async function expectLibraryCardError( + fn: () => Promise | unknown, + expectedCode: LibraryCardError['code'] +): Promise { + try { + await fn(); + } catch (err) { + expect(err).toBeInstanceOf(RangeError); + expect(err).toBeInstanceOf(LibraryCardError); + const typed = err as LibraryCardError; + expect(typed.code).toBe(expectedCode); + return typed; + } + throw new Error(`Expected LibraryCardError(${expectedCode}) to be thrown.`); +} + +const tempDirs: string[] = []; + +afterEach(async () => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir !== undefined) { + await rm(dir, { recursive: true, force: true }); + } + } +}); + +describe('MCP library-cards filesystem adapter', () => { + test('reads sections in manifest order, sorts slugs by code unit, normalizes tags, and preserves punctuation/Unicode and unverified cards', async () => { + const fake = createStandardFakeFs(); + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + + const cards = await reader.listLibraryCards({}); + + expect(cards.map(c => c.id)).toEqual([ + 'quant:live-ops/ibkr-margin', + 'quant:alphas/a-momentum', + 'quant:alphas/piotroski-f-score', + ]); + + expect(cards[0]).toEqual({ + id: 'quant:live-ops/ibkr-margin', + title: 'IBKR Margin & FX Rebalance Checklist', + tags: ['live-ops', 'execution', 'ibkr'], + summary: 'Pre-trade checks for USD/CAD margin accounts.', + body: 'Verify buying power and currency conversion buffers before routing.', + }); + + // Missing matches falls back to [sectionId]. + expect(cards[1]).toEqual({ + id: 'quant:alphas/a-momentum', + title: 'Cross-Sectional Momentum (12-1)', + tags: ['alphas'], + summary: 'Twelve-month return skipping the most recent month.', + body: 'Skipping the last month mitigates short-term reversal.', + }); + + // Quoted punctuation (:, ,, (), en-dash), URL array, deduplicated tags in first-seen order, verified: false included. + expect(cards[2]).toEqual({ + id: 'quant:alphas/piotroski-f-score', + title: 'Piotroski F-Score: Value, Quality (1976–2000)', + tags: ['alphas', 'value', 'fundamental', 'quality'], + summary: 'Nine-signal accounting screen: profitability, leverage, and operating efficiency.', + body: '# Piotroski F-Score\n\nNine binary fundamental signals evaluated strictly point-in-time.', + }); + }); + + test('supports exact case-sensitive q.id narrowing and blocks traversal/unknown IDs with zero card reads', async () => { + const fake = createStandardFakeFs(); + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + const manifestPath = path.join(VIRTUAL_ROOT, 'library.yml'); + const piotroskiPath = path.join(VIRTUAL_ROOT, 'cards/alphas/piotroski-f-score.md'); + + // Exact hit reads library.yml and only the target card. + const hit = await reader.listLibraryCards({ id: 'quant:alphas/piotroski-f-score' }); + expect(hit).toHaveLength(1); + expect(hit[0]?.id).toBe('quant:alphas/piotroski-f-score'); + expect(fake.readPaths).toEqual([manifestPath, piotroskiPath]); + + // Misses and traversal attempts must return frozen [] and read no card files. + const missIds = [ + 'QUANT:alphas/piotroski-f-score', + 'quant:Alphas/piotroski-f-score', + 'quant:alphas/Piotroski-f-score', + 'quant:unknown-section/piotroski-f-score', + 'quant:alphas/does-not-exist', + 'quant:../x', + 'quant:alphas/../../library', + '/etc/passwd', + 'quant:alphas/sub/nested', + '', + ]; + + for (const id of missIds) { + fake.readPaths.length = 0; + const result = await reader.listLibraryCards({ id }); + expect(result).toEqual([]); + expect(Object.isFrozen(result)).toBe(true); + expect(fake.readPaths).toEqual([manifestPath]); + for (const readPath of fake.readPaths) { + expect(readPath === manifestPath || readPath.startsWith(`${VIRTUAL_ROOT}/cards/`)).toBe( + true + ); + } + } + }); + + test('skips dotfiles, non-.md files, nested dirs, symlinks, undeclared sections, invalid slugs, invalid section IDs, and missing section dirs', async () => { + const fake = createFakeLibraryFs({ + files: { + 'library.yml': `id: quant +sections: + alphas: Alphas + Bad_Section: Invalid section name + empty-section: Declared section with no directory +`, + 'cards/alphas/valid-card.md': MOMENTUM_CARD, + 'cards/alphas/.hidden.md': MOMENTUM_CARD, + 'cards/alphas/README.txt': 'ignored', + 'cards/alphas/UpperCase.md': MOMENTUM_CARD, + 'cards/alphas/symlink-card.md': MOMENTUM_CARD, + 'cards/undeclared/secret.md': MOMENTUM_CARD, + 'cards/Bad_Section/valid-card.md': MOMENTUM_CARD, + }, + dirs: { + '': [ + { name: 'library.yml', isFile: true, isDirectory: false }, + { name: 'cards', isFile: false, isDirectory: true }, + ], + cards: [ + { name: 'alphas', isFile: false, isDirectory: true }, + { name: 'undeclared', isFile: false, isDirectory: true }, + { name: 'Bad_Section', isFile: false, isDirectory: true }, + { name: 'symlink-section', isFile: false, isDirectory: false }, + ], + 'cards/alphas': [ + { name: '.hidden.md', isFile: true, isDirectory: false }, + { name: 'README.txt', isFile: true, isDirectory: false }, + { name: 'nested.md', isFile: false, isDirectory: true }, + { name: 'symlink-card.md', isFile: false, isDirectory: false }, + { name: 'UpperCase.md', isFile: true, isDirectory: false }, + { name: 'valid-card.md', isFile: true, isDirectory: false }, + ], + }, + }); + + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + const cards = await reader.listLibraryCards({}); + + expect(cards.map(c => c.id)).toEqual(['quant:alphas/valid-card']); + expect(fake.readPaths).toEqual([ + path.join(VIRTUAL_ROOT, 'library.yml'), + path.join(VIRTUAL_ROOT, 'cards/alphas/valid-card.md'), + ]); + }); + + test('validates constructor options synchronously and fails closed on invalid manifest and I/O errors', async () => { + const fake = createStandardFakeFs(); + + await expectLibraryCardError( + () => createLibraryCardReader(null as unknown as { root: string; fs: LibraryCardFs }), + 'INVALID_ROOT' + ); + await expectLibraryCardError( + () => createLibraryCardReader({ root: ' ', fs: fake.fs }), + 'INVALID_ROOT' + ); + await expectLibraryCardError( + () => createLibraryCardReader({ root: '/tmp/bad\0path', fs: fake.fs }), + 'INVALID_ROOT' + ); + await expectLibraryCardError( + () => createLibraryCardReader({ root: VIRTUAL_ROOT, fs: null as unknown as LibraryCardFs }), + 'INVALID_FS' + ); + await expectLibraryCardError( + () => + createLibraryCardReader({ + root: VIRTUAL_ROOT, + fs: { readTextFile: fake.fs.readTextFile } as unknown as LibraryCardFs, + }), + 'INVALID_FS' + ); + + // Zero I/O happened during invalid option checks. + expect(fake.readPaths).toHaveLength(0); + expect(fake.listPaths).toHaveLength(0); + + // Missing library.yml + const missingManifestFs = createFakeLibraryFs({}); + const missingReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: missingManifestFs.fs }); + await expectLibraryCardError(() => missingReader.listLibraryCards({}), 'INVALID_LIBRARY'); + + // Malformed library.yml variants + const badManifests: readonly string[] = [ + 'sections:\n alphas: Alphas\n', // missing id + 'id:\nsections:\n alphas: Alphas\n', // empty id + 'id: quant\nname: Only name\n', // missing sections + 'id: quant\nsections:\n', // empty sections + 'id: quant\nid: quant2\nsections:\n alphas: Alphas\n', // duplicate id + 'id: quant\nsections:\n alphas: A\nsections:\n beta: B\n', // duplicate sections + 'id: quant\nsections:\n alphas: A\n alphas: B\n', // duplicate section key + 'id: quant\nsections: []\n', // non-map sections + ]; + + for (const manifest of badManifests) { + const f = createFakeLibraryFs({ files: { 'library.yml': manifest } }); + const r = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: f.fs }); + await expectLibraryCardError(() => r.listLibraryCards({}), 'INVALID_LIBRARY'); + } + + // Permission / generic I/O failure on listDir and card readTextFile + const ioFake = createStandardFakeFs(); + const eacces = Object.assign(new Error('EACCES: permission denied /secret/path'), { + code: 'EACCES', + }); + ioFake.listErrors.set(path.join(VIRTUAL_ROOT, 'cards/alphas'), eacces); + const ioReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: ioFake.fs }); + const listErr = await expectLibraryCardError( + () => ioReader.listLibraryCards({}), + 'INVALID_LIBRARY' + ); + expect(listErr.message).not.toContain('/secret/path'); + + ioFake.listErrors.clear(); + ioFake.readErrors.set( + path.join(VIRTUAL_ROOT, 'cards/alphas/a-momentum.md'), + new Error('EIO: raw disk failure secret-bytes') + ); + const readErr = await expectLibraryCardError( + () => ioReader.listLibraryCards({}), + 'INVALID_CARD' + ); + expect(readErr.message).toContain('cards/alphas/a-momentum.md'); + expect(readErr.message).not.toContain('secret-bytes'); + }); + + test('fails closed on malformed cards and duplicate card IDs, naming relative path without leaking card content', async () => { + const SECRET_MARKER = 'CONFIDENTIAL_CARD_BODY_MARKER_99123'; + + const badCards: readonly { readonly label: string; readonly content: string }[] = [ + { + label: 'missing opening delimiter', + content: `title: "T"\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'missing closing delimiter', + content: `---\ntitle: "T"\nsummary: "S"\n${SECRET_MARKER}`, + }, + { + label: 'missing title', + content: `---\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'blank title', + content: `---\ntitle: " "\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'missing summary', + content: `---\ntitle: "T"\n---\n${SECRET_MARKER}`, + }, + { + label: 'blank summary', + content: `---\ntitle: "T"\nsummary: ""\n---\n${SECRET_MARKER}`, + }, + { + label: 'unterminated double quote', + content: `---\ntitle: "Unterminated ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'single-quoted value', + content: `---\ntitle: 'Single ${SECRET_MARKER}'\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'multiline block scalar', + content: `---\ntitle: "T"\nsummary: |\n ${SECRET_MARKER}\n---\n${SECRET_MARKER}`, + }, + { + label: 'indented continuation', + content: `---\ntitle: "T"\n ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + { + label: 'invalid matches non-array', + content: `---\ntitle: "T"\nsummary: "S"\nmatches: "${SECRET_MARKER}"\n---\n${SECRET_MARKER}`, + }, + { + label: 'invalid matches non-string item', + content: `---\ntitle: "T"\nsummary: "S"\nmatches: ["ok", 42]\n---\n${SECRET_MARKER}`, + }, + { + label: 'duplicate key', + content: `---\ntitle: "First"\ntitle: "Second ${SECRET_MARKER}"\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, + ]; + + for (const tc of badCards) { + const fake = createFakeLibraryFs({ + files: { + 'library.yml': STANDARD_MANIFEST, + 'cards/alphas/broken-card.md': tc.content, + }, + dirs: { + '': [{ name: 'cards', isFile: false, isDirectory: true }], + cards: [{ name: 'alphas', isFile: false, isDirectory: true }], + 'cards/alphas': [{ name: 'broken-card.md', isFile: true, isDirectory: false }], + }, + }); + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + const err = await expectLibraryCardError(() => reader.listLibraryCards({}), 'INVALID_CARD'); + expect(err.message).toContain('cards/alphas/broken-card.md'); + expect(err.message).not.toContain(SECRET_MARKER); + } + + // Duplicate card ID via duplicate directory entries (both broad scan and exact ID lookup). + const dupFake = createFakeLibraryFs({ + files: { + 'library.yml': STANDARD_MANIFEST, + 'cards/alphas/dup-card.md': `---\ntitle: "Dup"\nsummary: "Summary"\n---\n${SECRET_MARKER}`, + }, + dirs: { + '': [{ name: 'cards', isFile: false, isDirectory: true }], + cards: [{ name: 'alphas', isFile: false, isDirectory: true }], + 'cards/alphas': [ + { name: 'dup-card.md', isFile: true, isDirectory: false }, + { name: 'dup-card.md', isFile: true, isDirectory: false }, + ], + }, + }); + const dupReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: dupFake.fs }); + const broadDupErr = await expectLibraryCardError( + () => dupReader.listLibraryCards({}), + 'INVALID_CARD' + ); + expect(broadDupErr.message).toContain('cards/alphas/dup-card.md'); + expect(broadDupErr.message).not.toContain(SECRET_MARKER); + + const exactDupErr = await expectLibraryCardError( + () => dupReader.listLibraryCards({ id: 'quant:alphas/dup-card' }), + 'INVALID_CARD' + ); + expect(exactDupErr.message).toContain('cards/alphas/dup-card.md'); + expect(exactDupErr.message).not.toContain(SECRET_MARKER); + }); + + test('integrates end-to-end with createReadKnowledgeTool while adapter returns all candidates untruncated', async () => { + const longBody = 'A'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 250); + const fake = createStandardFakeFs(); + fake.files.set( + path.join(VIRTUAL_ROOT, 'cards/alphas/piotroski-f-score.md'), + `--- +verified: false +title: "Piotroski F-Score: Value, Quality (1976–2000)" +summary: "Nine-signal accounting screen: profitability, leverage, and operating efficiency." +matches: ["Value", "Quality"] +--- + +${longBody} +` + ); + + const libraryReader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + + // Adapter itself ignores query/tags and does not truncate body text. + const rawCandidates = await libraryReader.listLibraryCards({ + query: 'piotroski', + tags: ['VALUE'], + }); + expect(rawCandidates).toHaveLength(3); + const rawPiotroski = rawCandidates.find(c => c.id === 'quant:alphas/piotroski-f-score'); + expect(rawPiotroski?.body.length).toBe(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 250); + + // Real read_knowledge tool filters by mixed-case tags + query and truncates long body. + const port: KnowledgePort = { + ...libraryReader, + async listFindings() { + return []; + }, + async listProviderCaveats() { + return []; + }, + }; + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [createReadKnowledgeTool({ port })], + }); + + const rawResponse = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'lib-e2e-1', + method: 'tools/call', + params: { + name: 'read_knowledge', + arguments: { + source: 'library', + tags: ['VALUE', 'Alphas'], + query: 'piotroski', + }, + }, + }) + ); + + expect(rawResponse).not.toBeNull(); + const parsed = JSON.parse(rawResponse as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(parsed.result.isError).toBeUndefined(); + const payload = JSON.parse(parsed.result.content[0]?.text ?? '') as ReadKnowledgeResultPayload; + expect(payload.rowCount).toBe(1); + expect(payload.sources).toEqual({ library: 1, findings: 0, provider_caveats: 0 }); + expect(payload.rows[0]).toEqual({ + source: 'library', + id: 'quant:alphas/piotroski-f-score', + title: 'Piotroski F-Score: Value, Quality (1976–2000)', + tags: ['alphas', 'value', 'quality'], + summary: 'Nine-signal accounting screen: profitability, leverage, and operating efficiency.', + body: 'A'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH), + truncated: true, + }); + }); + + test('reads fresh on every call and returns frozen result arrays, records, and tag arrays', async () => { + const fake = createStandardFakeFs(); + const reader = createLibraryCardReader({ root: VIRTUAL_ROOT, fs: fake.fs }); + + const first = await reader.listLibraryCards({}); + expect(Object.isFrozen(first)).toBe(true); + for (const card of first) { + expect(Object.isFrozen(card)).toBe(true); + expect(Object.isFrozen(card.tags)).toBe(true); + } + expect(first.find(c => c.id === 'quant:alphas/a-momentum')?.title).toBe( + 'Cross-Sectional Momentum (12-1)' + ); + + // Mutate card and manifest in the fake between calls. + fake.files.set( + path.join(VIRTUAL_ROOT, 'cards/alphas/a-momentum.md'), + `--- +title: "Updated Momentum Title" +summary: "Updated summary." +matches: ["updated-tag"] +--- + +Updated body. +` + ); + fake.files.set( + path.join(VIRTUAL_ROOT, 'library.yml'), + `id: quant-v2 +sections: + alphas: Alphas only +` + ); + + const second = await reader.listLibraryCards({}); + expect(second.map(c => c.id)).toEqual([ + 'quant-v2:alphas/a-momentum', + 'quant-v2:alphas/piotroski-f-score', + ]); + expect(second[0]).toEqual({ + id: 'quant-v2:alphas/a-momentum', + title: 'Updated Momentum Title', + tags: ['alphas', 'updated-tag'], + summary: 'Updated summary.', + body: 'Updated body.', + }); + expect(Object.isFrozen(second)).toBe(true); + expect(Object.isFrozen(second[0])).toBe(true); + expect(Object.isFrozen(second[0]?.tags)).toBe(true); + }); + + test('createNodeLibraryCardFs reads real temp fixtures and never follows symlinked files, sections, or manifests', async () => { + const tempBase = await mkdtemp(path.join(os.tmpdir(), 'stock-bot-library-cards-')); + tempDirs.push(tempBase); + + const libRoot = path.join(tempBase, 'library'); + const siblingDir = path.join(tempBase, 'sibling-outside-library'); + const siblingFile = path.join(siblingDir, 'leaked.md'); + + await mkdir(path.join(libRoot, 'cards', 'alphas'), { recursive: true }); + await mkdir(siblingDir, { recursive: true }); + + await writeFile( + path.join(libRoot, 'library.yml'), + `id: quant +sections: + alphas: Signal & alpha research + linked-section: Symlinked section +`, + 'utf8' + ); + await writeFile(path.join(libRoot, 'cards', 'alphas', 'piotroski-f-score.md'), PIOTROSKI_CARD, 'utf8'); + await writeFile( + siblingFile, + `--- +title: "Leaked Sibling Card" +summary: "Must never be read via symlink." +--- + +LEAKED_SIBLING_CONTENT +`, + 'utf8' + ); + + // Create symlinked file inside cards/alphas and symlinked section directory inside cards/. + await symlink(siblingFile, path.join(libRoot, 'cards', 'alphas', 'linked-card.md')); + await symlink(siblingDir, path.join(libRoot, 'cards', 'linked-section')); + + const nodeFs = createNodeLibraryCardFs(); + const reader = createLibraryCardReader({ root: libRoot, fs: nodeFs }); + + const cards = await reader.listLibraryCards({}); + expect(cards).toHaveLength(1); + expect(cards[0]?.id).toBe('quant:alphas/piotroski-f-score'); + + // Exact-ID lookups targeting symlinked file or symlinked section return empty without reading. + expect(await reader.listLibraryCards({ id: 'quant:alphas/linked-card' })).toEqual([]); + expect(await reader.listLibraryCards({ id: 'quant:linked-section/leaked' })).toEqual([]); + + // Direct symlinked library.yml must fail closed via O_NOFOLLOW. + const symlinkManifestRoot = path.join(tempBase, 'symlink-manifest-lib'); + await mkdir(symlinkManifestRoot, { recursive: true }); + await symlink(path.join(libRoot, 'library.yml'), path.join(symlinkManifestRoot, 'library.yml')); + const symlinkManifestReader = createLibraryCardReader({ + root: symlinkManifestRoot, + fs: nodeFs, + }); + await expectLibraryCardError( + () => symlinkManifestReader.listLibraryCards({}), + 'INVALID_LIBRARY' + ); + }); +}); From a255191b667f1a0e0c697fb5092942ec51a6eebf Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:28:22 -0500 Subject: [PATCH 2/4] =?UTF-8?q?T-163:=20M2.1m=20=E2=80=94=20Filesystem=20l?= =?UTF-8?q?ibrary=20adapter=20for=20the=20MCP=20copilot=20`read=5Fknowledg?= =?UTF-8?q?e`=20tool:=20`KnowledgePort.listLibraryCards`=20over=20`library?= =?UTF-8?q?.yml`=20+=20`cards/
/*.md`=20in=20`libs/research/src/mc?= =?UTF-8?q?p/adapters/library-cards.ts`=20(injected=20read-only=20fs=20por?= =?UTF-8?q?t,=20strict=20front-matter=20parser,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 4 +- .../src/mcp/adapters/library-cards.ts | 617 +++++++++++++----- libs/research/test/mcp-library-cards.test.ts | 160 ++++- 3 files changed, 604 insertions(+), 177 deletions(-) diff --git a/libs/research/README.md b/libs/research/README.md index bdad396f..e3e62776 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -266,8 +266,8 @@ 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`, `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), discovers `cards/` and declared section directories via parent listings so symbolic links are never followed, and opens text files read-only with `O_NOFOLLOW` + regular-file verification in `createNodeLibraryCardFs()`. +- **`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. - **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 a2798e97..6994f173 100644 --- a/libs/research/src/mcp/adapters/library-cards.ts +++ b/libs/research/src/mcp/adapters/library-cards.ts @@ -8,12 +8,13 @@ */ import { constants as fsConstants } from 'node:fs'; -import { open, readdir } from 'node:fs/promises'; +import { type FileHandle, open, readdir, stat } from 'node:fs/promises'; import path from 'node:path'; import type { KnowledgePort, LibraryCardQuery, LibraryCardRecord } from '../tools/read-knowledge'; 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 BLOCK_SCALAR_RE = /^[|>][+-]?$/; /** Error codes thrown by {@link LibraryCardError}. */ @@ -42,10 +43,19 @@ export interface LibraryCardDirEntry { readonly isDirectory: boolean; } +/** Anchored read-only directory handle for symlink-safe traversal below a configured root. */ +export interface LibraryCardDirHandle { + listDir(): Promise; + openSubdir(name: string): Promise; + readTextFile(name: string): Promise; + close(): Promise; +} + /** Minimal read-only filesystem port injected into {@link createLibraryCardReader}. */ export interface LibraryCardFs { readTextFile(filePath: string): Promise; listDir(dirPath: string): Promise; + openDir?(dirPath: string): Promise; } /** Factory options for {@link createLibraryCardReader}. */ @@ -113,7 +123,8 @@ function validateFactoryOptions(options: LibraryCardReaderOptions): { typeof fs !== 'object' || fs === null || typeof fs.readTextFile !== 'function' || - typeof fs.listDir !== 'function' + typeof fs.listDir !== 'function' || + (fs.openDir !== undefined && typeof fs.openDir !== 'function') ) { throw new LibraryCardError( 'INVALID_FS', @@ -128,7 +139,7 @@ function validateFactoryOptions(options: LibraryCardReaderOptions): { } function parseLibraryScalar(rawValue: string): string { - if (rawValue.length === 0) { + if (rawValue.length === 0 || rawValue.startsWith('#')) { throw invalidLibrary('"id" must not be empty.'); } if (rawValue.startsWith("'")) { @@ -229,13 +240,25 @@ function parseLibraryManifest(content: string): ParsedLibraryManifest { } const body = line.slice(indent); + if (body === '-' || body.startsWith('- ') || body.startsWith('-\t')) { + throw invalidLibrary('sequence entries are not supported inside "sections" map.'); + } const colonIdx = body.indexOf(':'); if (colonIdx <= 0) { throw invalidLibrary('malformed entry inside "sections" map.'); } - const sectionKey = body.slice(0, colonIdx).trim(); - const sectionTitle = body.slice(colonIdx + 1).trim(); - if (sectionKey.length === 0 || sectionTitle.length === 0) { + const rawKey = body.slice(0, colonIdx); + const sectionKey = rawKey.trim(); + const afterColon = body.slice(colonIdx + 1); + if ( + rawKey !== sectionKey || + !SECTION_KEY_SYNTAX_RE.test(sectionKey) || + (afterColon.length > 0 && afterColon[0] !== ' ' && afterColon[0] !== '\t') + ) { + throw invalidLibrary('malformed entry inside "sections" map.'); + } + const sectionTitle = afterColon.trim(); + if (sectionTitle.length === 0 || sectionTitle.startsWith('#')) { throw invalidLibrary('empty key or title inside "sections" map.'); } if (seenSectionKeys.has(sectionKey)) { @@ -262,7 +285,7 @@ function parseLibraryManifest(content: string): ParsedLibraryManifest { } function parseFrontMatterValue(rawValue: string, relPath: string): FrontMatterValue { - if (rawValue.length === 0) { + if (rawValue.length === 0 || rawValue.startsWith('#')) { throw invalidCard(relPath, 'empty or multiline front-matter value.'); } if (BLOCK_SCALAR_RE.test(rawValue)) { @@ -434,15 +457,104 @@ function parseExactCardId( return { sectionId, slug }; } -async function safeReadTextFile( +function assertSafeChildName(name: string): void { + if ( + name.length === 0 || + name === '.' || + name === '..' || + name.includes('/') || + name.includes('\\') || + name.includes('\0') + ) { + throw new Error('Invalid directory child entry name.'); + } +} + +function isValidDirHandle(value: unknown): value is LibraryCardDirHandle { + return ( + typeof value === 'object' && + value !== null && + typeof (value as { readonly listDir?: unknown }).listDir === 'function' && + typeof (value as { readonly openSubdir?: unknown }).openSubdir === 'function' && + typeof (value as { readonly readTextFile?: unknown }).readTextFile === 'function' && + typeof (value as { readonly close?: unknown }).close === 'function' + ); +} + +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, - filePath: string, + resolvedRoot: string +): Promise { + if (fs.openDir === undefined) { + return createPathBackedDirHandle(fs, resolvedRoot); + } + let handle: unknown; + try { + handle = await fs.openDir(resolvedRoot); + } catch { + throw new LibraryCardError( + 'INVALID_LIBRARY', + 'Invalid library.yml: failed to open library root directory.' + ); + } + if (!isValidDirHandle(handle)) { + throw new LibraryCardError( + 'INVALID_LIBRARY', + 'Invalid library.yml: failed to open library root directory.' + ); + } + return handle; +} + +async function safeOpenSubdir( + parent: LibraryCardDirHandle, + name: string, + errorMessage: string, + allowMissing: boolean +): Promise { + let handle: unknown; + try { + handle = await parent.openSubdir(name); + } catch (err) { + if (allowMissing && isEnoentError(err)) { + return null; + } + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + if (!isValidDirHandle(handle)) { + throw new LibraryCardError('INVALID_LIBRARY', errorMessage); + } + return handle; +} + +async function safeReadTextFileFromDir( + dir: LibraryCardDirHandle, + name: string, errorCode: 'INVALID_LIBRARY' | 'INVALID_CARD', errorMessage: string ): Promise { let content: unknown; try { - content = await fs.readTextFile(filePath); + content = await dir.readTextFile(name); } catch { throw new LibraryCardError(errorCode, errorMessage); } @@ -452,15 +564,14 @@ async function safeReadTextFile( return content; } -async function safeListDir( - fs: LibraryCardFs, - dirPath: string, +async function safeListDirHandle( + dir: LibraryCardDirHandle, errorMessage: string, allowMissing: boolean ): Promise { let rawEntries: unknown; try { - rawEntries = await fs.listDir(dirPath); + rawEntries = await dir.listDir(); } catch (err) { if (allowMissing && isEnoentError(err)) { return []; @@ -490,33 +601,43 @@ async function safeListDir( return entries; } -/** - * Creates a read-only {@link LibraryCardFs} backed by `node:fs/promises`. - * - * Opens text files read-only with `O_NOFOLLOW` (where supported) and confirms - * they are regular files before reading, and reports directory entry types - * without following symbolic links. - */ -export function createNodeLibraryCardFs(): LibraryCardFs { - const noFollowFlag = typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0; - const openFlags = fsConstants.O_RDONLY | noFollowFlag; +interface AnchoredOpenFlags { + readonly dirOpenFlags: number; + readonly subdirOpenFlags: number; + readonly fileOpenFlags: number; +} + +function getAnchoredOpenFlags(): AnchoredOpenFlags { + if ( + process.platform !== 'linux' || + typeof fsConstants.O_NOFOLLOW !== 'number' || + typeof fsConstants.O_DIRECTORY !== 'number' + ) { + throw new Error('Anchored no-follow directory operations are not supported on this platform.'); + } + return { + dirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY, + subdirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW, + fileOpenFlags: fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW, + }; +} + +function createAnchoredNodeDirHandle( + handle: FileHandle, + flags: AnchoredOpenFlags +): LibraryCardDirHandle { + let closed = false; + + const getFdBase = (): string => { + if (closed) { + throw new Error('Directory handle is closed.'); + } + return `/proc/self/fd/${handle.fd}`; + }; return { - async readTextFile(filePath: string): Promise { - const handle = await open(filePath, openFlags); - try { - const stats = await handle.stat(); - if (!stats.isFile()) { - throw new Error('Target path is not a regular file.'); - } - return await handle.readFile({ encoding: 'utf8' }); - } finally { - await handle.close(); - } - }, - - async listDir(dirPath: string): Promise { - const dirents = await readdir(dirPath, { withFileTypes: true }); + async listDir(): Promise { + const dirents = await readdir(getFdBase(), { withFileTypes: true }); const entries: LibraryCardDirEntry[] = []; for (let i = 0; i < dirents.length; i += 1) { const dirent = dirents[i]; @@ -530,6 +651,103 @@ export function createNodeLibraryCardFs(): LibraryCardFs { } return entries; }, + + async openSubdir(name: string): Promise { + assertSafeChildName(name); + const childHandle = await open(`${getFdBase()}/${name}`, flags.subdirOpenFlags); + try { + const stats = await childHandle.stat(); + if (!stats.isDirectory()) { + throw new Error('Target path is not a directory.'); + } + } catch (err) { + await childHandle.close(); + throw err; + } + return createAnchoredNodeDirHandle(childHandle, flags); + }, + + async readTextFile(name: string): Promise { + assertSafeChildName(name); + const fileHandle = await open(`${getFdBase()}/${name}`, flags.fileOpenFlags); + try { + const stats = await fileHandle.stat(); + if (!stats.isFile()) { + throw new Error('Target path is not a regular file.'); + } + return await fileHandle.readFile({ encoding: 'utf8' }); + } finally { + await fileHandle.close(); + } + }, + + async close(): Promise { + if (closed) { + return; + } + closed = true; + await handle.close(); + }, + }; +} + +/** + * Creates a read-only {@link LibraryCardFs} backed by `node:fs/promises`. + * + * Anchors directory listings and file reads to opened directory file descriptors + * via `/proc/self/fd/`, enforces `O_NOFOLLOW` on every component below the + * configured root, verifies regular-file/directory types via `fstat`, and fails + * closed on platforms that cannot enforce this boundary. + */ +export function createNodeLibraryCardFs(): LibraryCardFs { + return { + async readTextFile(filePath: string): Promise { + const flags = getAnchoredOpenFlags(); + const handle = await open(filePath, flags.fileOpenFlags); + try { + const stats = await handle.stat(); + if (!stats.isFile()) { + throw new Error('Target path is not a regular file.'); + } + return await handle.readFile({ encoding: 'utf8' }); + } finally { + await handle.close(); + } + }, + + async listDir(dirPath: string): Promise { + const flags = getAnchoredOpenFlags(); + const handle = await open(dirPath, flags.subdirOpenFlags); + try { + const stats = await handle.stat(); + if (!stats.isDirectory()) { + throw new Error('Target path is not a directory.'); + } + const anchored = createAnchoredNodeDirHandle(handle, flags); + return await anchored.listDir(); + } finally { + await handle.close(); + } + }, + + async openDir(dirPath: string): Promise { + const flags = getAnchoredOpenFlags(); + const handle = await open(dirPath, flags.dirOpenFlags); + try { + const stats = await handle.stat(); + if (!stats.isDirectory()) { + throw new Error('Target path is not a directory.'); + } + const procStats = await stat(`/proc/self/fd/${handle.fd}`); + if (!procStats.isDirectory()) { + throw new Error('Anchored directory descriptor is not accessible.'); + } + } catch (err) { + await handle.close(); + throw err; + } + return createAnchoredNodeDirHandle(handle, flags); + }, }; } @@ -545,29 +763,111 @@ export function createNodeLibraryCardFs(): LibraryCardFs { */ export function createLibraryCardReader(options: LibraryCardReaderOptions): LibraryCardReader { const { resolvedRoot, fs } = validateFactoryOptions(options); - const manifestPath = path.join(resolvedRoot, 'library.yml'); - const cardsDirPath = path.join(resolvedRoot, 'cards'); return { async listLibraryCards(q: LibraryCardQuery): Promise { - const manifestText = await safeReadTextFile( - fs, - manifestPath, - 'INVALID_LIBRARY', - 'Invalid library.yml: failed to read manifest.' - ); - const manifest = parseLibraryManifest(manifestText); - const declaredSections = new Set(manifest.sections); + const rootDir = await safeOpenRootDir(fs, resolvedRoot); + try { + const manifestText = await safeReadTextFileFromDir( + rootDir, + 'library.yml', + 'INVALID_LIBRARY', + 'Invalid library.yml: failed to read manifest.' + ); + const manifest = parseLibraryManifest(manifestText); + const declaredSections = new Set(manifest.sections); - if (q.id !== undefined) { - const target = parseExactCardId(q.id, manifest.id, declaredSections); - if (target === null) { - return Object.freeze([]); + if (q.id !== undefined) { + const 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 safeListDir( - fs, - resolvedRoot, + const rootEntries = await safeListDirHandle( + rootDir, 'Invalid library.yml: failed to list library root directory.', false ); @@ -578,131 +878,100 @@ export function createLibraryCardReader(options: LibraryCardReaderOptions): Libr return Object.freeze([]); } - const cardDirEntries = await safeListDir( - fs, - cardsDirPath, - 'Invalid library.yml: failed to list library cards directory.', + const cardsDir = await safeOpenSubdir( + rootDir, + 'cards', + 'Invalid library.yml: failed to open library cards directory.', true ); - const hasSectionDir = cardDirEntries.some( - entry => entry.name === target.sectionId && entry.isDirectory && !entry.isFile - ); - if (!hasSectionDir) { + if (cardsDir === null) { return Object.freeze([]); } - const sectionDirPath = path.join(cardsDirPath, target.sectionId); - const sectionEntries = await safeListDir( - fs, - sectionDirPath, - `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 safeReadTextFile( - fs, - path.join(sectionDirPath, 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]); - } - - const rootEntries = await safeListDir( - fs, - resolvedRoot, - '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 cardDirEntries = await safeListDir( - fs, - cardsDirPath, - 'Invalid library.yml: failed to list library cards directory.', - true - ); - const presentSectionDirs = new Set(); - for (let i = 0; i < cardDirEntries.length; i += 1) { - const entry = cardDirEntries[i] as LibraryCardDirEntry; - if (entry.isDirectory && !entry.isFile && SAFE_IDENT_RE.test(entry.name)) { - presentSectionDirs.add(entry.name); - } - } - - const cards: LibraryCardRecord[] = []; - const seenIds = new Set(); - - for (let s = 0; s < manifest.sections.length; s += 1) { - const sectionId = manifest.sections[s] as string; - if (!presentSectionDirs.has(sectionId)) { - continue; - } - - const sectionDirPath = path.join(cardsDirPath, sectionId); - const sectionEntries = await safeListDir( - fs, - sectionDirPath, - `Invalid library.yml: failed to list section directory "cards/${sectionId}".`, - true - ); - - const slugs: string[] = []; - for (let i = 0; i < sectionEntries.length; i += 1) { - const entry = sectionEntries[i] as LibraryCardDirEntry; - if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) { - continue; - } - const slug = entry.name.slice(0, -3); - if (!SAFE_IDENT_RE.test(slug)) { - continue; - } - slugs.push(slug); - } - - slugs.sort(compareCodeUnits); - - for (let i = 0; i < slugs.length; i += 1) { - const slug = slugs[i] as string; - const relPath = `cards/${sectionId}/${slug}.md`; - const canonicalId = `${manifest.id}:${sectionId}/${slug}`; - if (seenIds.has(canonicalId)) { - throw invalidCard(relPath, 'duplicate card id.'); - } - seenIds.add(canonicalId); - - const cardText = await safeReadTextFile( - fs, - path.join(sectionDirPath, `${slug}.md`), - 'INVALID_CARD', - `Invalid card "${relPath}": failed to read card file.` + try { + const cardDirEntries = await safeListDirHandle( + cardsDir, + 'Invalid library.yml: failed to list library cards directory.', + true ); - cards.push(parseCardDocument(cardText, manifest.id, sectionId, slug)); - } - } + const presentSectionDirs = new Set(); + for (let i = 0; i < cardDirEntries.length; i += 1) { + const entry = cardDirEntries[i] as LibraryCardDirEntry; + if (entry.isDirectory && !entry.isFile && SAFE_IDENT_RE.test(entry.name)) { + presentSectionDirs.add(entry.name); + } + } - return Object.freeze(cards); + const cards: LibraryCardRecord[] = []; + const seenIds = new Set(); + + for (let s = 0; s < manifest.sections.length; s += 1) { + const sectionId = manifest.sections[s] as string; + if (!presentSectionDirs.has(sectionId)) { + continue; + } + + const sectionDir = await safeOpenSubdir( + cardsDir, + sectionId, + `Invalid library.yml: failed to open section directory "cards/${sectionId}".`, + true + ); + if (sectionDir === null) { + continue; + } + + try { + const sectionEntries = await safeListDirHandle( + sectionDir, + `Invalid library.yml: failed to list section directory "cards/${sectionId}".`, + true + ); + + const slugs: string[] = []; + for (let i = 0; i < sectionEntries.length; i += 1) { + const entry = sectionEntries[i] as LibraryCardDirEntry; + if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) { + continue; + } + const slug = entry.name.slice(0, -3); + if (!SAFE_IDENT_RE.test(slug)) { + continue; + } + slugs.push(slug); + } + + slugs.sort(compareCodeUnits); + + for (let i = 0; i < slugs.length; i += 1) { + const slug = slugs[i] as string; + const relPath = `cards/${sectionId}/${slug}.md`; + const canonicalId = `${manifest.id}:${sectionId}/${slug}`; + if (seenIds.has(canonicalId)) { + throw invalidCard(relPath, 'duplicate card id.'); + } + seenIds.add(canonicalId); + + const cardText = await safeReadTextFileFromDir( + sectionDir, + `${slug}.md`, + 'INVALID_CARD', + `Invalid card "${relPath}": failed to read card file.` + ); + cards.push(parseCardDocument(cardText, manifest.id, sectionId, slug)); + } + } finally { + await sectionDir.close(); + } + } + + return Object.freeze(cards); + } finally { + await cardsDir.close(); + } + } finally { + await rootDir.close(); + } }, }; } diff --git a/libs/research/test/mcp-library-cards.test.ts b/libs/research/test/mcp-library-cards.test.ts index 04edcc91..e9ca8828 100644 --- a/libs/research/test/mcp-library-cards.test.ts +++ b/libs/research/test/mcp-library-cards.test.ts @@ -1,10 +1,11 @@ import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; +import { mkdir, mkdtemp, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { type KnowledgePort, type LibraryCardDirEntry, + type LibraryCardDirHandle, LibraryCardError, type LibraryCardFs, READ_KNOWLEDGE_MAX_TEXT_LENGTH, @@ -371,6 +372,11 @@ sections: 'id: quant\nsections:\n alphas: A\nsections:\n beta: B\n', // duplicate sections 'id: quant\nsections:\n alphas: A\n alphas: B\n', // duplicate section key 'id: quant\nsections: []\n', // non-map sections + 'id: quant\nsections:\n - alphas: Alphas\n', // YAML sequence under sections + 'id: quant\nsections:\n - alphas\n', // YAML bare sequence under sections + 'id: quant\nsections:\n alphas: # comment-only title\n', // comment-only title + 'id: quant\nsections:\n alphas:NoSpace\n', // missing space after colon + 'id: quant\nsections:\n bad key: Title\n', // whitespace in section key ]; for (const manifest of badManifests) { @@ -461,6 +467,14 @@ sections: label: 'duplicate key', content: `---\ntitle: "First"\ntitle: "Second ${SECRET_MARKER}"\nsummary: "S"\n---\n${SECRET_MARKER}`, }, + { + label: 'comment-only summary', + content: `---\ntitle: "T"\nsummary: # Fill in after review ${SECRET_MARKER}\n---\n${SECRET_MARKER}`, + }, + { + label: 'comment-only title', + content: `---\ntitle: # Draft title ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`, + }, ]; for (const tc of badCards) { @@ -702,4 +716,148 @@ LEAKED_SIBLING_CONTENT 'INVALID_LIBRARY' ); }); + + test('anchors directory listings and reads to open handles to block directory-symlink TOCTOU races', async () => { + const tempBase = await mkdtemp(path.join(os.tmpdir(), 'stock-bot-library-toctou-')); + tempDirs.push(tempBase); + + const libRoot = path.join(tempBase, 'library'); + const alphasDir = path.join(libRoot, 'cards', 'alphas'); + const outsideDir = path.join(tempBase, 'outside-corpus'); + const LEAK_MARKER = 'OUTSIDE_CORPUS_TOCTOU_LEAK_7741'; + + await mkdir(alphasDir, { recursive: true }); + await mkdir(outsideDir, { recursive: true }); + + await writeFile( + path.join(libRoot, 'library.yml'), + `id: quant\nsections:\n alphas: Signal & alpha research\n`, + 'utf8' + ); + await writeFile(path.join(alphasDir, 'piotroski-f-score.md'), PIOTROSKI_CARD, 'utf8'); + await writeFile( + path.join(outsideDir, 'piotroski-f-score.md'), + `---\ntitle: "Leaked Card"\nsummary: "Leaked summary"\n---\n\n${LEAK_MARKER}\n`, + 'utf8' + ); + + const baseNodeFs = createNodeLibraryCardFs(); + expect(typeof baseNodeFs.openDir).toBe('function'); + + // Race A: cards/alphas is replaced with a symlink after cards/ is listed, before opening alphas. + let raceATriggered = false; + const raceAFs: LibraryCardFs = { + readTextFile: p => baseNodeFs.readTextFile(p), + listDir: p => baseNodeFs.listDir(p), + async openDir(dirPath: string): Promise { + const rootHandle = await (baseNodeFs.openDir as NonNullable)( + dirPath + ); + return { + listDir: () => rootHandle.listDir(), + readTextFile: name => rootHandle.readTextFile(name), + close: () => rootHandle.close(), + async openSubdir(name: string): Promise { + const sub = await rootHandle.openSubdir(name); + if (name !== 'cards') { + return sub; + } + return { + async listDir(): Promise { + const entries = await sub.listDir(); + if (!raceATriggered) { + raceATriggered = true; + await rename(alphasDir, path.join(libRoot, 'cards', 'alphas-moved-a')); + await symlink(outsideDir, alphasDir); + } + return entries; + }, + openSubdir: child => sub.openSubdir(child), + readTextFile: child => sub.readTextFile(child), + close: () => sub.close(), + }; + }, + }; + }, + }; + + const raceAReader = createLibraryCardReader({ root: libRoot, fs: raceAFs }); + const raceAErr = await expectLibraryCardError( + () => raceAReader.listLibraryCards({}), + 'INVALID_LIBRARY' + ); + expect(raceATriggered).toBe(true); + expect(raceAErr.message).not.toContain(LEAK_MARKER); + + // Restore alphas directory for Race B. + await unlink(alphasDir); + await rename(path.join(libRoot, 'cards', 'alphas-moved-a'), alphasDir); + + // Race B: cards/alphas is replaced with a symlink after alphas is opened and listed, before reading the card. + let raceBTriggered = false; + const raceBFs: LibraryCardFs = { + readTextFile: p => baseNodeFs.readTextFile(p), + listDir: p => baseNodeFs.listDir(p), + async openDir(dirPath: string): Promise { + const rootHandle = await (baseNodeFs.openDir as NonNullable)( + dirPath + ); + return { + listDir: () => rootHandle.listDir(), + readTextFile: name => rootHandle.readTextFile(name), + close: () => rootHandle.close(), + async openSubdir(name: string): Promise { + const cardsHandle = await rootHandle.openSubdir(name); + if (name !== 'cards') { + return cardsHandle; + } + return { + listDir: () => cardsHandle.listDir(), + readTextFile: child => cardsHandle.readTextFile(child), + close: () => cardsHandle.close(), + async openSubdir(sectionName: string): Promise { + const sectionHandle = await cardsHandle.openSubdir(sectionName); + return { + async listDir(): Promise { + const entries = await sectionHandle.listDir(); + if (!raceBTriggered && sectionName === 'alphas') { + raceBTriggered = true; + await rename(alphasDir, path.join(libRoot, 'cards', 'alphas-moved-b')); + await symlink(outsideDir, alphasDir); + } + return entries; + }, + openSubdir: child => sectionHandle.openSubdir(child), + readTextFile: child => sectionHandle.readTextFile(child), + close: () => sectionHandle.close(), + }; + }, + }; + }, + }; + }, + }; + + const raceBReader = createLibraryCardReader({ root: libRoot, fs: raceBFs }); + const anchoredCards = await raceBReader.listLibraryCards({}); + expect(raceBTriggered).toBe(true); + expect(anchoredCards).toHaveLength(1); + expect(anchoredCards[0]?.id).toBe('quant:alphas/piotroski-f-score'); + expect(anchoredCards[0]?.body).not.toContain(LEAK_MARKER); + expect(anchoredCards[0]?.body).toContain('Piotroski F-Score'); + + // Unsupported boundary enforcement on openDir fails closed with INVALID_LIBRARY. + const unsupportedFs: LibraryCardFs = { + readTextFile: p => baseNodeFs.readTextFile(p), + listDir: p => baseNodeFs.listDir(p), + async openDir(): Promise { + throw new Error('Anchored no-follow directory operations are not supported.'); + }, + }; + const unsupportedReader = createLibraryCardReader({ root: libRoot, fs: unsupportedFs }); + await expectLibraryCardError( + () => unsupportedReader.listLibraryCards({}), + 'INVALID_LIBRARY' + ); + }); }); From e80b224e9bc04438b7b175f8148fba8bdaec32e2 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:40:05 -0500 Subject: [PATCH 3/4] =?UTF-8?q?T-163:=20M2.1m=20=E2=80=94=20Filesystem=20l?= =?UTF-8?q?ibrary=20adapter=20for=20the=20MCP=20copilot=20`read=5Fknowledg?= =?UTF-8?q?e`=20tool:=20`KnowledgePort.listLibraryCards`=20over=20`library?= =?UTF-8?q?.yml`=20+=20`cards/
/*.md`=20in=20`libs/research/src/mc?= =?UTF-8?q?p/adapters/library-cards.ts`=20(injected=20read-only=20fs=20por?= =?UTF-8?q?t,=20strict=20front-matter=20parser,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 2 +- .../src/mcp/adapters/library-cards.ts | 130 +++--------------- libs/research/test/mcp-library-cards.test.ts | 121 ++++++++++++---- 3 files changed, 113 insertions(+), 140 deletions(-) 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), From 5fa1b55342d0a40355ff011a2b1c5b9d1946c6f1 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:46:45 -0500 Subject: [PATCH 4/4] =?UTF-8?q?T-163:=20M2.1m=20=E2=80=94=20Filesystem=20l?= =?UTF-8?q?ibrary=20adapter=20for=20the=20MCP=20copilot=20`read=5Fknowledg?= =?UTF-8?q?e`=20tool:=20`KnowledgePort.listLibraryCards`=20over=20`library?= =?UTF-8?q?.yml`=20+=20`cards/
/*.md`=20in=20`libs/research/src/mc?= =?UTF-8?q?p/adapters/library-cards.ts`=20(injected=20read-only=20fs=20por?= =?UTF-8?q?t,=20strict=20front-matter=20parser,=20no=20new=20deps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/adapters/library-cards.ts | 2 +- libs/research/test/mcp-library-cards.test.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/libs/research/src/mcp/adapters/library-cards.ts b/libs/research/src/mcp/adapters/library-cards.ts index 5a31eac6..92935689 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 PLAIN_YAML_KEY_RE = /^[^?:,[\]{}#&*!|>'"%@`\s][^,[\]{}#\s]*$/; +const PLAIN_YAML_KEY_RE = /^[^?:,[\]{}#&*!|>'"%@`\s](?:(?:[^,[\]{}#\s]| )*[^,[\]{}#\s])?$/; const BLOCK_SCALAR_RE = /^[|>][+-]?$/; /** Error codes thrown by {@link LibraryCardError}. */ diff --git a/libs/research/test/mcp-library-cards.test.ts b/libs/research/test/mcp-library-cards.test.ts index fb173c01..ac6a35eb 100644 --- a/libs/research/test/mcp-library-cards.test.ts +++ b/libs/research/test/mcp-library-cards.test.ts @@ -338,6 +338,7 @@ sections: alphas: Alphas -draft: Draft notes .archived: Archived notes + old signals: Archived signals Bad_Section: Invalid section name empty-section: Declared section with no directory `, @@ -348,6 +349,7 @@ sections: 'cards/alphas/symlink-card.md': MOMENTUM_CARD, 'cards/undeclared/secret.md': MOMENTUM_CARD, 'cards/-draft/valid-card.md': MOMENTUM_CARD, + 'cards/old signals/valid-card.md': MOMENTUM_CARD, 'cards/Bad_Section/valid-card.md': MOMENTUM_CARD, }, dirs: { @@ -359,6 +361,7 @@ sections: { name: 'alphas', isFile: false, isDirectory: true }, { name: 'undeclared', isFile: false, isDirectory: true }, { name: '-draft', isFile: false, isDirectory: true }, + { name: 'old signals', isFile: false, isDirectory: true }, { name: 'Bad_Section', isFile: false, isDirectory: true }, { name: 'symlink-section', isFile: false, isDirectory: false }, ], @@ -370,6 +373,7 @@ sections: { name: 'UpperCase.md', isFile: true, isDirectory: false }, { name: 'valid-card.md', isFile: true, isDirectory: false }, ], + 'cards/old signals': [{ name: 'valid-card.md', isFile: true, isDirectory: false }], }, }); @@ -447,7 +451,6 @@ sections: 'id: quant\nsections:\n - alphas\n', // YAML bare sequence under sections 'id: quant\nsections:\n alphas: # comment-only title\n', // comment-only title 'id: quant\nsections:\n alphas:NoSpace\n', // missing space after colon - 'id: quant\nsections:\n bad key: Title\n', // whitespace in section key ]; for (const manifest of badManifests) {