T-176: merge dev
This commit is contained in:
commit
fc2ca6f483
13 changed files with 3618 additions and 369 deletions
933
libs/research/test/mcp-library-cards.test.ts
Normal file
933
libs/research/test/mcp-library-cards.test.ts
Normal file
|
|
@ -0,0 +1,933 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
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,
|
||||
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 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 = {
|
||||
readTextFile: readFileByPath,
|
||||
listDir: listDirByPath,
|
||||
async openDir(dirPath: string): Promise<LibraryCardDirHandle> {
|
||||
if (dirPath !== VIRTUAL_ROOT && !dirs.has(dirPath)) {
|
||||
throw makeEnoent(dirPath);
|
||||
}
|
||||
return createAnchoredFakeDirHandle(dirPath);
|
||||
},
|
||||
};
|
||||
|
||||
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
|
||||
-draft: Draft notes
|
||||
.archived: Archived notes
|
||||
old signals: Archived signals
|
||||
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/-draft/valid-card.md': MOMENTUM_CARD,
|
||||
'cards/old signals/valid-card.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: '-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 },
|
||||
],
|
||||
'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 },
|
||||
],
|
||||
'cards/old signals': [{ 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'
|
||||
);
|
||||
// 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);
|
||||
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
|
||||
'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
|
||||
];
|
||||
|
||||
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}`,
|
||||
},
|
||||
{
|
||||
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) {
|
||||
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'
|
||||
);
|
||||
});
|
||||
|
||||
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<LibraryCardDirHandle> {
|
||||
const rootHandle = await baseNodeFs.openDir(dirPath);
|
||||
return {
|
||||
listDir: () => rootHandle.listDir(),
|
||||
readTextFile: name => rootHandle.readTextFile(name),
|
||||
close: () => rootHandle.close(),
|
||||
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
|
||||
const sub = await rootHandle.openSubdir(name);
|
||||
if (name !== 'cards') {
|
||||
return sub;
|
||||
}
|
||||
return {
|
||||
async listDir(): Promise<readonly LibraryCardDirEntry[]> {
|
||||
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<LibraryCardDirHandle> {
|
||||
const rootHandle = await baseNodeFs.openDir(dirPath);
|
||||
return {
|
||||
listDir: () => rootHandle.listDir(),
|
||||
readTextFile: name => rootHandle.readTextFile(name),
|
||||
close: () => rootHandle.close(),
|
||||
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
|
||||
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<LibraryCardDirHandle> {
|
||||
const sectionHandle = await cardsHandle.openSubdir(sectionName);
|
||||
return {
|
||||
async listDir(): Promise<readonly LibraryCardDirEntry[]> {
|
||||
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<LibraryCardDirHandle> {
|
||||
throw new Error('Anchored no-follow directory operations are not supported.');
|
||||
},
|
||||
};
|
||||
const unsupportedReader = createLibraryCardReader({ root: libRoot, fs: unsupportedFs });
|
||||
await expectLibraryCardError(
|
||||
() => unsupportedReader.listLibraryCards({}),
|
||||
'INVALID_LIBRARY'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,10 +1,20 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { MarketDataStoreValidationError } from '../src/market-data-store';
|
||||
import {
|
||||
type AppendFindingResult,
|
||||
FILE_FINDING_ERROR_FILING_FAILED,
|
||||
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
|
||||
FILE_FINDING_INITIAL_STATUS,
|
||||
type FileFindingResultPayload,
|
||||
type FiledFindingRecord,
|
||||
type FindingWritePort,
|
||||
PostgresTrialRefError,
|
||||
type TrialRefExecutor,
|
||||
createFileFindingTool,
|
||||
createMcpServer,
|
||||
createPostgresTrialRefLookupPort,
|
||||
createPostgresTrialRefPort,
|
||||
} from '../src/mcp/index';
|
||||
import { utcDateOf } from '../src/mcp/tools/vault-fenced-input';
|
||||
|
||||
interface RecordedCall {
|
||||
readonly text: string;
|
||||
|
|
@ -28,92 +38,67 @@ function createFakeExecutor(rows: readonly Record<string, unknown>[] = []): {
|
|||
return { calls, executor };
|
||||
}
|
||||
|
||||
const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z
|
||||
const CUTOFF_DATE = '2025-06-30';
|
||||
function createFakeWritePort(): {
|
||||
readonly appended: FiledFindingRecord[];
|
||||
readonly port: FindingWritePort;
|
||||
} {
|
||||
const appended: FiledFindingRecord[] = [];
|
||||
const port: FindingWritePort = {
|
||||
async appendFinding(record: FiledFindingRecord): Promise<AppendFindingResult> {
|
||||
appended.push(record);
|
||||
return {
|
||||
status: 'created',
|
||||
id: record.id,
|
||||
createdAt: record.createdAt,
|
||||
};
|
||||
},
|
||||
};
|
||||
return { appended, port };
|
||||
}
|
||||
|
||||
describe('createPostgresTrialRefPort (fake executor)', () => {
|
||||
test('issues exact parameterized SELECT with default search_path and explicit quoted schema', async () => {
|
||||
const fakeDefault = createFakeExecutor([{ visible: 1 }]);
|
||||
const defaultPort = createPostgresTrialRefPort({
|
||||
executor: fakeDefault.executor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
});
|
||||
const CUTOFF_MIDNIGHT_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); // 2025-06-30T00:00:00.000Z
|
||||
|
||||
expect(await defaultPort.hasResearchVisibleTrial('42')).toBe(true);
|
||||
expect(fakeDefault.calls).toEqual([
|
||||
{
|
||||
text: 'SELECT 1 AS visible FROM trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1',
|
||||
params: ['42', CUTOFF_DATE],
|
||||
},
|
||||
]);
|
||||
|
||||
const fakeScoped = createFakeExecutor([{ visible: 1 }]);
|
||||
const scopedPort = createPostgresTrialRefPort({
|
||||
executor: fakeScoped.executor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
schema: 'research_iso_1',
|
||||
});
|
||||
|
||||
expect(await scopedPort.hasResearchVisibleTrial('42')).toBe(true);
|
||||
expect(fakeScoped.calls).toEqual([
|
||||
{
|
||||
text: 'SELECT 1 AS visible FROM "research_iso_1".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1',
|
||||
params: ['42', CUTOFF_DATE],
|
||||
},
|
||||
]);
|
||||
describe('createPostgresTrialRefLookupPort', () => {
|
||||
test('exposes createPostgresTrialRefPort as an alias', () => {
|
||||
expect(createPostgresTrialRefPort).toBe(createPostgresTrialRefLookupPort);
|
||||
});
|
||||
|
||||
test('converts vaultCutoffTs once to UTC calendar date across midnight boundaries', async () => {
|
||||
const lateFake = createFakeExecutor([]);
|
||||
// 2025-06-30T23:30:00.000Z is already 2025-07-01 in UTC+1 zones; must bind UTC date 2025-06-30.
|
||||
const latePort = createPostgresTrialRefPort({
|
||||
executor: lateFake.executor,
|
||||
vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 30, 0, 0),
|
||||
});
|
||||
expect(await latePort.hasResearchVisibleTrial('7')).toBe(false);
|
||||
expect(lateFake.calls[0]?.params).toEqual(['7', '2025-06-30']);
|
||||
|
||||
const nextFake = createFakeExecutor([]);
|
||||
const nextPort = createPostgresTrialRefPort({
|
||||
executor: nextFake.executor,
|
||||
vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0),
|
||||
});
|
||||
expect(await nextPort.hasResearchVisibleTrial('7')).toBe(false);
|
||||
expect(nextFake.calls[0]?.params).toEqual(['7', '2025-07-01']);
|
||||
});
|
||||
|
||||
test('rejects invalid options and executors with INVALID_EXECUTOR before any query', () => {
|
||||
test('rejects missing or non-callable executor with INVALID_EXECUTOR', () => {
|
||||
const invalidOptions: unknown[] = [
|
||||
null,
|
||||
undefined,
|
||||
{},
|
||||
{ executor: null, vaultCutoffTs: CUTOFF_TS },
|
||||
{ executor: {}, vaultCutoffTs: CUTOFF_TS },
|
||||
{ executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_TS },
|
||||
{ executor: null, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
|
||||
{ executor: {}, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
|
||||
{ executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_MIDNIGHT_TS },
|
||||
];
|
||||
|
||||
for (const opts of invalidOptions) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
createPostgresTrialRefPort(opts as Parameters<typeof createPostgresTrialRefPort>[0]);
|
||||
createPostgresTrialRefLookupPort(
|
||||
opts as Parameters<typeof createPostgresTrialRefLookupPort>[0]
|
||||
);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(PostgresTrialRefError);
|
||||
expect(caught).toBeInstanceOf(RangeError);
|
||||
expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR');
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects invalid schema identifiers with INVALID_SCHEMA before any query', () => {
|
||||
test('rejects invalid schema names with INVALID_SCHEMA before any query', () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const badSchemas: unknown[] = [
|
||||
'',
|
||||
'Public',
|
||||
'Bad-Schema',
|
||||
'a;drop',
|
||||
'1schema',
|
||||
'bad-name',
|
||||
'bad.name',
|
||||
'public"; DROP TABLE trial_ledger; --',
|
||||
'space name',
|
||||
'public"; DROP TABLE trial_ledger; --',
|
||||
123,
|
||||
null,
|
||||
];
|
||||
|
|
@ -121,9 +106,9 @@ describe('createPostgresTrialRefPort (fake executor)', () => {
|
|||
for (const schema of badSchemas) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
createPostgresTrialRefPort({
|
||||
createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
schema: schema as string,
|
||||
});
|
||||
} catch (err) {
|
||||
|
|
@ -136,150 +121,172 @@ describe('createPostgresTrialRefPort (fake executor)', () => {
|
|||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('accepts minimal valid schema identifiers and prototype-method pg.Pool-shaped executors', async () => {
|
||||
for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresTrialRefPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
schema,
|
||||
});
|
||||
await port.hasResearchVisibleTrial('1');
|
||||
expect(fake.calls[0]?.text).toContain(`FROM "${schema}".trial_ledger `);
|
||||
}
|
||||
|
||||
class PrototypeExecutor {
|
||||
readonly calls: RecordedCall[] = [];
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
this.calls.push({ text, params });
|
||||
return { rows: [{ visible: 1 }] as unknown as readonly Row[] };
|
||||
}
|
||||
}
|
||||
|
||||
const executor = new PrototypeExecutor();
|
||||
const port = createPostgresTrialRefPort({ executor, vaultCutoffTs: CUTOFF_TS });
|
||||
expect(await port.hasResearchVisibleTrial('101')).toBe(true);
|
||||
expect(executor.calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('rejects invalid or non-PostgreSQL-date vaultCutoffTs with MarketDataStoreValidationError', () => {
|
||||
test('rejects invalid or extended-year vaultCutoffTs with INVALID_VAULT_CUTOFF', () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const yearZeroTs = new Date('0000-06-15T00:00:00.000Z').getTime();
|
||||
const negativeYearTs = new Date('-000001-01-01T00:00:00.000Z').getTime();
|
||||
const fiveDigitYearTs = new Date('+010000-01-01T00:00:00.000Z').getTime();
|
||||
|
||||
const invalidCutoffs: unknown[] = [
|
||||
undefined,
|
||||
null,
|
||||
'2025-06-30',
|
||||
const badCutoffs: unknown[] = [
|
||||
Number.NaN,
|
||||
Number.POSITIVE_INFINITY,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
1.5,
|
||||
'2025-06-30',
|
||||
null,
|
||||
undefined,
|
||||
123.45,
|
||||
Number.MAX_SAFE_INTEGER + 1,
|
||||
8_640_000_000_000_000,
|
||||
-8_640_000_000_000_000,
|
||||
yearZeroTs,
|
||||
negativeYearTs,
|
||||
fiveDigitYearTs,
|
||||
Date.parse('+010000-01-01T00:00:00.000Z'),
|
||||
Date.parse('-000001-01-01T00:00:00.000Z'),
|
||||
Date.parse('0000-01-01T00:00:00.000Z'),
|
||||
];
|
||||
|
||||
for (const vaultCutoffTs of invalidCutoffs) {
|
||||
for (const vaultCutoffTs of badCutoffs) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
createPostgresTrialRefPort({
|
||||
createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: vaultCutoffTs as number,
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect((caught as MarketDataStoreValidationError).field).toBe('vaultCutoffTs');
|
||||
expect(caught).toBeInstanceOf(PostgresTrialRefError);
|
||||
expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF');
|
||||
}
|
||||
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('returns false with zero executor calls for every invalid, non-canonical, overflow, or injection-shaped ref', async () => {
|
||||
test('returns true for a visible trial with one parameterized read-only SELECT and exact params', async () => {
|
||||
const fake = createFakeExecutor([{ visible: 1 }]);
|
||||
const port = createPostgresTrialRefPort({
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
const visible = await port.hasResearchVisibleTrial('42');
|
||||
|
||||
expect(visible).toBe(true);
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
const call = fake.calls[0]!;
|
||||
expect(call.text.trimStart().startsWith('SELECT')).toBe(true);
|
||||
expect(call.text).not.toContain(';');
|
||||
expect(call.text).not.toMatch(/\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE)\b/i);
|
||||
expect(call.text).toBe(
|
||||
'SELECT 1 AS visible FROM trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1'
|
||||
);
|
||||
expect(call.params).toEqual(['42', '2025-06-30']);
|
||||
expect(typeof call.params?.[0]).toBe('string');
|
||||
});
|
||||
|
||||
test('returns false when the executor returns empty rows (unknown or Vault-only trial)', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
const visible = await port.hasResearchVisibleTrial('42');
|
||||
|
||||
expect(visible).toBe(false);
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']);
|
||||
});
|
||||
|
||||
test('maps midnight and non-midnight UTC vaultCutoffTs to the same UTC date as utcDateOf', async () => {
|
||||
const nonMidnightTs = Date.UTC(2025, 5, 30, 23, 59, 59, 999);
|
||||
const nextDayTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0);
|
||||
|
||||
const fakeSameDay = createFakeExecutor([{ visible: 1 }]);
|
||||
const sameDayPort = createPostgresTrialRefLookupPort({
|
||||
executor: fakeSameDay.executor,
|
||||
vaultCutoffTs: nonMidnightTs,
|
||||
});
|
||||
await sameDayPort.hasResearchVisibleTrial('7');
|
||||
expect(fakeSameDay.calls[0]!.params).toEqual(['7', utcDateOf(nonMidnightTs)]);
|
||||
expect(fakeSameDay.calls[0]!.params?.[1]).toBe('2025-06-30');
|
||||
|
||||
const fakeNextDay = createFakeExecutor([{ visible: 1 }]);
|
||||
const nextDayPort = createPostgresTrialRefLookupPort({
|
||||
executor: fakeNextDay.executor,
|
||||
vaultCutoffTs: nextDayTs,
|
||||
});
|
||||
await nextDayPort.hasResearchVisibleTrial('7');
|
||||
expect(fakeNextDay.calls[0]!.params).toEqual(['7', '2025-07-01']);
|
||||
});
|
||||
|
||||
test('returns false with zero executor calls for malformed, injection-shaped, overflowing, and non-string refs', async () => {
|
||||
const fake = createFakeExecutor([{ visible: 1 }]);
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
const invalidRefs: unknown[] = [
|
||||
'',
|
||||
' ',
|
||||
' 1',
|
||||
'1 ',
|
||||
'\t1',
|
||||
'1\n',
|
||||
' 42',
|
||||
'42 ',
|
||||
'042',
|
||||
'0',
|
||||
'-1',
|
||||
'+1',
|
||||
'01',
|
||||
'0001',
|
||||
'1.0',
|
||||
'1e2',
|
||||
'1E2',
|
||||
'1e3',
|
||||
'0x10',
|
||||
'1_000',
|
||||
'abc',
|
||||
'1; DROP TABLE trial_ledger',
|
||||
'1 OR 1=1',
|
||||
'42; DROP TABLE trial_ledger',
|
||||
'9223372036854775808',
|
||||
'9999999999999999999',
|
||||
'10000000000000000000',
|
||||
1,
|
||||
0,
|
||||
42,
|
||||
42n,
|
||||
null,
|
||||
undefined,
|
||||
{},
|
||||
[],
|
||||
1n,
|
||||
];
|
||||
|
||||
for (const ref of invalidRefs) {
|
||||
expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false);
|
||||
const result = await port.hasResearchVisibleTrial(ref as string);
|
||||
expect(result).toBe(false);
|
||||
}
|
||||
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('passes 9223372036854775807 as an exact string without Number coercion and skips 9223372036854775808', async () => {
|
||||
test('queries the maximum signed 64-bit BIGINT verbatim as a string without numeric coercion', async () => {
|
||||
const maxBigIntRef = '9223372036854775807';
|
||||
const fake = createFakeExecutor([{ visible: 1 }]);
|
||||
const port = createPostgresTrialRefPort({
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
expect(await port.hasResearchVisibleTrial('9223372036854775807')).toBe(true);
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
expect(fake.calls[0]?.params).toEqual(['9223372036854775807', CUTOFF_DATE]);
|
||||
expect(typeof fake.calls[0]?.params?.[0]).toBe('string');
|
||||
const visible = await port.hasResearchVisibleTrial(maxBigIntRef);
|
||||
|
||||
expect(await port.hasResearchVisibleTrial('9223372036854775808')).toBe(false);
|
||||
expect(visible).toBe(true);
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
expect(fake.calls[0]!.text).not.toContain(maxBigIntRef);
|
||||
expect(fake.calls[0]!.params).toEqual([maxBigIntRef, '2025-06-30']);
|
||||
});
|
||||
|
||||
test('returns false for zero rows and true for exactly one valid visibility row', async () => {
|
||||
const emptyFake = createFakeExecutor([]);
|
||||
const emptyPort = createPostgresTrialRefPort({
|
||||
executor: emptyFake.executor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
test('quotes validated optional schema and leaves table unqualified when omitted', async () => {
|
||||
const fakeDefault = createFakeExecutor([]);
|
||||
const defaultPort = createPostgresTrialRefLookupPort({
|
||||
executor: fakeDefault.executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
expect(await emptyPort.hasResearchVisibleTrial('123')).toBe(false);
|
||||
await defaultPort.hasResearchVisibleTrial('1');
|
||||
expect(fakeDefault.calls[0]!.text).toContain('FROM trial_ledger ');
|
||||
|
||||
const hitFake = createFakeExecutor([{ visible: 1 }]);
|
||||
const hitPort = createPostgresTrialRefPort({
|
||||
executor: hitFake.executor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
});
|
||||
expect(await hitPort.hasResearchVisibleTrial('123')).toBe(true);
|
||||
for (const schema of ['_', 'a', 'research_x', 'stock_bot_safety_0abc']) {
|
||||
const fakeScoped = createFakeExecutor([]);
|
||||
const scopedPort = createPostgresTrialRefLookupPort({
|
||||
executor: fakeScoped.executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
schema,
|
||||
});
|
||||
await scopedPort.hasResearchVisibleTrial('1');
|
||||
expect(fakeScoped.calls[0]!.text).toContain(`FROM "${schema}".trial_ledger `);
|
||||
}
|
||||
});
|
||||
|
||||
test('throws INVALID_ROW for malformed envelopes, invalid singleton rows, and multiple rows (regression)', async () => {
|
||||
|
|
@ -309,9 +316,9 @@ describe('createPostgresTrialRefPort (fake executor)', () => {
|
|||
return response as { readonly rows: readonly never[] };
|
||||
},
|
||||
};
|
||||
const port = createPostgresTrialRefPort({
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
|
|
@ -326,7 +333,7 @@ describe('createPostgresTrialRefPort (fake executor)', () => {
|
|||
});
|
||||
|
||||
test('propagates rejected and synchronously thrown executor errors unchanged without retrying', async () => {
|
||||
const asyncFailure = new Error('connection terminated');
|
||||
const asyncFailure = new Error('postgres connection lost');
|
||||
let asyncAttempts = 0;
|
||||
const asyncExecutor: TrialRefExecutor = {
|
||||
async query() {
|
||||
|
|
@ -334,28 +341,225 @@ describe('createPostgresTrialRefPort (fake executor)', () => {
|
|||
throw asyncFailure;
|
||||
},
|
||||
};
|
||||
const asyncPort = createPostgresTrialRefPort({
|
||||
const asyncPort = createPostgresTrialRefLookupPort({
|
||||
executor: asyncExecutor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
await expect(asyncPort.hasResearchVisibleTrial('101')).rejects.toBe(asyncFailure);
|
||||
await expect(asyncPort.hasResearchVisibleTrial('42')).rejects.toBe(asyncFailure);
|
||||
expect(asyncAttempts).toBe(1);
|
||||
|
||||
const syncFailure = new Error('sync driver failure');
|
||||
const syncFailure = new Error('pool exhausted');
|
||||
let syncAttempts = 0;
|
||||
const syncExecutor: TrialRefExecutor = {
|
||||
const syncExecutor = {
|
||||
query() {
|
||||
syncAttempts += 1;
|
||||
throw syncFailure;
|
||||
},
|
||||
};
|
||||
const syncPort = createPostgresTrialRefPort({
|
||||
} as unknown as TrialRefExecutor;
|
||||
const syncPort = createPostgresTrialRefLookupPort({
|
||||
executor: syncExecutor,
|
||||
vaultCutoffTs: CUTOFF_TS,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
await expect(syncPort.hasResearchVisibleTrial('101')).rejects.toBe(syncFailure);
|
||||
await expect(syncPort.hasResearchVisibleTrial('42')).rejects.toBe(syncFailure);
|
||||
expect(syncAttempts).toBe(1);
|
||||
});
|
||||
|
||||
test('accepts a pg.Pool-shaped executor with query on its prototype', async () => {
|
||||
class PoolLikeExecutor {
|
||||
readonly calls: RecordedCall[] = [];
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
this.calls.push({ text, params });
|
||||
return { rows: [{ visible: 1 }] as unknown as readonly Row[] };
|
||||
}
|
||||
}
|
||||
|
||||
const executor = new PoolLikeExecutor();
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
expect(await port.hasResearchVisibleTrial('99')).toBe(true);
|
||||
expect(executor.calls).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', () => {
|
||||
async function callFileFinding(
|
||||
executor: TrialRefExecutor,
|
||||
trialRefs: readonly string[]
|
||||
): Promise<{
|
||||
readonly appended: FiledFindingRecord[];
|
||||
readonly result: { readonly content: readonly { type: string; text: string }[]; readonly isError?: boolean };
|
||||
}> {
|
||||
const trialLookup = createPostgresTrialRefLookupPort({
|
||||
executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
const { appended, port } = createFakeWritePort();
|
||||
const tool = createFileFindingTool({
|
||||
port,
|
||||
trialLookup,
|
||||
newId: () => 'finding-0001',
|
||||
now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0),
|
||||
});
|
||||
const server = createMcpServer({
|
||||
name: 'test-copilot',
|
||||
version: '0.1.0',
|
||||
tools: [tool],
|
||||
});
|
||||
|
||||
const rawResponse = await server.handleMessage(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'file_finding',
|
||||
arguments: {
|
||||
kind: 'finding',
|
||||
title: 'Pre-vault momentum signal',
|
||||
summary: 'Observed stable rank IC across US equities prior to cutoff.',
|
||||
trialRefs,
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const parsed = JSON.parse(rawResponse!) as {
|
||||
readonly result: {
|
||||
readonly content: readonly { type: string; text: string }[];
|
||||
readonly isError?: boolean;
|
||||
};
|
||||
};
|
||||
return { appended, result: parsed.result };
|
||||
}
|
||||
|
||||
test('files a pending_review finding and returns a created receipt when the trial is visible', async () => {
|
||||
const fake = createFakeExecutor([{ visible: 1 }]);
|
||||
const { appended, result } = await callFileFinding(fake.executor, ['42']);
|
||||
|
||||
expect(result.isError).toBeUndefined();
|
||||
const payload = JSON.parse(result.content[0]!.text) as FileFindingResultPayload;
|
||||
expect(payload).toEqual({
|
||||
id: 'finding-0001',
|
||||
createdAt: '2025-06-29T12:00:00.000Z',
|
||||
created: true,
|
||||
});
|
||||
expect(appended).toHaveLength(1);
|
||||
expect(appended[0]).toEqual({
|
||||
id: 'finding-0001',
|
||||
kind: 'finding',
|
||||
title: 'Pre-vault momentum signal',
|
||||
status: FILE_FINDING_INITIAL_STATUS,
|
||||
createdAt: '2025-06-29T12:00:00.000Z',
|
||||
summary: 'Observed stable rank IC across US equities prior to cutoff.',
|
||||
trialRefs: ['42'],
|
||||
evidenceRefs: [],
|
||||
});
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
expect(fake.calls[0]!.params).toEqual(['42', '2025-06-30']);
|
||||
});
|
||||
|
||||
test('returns FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF with zero appends when executor returns no rows', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const { appended, result } = await callFileFinding(fake.executor, ['42']);
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
|
||||
expect(appended).toHaveLength(0);
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('returns FILE_FINDING_ERROR_FILING_FAILED with zero appends when executor rejects', async () => {
|
||||
const executor: TrialRefExecutor = {
|
||||
async query() {
|
||||
throw new Error('database unavailable');
|
||||
},
|
||||
};
|
||||
const { appended, result } = await callFileFinding(executor, ['42']);
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0]!.text).toBe(FILE_FINDING_ERROR_FILING_FAILED);
|
||||
expect(appended).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createPostgresTrialRefLookupPort (QA edge cases)', () => {
|
||||
test('queries in-range 19-digit refs and rejects 19-digit refs above the signed BIGINT max', async () => {
|
||||
const fake = createFakeExecutor([{ visible: 1 }]);
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
expect(await port.hasResearchVisibleTrial('1000000000000000000')).toBe(true);
|
||||
expect(await port.hasResearchVisibleTrial('9223372036854775806')).toBe(true);
|
||||
expect(await port.hasResearchVisibleTrial('9223372036854775900')).toBe(false);
|
||||
expect(await port.hasResearchVisibleTrial('9999999999999999999')).toBe(false);
|
||||
|
||||
expect(fake.calls.map(c => c.params?.[0])).toEqual([
|
||||
'1000000000000000000',
|
||||
'9223372036854775806',
|
||||
]);
|
||||
});
|
||||
|
||||
test('rejects trailing-newline, tab, fullwidth-digit, and boxed-String refs without querying', async () => {
|
||||
const fake = createFakeExecutor([{ visible: 1 }]);
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
for (const ref of ['42\n', '\n42', '4\t2', '42', '42\u0000', new String('42')] as unknown[]) {
|
||||
expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false);
|
||||
}
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('accepts the four-digit PostgreSQL calendar bounds 0001-01-01 and 9999-12-31 as cutoff dates', async () => {
|
||||
const earliest = Date.parse('0001-01-01T00:00:00.000Z');
|
||||
const latest = Date.parse('9999-12-31T23:59:59.999Z');
|
||||
|
||||
for (const [ts, expected] of [
|
||||
[earliest, '0001-01-01'],
|
||||
[latest, '9999-12-31'],
|
||||
[Date.UTC(1969, 11, 31, 23, 59, 59, 999), '1969-12-31'],
|
||||
] as const) {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: ts });
|
||||
await port.hasResearchVisibleTrial('5');
|
||||
expect(fake.calls[0]!.params).toEqual(['5', expected]);
|
||||
}
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
createPostgresTrialRefLookupPort({
|
||||
executor: createFakeExecutor().executor,
|
||||
vaultCutoffTs: latest + 1,
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF');
|
||||
});
|
||||
|
||||
test('freezes the cutoff date and SQL text at construction across repeated lookups', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const options = { executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS };
|
||||
const port = createPostgresTrialRefLookupPort(options);
|
||||
|
||||
await port.hasResearchVisibleTrial('1');
|
||||
(options as { vaultCutoffTs: number }).vaultCutoffTs = Date.UTC(2030, 0, 1);
|
||||
await port.hasResearchVisibleTrial('2');
|
||||
|
||||
expect(fake.calls).toHaveLength(2);
|
||||
expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text);
|
||||
expect(fake.calls[1]!.params).toEqual(['2', '2025-06-30']);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue