T-212: merge dev

This commit is contained in:
Studio 2026-12-04 16:55:37 -05:00
commit 3dd679e9fd
24 changed files with 5542 additions and 10 deletions

View file

@ -0,0 +1,101 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'bun:test';
// Guards the T-203 M2 gap audit (design/m2-gap-audit.md) against citation rot:
// every repo path it cites must resolve, and every symbol it reports as
// "present" must still live in the file it names. Gaps the audit reports as
// missing are deliberately NOT asserted, so landing a fix never breaks this test.
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
const auditPath = join(repoRoot, 'design/m2-gap-audit.md');
const audit = readFileSync(auditPath, 'utf8');
// Paths the audit cites as absent (the gap itself) or as the wrong location.
const CITED_AS_ABSENT = new Set(['scripts/research-copilot-mcp.ts', 'docs/']);
function expandBraces(path: string): string[] {
const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path);
if (!match) return [path];
const [, prefix, options, suffix] = match;
return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`));
}
function citedRepoPaths(markdown: string): string[] {
const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!);
const pathLike = spans.filter(
(span) =>
/^(apps|libs|tools|python|scripts|design|test|docs)\//.test(span) ||
/^[A-Za-z0-9_.-]+\.(md|json|yml)$/.test(span)
);
return [...new Set(pathLike.map((span) => span.replace(/:\d+$/, '')).flatMap(expandBraces))].sort();
}
describe('design/m2-gap-audit.md citations', () => {
test('cites only repo paths that exist, except those it reports as absent', () => {
const cited = citedRepoPaths(audit);
expect(cited.length).toBeGreaterThan(30);
const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p)));
expect(missing).toEqual([]);
});
test('every path listed as absent is actually absent in the audited checkout or is the docs/ relocation note', () => {
// docs/ is cited because milestone docs moved to design/; it must stay absent for that note to hold.
expect(existsSync(join(repoRoot, 'docs'))).toBe(false);
expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true);
});
// Symbols the audit reports as PRESENT, keyed by the file it attributes them to.
const presentSymbols: Array<[file: string, symbol: string | RegExp]> = [
['libs/research/src/mcp/tools/query-data.ts', 'createQueryDataTool'],
['libs/research/src/mcp/tools/query-data.ts', 'fenceVaultQueryBounds'],
['libs/research/src/mcp/tools/query-data.ts', "'vault_fenced'"],
['libs/research/src/mcp/adapters/postgres-copilot.ts', 'createPostgresResearchCopilotServer'],
['libs/data/duckdb/src/research-copilot-store.ts', 'openResearchCopilotStore'],
['libs/data/postgres/src/research-copilot-executor.ts', 'openResearchCopilotExecutor'],
['libs/research/src/notebook-snapshot.ts', 'exportNotebookSnapshot'],
['libs/research/src/mcp/host/stdio-host.ts', 'runResearchCopilotStdioHost'],
['libs/research/src/feature-library.ts', 'registerSignal'],
['libs/research/src/feature-library.ts', 'runFeatureBatch'],
['libs/data/questdb/src/schema.ts', 'M2_INTRADAY_SCHEMAS'],
['libs/data/questdb/src/schema.ts', 'getM2IntradayDDL'],
['libs/research/src/market-data-store-routed.ts', 'createRoutedMarketDataStore'],
['libs/research/src/market-data-store-questdb.ts', 'createQuestDbIntradayBarsReader'],
['tools/curate-etl/src/cli.rs', 'CurateMacro('],
['tools/curate-etl/src/cli.rs', 'SendIlp('],
['tools/curate-etl/src/cli.rs', 'CuratePosts('],
['tools/curate-etl/src/cli.rs', 'CurateFundamentals('],
['tools/curate-etl/src/cli.rs', 'CurateBars1m('],
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
['tools/curate-etl/src/run_curate_bars_1m_tests.rs', 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes'],
['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'],
['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/],
['tools/curate-etl/src/fundamentals.rs', 'build_fundamentals_rows'],
];
test.each(presentSymbols)('%s defines %p as the audit reports', (file, symbol) => {
const source = readFileSync(join(repoRoot, file), 'utf8');
if (typeof symbol === 'string') expect(source).toContain(symbol);
else expect(source).toMatch(symbol);
});
test('pins QuestDB 10.2.0 in every compose file the audit cites', () => {
for (const file of ['docker-compose.yml', 'docker-compose.dev.yml', 'docker-compose.prod.yml']) {
expect(readFileSync(join(repoRoot, file), 'utf8')).toContain('questdb/questdb:10.2.0');
}
});
test('lists the three closure-checklist sections the task requires', () => {
expect(audit).toMatch(/^## 2\. Verified on `master`/m);
expect(audit).toMatch(/^## 3\. Remaining M2 Code Gaps/m);
expect(audit).toMatch(/^## 4\. Manual Host-Only Closure Gates/m);
});
test('keeps master verification pending rather than claiming unverified passes', () => {
expect(audit).toContain('**OPEN');
expect(audit).toMatch(/PENDING/);
expect(audit).not.toMatch(/\|\s*\*\*PASS\*\*\s*\|/);
});
});

View file

@ -0,0 +1,208 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'bun:test';
// Guards the T-208 M2 master audit (design/m2-master-audit.md) against citation rot.
// Every repo path it cites must still resolve, every symbol or test it reports as
// landed must still be in the file it names, and the audited baseline must stay
// pinned. The gaps it reports as missing are deliberately not asserted, so closing
// a gap never breaks this test.
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
const audit = readFileSync(join(repoRoot, 'design/m2-master-audit.md'), 'utf8');
const designIndex = readFileSync(join(repoRoot, 'design/README.md'), 'utf8');
// Cited as gaps or future outputs, so they must not be required to exist.
const CITED_AS_ABSENT = new Set([
'scripts/export-notebook-snapshot.ts',
'design/m2-close-evidence.md',
'docs/',
'docs/*.md',
'design/*.md',
]);
function expandBraces(path: string): string[] {
const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path);
if (!match) return [path];
const [, prefix, options, suffix] = match;
return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`));
}
function citedRepoPaths(markdown: string): string[] {
const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!);
const repoRelative = spans.filter((span) =>
/^(apps|libs|tools|python|scripts|design|test|database|docs)\//.test(span)
);
return [
...new Set(repoRelative.map((span) => span.replace(/:[\d,-]+$/, '')).flatMap(expandBraces)),
]
.filter((p) => !p.includes('*') || CITED_AS_ABSENT.has(p))
.sort();
}
function lineAt(file: string, line: number): string {
return readFileSync(join(repoRoot, file), 'utf8').split('\n')[line - 1] ?? '';
}
describe('design/m2-master-audit.md citations', () => {
test('cites only repo paths that exist, except gaps and future evidence files', () => {
const cited = citedRepoPaths(audit);
expect(cited.length).toBeGreaterThan(40);
const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p)));
expect(missing).toEqual([]);
});
test('paths cited as gaps are still absent, and specs live under design/', () => {
expect(existsSync(join(repoRoot, 'docs'))).toBe(false);
expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true);
});
// [file, 1-based line the audit cites, text that line must contain]
const lineCitations: Array<[file: string, line: number, expected: string]> = [
['tools/curate-etl/src/parquet_posts.rs', 22, 'EVENT_KIND_POST'],
['tools/curate-etl/src/run_curate_posts.rs', 133, 'EventsDatasetExists'],
['tools/curate-etl/src/mongo_stream.rs', 53, 'pub enum SourceCollection'],
['tools/curate-etl/src/run_curate_fundamentals.rs', 113, 'pub struct CurateFundamentalsArgs'],
['tools/curate-etl/src/cli.rs', 98, 'CurateBars1m('],
['tools/curate-etl/src/cli.rs', 99, 'CurateQmBars1m('],
['tools/curate-etl/src/cli.rs', 100, 'CurateFx1m('],
['tools/curate-etl/src/cli.rs', 101, 'CuratePosts('],
['tools/curate-etl/src/cli.rs', 102, 'CurateFundamentals('],
['tools/curate-etl/src/cli.rs', 103, 'CurateMacro('],
['tools/curate-etl/src/cli.rs', 104, 'SendIlp('],
['tools/curate-etl/src/cli.rs', 1317, 'CliAction::CuratePosts'],
['tools/curate-etl/src/cli.rs', 1636, 'CliAction::CurateFundamentals'],
['tools/curate-etl/src/cli.rs', 1689, 'CliAction::CurateMacro'],
['tools/curate-etl/src/cli.rs', 2110, 'CliAction::CurateBars1m'],
['tools/curate-etl/src/cli.rs', 2277, 'CliAction::CurateQmBars1m'],
['tools/curate-etl/src/cli.rs', 2381, 'CliAction::CurateFx1m'],
['tools/curate-etl/src/cli.rs', 2461, 'CliAction::SendIlp'],
['tools/curate-etl/src/main.rs', 22, 'run_send_ilp'],
['tools/curate-etl/src/main.rs', 39, 'run_curate_qm_bars_1m'],
[
'tools/curate-etl/src/fundamentals_tests.rs',
104,
'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2',
],
[
'tools/curate-etl/src/parquet_fundamentals_tests.rs',
1107,
'fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm',
],
[
'tools/curate-etl/src/run_curate_bars_1m_tests.rs',
402,
'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes',
],
['tools/curate-etl/tests/cli.rs', 1747, 'fn send_ilp_cli_help_missing_flag_success_and_partial_error_routing'],
['tools/curate-etl/tests/cli.rs', 1787, 'TcpListener::bind("127.0.0.1:0")'],
[
'tools/curate-etl/tests/cli.rs',
1877,
'fn send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage',
],
['tools/curate-etl/tests/cli.rs', 1939, 'fn send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr'],
[
'tools/curate-etl/tests/curate_macro.rs',
178,
'fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage',
],
[
'tools/curate-etl/tests/curate_macro.rs',
471,
'fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel',
],
['tools/curate-etl/tests/curate_macro.rs', 709, 'fn cli_rerun_on_same_inputs_is_byte_deterministic'],
[
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
336,
'fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants',
],
[
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
527,
'fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards',
],
[
'tools/curate-etl/tests/curate_qm_bars_1m.rs',
622,
'fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped',
],
['tools/curate-etl/src/run_curate_fx_1m.rs', 24, 'bar-start `ts`'],
['libs/data/questdb/src/schema.ts', 33, 'fx_1m: {'],
['libs/data/questdb/src/schema.ts', 139, 'export function getM2IntradayDDL'],
['libs/data/duckdb/src/research-copilot-store.ts', 33, 'export const openResearchCopilotStore'],
['libs/data/duckdb/src/research-copilot-store.ts', 40, 'vaultOperatorAuthorized: false'],
['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 251, 'fundamentalsAsOf enforces restatement non-overwrite'],
['libs/research/src/market-data-store-duckdb.ts', 1448, "'events/year=*/part.parquet'"],
['libs/research/src/market-data-store-duckdb.ts', 1529, "timeframe === '1m'"],
['libs/research/src/market-data-store-duckdb.ts', 2283, 'crossSection('],
['libs/research/src/market-data-store-duckdb.ts', 2287, 'async fundamentalsAsOf('],
['libs/research/src/market-data-store-duckdb.ts', 2294, 'macroAsOf('],
['libs/research/src/market-data-store-routed.ts', 185, 'return daily.fx(q)'],
['libs/research/src/mcp/tools/analyze-signal.ts', 122, 'discriminatedUnion'],
['libs/research/src/feature-library.ts', 29, 'RET_1D_V1'],
['libs/research/src/feature-library.ts', 61, 'export const FEATURE_INPUT_DATASETS'],
['libs/research/src/notebook-snapshot-node.ts', 67, 'export function createNodeNotebookCommandRunner'],
['scripts/research-copilot-mcp.ts', 77, 'export async function runResearchCopilotMcp'],
['python/stockbot/data.py', 21, '"ceo_post"'],
['python/stockbot/data.py', 71, 'events/year=*/part.parquet'],
['python/stockbot/data.py', 259, 'NotImplementedError'],
['package.json', 56, '"mcp:research-copilot"'],
['design/MILESTONES.md', 96, 'eodIntraday1M'],
['docker-compose.quant.yml', 35, '1048576'],
];
test.each(lineCitations)('%s:%d contains %p as cited', (file, line, expected) => {
expect(audit).toContain(file.split('/').pop()!);
expect(lineAt(file, line)).toContain(expected);
});
test('pins the audited master baseline and accepted M1 separately from the review branch', () => {
expect(audit).toContain('d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52');
expect(audit).toContain('d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1');
expect(audit).toContain('git rev-parse master');
expect(audit).toMatch(/not `git rev-parse HEAD`/);
});
test('maps every M2 deliverable and exit criterion to a Done/Partial/Missing status', () => {
for (const row of ['M2.1', 'M2.2', 'M2.3', 'M2.4', 'EC-1', 'EC-2', 'EC-3']) {
const line = audit.split('\n').find((l) => l.startsWith(`| **${row}`));
expect(line, row).toBeDefined();
expect(line!).toMatch(/\|\s*\*\*(Done|Partial|Missing)\b/);
}
});
test('keeps host and quant checks pending rather than claiming them passed', () => {
expect(audit).toMatch(/\*\*PENDING \(host closure\)\*\*/);
expect(audit).toMatch(/\*\*PENDING \(host\/`quant`\)\*\*/);
expect(audit).toMatch(/\*\*Partial \(Synthetic Done; Live `quant` Missing\)\*\*/);
});
test('lists the seven approved backlog keys in dependency order', () => {
const keys = [
'm2-ceo-posts-events-compat',
'm2-store-macro-cross-section-fx1m',
'm2-data-pipeline-m2-inputs-and-probes',
'm2-curate-etl-mongo-and-financials-old',
'm2-python-sdk-m2-parity',
'm2-ec1-snapshot-cli-and-doc-paths',
'm2-host-quant-verification-and-closure',
];
const section = audit.slice(audit.indexOf('## 5. Ordered M2 Closure Backlog'));
const rows = section.split('\n').filter((l) => /^\| \*\*\d\*\* \|/.test(l));
expect(rows.map((r) => /`(m2-[a-z0-9-]+)`/.exec(r)?.[1])).toEqual(keys);
rows.forEach((row, i) => {
for (const dep of [...row.split('|')[4]!.matchAll(/`(m2-[a-z0-9-]+)`/g)].map((m) => m[1]!)) {
expect(keys.indexOf(dep), `${keys[i]} depends on ${dep}`).toBeLessThan(i);
}
});
});
test('proposes no CI workflow and is indexed in design/README.md', () => {
expect(audit).not.toMatch(/\.github\/workflows/);
expect(designIndex).toContain('[m2-master-audit.md](m2-master-audit.md)');
});
});

