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:18:11 -05:00 • committed by Boki
parent 17120d7e28
commit 8ee307678f
4 changed files with 1420 additions and 0 deletions

View file

@ -0,0 +1,708 @@
/**
* Read-only filesystem adapter for the MCP copilot `read_knowledge` tool,
* implementing {@link KnowledgePort.listLibraryCards} over `<root>/library.yml`
* and `<root>/cards/<sectionId>/<slug>.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<string>;
listDir(dirPath: string): Promise<readonly LibraryCardDirEntry[]>;
}
/** Factory options for {@link createLibraryCardReader}. */
export interface LibraryCardReaderOptions {
readonly root: string;
readonly fs: LibraryCardFs;
}
/** Library-card subset of {@link KnowledgePort}. */
export type LibraryCardReader = Pick<KnowledgePort, 'listLibraryCards'>;
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<string>();
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<string, FrontMatterValue>();
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<string>();
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<string>
): { 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<string> {
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<readonly LibraryCardDirEntry[]> {
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<string> {
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<readonly LibraryCardDirEntry[]> {
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 `<root>/library.yml` and
* `<root>/cards/<sectionId>/<slug>.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<readonly LibraryCardRecord[]> {
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<string>();
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<string>();
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);
},
};
}