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,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<string, string>;
readonly dirs: Map<string, LibraryCardDirEntry[]>;
readonly readPaths: string[];
readonly listPaths: string[];
readonly readErrors: Map<string, Error>;
readonly listErrors: Map<string, Error>;
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<Record<string, string>>;
readonly dirs?: Readonly<Record<string, readonly LibraryCardDirEntry[]>>;
}): FakeFsState {
const files = new Map<string, string>();
const dirs = new Map<string, LibraryCardDirEntry[]>();
const readPaths: string[] = [];
const listPaths: string[] = [];
const readErrors = new Map<string, Error>();
const listErrors = new Map<string, Error>();
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<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) {
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> | unknown,
expectedCode: LibraryCardError['code']
): Promise<LibraryCardError> {
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'
);
});
});