View file

@ -0,0 +1,332 @@
import { describe, expect, test } from 'bun:test';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store';
import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb';
import {
type LibraryCardReaderHandle,
MCP_PROTOCOL_VERSION,
type PostgresResearchCopilotExecutor,
type ReadKnowledgeResultPayload,
RESEARCH_COPILOT_TOOL_NAMES,
type StdioInput,
type StdioOutput,
} from '@stock-bot/research/mcp';
import {
RESEARCH_COPILOT_HOST_ERROR_LINE,
runResearchCopilotMcp,
} from '../research-copilot-mcp';
const FAKE_PASSWORD = 's3cr@t-default-pw#42';
const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_PASSWORD);
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z';
const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0);
function createMemoryWriter(): {
readonly stream: StdioOutput;
text(): string;
} {
const chunks: string[] = [];
return {
stream: {
write(chunk: string): boolean {
chunks.push(chunk);
return true;
},
},
text: () => chunks.join(''),
};
}
function createMemoryInput(lines: readonly string[]): StdioInput {
return {
async *[Symbol.asyncIterator](): AsyncIterator<string> {
for (const line of lines) {
yield `${line}\n`;
}
},
};
}
function createFakeExecutor(): PostgresResearchCopilotExecutor {
return {
async query<Row = Record<string, unknown>>(): Promise<{ readonly rows: readonly Row[] }> {
return { rows: [] };
},
};
}
function createFakeStore(): MarketDataStore {
return {
async *bars(q: BarQuery): AsyncIterable<BarBatch> {
yield {
listingId: q.listingIds[0] ?? 0,
timeframe: q.timeframe,
rows: [],
};
},
async crossSection() {
throw new MarketDataStoreNotImplementedError('crossSection');
},
async fundamentalsAsOf() {
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
},
async events() {
throw new MarketDataStoreNotImplementedError('events');
},
async shortsAsOf() {
throw new MarketDataStoreNotImplementedError('shortsAsOf');
},
async macroAsOf() {
throw new MarketDataStoreNotImplementedError('macroAsOf');
},
async fx() {
throw new MarketDataStoreNotImplementedError('fx');
},
async universe() {
return [];
},
};
}
function createFakeLibraryReader(): LibraryCardReaderHandle {
return {
async listLibraryCards() {
return [];
},
};
}
describe('scripts/research-copilot-mcp.ts default factory wiring', () => {
test('default createLibraryCardReader resolves master createLibraryCardReader + createNodeLibraryCardFs over a temp dir', async () => {
const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-mcp-lib-'));
try {
await mkdir(join(tempDir, 'cards', 'quant'), { recursive: true });
await writeFile(
join(tempDir, 'library.yml'),
'id: research-lib\nsections:\n quant: Quantitative Methods\n',
'utf8'
);
await writeFile(
join(tempDir, 'cards', 'quant', 'dsr-basics.md'),
[
'---',
'title: "Deflated Sharpe Ratio"',
'summary: "Adjusts Sharpe for multiple testing."',
'matches: ["dsr", "sharpe"]',
'---',
'',
'Use DSR to account for trial count.',
].join('\n'),
'utf8'
);
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const input = createMemoryInput([
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'defaults-test', version: '1.0.0' },
},
}),
JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/call',
params: {
name: 'read_knowledge',
arguments: {
source: 'library',
id: 'research-lib:quant/dsr-basics',
},
},
}),
]);
const exitCode = await runResearchCopilotMcp({
env: {
RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`,
RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root',
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
RESEARCH_MCP_LIBRARY_ROOT: tempDir,
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }),
},
input,
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
openStore: () => ({
store: createFakeStore(),
close: () => {
closed.push('store');
},
}),
// Intentionally omit createLibraryCardReader to exercise the default factory.
newId: () => '00000000-0000-4000-8000-000000000002',
now: () => FIXED_NOW_MS,
});
expect(exitCode).toBe(0);
expect(stderr.text()).toBe('');
expect(closed).toEqual(['store', 'executor']);
const responses = stdout
.text()
.trim()
.split('\n')
.map(line => JSON.parse(line) as Record<string, unknown>);
expect(responses).toHaveLength(2);
const callResp = responses[1] as {
id: number;
result: {
isError?: boolean;
content: Array<{ type: string; text: string }>;
};
};
expect(callResp.id).toBe(2);
expect(callResp.result.isError).not.toBe(true);
const payload = JSON.parse(callResp.result.content[0]!.text) as ReadKnowledgeResultPayload;
expect(payload.rowCount).toBe(1);
expect(payload.rows).toHaveLength(1);
const firstRow = payload.rows[0];
expect(firstRow?.source).toBe('library');
if (firstRow?.source === 'library') {
expect(firstRow.id).toBe('research-lib:quant/dsr-basics');
expect(firstRow.title).toBe('Deflated Sharpe Ratio');
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}
});
test('default openExecutor resolves master openResearchCopilotExecutor and fails closed without opening a DB socket', async () => {
// Passes parseResearchCopilotHostConfig (valid scheme + host), but fails
// openResearchCopilotExecutor synchronously (missing database path) before creating pg.Pool.
const urlWithoutDatabase = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433`;
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
let openStoreCalled = false;
const exitCode = await runResearchCopilotMcp({
env: {
RESEARCH_MCP_POSTGRES_URL: urlWithoutDatabase,
RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root',
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root',
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }),
},
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
// Intentionally omit openExecutor to exercise lazy import of openResearchCopilotExecutor.
openStore: () => {
openStoreCalled = true;
return { store: createFakeStore(), close: () => undefined };
},
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
expect(stderr.text()).toBe(RESEARCH_COPILOT_HOST_ERROR_LINE);
expect(stderr.text()).not.toContain(FAKE_PASSWORD);
expect(stderr.text()).not.toContain(FAKE_ENCODED_PASSWORD);
expect(stderr.text()).not.toContain(urlWithoutDatabase);
expect(openStoreCalled).toBe(false);
});
test('default openStore resolves master openResearchCopilotStore (in-memory DuckDB) and closes cleanly', async () => {
const tempCuratedRoot = await mkdtemp(join(tmpdir(), 'stockbot-mcp-curated-'));
try {
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const input = createMemoryInput([
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'defaults-store-test', version: '1.0.0' },
},
}),
JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/list',
params: {},
}),
]);
const exitCode = await runResearchCopilotMcp({
env: {
RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`,
RESEARCH_MCP_CURATED_ROOT: tempCuratedRoot,
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root',
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }),
},
input,
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
// Intentionally omit openStore to exercise lazy import of openResearchCopilotStore.
createLibraryCardReader: () => createFakeLibraryReader(),
newId: () => '00000000-0000-4000-8000-000000000003',
now: () => FIXED_NOW_MS,
});
expect(exitCode).toBe(0);
expect(stderr.text()).toBe('');
expect(closed).toEqual(['executor']);
const responses = stdout
.text()
.trim()
.split('\n')
.map(line => JSON.parse(line) as Record<string, unknown>);
expect(responses).toHaveLength(2);
const listResp = responses[1] as {
id: number;
result: { tools: Array<{ name: string }> };
};
expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]);
} finally {
await rm(tempCuratedRoot, { recursive: true, force: true });
}
});
});

View file

@ -0,0 +1,391 @@
import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store';
import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb';
import {
type LibraryCardReaderHandle,
MCP_PROTOCOL_VERSION,
type PostgresResearchCopilotExecutor,
RESEARCH_COPILOT_HOST_NAME,
RESEARCH_COPILOT_HOST_VERSION,
RESEARCH_COPILOT_TOOL_NAMES,
type StdioInput,
type StdioOutput,
} from '@stock-bot/research/mcp';
import {
RESEARCH_COPILOT_CONFIG_ERROR_LINE,
RESEARCH_COPILOT_HOST_ERROR_LINE,
runResearchCopilotMcp,
} from '../research-copilot-mcp';
const FAKE_DECODED_PASSWORD = 's3cr@t pass#99!';
const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD);
const FAKE_POSTGRES_URL = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev?sslmode=disable`;
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z';
const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0);
function buildValidEnv(
overrides: Readonly<Record<string, string | undefined>> = {}
): Record<string, string | undefined> {
return {
PATH: '/usr/local/bin:/usr/bin',
NODE_ENV: 'test',
RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL,
RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro',
RESEARCH_MCP_CURATED_ROOT: '/tmp/fake-curated-root-secret-path',
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
RESEARCH_MCP_LIBRARY_ROOT: '/tmp/fake-library-root-secret-path',
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({
XNYS: [101],
}),
...overrides,
};
}
function createMemoryWriter(): {
readonly stream: StdioOutput;
readonly chunks: string[];
text(): string;
} {
const chunks: string[] = [];
return {
stream: {
write(chunk: string): boolean {
chunks.push(chunk);
return true;
},
},
chunks,
text: () => chunks.join(''),
};
}
function createMemoryInput(lines: readonly string[]): StdioInput {
return {
async *[Symbol.asyncIterator](): AsyncIterator<string> {
for (const line of lines) {
yield `${line}\n`;
}
},
};
}
function createFakeExecutor(): PostgresResearchCopilotExecutor {
return {
async query<Row = Record<string, unknown>>(): Promise<{ readonly rows: readonly Row[] }> {
return { rows: [] };
},
};
}
function createFakeStore(): MarketDataStore {
return {
async *bars(q: BarQuery): AsyncIterable<BarBatch> {
yield {
listingId: q.listingIds[0] ?? 0,
timeframe: q.timeframe,
rows: [],
};
},
async crossSection() {
throw new MarketDataStoreNotImplementedError('crossSection');
},
async fundamentalsAsOf() {
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
},
async events() {
throw new MarketDataStoreNotImplementedError('events');
},
async shortsAsOf() {
throw new MarketDataStoreNotImplementedError('shortsAsOf');
},
async macroAsOf() {
throw new MarketDataStoreNotImplementedError('macroAsOf');
},
async fx() {
throw new MarketDataStoreNotImplementedError('fx');
},
async universe() {
return [];
},
};
}
function createFakeLibraryReader(): LibraryCardReaderHandle {
return {
async listLibraryCards() {
return [];
},
};
}
function assertSingleFixedLineNoSecrets(
stderrText: string,
expectedLine: string,
env: Readonly<Record<string, string | undefined>>
): void {
expect(stderrText).toBe(expectedLine);
expect(stderrText.endsWith('\n')).toBe(true);
expect(stderrText.slice(0, -1)).not.toContain('\n');
const forbidden = [
FAKE_POSTGRES_URL,
FAKE_ENCODED_PASSWORD,
FAKE_DECODED_PASSWORD,
env.RESEARCH_MCP_POSTGRES_URL,
env.RESEARCH_MCP_CURATED_ROOT,
env.RESEARCH_MCP_LIBRARY_ROOT,
env.RESEARCH_MCP_PRINCIPAL_ID,
].filter((value): value is string => typeof value === 'string' && value.length > 0);
for (const secret of forbidden) {
expect(stderrText).not.toContain(secret);
}
}
describe('scripts/research-copilot-mcp.ts', () => {
test('package.json defines mcp:research-copilot pointing to scripts/research-copilot-mcp.ts', () => {
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
const pkg = JSON.parse(readFileSync(join(repoRoot, 'package.json'), 'utf8')) as {
scripts?: Record<string, string>;
};
expect(pkg.scripts?.['mcp:research-copilot']).toBe('bun run scripts/research-copilot-mcp.ts');
});
test('missing required RESEARCH_MCP_* env returns exit code 1, one fixed stderr line, and zero stdout bytes', async () => {
const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: undefined });
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
let openExecutorCalled = false;
let openStoreCalled = false;
const exitCode = await runResearchCopilotMcp({
env,
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => {
openExecutorCalled = true;
return { executor: createFakeExecutor(), close: () => undefined };
},
openStore: () => {
openStoreCalled = true;
return { store: createFakeStore(), close: () => undefined };
},
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env);
expect(openExecutorCalled).toBe(false);
expect(openStoreCalled).toBe(false);
});
test('invalid RESEARCH_MCP_* env fails closed with one fixed stderr line and zero stdout bytes', async () => {
const env = buildValidEnv({
RESEARCH_MCP_POSTGRES_URL: `http://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`,
});
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const exitCode = await runResearchCopilotMcp({
env,
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({ executor: createFakeExecutor(), close: () => undefined }),
openStore: () => ({ store: createFakeStore(), close: () => undefined }),
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env);
});
test('openExecutor failure returns 1 with fixed stderr line leaking no DSN, password, or env values', async () => {
const env = buildValidEnv();
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
let openStoreCalled = false;
const exitCode = await runResearchCopilotMcp({
env,
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => {
throw new Error(
`connect failed for ${FAKE_POSTGRES_URL} (pw=${FAKE_DECODED_PASSWORD}) root=${env.RESEARCH_MCP_CURATED_ROOT}`
);
},
openStore: () => {
openStoreCalled = true;
return { store: createFakeStore(), close: () => undefined };
},
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env);
expect(openStoreCalled).toBe(false);
});
test('openStore failure closes already-opened executor and returns 1 with fixed stderr line', async () => {
const env = buildValidEnv();
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const exitCode = await runResearchCopilotMcp({
env,
input: createMemoryInput([]),
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
openStore: () => {
throw new Error(`DuckDB failed for ${env.RESEARCH_MCP_CURATED_ROOT} ${FAKE_POSTGRES_URL}`);
},
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env);
expect(closed).toEqual(['executor']);
});
test('stdio host failure closes store and executor in reverse order and leaks no secrets', async () => {
const env = buildValidEnv();
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const failingInput: StdioInput = {
async *[Symbol.asyncIterator](): AsyncIterator<string> {
throw new Error(`stdin boom ${FAKE_POSTGRES_URL} ${FAKE_DECODED_PASSWORD}`);
},
};
const exitCode = await runResearchCopilotMcp({
env,
input: failingInput,
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
openStore: () => ({
store: createFakeStore(),
close: () => {
closed.push('store');
},
}),
createLibraryCardReader: () => createFakeLibraryReader(),
});
expect(exitCode).toBe(1);
expect(stdout.text()).toBe('');
assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env);
expect(closed).toEqual(['store', 'executor']);
});
test('MCP initialize + tools/list round trip returns all 6 copilot tools on stdout, exit 0, and closes resources', async () => {
const env = buildValidEnv();
const stdout = createMemoryWriter();
const stderr = createMemoryWriter();
const closed: string[] = [];
const input = createMemoryInput([
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'test-client', version: '1.0.0' },
},
}),
JSON.stringify({
jsonrpc: '2.0',
method: 'notifications/initialized',
}),
JSON.stringify({
jsonrpc: '2.0',
id: 2,
method: 'tools/list',
params: {},
}),
]);
const exitCode = await runResearchCopilotMcp({
env,
input,
output: stdout.stream,
stderr: stderr.stream,
openExecutor: () => ({
executor: createFakeExecutor(),
close: () => {
closed.push('executor');
},
}),
openStore: () => ({
store: createFakeStore(),
close: () => {
closed.push('store');
},
}),
createLibraryCardReader: () => createFakeLibraryReader(),
newId: () => '00000000-0000-4000-8000-000000000001',
now: () => FIXED_NOW_MS,
});
expect(exitCode).toBe(0);
expect(stderr.text()).toBe('');
expect(closed).toEqual(['store', 'executor']);
const lines = stdout
.text()
.trim()
.split('\n')
.map(line => JSON.parse(line) as Record<string, unknown>);
expect(lines).toHaveLength(2);
const initResp = lines[0] as {
id: number;
result: {
protocolVersion: string;
serverInfo: { name: string; version: string };
};
};
expect(initResp.id).toBe(1);
expect(initResp.result.protocolVersion).toBe(MCP_PROTOCOL_VERSION);
expect(initResp.result.serverInfo).toEqual({
name: RESEARCH_COPILOT_HOST_NAME,
version: RESEARCH_COPILOT_HOST_VERSION,
});
const listResp = lines[1] as {
id: number;
result: { tools: Array<{ name: string }> };
};
expect(listResp.id).toBe(2);
expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]);
expect(listResp.result.tools).toHaveLength(6);
});
});