T-212: merge dev
This commit is contained in:
commit
3dd679e9fd
24 changed files with 5542 additions and 10 deletions
404
test/postgres/mcp-copilot-executor.test.ts
Normal file
404
test/postgres/mcp-copilot-executor.test.ts
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Client, Pool, type PoolConfig } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import {
|
||||
PostgreSQLClient,
|
||||
RESEARCH_COPILOT_PG_POOL_MAX,
|
||||
ResearchCopilotExecutorError,
|
||||
openResearchCopilotExecutor,
|
||||
runPostgresMigrations,
|
||||
} from '@stock-bot/postgres';
|
||||
import {
|
||||
createPostgresFindingWritePort,
|
||||
createPostgresKnowledgeReaders,
|
||||
createPostgresTrialRefLookupPort,
|
||||
} from '../../libs/research/src/mcp/index';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('mcp-copilot-executor-pg-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
|
||||
|
||||
const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0);
|
||||
const FIXED_TS = '2026-01-15T12:34:56.789Z';
|
||||
|
||||
const cleanup: Array<() => Promise<void> | void> = [];
|
||||
afterEach(async () => {
|
||||
let firstError: unknown;
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
try {
|
||||
await close();
|
||||
} catch (err) {
|
||||
firstError ??= err;
|
||||
}
|
||||
}
|
||||
if (firstError !== undefined) {
|
||||
throw firstError;
|
||||
}
|
||||
});
|
||||
|
||||
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
|
||||
if (!connectionString) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(connectionString);
|
||||
} catch {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const client = new Client({ connectionString });
|
||||
const effectiveDb = (
|
||||
client as unknown as { connectionParameters?: { database?: unknown } }
|
||||
).connectionParameters?.database;
|
||||
if (
|
||||
typeof effectiveDb !== 'string' ||
|
||||
!effectiveDb.startsWith('stock_bot_safety') ||
|
||||
!parsed.pathname.startsWith('/stock_bot_safety')
|
||||
) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
return connectionString;
|
||||
}
|
||||
|
||||
function buildIsolatedPoolConfig(connectionString: string, schema: string): PoolConfig {
|
||||
const safeUrl = assertSafetyDatabaseUrl(connectionString);
|
||||
const parsed = new URL(safeUrl);
|
||||
const existingOptions = parsed.searchParams
|
||||
.getAll('options')
|
||||
.map(value => value.trim())
|
||||
.filter(value => value.length > 0);
|
||||
parsed.searchParams.delete('options');
|
||||
|
||||
const options = [
|
||||
...existingOptions,
|
||||
`-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
|
||||
].join(' ');
|
||||
|
||||
return {
|
||||
connectionString: parsed.toString(),
|
||||
options,
|
||||
};
|
||||
}
|
||||
|
||||
function buildExecutorUrl(
|
||||
connectionString: string,
|
||||
schema: string,
|
||||
applicationName: string,
|
||||
extraParams?: Readonly<Record<string, string>>
|
||||
): string {
|
||||
const safeUrl = assertSafetyDatabaseUrl(connectionString);
|
||||
const parsed = new URL(safeUrl);
|
||||
const existingOptions = parsed.searchParams
|
||||
.getAll('options')
|
||||
.map(value => value.trim())
|
||||
.filter(value => value.length > 0);
|
||||
parsed.searchParams.delete('options');
|
||||
const combinedOptions = [...existingOptions, `-c search_path=${schema}`].join(' ');
|
||||
parsed.searchParams.set('options', combinedOptions);
|
||||
parsed.searchParams.set('application_name', applicationName);
|
||||
if (extraParams) {
|
||||
for (const [k, v] of Object.entries(extraParams)) {
|
||||
parsed.searchParams.set(k, v);
|
||||
}
|
||||
}
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
async function createIsolatedFixture(connectionString: string | undefined = url) {
|
||||
const safeUrl = assertSafetyDatabaseUrl(connectionString);
|
||||
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: safeUrl });
|
||||
cleanup.push(() => admin.end());
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined));
|
||||
|
||||
const setupPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
|
||||
cleanup.push(() => setupPool.end());
|
||||
|
||||
const { rows: schemaRows } = await setupPool.query<{ current_schema: string | null }>(
|
||||
'SELECT current_schema() AS current_schema'
|
||||
);
|
||||
if (schemaRows[0]?.current_schema !== schema) {
|
||||
throw new Error(
|
||||
`Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}`
|
||||
);
|
||||
}
|
||||
|
||||
for (const filename of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
'08-create-runs-table.sql',
|
||||
]) {
|
||||
await setupPool.query(readFileSync(`${initDir}${filename}`, 'utf8'));
|
||||
}
|
||||
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', {
|
||||
get: () => ({
|
||||
connect: () => setupPool.connect(),
|
||||
}),
|
||||
});
|
||||
|
||||
await runPostgresMigrations(postgres, { track: 'research' });
|
||||
|
||||
return { admin, setupPool, schema, safeUrl };
|
||||
}
|
||||
|
||||
async function waitForZeroBackends(admin: Pool, applicationName: string): Promise<number> {
|
||||
const deadline = Date.now() + 2_000;
|
||||
let count = -1;
|
||||
while (Date.now() < deadline) {
|
||||
const { rows } = await admin.query<{ c: number }>(
|
||||
'SELECT count(*)::int AS c FROM pg_stat_activity WHERE application_name = $1',
|
||||
[applicationName]
|
||||
);
|
||||
count = rows[0]?.c ?? -1;
|
||||
if (count === 0) {
|
||||
return 0;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 25));
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
describe('PostgreSQL MCP copilot executor safety guard', () => {
|
||||
test('rejects missing or non-safety database URLs', () => {
|
||||
expect(() => assertSafetyDatabaseUrl(undefined)).toThrow(
|
||||
'Dedicated stock_bot_safety database required'
|
||||
);
|
||||
expect(() =>
|
||||
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot')
|
||||
).toThrow('Dedicated stock_bot_safety database required');
|
||||
expect(() =>
|
||||
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev')
|
||||
).toThrow('Dedicated stock_bot_safety database required');
|
||||
expect(
|
||||
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test')
|
||||
).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test');
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () => {
|
||||
test('enforces effective 10s statement_timeout and 2s lock_timeout even when URL specifies overrides', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const appName = `copilot_timeouts_${randomUUID().slice(0, 8)}`;
|
||||
const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName, {
|
||||
statement_timeout: '99999',
|
||||
lock_timeout: '99999',
|
||||
query_timeout: '99999',
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl });
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>(
|
||||
'SHOW statement_timeout'
|
||||
);
|
||||
const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>(
|
||||
'SHOW lock_timeout'
|
||||
);
|
||||
|
||||
expect(stmtRows[0]?.statement_timeout).toBe('10s');
|
||||
expect(lockRows[0]?.lock_timeout).toBe('2s');
|
||||
});
|
||||
|
||||
test('preserves PGOPTIONS search_path when URL omits options while enforcing 10s/2s timeouts', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const appName = `copilot_pgoptions_${randomUUID().slice(0, 8)}`;
|
||||
|
||||
// Build a URL with NO options query parameter so pg must honor PGOPTIONS.
|
||||
const parsed = new URL(f.safeUrl);
|
||||
parsed.searchParams.delete('options');
|
||||
parsed.searchParams.set('application_name', appName);
|
||||
|
||||
const previousPgOptions = process.env.PGOPTIONS;
|
||||
process.env.PGOPTIONS = `-c search_path=${f.schema} -c statement_timeout=99999 -c lock_timeout=88888`;
|
||||
cleanup.push(() => {
|
||||
if (previousPgOptions === undefined) {
|
||||
delete process.env.PGOPTIONS;
|
||||
} else {
|
||||
process.env.PGOPTIONS = previousPgOptions;
|
||||
}
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor({ postgresUrl: parsed.toString() });
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const { rows: schemaRows } = await handle.executor.query<{ current_schema: string | null }>(
|
||||
'SELECT current_schema() AS current_schema'
|
||||
);
|
||||
const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>(
|
||||
'SHOW statement_timeout'
|
||||
);
|
||||
const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>(
|
||||
'SHOW lock_timeout'
|
||||
);
|
||||
|
||||
expect(schemaRows[0]?.current_schema).toBe(f.schema);
|
||||
expect(stmtRows[0]?.statement_timeout).toBe('10s');
|
||||
expect(lockRows[0]?.lock_timeout).toBe('2s');
|
||||
|
||||
// Verify unqualified findings writes and reads resolve against the PGOPTIONS search_path.
|
||||
const writePort = createPostgresFindingWritePort({ executor: handle.executor });
|
||||
const readers = createPostgresKnowledgeReaders({ executor: handle.executor });
|
||||
const created = await writePort.appendFinding(
|
||||
{
|
||||
id: 'finding-pgoptions-0001',
|
||||
kind: 'finding',
|
||||
title: 'PGOPTIONS search_path finding',
|
||||
summary: 'Resolved via PGOPTIONS search_path without explicit schema option.',
|
||||
status: 'pending_review',
|
||||
createdAt: FIXED_TS,
|
||||
trialRefs: [],
|
||||
evidenceRefs: [],
|
||||
},
|
||||
'idem-pgoptions-0001'
|
||||
);
|
||||
expect(created.status).toBe('created');
|
||||
|
||||
const listed = await readers.listFindings({ query: 'PGOPTIONS search_path' });
|
||||
expect(listed).toHaveLength(1);
|
||||
expect(listed[0]?.id).toBe('finding-pgoptions-0001');
|
||||
});
|
||||
|
||||
test('supports migrated findings writes, reads, idempotent replay, and real 23505 preservation', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const appName = `copilot_findings_${randomUUID().slice(0, 8)}`;
|
||||
const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName);
|
||||
|
||||
const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl });
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const writePort = createPostgresFindingWritePort({
|
||||
executor: handle.executor,
|
||||
schema: f.schema,
|
||||
});
|
||||
const readers = createPostgresKnowledgeReaders({
|
||||
executor: handle.executor,
|
||||
schema: f.schema,
|
||||
});
|
||||
|
||||
const record = {
|
||||
id: 'finding-exec-0001',
|
||||
kind: 'finding' as const,
|
||||
title: 'Executor integration finding',
|
||||
summary: 'Verified against migrated schema via openResearchCopilotExecutor.',
|
||||
status: 'pending_review' as const,
|
||||
createdAt: FIXED_TS,
|
||||
trialRefs: ['101'],
|
||||
evidenceRefs: ['snap:2025-06-29:ic'],
|
||||
};
|
||||
|
||||
const first = await writePort.appendFinding(record, 'idem-key-0001');
|
||||
expect(first).toEqual({
|
||||
status: 'created',
|
||||
id: 'finding-exec-0001',
|
||||
createdAt: FIXED_TS,
|
||||
});
|
||||
|
||||
// Same-ID, same-key replay must return the original finding and timestamp.
|
||||
const replay = await writePort.appendFinding(record, 'idem-key-0001');
|
||||
expect(replay).toEqual({
|
||||
status: 'replayed',
|
||||
id: 'finding-exec-0001',
|
||||
createdAt: FIXED_TS,
|
||||
});
|
||||
|
||||
// Unkeyed duplicate-PK insert hits PostgreSQL's primary-key constraint directly;
|
||||
// verify the executor preserves SQLSTATE 23505 without leaking driver fields.
|
||||
let pkCollisionErr: unknown;
|
||||
try {
|
||||
await writePort.appendFinding(record);
|
||||
} catch (err) {
|
||||
pkCollisionErr = err;
|
||||
}
|
||||
expect(pkCollisionErr).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((pkCollisionErr as ResearchCopilotExecutorError).code).toBe('23505');
|
||||
expect('cause' in (pkCollisionErr as object)).toBe(false);
|
||||
expect('detail' in (pkCollisionErr as object)).toBe(false);
|
||||
|
||||
const listed = await readers.listFindings({ query: 'Executor integration' });
|
||||
expect(listed).toHaveLength(1);
|
||||
expect(listed[0]?.id).toBe('finding-exec-0001');
|
||||
expect(listed[0]?.trialRefs).toEqual(['101']);
|
||||
|
||||
// Executor remains usable after 23505 collision.
|
||||
const { rows } = await handle.executor.query<{ count: number }>(
|
||||
`SELECT count(*)::int AS count FROM "${f.schema}".findings`
|
||||
);
|
||||
expect(rows[0]?.count).toBe(1);
|
||||
});
|
||||
|
||||
test('enforces Vault cutoff when wired into createPostgresTrialRefLookupPort', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
await f.setupPool.query(
|
||||
`INSERT INTO trial_ledger (
|
||||
trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash,
|
||||
sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series
|
||||
)
|
||||
OVERRIDING SYSTEM VALUE
|
||||
VALUES
|
||||
(1, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-29'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[]),
|
||||
(2, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`
|
||||
);
|
||||
|
||||
const appName = `copilot_vault_${randomUUID().slice(0, 8)}`;
|
||||
const handle = await openResearchCopilotExecutor({
|
||||
postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName),
|
||||
});
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const trialLookup = createPostgresTrialRefLookupPort({
|
||||
executor: handle.executor,
|
||||
vaultCutoffTs: VAULT_CUTOFF_TS,
|
||||
schema: f.schema,
|
||||
});
|
||||
|
||||
expect(await trialLookup.hasResearchVisibleTrial('1')).toBe(true);
|
||||
expect(await trialLookup.hasResearchVisibleTrial('2')).toBe(false);
|
||||
});
|
||||
|
||||
test('caps concurrent backend connections at 4 and disconnects all backends on close()', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const appName = `copilot_cap_${randomUUID().slice(0, 8)}`;
|
||||
const handle = await openResearchCopilotExecutor({
|
||||
postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName),
|
||||
});
|
||||
cleanup.push(() => handle.close());
|
||||
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: RESEARCH_COPILOT_PG_POOL_MAX + 2 }, () =>
|
||||
handle.executor.query<{ pid: number }>(
|
||||
'SELECT pg_backend_pid() AS pid FROM pg_sleep(0.15)'
|
||||
)
|
||||
)
|
||||
);
|
||||
const distinctPids = new Set(results.map(r => r.rows[0]?.pid));
|
||||
expect(distinctPids.size).toBeGreaterThanOrEqual(1);
|
||||
expect(distinctPids.size).toBeLessThanOrEqual(RESEARCH_COPILOT_PG_POOL_MAX);
|
||||
|
||||
await handle.close();
|
||||
|
||||
const remainingBackends = await waitForZeroBackends(f.admin, appName);
|
||||
expect(remainingBackends).toBe(0);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.executor.query('SELECT 1');
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED');
|
||||
});
|
||||
});
|
||||
175
test/unit/m2-completion-audit-doc.test.ts
Normal file
175
test/unit/m2-completion-audit-doc.test.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
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-204 M2 completion audit (design/m2-completion-audit.md) against
|
||||
// citation rot: every repo path it cites must resolve, every symbol it reports as
|
||||
// landed must still live in the file it names, and the report must keep host-only
|
||||
// verification marked pending. Gaps the audit reports as missing are deliberately
|
||||
// NOT asserted, so landing an M2 fix never breaks this test.
|
||||
|
||||
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const audit = readFileSync(join(repoRoot, 'design/m2-completion-audit.md'), 'utf8');
|
||||
const designIndex = readFileSync(join(repoRoot, 'design/README.md'), 'utf8');
|
||||
|
||||
// Cited as the gap itself (absent today), as already-retired code, as a sandbox env
|
||||
// note, or as the stale pre-rename docs/ location.
|
||||
const CITED_AS_ABSENT = new Set([
|
||||
'scripts/research-copilot-mcp.ts',
|
||||
'apps/stock/analytics',
|
||||
'python/.venv',
|
||||
'docs',
|
||||
'docs/',
|
||||
'docs/*.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 pathLike = spans.filter(
|
||||
(span) =>
|
||||
/^(apps|libs|tools|python|scripts|design|test|database|docs)\//.test(span) ||
|
||||
/^[A-Za-z0-9_.-]+\.(md|json|yml)$/.test(span)
|
||||
);
|
||||
return [
|
||||
...new Set(
|
||||
pathLike
|
||||
// Strip `:line`, `:a-b`, and `:a-b,c` suffixes and trailing globs.
|
||||
.map((span) => span.replace(/:[\d,-]+$/, '').replace(/\/\*$/, ''))
|
||||
.flatMap(expandBraces)
|
||||
),
|
||||
].sort();
|
||||
}
|
||||
|
||||
describe('design/m2-completion-audit.md citations', () => {
|
||||
test('cites only repo paths that exist, except those it reports as absent', () => {
|
||||
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('docs/ stays absent so the documentation path-drift note holds', () => {
|
||||
expect(existsSync(join(repoRoot, 'docs'))).toBe(false);
|
||||
expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true);
|
||||
});
|
||||
|
||||
// Symbols the audit reports as LANDED, keyed by the file it attributes them to.
|
||||
const landedSymbols: Array<[file: string, symbol: string | RegExp]> = [
|
||||
['libs/research/src/mcp/copilot-server.ts', 'createResearchCopilotMcpServer'],
|
||||
['libs/research/src/mcp/host/stdio-host.ts', 'runResearchCopilotStdioHost'],
|
||||
['libs/data/postgres/src/research-copilot-executor.ts', 'openResearchCopilotExecutor'],
|
||||
['libs/data/duckdb/src/research-copilot-store.ts', 'openResearchCopilotStore'],
|
||||
['libs/data/duckdb/src/research-copilot-store.ts', 'vaultOperatorAuthorized: false'],
|
||||
['libs/research/src/mcp/tools/query-data.ts', 'createQueryDataTool'],
|
||||
['libs/research/src/notebook-snapshot.ts', 'exportNotebookSnapshot'],
|
||||
['libs/research/src/notebook-snapshot-node.ts', 'exportNotebookSnapshot'],
|
||||
['libs/research/src/market-data-store-duckdb.ts', 'fundamentalsAsOf'],
|
||||
['libs/research/src/market-data-store-routed.ts', 'createRoutedMarketDataStore'],
|
||||
['libs/research/src/market-data-store-questdb.ts', 'createQuestDbIntradayBarsReader'],
|
||||
['libs/research/src/feature-library.ts', 'registerSignal'],
|
||||
['libs/research/src/feature-library.ts', 'runFeatureBatch'],
|
||||
['libs/research/src/feature-library.ts', 'export const RET_1D_V1'],
|
||||
['libs/research/src/feature-library.ts', 'export const FEATURE_INPUT_DATASETS'],
|
||||
['libs/data/questdb/src/schema.ts', 'M2_INTRADAY_SCHEMAS'],
|
||||
['libs/data/questdb/src/schema.ts', 'getM2IntradayDDL'],
|
||||
// The schema is declarative; DDL keywords are rendered from these fields.
|
||||
['libs/data/questdb/src/schema.ts', "capacity: 65536, cache: false"],
|
||||
['libs/data/questdb/src/schema.ts', "partitionBy: 'MONTH'"],
|
||||
['libs/data/questdb/src/schema.ts', 'dedupUpsertKeys'],
|
||||
['tools/curate-etl/src/cli.rs', 'SendIlp('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateFundamentals('],
|
||||
['tools/curate-etl/src/cli.rs', 'CuratePosts('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateMacro('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateBars1m('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
|
||||
['tools/curate-etl/src/main.rs', 'run_send_ilp('],
|
||||
['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'],
|
||||
['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/ilp_send_tests.rs', 'fn tcp_sends_separate_shards_and_half_closes'],
|
||||
[
|
||||
'tools/curate-etl/src/fundamentals_tests.rs',
|
||||
'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2',
|
||||
],
|
||||
[
|
||||
'tools/curate-etl/src/run_curate_bars_1m_tests.rs',
|
||||
'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes',
|
||||
],
|
||||
['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 'restatement non-overwrite'],
|
||||
['docker-compose.quant.yml', 'hard: 1048576'],
|
||||
['docker-compose.quant.yml', 'QDB_RAM_USAGE_LIMIT_BYTES=21474836480'],
|
||||
['database/postgres/init/37-research-findings.sql', 'provider_caveats'],
|
||||
['database/postgres/init/36-trial-ledger.sql', 'vault_evaluations'],
|
||||
];
|
||||
|
||||
test.each(landedSymbols)('%s contains %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('every MCP tool the audit counts is registered in the copilot server', () => {
|
||||
const server = readFileSync(join(repoRoot, 'libs/research/src/mcp/copilot-server.ts'), 'utf8');
|
||||
const tools = ['search_symbols', 'query_data', 'analyze_signal', 'event_study', 'file_finding', 'read_knowledge'];
|
||||
for (const tool of tools) {expect(server).toContain(`'${tool}'`);}
|
||||
expect(audit).toContain('6 MCP tools');
|
||||
});
|
||||
|
||||
test('the synthetic split fixture still documents the observed-data comparison as open', () => {
|
||||
// The audit's EC-3 "synthetic only" status rests on this scope note.
|
||||
const fixture = readFileSync(join(repoRoot, 'tools/curate-etl/src/run_curate_bars_1m_tests.rs'), 'utf8');
|
||||
expect(fixture).toMatch(/Does NOT prove .* against retained `bars_1d` data/);
|
||||
expect(audit).toMatch(/OPEN \(Synthetic Only\)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('design/m2-completion-audit.md structure and honesty', () => {
|
||||
test('holds M3 and covers every section the task requires', () => {
|
||||
expect(audit).toMatch(/HOLD M3/);
|
||||
expect(audit).toMatch(/^## 1\. Verification Gate Results/m);
|
||||
expect(audit).toMatch(/^## 2\. M2 Deliverables & Exit Criteria Matrix/m);
|
||||
expect(audit).toMatch(/^## 3\. Candidate Causes/m);
|
||||
expect(audit).toMatch(/^## 4\. Concrete Blockers Needing Director Decisions/m);
|
||||
expect(audit).toMatch(/^## 5\. M3 Readiness Mapping/m);
|
||||
});
|
||||
|
||||
test('covers all four M2 deliverables and all three M2 exit criteria', () => {
|
||||
for (const area of ['M2.1', 'M2.2', 'M2.3', 'M2.4']) {expect(audit).toContain(`**${area}**`);}
|
||||
for (const ec of ['EC-1', 'EC-2', 'EC-3']) {expect(audit).toContain(`**${ec}:**`);}
|
||||
for (const ec of ['M3 EC-1', 'M3 EC-2', 'M3 EC-3']) {expect(audit).toContain(`**${ec}:**`);}
|
||||
});
|
||||
|
||||
test('keeps host-only verification pending and parking causes unattributed', () => {
|
||||
expect(audit).toMatch(/\|\s*\*\*PENDING\*\*\s*\|/);
|
||||
expect(audit).toContain('none of the four items below can be attributed to a specific parked task');
|
||||
expect(audit).not.toMatch(/EC-3[^|]*\|\s*\*\*SATISFIED/);
|
||||
});
|
||||
|
||||
test('asks the director three decisions, each with a recommendation', () => {
|
||||
const decisions = audit.split(/^## 4\./m)[1]!.split(/^## 5\./m)[0]!;
|
||||
expect(decisions.match(/^\d\. \*\*/gm)?.length).toBe(3);
|
||||
expect(decisions.match(/\*Recommended:\*/g)?.length).toBe(3);
|
||||
});
|
||||
|
||||
test('carries the teData regime-filter-only limit into macro follow-ups', () => {
|
||||
expect(audit).toContain('design/DATA-CONTRACTS.md:26');
|
||||
expect(readFileSync(join(repoRoot, 'design/DATA-CONTRACTS.md'), 'utf8').split('\n')[25]).toContain(
|
||||
'final-revised values only'
|
||||
);
|
||||
});
|
||||
|
||||
test('is indexed exactly once in design/README.md', () => {
|
||||
const rows = designIndex.split('\n').filter((line) => line.includes('(m2-completion-audit.md)'));
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatch(/^\| \*\*\[m2-completion-audit\.md\]\(m2-completion-audit\.md\)\*\* \|.*\|.*\|$/);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue