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

@ -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);
}