T-163: M2.1m — Filesystem library adapter for the MCP copilot read_knowledge tool: KnowledgePort.listLibraryCards over library.yml + cards/<section>/*.md in libs/research/src/mcp/adapters/library-cards.ts (injected read-only fs port, strict front-matter parser, no new deps)

This commit is contained in:
Studio 2026-12-02 10:40:05 -05:00 • committed by Boki
parent a255191b66
commit e80b224e9b
3 changed files with 113 additions and 140 deletions

View file

@ -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<KnowledgePort, 'listLibraryCards'>` over a configured read-only library root (`<root>/library.yml` and `<root>/cards/<sectionId>/<slug>.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/<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/<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

View file

@ -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<string>;
listDir(dirPath: string): Promise<readonly LibraryCardDirEntry[]>;
openDir?(dirPath: string): Promise<LibraryCardDirHandle>;
openDir(dirPath: string): Promise<LibraryCardDirHandle>;
}
/** 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<readonly LibraryCardDirEntry[]> {
return fs.listDir(dirPath);
},
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
assertSafeChildName(name);
return createPathBackedDirHandle(fs, path.join(dirPath, name));
},
readTextFile(name: string): Promise<string> {
assertSafeChildName(name);
return fs.readTextFile(path.join(dirPath, name));
},
async close(): Promise<void> {
// No underlying OS handle to close for path-backed adapters.
},
};
}
async function safeOpenRootDir(
fs: LibraryCardFs,
resolvedRoot: string
): Promise<LibraryCardDirHandle> {
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<string>();
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<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')) {
@ -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);
}

View file

@ -110,30 +110,84 @@ function createFakeLibraryFs(init?: {
}
}
const readFileByPath = async (filePath: string): Promise<string> => {
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<readonly LibraryCardDirEntry[]> => {
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<readonly LibraryCardDirEntry[]> {
assertOpen();
return listDirByPath(dirPath);
},
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
assertOpen();
assertChildName(name);
const childPath = path.join(dirPath, name);
if (!dirs.has(childPath)) {
throw makeEnoent(childPath);
}
return createAnchoredFakeDirHandle(childPath);
},
async readTextFile(name: string): Promise<string> {
assertOpen();
assertChildName(name);
return readFileByPath(path.join(dirPath, name));
},
async close(): Promise<void> {
closed = true;
},
};
};
const fs: LibraryCardFs = {
async readTextFile(filePath: string): Promise<string> {
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<readonly LibraryCardDirEntry[]> {
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<LibraryCardDirHandle> {
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<LibraryCardDirHandle> {
const rootHandle = await (baseNodeFs.openDir as NonNullable<LibraryCardFs['openDir']>)(
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<LibraryCardDirHandle> {
const rootHandle = await (baseNodeFs.openDir as NonNullable<LibraryCardFs['openDir']>)(
dirPath
);
const rootHandle = await baseNodeFs.openDir(dirPath);
return {
listDir: () => rootHandle.listDir(),
readTextFile: name => rootHandle.readTextFile(name),