From 2e71dda7f281f0b669d594604f517898745d45ce Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 5 Dec 2026 13:45:27 -0500 Subject: [PATCH 1/3] =?UTF-8?q?T-214:=20M2.1w=20=E2=80=94=20Add=20notebook?= =?UTF-8?q?=20snapshot=20CLI,=20MCP=20end-to-end=20study+snapshot+finding?= =?UTF-8?q?=20test,=20and=20fix=20docs/->design/=20path=20drift?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 12 +- CLAUDE.md | 12 +- README.md | 16 +- package.json | 1 + scripts/export-notebook-snapshot.ts | 310 ++++ scripts/research-copilot-mcp.ts | 7 +- scripts/test/export-notebook-snapshot.test.ts | 505 +++++++ scripts/test/research-copilot-mcp-e2e.test.ts | 1333 +++++++++++++++++ studio.config.json | 16 +- tools/curate-etl/README.md | 23 +- 10 files changed, 2192 insertions(+), 43 deletions(-) create mode 100644 scripts/export-notebook-snapshot.ts create mode 100644 scripts/test/export-notebook-snapshot.test.ts create mode 100644 scripts/test/research-copilot-mcp-e2e.test.ts diff --git a/AGENTS.md b/AGENTS.md index e17d8648..ea0e211b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,9 +40,9 @@ - `apps/stock/orchestrator` & `apps/stock/engine`: Backtest/paper/live orchestration and Rust execution engine. ## Documentation -- `docs/README.md`: Documentation index and navigation map. -- `docs/PLATFORM-PLAN.md`: Target platform architecture and locked decisions (`D1`–`D12`). -- `docs/MILESTONES.md`: Ordered `M0`–`M5` build plan, file targets, and exit criteria. -- `docs/DATA-CONTRACTS.md`: Empirical MongoDB provider rules, PostgreSQL security master, DuckDB/Parquet, and QuestDB `10.2.0` schemas. -- `docs/VALIDATION-AND-RIGOR.md`: Canonical metrics, `trial_ledger`, DSR/PBO/CPCV math, 6-month vault + post-2023 recency gate, and IBKR Margin (`USD`/`CAD`) execution rules. -- `docs/servers.md`: Hardware and container topology (`quant` `10.0.0.51`, `9900K`, `TrueNAS`, local dev). +- `design/README.md`: Documentation index and navigation map. +- `design/PLATFORM-PLAN.md`: Target platform architecture and locked decisions (`D1`–`D12`). +- `design/MILESTONES.md`: Ordered `M0`–`M5` build plan, file targets, and exit criteria. +- `design/DATA-CONTRACTS.md`: Empirical MongoDB provider rules, PostgreSQL security master, DuckDB/Parquet, and QuestDB `10.2.0` schemas. +- `design/VALIDATION-AND-RIGOR.md`: Canonical metrics, `trial_ledger`, DSR/PBO/CPCV math, 6-month vault + post-2023 recency gate, and IBKR Margin (`USD`/`CAD`) execution rules. +- `design/servers.md`: Hardware and container topology (`quant` `10.0.0.51`, `9900K`, `TrueNAS`, local dev). diff --git a/CLAUDE.md b/CLAUDE.md index d9461a34..ba04bdbb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,14 +1,14 @@ # CLAUDE.md — Stock Bot Engineering & Quant Guide -Read [AGENTS.md](./AGENTS.md) first for mandatory environment and database safety rules, then [docs/README.md](./docs/README.md) for the platform architecture and active milestone checklist. +Read [AGENTS.md](./AGENTS.md) first for mandatory environment and database safety rules, then [design/README.md](./design/README.md) for the platform architecture and active milestone checklist. ## 1. Canonical Documentation - [AGENTS.md](./AGENTS.md) — Runtime commands (`bun`, `turbo`), `dev` vs `qa` port isolation, and strict QA MongoDB/PostgreSQL protection rules. -- [docs/PLATFORM-PLAN.md](./docs/PLATFORM-PLAN.md) — North-star architecture and locked design decisions (`D1`–`D12`). -- [docs/MILESTONES.md](./docs/MILESTONES.md) — Ordered implementation roadmap (`M0` → `M5`) with file targets and falsifiable exit criteria. -- [docs/DATA-CONTRACTS.md](./docs/DATA-CONTRACTS.md) — Empirical schemas and adjustment/PIT rules for all 31 QA MongoDB collections, PostgreSQL security master (`instruments`, `instrument_listings`, `corporate_actions`), DuckDB/Parquet, and QuestDB `10.2.0`. -- [docs/VALIDATION-AND-RIGOR.md](./docs/VALIDATION-AND-RIGOR.md) — `@stock-bot/calculations` single-source metric formulas, append-only `trial_ledger`, $\hat{N}$ Deflated Sharpe, CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, and IBKR Margin (`USD`/`CAD`) execution rules. -- [docs/servers.md](./docs/servers.md) — Hardware & container topology (`quant` `10.0.0.51`, `9900K` execution host, `TrueNAS`, local dev). +- [design/PLATFORM-PLAN.md](./design/PLATFORM-PLAN.md) — North-star architecture and locked design decisions (`D1`–`D12`). +- [design/MILESTONES.md](./design/MILESTONES.md) — Ordered implementation roadmap (`M0` → `M5`) with file targets and falsifiable exit criteria. +- [design/DATA-CONTRACTS.md](./design/DATA-CONTRACTS.md) — Empirical schemas and adjustment/PIT rules for all 31 QA MongoDB collections, PostgreSQL security master (`instruments`, `instrument_listings`, `corporate_actions`), DuckDB/Parquet, and QuestDB `10.2.0`. +- [design/VALIDATION-AND-RIGOR.md](./design/VALIDATION-AND-RIGOR.md) — `@stock-bot/calculations` single-source metric formulas, append-only `trial_ledger`, $\hat{N}$ Deflated Sharpe, CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, and IBKR Margin (`USD`/`CAD`) execution rules. +- [design/servers.md](./design/servers.md) — Hardware & container topology (`quant` `10.0.0.51`, `9900K` execution host, `TrueNAS`, local dev). ## 2. Non-Negotiable Architecture & Data Invariants 1. **Protect QA Data:** Never drop, reset, or write to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`) from `dev` or tests. Query QA MongoDB strictly read-only via `MONGODB_READ_URI` (`studio_stock_bot_read`). diff --git a/README.md b/README.md index 004c7e61..6b2ff2db 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,13 @@ Bun/TypeScript workspaces for market-data collection, processing, APIs, and a Re with a Rust native trading engine. `apps/wcag-ada` is an independent project and is not part of the root workspace checks. -**New to the codebase? Start with [Understanding Stock Bot](docs/guide/README.md):** a +**New to the codebase? Start with [Understanding Stock Bot](design/guide/README.md):** a system map, a complete backtest walkthrough, TypeScript strategy authoring, and a -[function-by-function code tour](docs/guide/code-reading.md). For the target AI quant +[function-by-function code tour](design/guide/code-reading.md). For the target AI quant research architecture and milestone roadmap (`M0`–`M5`), see the -[documentation index](docs/README.md) ([PLATFORM-PLAN.md](docs/PLATFORM-PLAN.md), -[MILESTONES.md](docs/MILESTONES.md), [DATA-CONTRACTS.md](docs/DATA-CONTRACTS.md), -[VALIDATION-AND-RIGOR.md](docs/VALIDATION-AND-RIGOR.md)). +[documentation index](design/README.md) ([PLATFORM-PLAN.md](design/PLATFORM-PLAN.md), +[MILESTONES.md](design/MILESTONES.md), [DATA-CONTRACTS.md](design/DATA-CONTRACTS.md), +[VALIDATION-AND-RIGOR.md](design/VALIDATION-AND-RIGOR.md)). ## Start the research workbench @@ -139,7 +139,7 @@ request. Do not blindly restart a cycle: hypothesis, family and finding creation have replay keys. The client cannot promote or activate paper/live trading. Human paper promotion uses the separate `/paper` workflow and a configured, initially -halted paper host. See [paper setup and evidence requirements](docs/development/architecture/research-product.md). +halted paper host. See [paper setup and evidence requirements](design/development/architecture/research-product.md). Creating a deployment is distinct from binding and activating it; development tests use disposable accounts only. @@ -261,7 +261,7 @@ and `MeanReversionStrategy`. Optional ML research lives in `strategies/experimen lazy-loaded and unavailable for paper execution. The unregistered strategy variants and their private position/risk framework have been removed; `ExecutionService` remains the financial authority. File/class relocation preserves the existing aliases and v2 checkpoint versions. -Use the [strategy development guide](docs/guide/strategy-development.md) +Use the [strategy development guide](design/guide/strategy-development.md) for the supported lifecycle and a type-checked, integration-tested runner example. Removed internal deep imports must migrate; their source remains recoverable in Git history. @@ -432,7 +432,7 @@ calls can load data for diagnostics, but durable replay/persistence requires the Dataset preparation has no application-level instrument, bar-count or payload-size caps. Internal handoffs reuse deeply frozen validated inputs; restored snapshots are always content-checked. Existing v1 hashes and replay identities are unchanged. Snapshots remain -JSONB and load in memory. See [dataset preparation](docs/backtest-datasets.md). +JSONB and load in memory. See [dataset preparation](design/backtest-datasets.md). ## Simulation order execution diff --git a/package.json b/package.json index e295375c..a182471b 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "backtest": "turbo run backtest", "benchmark:dataset": "bun run scripts/benchmark-dataset.ts", "mcp:research-copilot": "bun run scripts/research-copilot-mcp.ts", + "notebook:snapshot": "bun run scripts/export-notebook-snapshot.ts", "docker:start": "./scripts/docker.sh start --dev", "docker:stop": "./scripts/docker.sh stop --dev", "docker:restart": "./scripts/docker.sh restart --dev", diff --git a/scripts/export-notebook-snapshot.ts b/scripts/export-notebook-snapshot.ts new file mode 100644 index 00000000..869d0b7d --- /dev/null +++ b/scripts/export-notebook-snapshot.ts @@ -0,0 +1,310 @@ +/** + * Runnable CLI wrapper for `marimo check`-gated static HTML notebook exports. + * + * Enforces D9 (`design/PLATFORM-PLAN.md`): runs `marimo check --format=json` + * before `marimo export html` and publishes the HTML atomically via a sibling + * temp file. Emits the frozen JSON `NotebookSnapshotReceipt` to stdout on + * success, or a single concise error line to stderr with zero stdout bytes and + * exit code 1 on any validation, check, export, or timeout failure. + */ + +import { resolve } from 'node:path'; +import { + DEFAULT_MARIMO_COMMAND, + DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS, + type NotebookCommandRunner, + NotebookSnapshotError, + type NotebookSnapshotFs, + exportNotebookSnapshot, +} from '@stock-bot/research'; +import { + createNodeNotebookCommandRunner, + createNodeNotebookSnapshotFs, +} from '@stock-bot/research/notebook-snapshot-node'; + +const STRICT_POSITIVE_INT_RE = /^[1-9]\d*$/; + +export interface ExportNotebookSnapshotStream { + write(chunk: string): boolean; +} + +export interface ParseExportNotebookSnapshotArgsOptions { + readonly cwd?: string; + readonly env?: Readonly>; +} + +export interface ParsedExportNotebookSnapshotRun { + readonly kind: 'run'; + readonly notebookPath: string; + readonly outputPath: string; + readonly marimoCommand: string; + readonly timeoutMs: number; + readonly cwd?: string; + readonly allowedNotebookRoot?: string; + readonly allowedOutputRoot?: string; +} + +export interface ParsedExportNotebookSnapshotHelp { + readonly kind: 'help'; +} + +export type ParsedExportNotebookSnapshotArgs = + | ParsedExportNotebookSnapshotRun + | ParsedExportNotebookSnapshotHelp; + +export interface ExportNotebookSnapshotCliDeps { + readonly argv?: readonly string[]; + readonly cwd?: string; + readonly env?: Readonly>; + readonly stdout?: ExportNotebookSnapshotStream; + readonly stderr?: ExportNotebookSnapshotStream; + readonly runner?: NotebookCommandRunner; + readonly fs?: NotebookSnapshotFs; +} + +export class ExportNotebookSnapshotCliError extends Error { + constructor(message: string) { + super(message); + this.name = 'ExportNotebookSnapshotCliError'; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export const EXPORT_NOTEBOOK_SNAPSHOT_USAGE = [ + 'Usage: bun run notebook:snapshot --notebook --out [options]', + '', + 'Options:', + ' --notebook Required marimo notebook file (.py)', + ' --out Required output HTML snapshot path (.html)', + ` --marimo marimo executable (default: $MARIMO_COMMAND or ${DEFAULT_MARIMO_COMMAND})`, + ` --timeout-ms Per-command timeout in ms (default: ${DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS})`, + ' --cwd Working directory passed to marimo subprocesses', + ' --allowed-notebook-root Optional root directory bounding --notebook', + ' --allowed-output-root Optional root directory bounding --out', + ' -h, --help Show this help message', + '', +].join('\n'); + +const VALUE_FLAGS = new Set([ + '--notebook', + '--out', + '--marimo', + '--timeout-ms', + '--cwd', + '--allowed-notebook-root', + '--allowed-output-root', +]); + +function sanitizeSingleLine(message: string): string { + return message.replace(/\r?\n/g, ' ').trim(); +} + +function validateRawTokenValue(flag: string, rawValue: string): string { + if (rawValue.length === 0 || rawValue.trim().length === 0) { + throw new ExportNotebookSnapshotCliError(`Flag '${flag}' requires a non-empty value.`); + } + if (rawValue.includes('\0')) { + throw new ExportNotebookSnapshotCliError(`Flag '${flag}' value must not contain NUL bytes.`); + } + if (rawValue.startsWith('-')) { + throw new ExportNotebookSnapshotCliError( + `Flag '${flag}' value must not start with '-' (received '${rawValue}').` + ); + } + return rawValue; +} + +function parsePositiveIntFlag(flag: string, rawValue: string): number { + const validated = validateRawTokenValue(flag, rawValue); + if (!STRICT_POSITIVE_INT_RE.test(validated)) { + throw new ExportNotebookSnapshotCliError( + `Flag '${flag}' must be a positive integer (received '${validated}').` + ); + } + const parsed = Number(validated); + if (!Number.isSafeInteger(parsed) || parsed <= 0) { + throw new ExportNotebookSnapshotCliError( + `Flag '${flag}' must be a positive safe integer (received '${validated}').` + ); + } + return parsed; +} + +function resolveValidatedPath(baseCwd: string, flag: string, rawValue: string): string { + const validated = validateRawTokenValue(flag, rawValue); + return resolve(baseCwd, validated); +} + +/** + * Parses and validates CLI arguments for `scripts/export-notebook-snapshot.ts`. + * + * Rejects missing required flags, duplicate flags, unknown flags, positional + * arguments, NUL bytes, and values starting with `-` prior to `path.resolve`. + */ +export function parseExportNotebookSnapshotArgs( + argv: readonly string[], + options?: ParseExportNotebookSnapshotArgsOptions +): ParsedExportNotebookSnapshotArgs { + const baseCwd = options?.cwd ?? process.cwd(); + const env = options?.env ?? process.env; + + const seen = new Map(); + + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i] as string; + if (token === '--help' || token === '-h') { + return { kind: 'help' }; + } + if (token === '--') { + throw new ExportNotebookSnapshotCliError('Unexpected positional argument separator "--".'); + } + if (!token.startsWith('-')) { + throw new ExportNotebookSnapshotCliError(`Unexpected positional argument '${token}'.`); + } + + const eqIndex = token.indexOf('='); + let flag: string; + let rawValue: string; + + if (eqIndex !== -1) { + flag = token.slice(0, eqIndex); + rawValue = token.slice(eqIndex + 1); + if (!VALUE_FLAGS.has(flag)) { + throw new ExportNotebookSnapshotCliError(`Unknown flag '${flag}'.`); + } + } else { + flag = token; + if (!VALUE_FLAGS.has(flag)) { + throw new ExportNotebookSnapshotCliError(`Unknown flag '${flag}'.`); + } + if (i + 1 >= argv.length) { + throw new ExportNotebookSnapshotCliError(`Flag '${flag}' requires a value.`); + } + i += 1; + rawValue = argv[i] as string; + } + + if (seen.has(flag)) { + throw new ExportNotebookSnapshotCliError(`Duplicate flag '${flag}'.`); + } + seen.set(flag, validateRawTokenValue(flag, rawValue)); + } + + const rawNotebook = seen.get('--notebook'); + if (rawNotebook === undefined) { + throw new ExportNotebookSnapshotCliError('Missing required flag --notebook .'); + } + const rawOut = seen.get('--out'); + if (rawOut === undefined) { + throw new ExportNotebookSnapshotCliError('Missing required flag --out .'); + } + + const notebookPath = resolveValidatedPath(baseCwd, '--notebook', rawNotebook); + const outputPath = resolveValidatedPath(baseCwd, '--out', rawOut); + + const rawMarimo = seen.get('--marimo'); + let marimoCommand: string; + if (rawMarimo !== undefined) { + marimoCommand = rawMarimo; + } else { + const envMarimo = env.MARIMO_COMMAND; + marimoCommand = + typeof envMarimo === 'string' && envMarimo.trim().length > 0 + ? envMarimo + : DEFAULT_MARIMO_COMMAND; + } + + const rawTimeoutMs = seen.get('--timeout-ms'); + const timeoutMs = + rawTimeoutMs !== undefined + ? parsePositiveIntFlag('--timeout-ms', rawTimeoutMs) + : DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS; + + const rawCwd = seen.get('--cwd'); + const cwd = rawCwd !== undefined ? resolveValidatedPath(baseCwd, '--cwd', rawCwd) : undefined; + + const rawAllowedNotebookRoot = seen.get('--allowed-notebook-root'); + const allowedNotebookRoot = + rawAllowedNotebookRoot !== undefined + ? resolveValidatedPath(baseCwd, '--allowed-notebook-root', rawAllowedNotebookRoot) + : undefined; + + const rawAllowedOutputRoot = seen.get('--allowed-output-root'); + const allowedOutputRoot = + rawAllowedOutputRoot !== undefined + ? resolveValidatedPath(baseCwd, '--allowed-output-root', rawAllowedOutputRoot) + : undefined; + + return { + kind: 'run', + notebookPath, + outputPath, + marimoCommand, + timeoutMs, + ...(cwd !== undefined ? { cwd } : {}), + ...(allowedNotebookRoot !== undefined ? { allowedNotebookRoot } : {}), + ...(allowedOutputRoot !== undefined ? { allowedOutputRoot } : {}), + }; +} + +/** + * Executes the notebook snapshot CLI with injectable I/O, runner, and fs deps. + */ +export async function runExportNotebookSnapshotCli( + deps: ExportNotebookSnapshotCliDeps = {} +): Promise { + const argv = deps.argv ?? process.argv.slice(2); + const stdout = deps.stdout ?? process.stdout; + const stderr = deps.stderr ?? process.stderr; + + let parsed: ParsedExportNotebookSnapshotArgs; + try { + parsed = parseExportNotebookSnapshotArgs(argv, { + ...(deps.cwd !== undefined ? { cwd: deps.cwd } : {}), + ...(deps.env !== undefined ? { env: deps.env } : {}), + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + stderr.write(`Invalid arguments: ${sanitizeSingleLine(message)}\n`); + return 1; + } + + if (parsed.kind === 'help') { + stdout.write(EXPORT_NOTEBOOK_SNAPSHOT_USAGE); + return 0; + } + + try { + const receipt = await exportNotebookSnapshot({ + notebookPath: parsed.notebookPath, + outputPath: parsed.outputPath, + marimoCommand: parsed.marimoCommand, + timeoutMs: parsed.timeoutMs, + ...(parsed.cwd !== undefined ? { cwd: parsed.cwd } : {}), + ...(parsed.allowedNotebookRoot !== undefined + ? { allowedNotebookRoot: parsed.allowedNotebookRoot } + : {}), + ...(parsed.allowedOutputRoot !== undefined + ? { allowedOutputRoot: parsed.allowedOutputRoot } + : {}), + runner: deps.runner ?? createNodeNotebookCommandRunner(), + fs: deps.fs ?? createNodeNotebookSnapshotFs(), + }); + stdout.write(`${JSON.stringify(receipt)}\n`); + return 0; + } catch (err) { + if (err instanceof NotebookSnapshotError) { + stderr.write( + `Notebook snapshot export failed [${err.code}]: ${sanitizeSingleLine(err.message)}\n` + ); + return 1; + } + const message = err instanceof Error ? err.message : String(err); + stderr.write(`Notebook snapshot export failed: ${sanitizeSingleLine(message)}\n`); + return 1; + } +} + +if (import.meta.main) { + process.exitCode = await runExportNotebookSnapshotCli(); +} diff --git a/scripts/research-copilot-mcp.ts b/scripts/research-copilot-mcp.ts index 391d5f00..69234067 100644 --- a/scripts/research-copilot-mcp.ts +++ b/scripts/research-copilot-mcp.ts @@ -57,12 +57,13 @@ async function defaultOpenExecutor( } async function defaultOpenStore( - config: ResearchCopilotHostConfig + config: ResearchCopilotHostConfig, + env?: Readonly> ): Promise { const { openResearchCopilotStore } = await import( '../libs/data/duckdb/src/research-copilot-store' ); - return openResearchCopilotStore(config); + return openResearchCopilotStore(config, env !== undefined ? { env } : undefined); } function defaultCreateLibraryCardReader( @@ -91,7 +92,7 @@ export async function runResearchCopilotMcp( await runResearchCopilotStdioHost({ config, openExecutor: deps.openExecutor ?? defaultOpenExecutor, - openStore: deps.openStore ?? defaultOpenStore, + openStore: deps.openStore ?? (hostConfig => defaultOpenStore(hostConfig, deps.env)), createLibraryCardReader: deps.createLibraryCardReader ?? defaultCreateLibraryCardReader, newId: deps.newId ?? randomUUID, now: deps.now ?? Date.now, diff --git a/scripts/test/export-notebook-snapshot.test.ts b/scripts/test/export-notebook-snapshot.test.ts new file mode 100644 index 00000000..8b363514 --- /dev/null +++ b/scripts/test/export-notebook-snapshot.test.ts @@ -0,0 +1,505 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { + chmod, + mkdir, + mkdtemp, + readdir, + readFile, + realpath, + rm, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import type { NotebookSnapshotReceipt } from '@stock-bot/research'; + +const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url)); +const CLI_SCRIPT_PATH = join(REPO_ROOT, 'scripts/export-notebook-snapshot.ts'); + +type FakeMarimoMode = + | 'clean' + | 'check_nonzero' + | 'check_errored_zero' + | 'check_breaking_zero' + | 'export_nonzero' + | 'export_hang'; + +interface SpawnCliResult { + readonly exitCode: number; + readonly stdout: string; + readonly stderr: string; +} + +function getErrorCode(err: unknown): string | undefined { + if (typeof err === 'object' && err !== null && 'code' in err) { + const code = (err as { code?: unknown }).code; + if (typeof code === 'string') { + return code; + } + } + return undefined; +} + +async function runCliSubprocess( + args: readonly string[], + options?: { + readonly cwd?: string; + readonly env?: Readonly>; + } +): Promise { + const proc = Bun.spawn([process.execPath, 'run', CLI_SCRIPT_PATH, ...args], { + cwd: options?.cwd ?? REPO_ROOT, + env: options?.env ? { ...process.env, ...options.env } : process.env, + stdin: 'ignore', + stdout: 'pipe', + stderr: 'pipe', + }); + + const [exitCode, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]); + + return { exitCode, stdout, stderr }; +} + +function assertSingleLineStderr(stderr: string): void { + expect(stderr.length).toBeGreaterThan(0); + expect(stderr.endsWith('\n')).toBe(true); + expect(stderr.slice(0, -1)).not.toContain('\n'); +} + +describe('scripts/export-notebook-snapshot.ts', () => { + let workDir = ''; + + beforeEach(async () => { + const rawDir = await mkdtemp(join(tmpdir(), 'export-notebook-snapshot-cli-')); + workDir = await realpath(rawDir); + }); + + afterEach(async () => { + if (workDir) { + await rm(workDir, { recursive: true, force: true }); + workDir = ''; + } + }); + + async function writeFakeMarimoShim( + name: string, + mode: FakeMarimoMode, + logPath: string, + extra?: { readonly htmlContent?: string; readonly pidPath?: string } + ): Promise { + const shimPath = join(workDir, name); + const htmlContent = extra?.htmlContent ?? 'Snapshot OK\n'; + const pidPath = extra?.pidPath ?? ''; + + const script = [ + '#!/usr/bin/env bun', + "import { appendFileSync, writeFileSync } from 'node:fs';", + 'const args = process.argv.slice(2);', + `const mode = ${JSON.stringify(mode)};`, + `const logPath = ${JSON.stringify(logPath)};`, + `const htmlContent = ${JSON.stringify(htmlContent)};`, + `const pidPath = ${JSON.stringify(pidPath)};`, + 'appendFileSync(logPath, JSON.stringify({ args, pid: process.pid }) + "\\n", "utf8");', + 'if (args[0] === "check") {', + ' if (mode === "check_nonzero") {', + ' process.stderr.write("syntax error in cell 2\\n");', + ' process.exit(1);', + ' }', + ' if (mode === "check_errored_zero") {', + ' process.stdout.write(JSON.stringify({', + ' issues: [{ type: "error", message: "undefined variable" }],', + ' summary: { errored: true, total_files: 1 },', + ' }));', + ' process.exit(0);', + ' }', + ' if (mode === "check_breaking_zero") {', + ' process.stdout.write(JSON.stringify({', + ' issues: [{ severity: "breaking", message: "cyclic cell graph" }],', + ' summary: { errored: false, total_files: 1 },', + ' }));', + ' process.exit(0);', + ' }', + ' process.stdout.write(JSON.stringify({', + ' issues: [],', + ' summary: { errored: false, total_files: 1 },', + ' }));', + ' process.exit(0);', + '}', + 'if (args[0] === "export" && args[1] === "html") {', + ' const outPath = args[4];', + ' if (mode === "export_nonzero") {', + ' writeFileSync(outPath, "partial-failure", "utf8");', + ' process.stderr.write("export crashed\\n");', + ' process.exit(2);', + ' }', + ' if (mode === "export_hang") {', + ' writeFileSync(outPath, "partial-timeout", "utf8");', + ' if (pidPath) writeFileSync(pidPath, String(process.pid), "utf8");', + ' setInterval(() => {}, 10_000);', + ' } else {', + ' writeFileSync(outPath, htmlContent, "utf8");', + ' process.exit(0);', + ' }', + '} else {', + ' process.stderr.write("unexpected args: " + JSON.stringify(args));', + ' process.exit(2);', + '}', + ].join('\n'); + + await writeFile(shimPath, `${script}\n`, 'utf8'); + await chmod(shimPath, 0o755); + return shimPath; + } + + test('package.json defines notebook:snapshot pointing to scripts/export-notebook-snapshot.ts', () => { + const pkg = JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')) as { + scripts?: Record; + }; + expect(pkg.scripts?.['notebook:snapshot']).toBe('bun run scripts/export-notebook-snapshot.ts'); + }); + + test('clean check + HTML export succeeds with absolute paths, matching receipt sha256/bytes and zero temp leftovers', async () => { + const notebookDir = join(workDir, 'notebooks'); + const outputDir = join(workDir, 'out'); + await mkdir(notebookDir); + await mkdir(outputDir); + + const notebookPath = join(notebookDir, 'study.py'); + const outputPath = join(outputDir, 'study.html'); + const logPath = join(workDir, 'clean-abs.log.jsonl'); + const expectedHtml = '

Study Snapshot

\n'; + const expectedBytes = Buffer.from(expectedHtml, 'utf8'); + const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex'); + + await writeFile(notebookPath, '# marimo notebook fixture\n', 'utf8'); + const shimPath = await writeFakeMarimoShim('fake-marimo-clean-abs', 'clean', logPath, { + htmlContent: expectedHtml, + }); + + const result = await runCliSubprocess([ + '--notebook', + notebookPath, + '--out', + outputPath, + '--marimo', + shimPath, + '--allowed-notebook-root', + notebookDir, + '--allowed-output-root', + outputDir, + '--timeout-ms', + '10000', + ]); + + expect(result.exitCode).toBe(0); + expect(result.stderr).toBe(''); + + const receipt = JSON.parse(result.stdout.trim()) as NotebookSnapshotReceipt; + expect(receipt.notebookPath).toBe(notebookPath); + expect(receipt.outputPath).toBe(outputPath); + expect(receipt.bytes).toBe(expectedBytes.byteLength); + expect(receipt.sha256).toBe(expectedSha256); + expect(receipt.checkDiagnostics).toEqual({ + issues: [], + summary: { errored: false, total_files: 1 }, + }); + + const diskBytes = await readFile(outputPath); + expect(diskBytes.byteLength).toBe(receipt.bytes); + expect(createHash('sha256').update(diskBytes).digest('hex')).toBe(receipt.sha256); + expect(await readdir(outputDir)).toEqual(['study.html']); + + const invocations = (await readFile(logPath, 'utf8')) + .trim() + .split('\n') + .map(line => JSON.parse(line) as { args: string[] }); + expect(invocations).toHaveLength(2); + expect(invocations[0]?.args).toEqual(['check', '--format=json', notebookPath]); + expect(invocations[1]?.args[0]).toBe('export'); + expect(invocations[1]?.args[1]).toBe('html'); + expect(invocations[1]?.args[2]).toBe(notebookPath); + }); + + test('clean check + HTML export resolves relative paths against cwd and supports --flag=value and MARIMO_COMMAND', async () => { + const notebookDir = join(workDir, 'notebooks'); + const outputDir = join(workDir, 'out'); + await mkdir(notebookDir); + await mkdir(outputDir); + + const notebookPath = join(notebookDir, 'relative.py'); + const outputPath = join(outputDir, 'relative.html'); + const logPath = join(workDir, 'clean-rel.log.jsonl'); + const expectedHtml = 'Relative OK\n'; + const expectedSha256 = createHash('sha256').update(expectedHtml, 'utf8').digest('hex'); + + await writeFile(notebookPath, '# relative fixture\n', 'utf8'); + const shimPath = await writeFakeMarimoShim('fake-marimo-clean-rel', 'clean', logPath, { + htmlContent: expectedHtml, + }); + + const result = await runCliSubprocess( + [ + '--notebook=notebooks/relative.py', + '--out=out/relative.html', + '--allowed-notebook-root=notebooks', + '--allowed-output-root=out', + ], + { + cwd: workDir, + env: { MARIMO_COMMAND: shimPath }, + } + ); + + expect(result.exitCode).toBe(0); + expect(result.stderr).toBe(''); + + const receipt = JSON.parse(result.stdout.trim()) as NotebookSnapshotReceipt; + expect(receipt.notebookPath).toBe(notebookPath); + expect(receipt.outputPath).toBe(outputPath); + expect(receipt.sha256).toBe(expectedSha256); + expect(await readdir(outputDir)).toEqual(['relative.html']); + }); + + test('fails closed on non-zero marimo check exit, preserves pre-existing HTML, and never invokes export', async () => { + const notebookDir = join(workDir, 'notebooks'); + const outputDir = join(workDir, 'out'); + await mkdir(notebookDir); + await mkdir(outputDir); + + const notebookPath = join(notebookDir, 'broken.py'); + const outputPath = join(outputDir, 'existing.html'); + const logPath = join(workDir, 'check-nonzero.log.jsonl'); + const priorHtml = 'Prior Verified Snapshot\n'; + + await writeFile(notebookPath, '# broken\n', 'utf8'); + await writeFile(outputPath, priorHtml, 'utf8'); + const shimPath = await writeFakeMarimoShim('fake-marimo-check-nz', 'check_nonzero', logPath); + + const result = await runCliSubprocess([ + '--notebook', + notebookPath, + '--out', + outputPath, + '--marimo', + shimPath, + ]); + + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(''); + assertSingleLineStderr(result.stderr); + expect(result.stderr).toContain('CHECK_FAILED'); + expect(await readFile(outputPath, 'utf8')).toBe(priorHtml); + expect(await readdir(outputDir)).toEqual(['existing.html']); + + const invocations = (await readFile(logPath, 'utf8')) + .trim() + .split('\n') + .map(line => JSON.parse(line) as { args: string[] }); + expect(invocations).toHaveLength(1); + expect(invocations[0]?.args[0]).toBe('check'); + }); + + test('fails closed on exit 0 with summary.errored=true or severity=breaking, preserving pre-existing HTML', async () => { + const notebookDir = join(workDir, 'notebooks'); + const outputDir = join(workDir, 'out'); + await mkdir(notebookDir); + await mkdir(outputDir); + + const notebookPath = join(notebookDir, 'errored.py'); + const outputPath = join(outputDir, 'preserved.html'); + const priorHtml = 'Preserved\n'; + await writeFile(notebookPath, '# errored\n', 'utf8'); + await writeFile(outputPath, priorHtml, 'utf8'); + + for (const mode of ['check_errored_zero', 'check_breaking_zero'] as const) { + const logPath = join(workDir, `${mode}.log.jsonl`); + const shimPath = await writeFakeMarimoShim(`fake-marimo-${mode}`, mode, logPath); + + const result = await runCliSubprocess([ + '--notebook', + notebookPath, + '--out', + outputPath, + '--marimo', + shimPath, + ]); + + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(''); + assertSingleLineStderr(result.stderr); + expect(result.stderr).toContain('CHECK_FAILED'); + expect(await readFile(outputPath, 'utf8')).toBe(priorHtml); + expect(await readdir(outputDir)).toEqual(['preserved.html']); + + const invocations = (await readFile(logPath, 'utf8')) + .trim() + .split('\n') + .map(line => JSON.parse(line) as { args: string[] }); + expect(invocations).toHaveLength(1); + expect(invocations[0]?.args[0]).toBe('check'); + } + }); + + test('fails closed on export non-zero exit, cleans temp file, and preserves pre-existing HTML', async () => { + const notebookDir = join(workDir, 'notebooks'); + const outputDir = join(workDir, 'out'); + await mkdir(notebookDir); + await mkdir(outputDir); + + const notebookPath = join(notebookDir, 'export-fail.py'); + const outputPath = join(outputDir, 'stable.html'); + const logPath = join(workDir, 'export-nz.log.jsonl'); + const priorHtml = 'Stable Prior\n'; + + await writeFile(notebookPath, '# export fail\n', 'utf8'); + await writeFile(outputPath, priorHtml, 'utf8'); + const shimPath = await writeFakeMarimoShim('fake-marimo-export-nz', 'export_nonzero', logPath); + + const result = await runCliSubprocess([ + '--notebook', + notebookPath, + '--out', + outputPath, + '--marimo', + shimPath, + ]); + + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(''); + assertSingleLineStderr(result.stderr); + expect(result.stderr).toContain('EXPORT_FAILED'); + expect(await readFile(outputPath, 'utf8')).toBe(priorHtml); + expect(await readdir(outputDir)).toEqual(['stable.html']); + }); + + test('fails closed on partial-write export timeout, reaps child process, cleans temp file, and preserves pre-existing HTML', async () => { + const notebookDir = join(workDir, 'notebooks'); + const outputDir = join(workDir, 'out'); + await mkdir(notebookDir); + await mkdir(outputDir); + + const notebookPath = join(notebookDir, 'hang.py'); + const outputPath = join(outputDir, 'stable.html'); + const logPath = join(workDir, 'hang.log.jsonl'); + const pidPath = join(workDir, 'hang.pid'); + const priorHtml = 'Stable Before Timeout\n'; + + await writeFile(notebookPath, '# hang\n', 'utf8'); + await writeFile(outputPath, priorHtml, 'utf8'); + const shimPath = await writeFakeMarimoShim('fake-marimo-hang', 'export_hang', logPath, { + pidPath, + }); + + const result = await runCliSubprocess([ + '--notebook', + notebookPath, + '--out', + outputPath, + '--marimo', + shimPath, + '--timeout-ms', + '600', + ]); + + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(''); + assertSingleLineStderr(result.stderr); + expect(result.stderr).toContain('TIMEOUT'); + expect(await readFile(outputPath, 'utf8')).toBe(priorHtml); + expect(await readdir(outputDir)).toEqual(['stable.html']); + + const pid = Number.parseInt(readFileSync(pidPath, 'utf8').trim(), 10); + expect(Number.isInteger(pid) && pid > 0).toBe(true); + let probeErr: unknown; + try { + process.kill(pid, 0); + } catch (err) { + probeErr = err; + } + expect(getErrorCode(probeErr)).toBe('ESRCH'); + }); + + test('rejects missing, unknown, duplicate flags, positional args, leading-dash values, and root traversal escapes', async () => { + const notebookDir = join(workDir, 'notebooks'); + const outputDir = join(workDir, 'out'); + await mkdir(notebookDir); + await mkdir(outputDir); + + const notebookPath = join(notebookDir, 'study.py'); + const outputPath = join(outputDir, 'study.html'); + const logPath = join(workDir, 'never-called.log.jsonl'); + await writeFile(notebookPath, '# ok\n', 'utf8'); + const shimPath = await writeFakeMarimoShim('fake-marimo-never', 'clean', logPath); + + const invalidInvocations: readonly (readonly string[])[] = [ + // Missing --out + ['--notebook', notebookPath, '--marimo', shimPath], + // Unknown flag + ['--notebook', notebookPath, '--out', outputPath, '--bogus', '1'], + // Duplicate flag + ['--notebook', notebookPath, '--notebook', notebookPath, '--out', outputPath], + // Positional arg + [notebookPath, '--out', outputPath], + // Leading-dash path (option injection) + ['--notebook', '-evil.py', '--out', outputPath, '--marimo', shimPath], + // Invalid timeout + ['--notebook', notebookPath, '--out', outputPath, '--timeout-ms', '0'], + // Traversal escape outside --allowed-notebook-root + [ + '--notebook', + join(notebookDir, '..', 'escape.py'), + '--out', + outputPath, + '--marimo', + shimPath, + '--allowed-notebook-root', + notebookDir, + ], + // Traversal escape outside --allowed-output-root + [ + '--notebook', + notebookPath, + '--out', + join(outputDir, '..', 'escape.html'), + '--marimo', + shimPath, + '--allowed-output-root', + outputDir, + ], + ]; + + for (const argv of invalidInvocations) { + const result = await runCliSubprocess(argv); + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(''); + assertSingleLineStderr(result.stderr); + } + + // Traversal escapes must specifically report INVALID_PATH. + const escapeResult = await runCliSubprocess([ + '--notebook', + join(notebookDir, '..', 'escape.py'), + '--out', + outputPath, + '--marimo', + shimPath, + '--allowed-notebook-root', + notebookDir, + ]); + expect(escapeResult.exitCode).toBe(1); + expect(escapeResult.stderr).toContain('INVALID_PATH'); + + // Help exits 0 with usage on stdout and empty stderr. + const helpResult = await runCliSubprocess(['--help']); + expect(helpResult.exitCode).toBe(0); + expect(helpResult.stderr).toBe(''); + expect(helpResult.stdout).toContain('Usage:'); + }); +}); diff --git a/scripts/test/research-copilot-mcp-e2e.test.ts b/scripts/test/research-copilot-mcp-e2e.test.ts new file mode 100644 index 00000000..db813601 --- /dev/null +++ b/scripts/test/research-copilot-mcp-e2e.test.ts @@ -0,0 +1,1333 @@ +import { createHash } from 'node:crypto'; +import { chmod, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { trialMoments } from '@stock-bot/calculations'; +import type { NotebookSnapshotReceipt } from '@stock-bot/research'; +import { + FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + MCP_PROTOCOL_VERSION, + type PostgresResearchCopilotExecutor, + RESEARCH_COPILOT_TOOL_NAMES, + type StdioInput, + type StdioOutput, +} from '@stock-bot/research/mcp'; +import { createNodeDuckDbExecutor } from '../../libs/data/duckdb/src/index'; +import { openResearchCopilotStore } from '../../libs/data/duckdb/src/research-copilot-store'; +import { runResearchCopilotMcp } from '../research-copilot-mcp'; + +const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url)); +const SNAPSHOT_CLI_PATH = join(REPO_ROOT, 'scripts/export-notebook-snapshot.ts'); + +const DATASET_ID = 'synthetic:mcp-copilot-ec1:seed-20261205:v1'; +const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const VAULT_CUTOFF_ISO = '2024-07-01T00:00:00Z'; +const VAULT_CUTOFF_DATE = '2024-07-01'; +const VAULT_CUTOFF_TS = Date.parse(VAULT_CUTOFF_ISO); +const FIXED_NOW_MS = Date.UTC(2024, 5, 29, 12, 0, 0, 0); +const PRE_CUTOFF_LISTING_IDS = [101, 102, 103, 104, 105, 106, 107, 108] as const; +const VAULT_ONLY_TRIAL_ID = 99; + +interface StoredTrialRow { + readonly trial_id: number; + readonly created_at: string; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: number[]; +} + +interface StoredFindingRow { + readonly id: string; + readonly kind: string; + readonly title: string; + readonly summary: string; + readonly status: string; + readonly created_at: string; + readonly trial_refs: readonly string[]; + readonly evidence_refs: readonly string[]; + readonly idempotency_key: string | null; +} + +interface SecurityMasterListingFixture { + readonly listing_id: number; + readonly instrument_id: number; + readonly ticker: string; + readonly class_suffix: string | null; + readonly name: string; + readonly mic: string; + readonly country_iso: string; + readonly calendar_code: string; + readonly currency: string; + readonly isin: string | null; + readonly first_bar_date: string; + readonly last_bar_date: string; + readonly delisted_at: string | null; +} + +interface InMemoryCopilotDatabase { + readonly executor: PostgresResearchCopilotExecutor; + readonly trials: StoredTrialRow[]; + readonly findings: StoredFindingRow[]; +} + +function sqlString(value: string): string { + return `'${value.replace(/'/g, "''")}'`; +} + +function generateWeekdays(startDate: string, endDate: string): string[] { + const out: string[] = []; + const startMs = Date.parse(`${startDate}T00:00:00Z`); + const endMs = Date.parse(`${endDate}T00:00:00Z`); + for (let ms = startMs; ms <= endMs; ms += 86_400_000) { + const dt = new Date(ms); + const day = dt.getUTCDay(); + if (day !== 0 && day !== 6) { + out.push(dt.toISOString().slice(0, 10)); + } + } + return out; +} + +function createInteractiveStdioHarness(): { + readonly input: StdioInput; + readonly output: StdioOutput; + readonly stderr: { write(chunk: string): boolean; text(): string }; + request(method: string, params?: Record): Promise>; + notify(method: string, params?: Record): void; + callTool( + name: string, + args: Record + ): Promise<{ readonly isError: boolean; readonly text: string; readonly parsed: unknown }>; + closeInput(): void; +} { + const incomingQueue: string[] = []; + let incomingResolver: ((value: IteratorResult) => void) | null = null; + let inputClosed = false; + + const responseQueue: Record[] = []; + const responseWaiters: Array<(msg: Record) => void> = []; + let outputBuffer = ''; + const stderrChunks: string[] = []; + let nextRpcId = 1; + + const pushInputLine = (line: string): void => { + if (incomingResolver !== null) { + const resolve = incomingResolver; + incomingResolver = null; + resolve({ value: line, done: false }); + return; + } + incomingQueue.push(line); + }; + + const input: StdioInput = { + [Symbol.asyncIterator](): AsyncIterator { + return { + next(): Promise> { + if (incomingQueue.length > 0) { + return Promise.resolve({ value: incomingQueue.shift() as string, done: false }); + } + if (inputClosed) { + return Promise.resolve({ value: undefined as unknown as string, done: true }); + } + return new Promise>(resolve => { + incomingResolver = resolve; + }); + }, + }; + }, + }; + + const output: StdioOutput = { + write(chunk: string): boolean { + outputBuffer += chunk; + let newlineIdx = outputBuffer.indexOf('\n'); + while (newlineIdx !== -1) { + const line = outputBuffer.slice(0, newlineIdx); + outputBuffer = outputBuffer.slice(newlineIdx + 1); + if (line.trim().length > 0) { + const parsed = JSON.parse(line) as Record; + const waiter = responseWaiters.shift(); + if (waiter !== undefined) { + waiter(parsed); + } else { + responseQueue.push(parsed); + } + } + newlineIdx = outputBuffer.indexOf('\n'); + } + return true; + }, + }; + + const readNextResponse = (): Promise> => { + if (responseQueue.length > 0) { + return Promise.resolve(responseQueue.shift() as Record); + } + return new Promise>(resolve => { + responseWaiters.push(resolve); + }); + }; + + const request = async ( + method: string, + params: Record = {} + ): Promise> => { + const id = nextRpcId; + nextRpcId += 1; + pushInputLine(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`); + const response = await readNextResponse(); + expect(response.id).toBe(id); + return response; + }; + + const notify = (method: string, params?: Record): void => { + const payload = + params !== undefined + ? { jsonrpc: '2.0', method, params } + : { jsonrpc: '2.0', method }; + pushInputLine(`${JSON.stringify(payload)}\n`); + }; + + const callTool = async ( + name: string, + args: Record + ): Promise<{ readonly isError: boolean; readonly text: string; readonly parsed: unknown }> => { + const resp = await request('tools/call', { name, arguments: args }); + expect(resp.error).toBeUndefined(); + const result = resp.result as { + isError?: boolean; + content: Array<{ type: string; text: string }>; + }; + expect(result.content).toHaveLength(1); + const text = result.content[0]?.text ?? ''; + let parsed: unknown = null; + try { + parsed = JSON.parse(text); + } catch { + parsed = null; + } + return { + isError: result.isError === true, + text, + parsed, + }; + }; + + const closeInput = (): void => { + inputClosed = true; + if (incomingResolver !== null) { + const resolve = incomingResolver; + incomingResolver = null; + resolve({ value: undefined as unknown as string, done: true }); + } + }; + + return { + input, + output, + stderr: { + write(chunk: string): boolean { + stderrChunks.push(chunk); + return true; + }, + text: () => stderrChunks.join(''), + }, + request, + notify, + callTool, + closeInput, + }; +} + +function createInMemoryCopilotDatabase(): InMemoryCopilotDatabase { + const listings: SecurityMasterListingFixture[] = [ + { + listing_id: 101, + instrument_id: 1001, + ticker: 'ACME', + class_suffix: null, + name: 'Acme Holdings Corp', + mic: 'XNYS', + country_iso: 'US', + calendar_code: 'XNYS', + currency: 'USD', + isin: 'US0000001011', + first_bar_date: '2020-01-02', + last_bar_date: '2024-09-15', + delisted_at: '2024-09-15', + }, + ...PRE_CUTOFF_LISTING_IDS.slice(1).map((listingId, idx) => ({ + listing_id: listingId, + instrument_id: 1002 + idx, + ticker: `SYN${idx + 2}`, + class_suffix: null, + name: `Synthetic Equity ${idx + 2} Inc`, + mic: 'XNYS', + country_iso: 'US', + calendar_code: 'XNYS', + currency: 'USD', + isin: `US000000${listingId}1`, + first_bar_date: '2020-01-02', + last_bar_date: '2024-09-15', + delisted_at: null, + })), + { + listing_id: 109, + instrument_id: 1009, + ticker: 'ACME2', + class_suffix: null, + name: 'Acme Post-Cutoff Listing Corp', + mic: 'XNYS', + country_iso: 'US', + calendar_code: 'XNYS', + currency: 'USD', + isin: 'US0000001091', + first_bar_date: '2024-07-02', + last_bar_date: '2024-09-15', + delisted_at: null, + }, + ]; + + // Pre-seed a Vault-only trial (sample_end >= 2024-07-01) in an unrelated cluster + // so file_finding can verify fail-closed rejection without polluting US_EQ / swing_1_10d. + const trials: StoredTrialRow[] = [ + { + trial_id: VAULT_ONLY_TRIAL_ID, + created_at: '2024-07-16T00:00:00.000000Z', + principal_id: AGENT_PRINCIPAL, + campaign_id: null, + stage: 'signal_ic', + universe_market: 'FX', + horizon_bucket: 'position_10d_plus', + hypothesis_id: null, + expression_hash: '0'.repeat(64), + sample_start: '2024-07-01', + sample_end: '2024-07-15', + n_obs: 10, + sharpe_unann: 0.25, + skewness: 0, + kurtosis: 3, + daily_series: [0.01, -0.02, 0.03, 0.01, -0.01, 0.02, 0.01, -0.02, 0.02, 0.01], + }, + ]; + let nextTrialId = 100; + + const findings: StoredFindingRow[] = []; + const providerCaveats = [ + { + id: 'caveat-ceo-shorts-lag', + provider: 'ceo_ca', + dataset: 'shorts', + caveat: 'CIRO semi-monthly short interest is published +4 TSX business days after report_date at 17:00 ET.', + created_at: '2024-01-10T00:00:00.000Z', + }, + ]; + + const executor: PostgresResearchCopilotExecutor = { + async query>( + text: string, + params: readonly unknown[] = [] + ): Promise<{ readonly rows: readonly Row[] }> { + // 1. search_symbols + if (text.includes('listing_symbol_history')) { + const cutoffDate = String(params[0] ?? ''); + const rawQuery = String(params[2] ?? '').toLowerCase(); + const country = params[3] === null || params[3] === undefined ? null : String(params[3]); + const includeDelisted = Boolean(params[4]); + + const matched = listings + .filter(row => { + if (row.first_bar_date > cutoffDate) { + return false; + } + if (country !== null && row.country_iso !== country) { + return false; + } + if (!includeDelisted && row.delisted_at !== null && row.delisted_at <= cutoffDate) { + return false; + } + return ( + row.ticker.toLowerCase().includes(rawQuery) || + row.name.toLowerCase().includes(rawQuery) || + (row.isin !== null && row.isin.toLowerCase() === rawQuery) + ); + }) + .map(row => ({ + listing_id: row.listing_id, + instrument_id: row.instrument_id, + ticker: row.ticker, + class_suffix: row.class_suffix, + name: row.name, + mic: row.mic, + currency: row.currency, + isin: row.isin, + first_bar_date: row.first_bar_date, + last_bar_date: row.last_bar_date, + delisted_at: row.delisted_at, + })); + return { rows: matched as unknown as readonly Row[] }; + } + + // 2. Listing exchange calendar lookup (event_study) + if (text.includes('calendar_code AS calendar_code')) { + const requestedIds = new Set((params[0] as readonly number[]) ?? []); + const matched = listings + .filter(row => requestedIds.has(row.listing_id)) + .map(row => ({ + listing_id: row.listing_id, + calendar_code: row.calendar_code, + })); + return { rows: matched as unknown as readonly Row[] }; + } + + // 3. trial_ledger INSERT + if (text.startsWith('INSERT INTO trial_ledger')) { + const receipts: Array<{ trial_id: string; created_at: string }> = []; + for (let offset = 0; offset < params.length; offset += 14) { + const id = nextTrialId; + nextTrialId += 1; + const createdAt = new Date(FIXED_NOW_MS + id * 1000).toISOString(); + const rawSeries = params[offset + 13] as readonly number[]; + // Round-trip through Float32Array to mirror PostgreSQL `real[]`. + const storedSeries = Array.from(Float32Array.from(rawSeries)); + trials.push({ + trial_id: id, + created_at: createdAt, + principal_id: String(params[offset]), + campaign_id: (params[offset + 1] as string | null) ?? null, + stage: String(params[offset + 2]), + universe_market: String(params[offset + 3]), + horizon_bucket: String(params[offset + 4]), + hypothesis_id: (params[offset + 5] as string | null) ?? null, + expression_hash: String(params[offset + 6]), + sample_start: String(params[offset + 7]), + sample_end: String(params[offset + 8]), + n_obs: Number(params[offset + 9]), + sharpe_unann: Number(params[offset + 10]), + skewness: Number(params[offset + 11]), + kurtosis: Number(params[offset + 12]), + daily_series: storedSeries, + }); + receipts.push({ trial_id: String(id), created_at: createdAt }); + } + return { rows: receipts as unknown as readonly Row[] }; + } + + // 4. trial_ledger visibility lookup (file_finding) + if (text.includes('SELECT 1 AS visible FROM') && text.includes('trial_ledger')) { + const trialRef = String(params[0] ?? ''); + const cutoffDate = String(params[1] ?? ''); + const visible = trials.some( + row => String(row.trial_id) === trialRef && row.sample_end < cutoffDate + ); + return { rows: (visible ? [{ visible: 1 }] : []) as unknown as readonly Row[] }; + } + + // 5. trial_ledger target lookup by trial_id + if (text.includes('FROM trial_ledger') && text.includes('WHERE trial_id = $1::bigint')) { + const targetId = Number(params[0]); + const found = trials.filter(row => row.trial_id === targetId); + return { rows: found as unknown as readonly Row[] }; + } + + // 6. trial_ledger cluster lookup + if ( + text.includes('FROM trial_ledger') && + text.includes('WHERE universe_market = $1') && + text.includes('AND horizon_bucket = $2') + ) { + const market = String(params[0]); + const bucket = String(params[1]); + const asOf = params[2] !== undefined ? String(params[2]) : undefined; + const found = trials + .filter( + row => + row.universe_market === market && + row.horizon_bucket === bucket && + (asOf === undefined || row.created_at <= asOf) + ) + .sort((a, b) => a.trial_id - b.trial_id); + return { rows: found as unknown as readonly Row[] }; + } + + // 7. findings INSERT + if (text.includes('INSERT INTO') && text.includes('findings')) { + const id = String(params[0]); + const kind = String(params[1]); + const title = String(params[2]); + const summary = String(params[3]); + const status = String(params[4]); + const createdAt = String(params[5]); + const trialRefs = [...(params[6] as readonly string[])]; + const evidenceRefs = [...(params[7] as readonly string[])]; + const idempotencyKey = + params[8] === null || params[8] === undefined ? null : String(params[8]); + + if ( + idempotencyKey !== null && + findings.some(row => row.idempotency_key === idempotencyKey) + ) { + return { rows: [] }; + } + + findings.push({ + id, + kind, + title, + summary, + status, + created_at: createdAt, + trial_refs: trialRefs, + evidence_refs: evidenceRefs, + idempotency_key: idempotencyKey, + }); + return { rows: [{ id, created_at: createdAt }] as unknown as readonly Row[] }; + } + + // 8. findings SELECT by idempotency_key + if (text.includes('findings') && text.includes('WHERE idempotency_key = $1::text')) { + const key = String(params[0]); + const found = findings.filter(row => row.idempotency_key === key); + return { rows: found as unknown as readonly Row[] }; + } + + // 9. findings SELECT (read_knowledge) + if (text.includes('findings') && text.includes('FROM')) { + const sorted = [...findings].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); + return { rows: sorted as unknown as readonly Row[] }; + } + + // 10. provider_caveats SELECT (read_knowledge) + if (text.includes('provider_caveats')) { + return { rows: providerCaveats as unknown as readonly Row[] }; + } + + throw new Error(`Unhandled SQL in in-memory copilot executor: ${text}`); + }, + }; + + return { executor, trials, findings }; +} + +async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{ + readonly preCutoffSessions: readonly string[]; + readonly restatedQ1TtmNetIncome: number; +}> { + const barsDir = join(curatedRoot, 'bars_1d', 'year=2024'); + const fundDir = join(curatedRoot, 'fundamentals_pit', 'year=2024'); + const shortsDir = join(curatedRoot, 'shorts'); + const eventsDir = join(curatedRoot, 'events', 'year=2024'); + await Promise.all([ + mkdir(barsDir, { recursive: true }), + mkdir(fundDir, { recursive: true }), + mkdir(shortsDir, { recursive: true }), + mkdir(eventsDir, { recursive: true }), + ]); + + const preCutoffSessions = generateWeekdays('2024-04-01', '2024-06-28'); + const postCutoffSessions = ['2024-07-01', '2024-07-02', '2024-07-03']; + + const builder = await createNodeDuckDbExecutor(); + try { + // 1. bars_1d/year=2024/part.parquet + await builder.run(` + CREATE TABLE bars_1d ( + listing_id INTEGER, + ts TIMESTAMPTZ, + session_date DATE, + open DOUBLE, + high DOUBLE, + low DOUBLE, + close DOUBLE, + volume DOUBLE, + vwap DOUBLE, + currency VARCHAR, + source VARCHAR, + known_at TIMESTAMPTZ + ); + `); + + const barValues: string[] = []; + for (let i = 0; i < PRE_CUTOFF_LISTING_IDS.length; i += 1) { + const listingId = PRE_CUTOFF_LISTING_IDS[i] as number; + let price = 50 + i * 5; + for (let d = 0; d < preCutoffSessions.length; d += 1) { + const sessionDate = preCutoffSessions[d] as string; + const dailyRet = + 0.0015 * (i - 3.5) * Math.sin(0.27 * d + 0.5) + + 0.008 * Math.cos(0.41 * d + 0.9 * i) + + 0.0007 * (i - 3.5); + price = Math.max(5, price * (1 + dailyRet)); + const open = Number((price * 0.998).toFixed(6)); + const high = Number((price * 1.005).toFixed(6)); + const low = Number((price * 0.995).toFixed(6)); + const close = Number(price.toFixed(6)); + const volume = 100_000 + i * 5_000 + d * 100; + const tsIso = `${sessionDate}T20:00:00Z`; + barValues.push( + `(${listingId}, TIMESTAMPTZ ${sqlString(tsIso)}, DATE ${sqlString(sessionDate)}, ${open}, ${high}, ${low}, ${close}, ${volume}, ${close}, 'USD', 'eod_prices', TIMESTAMPTZ ${sqlString(tsIso)})` + ); + } + + // Post-cutoff Vault sentinel bars at close = 9999.0. + for (const sessionDate of postCutoffSessions) { + const tsIso = `${sessionDate}T20:00:00Z`; + barValues.push( + `(${listingId}, TIMESTAMPTZ ${sqlString(tsIso)}, DATE ${sqlString(sessionDate)}, 9999.0, 9999.0, 9999.0, 9999.0, 500000.0, 9999.0, 'USD', 'eod_prices', TIMESTAMPTZ ${sqlString(tsIso)})` + ); + } + } + await builder.run(`INSERT INTO bars_1d VALUES ${barValues.join(', ')};`); + await builder.run( + `COPY (SELECT * FROM bars_1d ORDER BY listing_id ASC, session_date ASC) TO ${sqlString(join(barsDir, 'part.parquet'))} (FORMAT PARQUET);` + ); + + // 2. fundamentals_pit/year=2024/part.parquet + await builder.run(` + CREATE TABLE fundamentals_pit ( + listing_id INTEGER, + effective_known_at TIMESTAMPTZ, + known_at_source VARCHAR, + has_estimated_lag BOOLEAN, + period_end DATE, + fiscal_period VARCHAR, + currency VARCHAR, + period_known_at TIMESTAMPTZ, + revenue DOUBLE, + net_income DOUBLE, + operating_cash_flow DOUBLE, + total_assets DOUBLE, + total_equity DOUBLE, + shares_outstanding DOUBLE, + ttm_revenue DOUBLE, + ttm_net_income DOUBLE, + ttm_operating_cash_flow DOUBLE, + ttm_period_end DATE, + ttm_currency VARCHAR, + ttm_has_estimated_lag BOOLEAN + ); + `); + + const fundValues: string[] = []; + const restatedQ1TtmNetIncome = 42_500_000.0; + // Verified Q1 + Q2 snapshots for listings 101..107 (7 listings >= DEFAULT_MIN_CROSS_SECTION = 5). + for (let i = 0; i < 7; i += 1) { + const listingId = PRE_CUTOFF_LISTING_IDS[i] as number; + const q1Ttm = 10_000_000 * (i + 1); + const q2Ttm = 12_000_000 * (i + 1) + (i % 2 === 0 ? 1_500_000 : -500_000); + fundValues.push( + `(${listingId}, TIMESTAMPTZ '2024-03-20T20:00:00Z', 'filing_timestamp', FALSE, DATE '2024-03-31', 'Q1', 'USD', TIMESTAMPTZ '2024-03-20T20:00:00Z', ${q1Ttm * 2}, ${q1Ttm / 4}, ${q1Ttm / 3}, 100000000.0, 50000000.0, 10000000.0, ${q1Ttm * 4}, ${q1Ttm}, ${q1Ttm * 1.1}, DATE '2024-03-31', 'USD', FALSE)` + ); + fundValues.push( + `(${listingId}, TIMESTAMPTZ '2024-05-10T20:00:00Z', 'filing_timestamp', FALSE, DATE '2024-04-30', 'Q2', 'USD', TIMESTAMPTZ '2024-05-10T20:00:00Z', ${q2Ttm * 2}, ${q2Ttm / 4}, ${q2Ttm / 3}, 105000000.0, 52000000.0, 10000000.0, ${q2Ttm * 4}, ${q2Ttm}, ${q2Ttm * 1.1}, DATE '2024-04-30', 'USD', FALSE)` + ); + } + // Restated Q1 for listing 101 with effective_known_at > Q2 that updates ttm_net_income + // while preserving Q2's period_end ('2024-04-30'). + fundValues.push( + `(101, TIMESTAMPTZ '2024-05-20T20:00:00Z', 'filing_timestamp', FALSE, DATE '2024-04-30', 'Q2', 'USD', TIMESTAMPTZ '2024-05-10T20:00:00Z', 85000000.0, 10625000.0, 14000000.0, 105000000.0, 52000000.0, 10000000.0, 170000000.0, ${restatedQ1TtmNetIncome}, 46000000.0, DATE '2024-04-30', 'USD', FALSE)` + ); + // Estimated-lag snapshot for listing 108 (excluded when allowEstimatedLag: false). + fundValues.push( + `(108, TIMESTAMPTZ '2024-03-25T20:00:00Z', 'statutory_lag_estimate', TRUE, DATE '2024-03-31', 'Q1', 'USD', TIMESTAMPTZ '2024-03-25T20:00:00Z', 20000000.0, 5000000.0, 6000000.0, 90000000.0, 45000000.0, 10000000.0, 80000000.0, 20000000.0, 22000000.0, DATE '2024-03-31', 'USD', TRUE)` + ); + // Post-cutoff Vault snapshot for listing 101 (must be excluded by Vault fence). + fundValues.push( + `(101, TIMESTAMPTZ '2024-07-02T20:00:00Z', 'filing_timestamp', FALSE, DATE '2024-06-30', 'Q3', 'USD', TIMESTAMPTZ '2024-07-02T20:00:00Z', 999999999.0, 999999999.0, 999999999.0, 999999999.0, 999999999.0, 10000000.0, 999999999.0, 999999999.0, 999999999.0, DATE '2024-06-30', 'USD', FALSE)` + ); + await builder.run(`INSERT INTO fundamentals_pit VALUES ${fundValues.join(', ')};`); + await builder.run( + `COPY (SELECT * FROM fundamentals_pit ORDER BY listing_id ASC, effective_known_at ASC) TO ${sqlString(join(fundDir, 'part.parquet'))} (FORMAT PARQUET);` + ); + + // 3. shorts/part.parquet (+4 TSX business-day known_at + post-cutoff row) + await builder.run(` + CREATE TABLE shorts ( + listing_id INTEGER, + report_date DATE, + known_at TIMESTAMPTZ, + shares_short DOUBLE, + net_change DOUBLE, + pct_float DOUBLE, + source VARCHAR + ); + `); + + const shortSchedule: ReadonlyArray = [ + ['2024-04-15', '2024-04-19T21:00:00Z'], + ['2024-04-30', '2024-05-06T21:00:00Z'], + ['2024-05-15', '2024-05-22T21:00:00Z'], + ['2024-05-31', '2024-06-06T21:00:00Z'], + ['2024-06-15', '2024-06-21T21:00:00Z'], + // Post-cutoff known_at (excluded by Vault fence) + ['2024-06-30', '2024-07-05T21:00:00Z'], + ]; + const shortValues: string[] = []; + for (let i = 0; i < PRE_CUTOFF_LISTING_IDS.length; i += 1) { + const listingId = PRE_CUTOFF_LISTING_IDS[i] as number; + for (let s = 0; s < shortSchedule.length; s += 1) { + const [reportDate, knownAtIso] = shortSchedule[s] as readonly [string, string]; + const pctFloat = Number((0.02 + 0.015 * ((i + s) % 8) + 0.002 * i).toFixed(6)); + const sharesShort = Math.round(pctFloat * 10_000_000); + const netChange = (s % 2 === 0 ? 1 : -1) * (10_000 + i * 2_500); + shortValues.push( + `(${listingId}, DATE ${sqlString(reportDate)}, TIMESTAMPTZ ${sqlString(knownAtIso)}, ${sharesShort}, ${netChange}, ${pctFloat}, 'ceo_shorts')` + ); + } + } + await builder.run(`INSERT INTO shorts VALUES ${shortValues.join(', ')};`); + await builder.run( + `COPY (SELECT * FROM shorts ORDER BY listing_id ASC, report_date ASC) TO ${sqlString(join(shortsDir, 'part.parquet'))} (FORMAT PARQUET);` + ); + + // 4. events/year=2024/part.parquet (filing + earnings + ceo_post newswire/retail + post-cutoff) + await builder.run(` + CREATE TABLE events ( + listing_id INTEGER, + ts TIMESTAMPTZ, + known_at TIMESTAMPTZ, + known_at_source VARCHAR, + kind VARCHAR, + subtype VARCHAR, + payload_json VARCHAR + ); + `); + + const eventRows: Array<{ + readonly listingId: number; + readonly ts: string; + readonly knownAt: string; + readonly knownAtSource: string; + readonly kind: string; + readonly subtype: string; + readonly payload: string; + }> = [ + // Filings & earnings + { + listingId: 101, + ts: '2024-04-12T15:00:00Z', + knownAt: '2024-04-12T15:00:00Z', + knownAtSource: 'filing_timestamp', + kind: 'filing', + subtype: '8-k', + payload: '{"form_type":"8-K"}', + }, + { + listingId: 102, + ts: '2024-05-01T20:05:00Z', + knownAt: '2024-05-01T20:05:00Z', + knownAtSource: 'statutory_lag_estimate', + kind: 'earnings', + subtype: 'amc', + payload: '{"eps":1.25}', + }, + // 8 pre-cutoff ceo_post newswire events across 4 distinct trading dates + // (including known_at > ts post_edited on listing 101) + { + listingId: 101, + ts: '2024-04-18T14:00:00Z', + knownAt: '2024-04-18T15:30:00Z', + knownAtSource: 'post_edited', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-101","is_edited":true}', + }, + { + listingId: 102, + ts: '2024-04-18T14:15:00Z', + knownAt: '2024-04-18T14:15:00Z', + knownAtSource: 'post_timestamp', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-102","is_edited":false}', + }, + { + listingId: 103, + ts: '2024-05-02T14:00:00Z', + knownAt: '2024-05-02T14:00:00Z', + knownAtSource: 'post_timestamp', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-103","is_edited":false}', + }, + { + listingId: 104, + ts: '2024-05-02T14:30:00Z', + knownAt: '2024-05-02T14:30:00Z', + knownAtSource: 'post_timestamp', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-104","is_edited":false}', + }, + { + listingId: 105, + ts: '2024-05-16T14:00:00Z', + knownAt: '2024-05-16T14:00:00Z', + knownAtSource: 'post_timestamp', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-105","is_edited":false}', + }, + { + listingId: 106, + ts: '2024-05-16T14:30:00Z', + knownAt: '2024-05-16T14:30:00Z', + knownAtSource: 'post_timestamp', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-106","is_edited":false}', + }, + { + listingId: 107, + ts: '2024-06-04T14:00:00Z', + knownAt: '2024-06-04T14:00:00Z', + knownAtSource: 'post_timestamp', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-107","is_edited":false}', + }, + { + listingId: 108, + ts: '2024-06-04T14:30:00Z', + knownAt: '2024-06-04T14:30:00Z', + knownAtSource: 'post_timestamp', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-108","is_edited":false}', + }, + // Pre-cutoff retail posts (must be excluded by subtypes: ['newswire']) + { + listingId: 101, + ts: '2024-04-22T15:00:00Z', + knownAt: '2024-04-22T15:00:00Z', + knownAtSource: 'post_timestamp', + kind: 'ceo_post', + subtype: 'retail', + payload: '{"spiel_id":"rt-101","is_edited":false}', + }, + // Post-cutoff Vault ceo_post (must be excluded by Vault fence) + { + listingId: 101, + ts: '2024-07-02T14:00:00Z', + knownAt: '2024-07-02T14:00:00Z', + knownAtSource: 'post_timestamp', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-vault-101","is_edited":false}', + }, + ]; + + const eventValues = eventRows.map( + row => + `(${row.listingId}, TIMESTAMPTZ ${sqlString(row.ts)}, TIMESTAMPTZ ${sqlString(row.knownAt)}, ${sqlString(row.knownAtSource)}, ${sqlString(row.kind)}, ${sqlString(row.subtype)}, ${sqlString(row.payload)})` + ); + await builder.run(`INSERT INTO events VALUES ${eventValues.join(', ')};`); + await builder.run( + `COPY (SELECT * FROM events ORDER BY listing_id ASC, ts ASC, kind ASC, subtype ASC, payload_json ASC, known_at ASC, known_at_source ASC) TO ${sqlString(join(eventsDir, 'part.parquet'))} (FORMAT PARQUET);` + ); + + return { preCutoffSessions, restatedQ1TtmNetIncome }; + } finally { + await builder.close(); + } +} + +async function writeLibraryFixture(libraryRoot: string): Promise { + const methodologyDir = join(libraryRoot, 'cards', 'methodology'); + await mkdir(methodologyDir, { recursive: true }); + await writeFile( + join(libraryRoot, 'library.yml'), + ['id: research_lib', 'sections:', ' methodology: Methodology Cards', ''].join('\n'), + 'utf8' + ); + await writeFile( + join(methodologyDir, 'pit-event-studies.md'), + [ + '---', + 'title: Point-in-Time Event Studies', + 'summary: Anchor events on known_at and fence all windows strictly before Vault cutoff.', + 'matches: ["pit", "event-study", "vault"]', + '---', + 'Always align filings and ceo_post text events on known_at rather than event timestamp.', + '', + ].join('\n'), + 'utf8' + ); +} + +async function writeCleanFakeMarimoShim(workDir: string, htmlContent: string): Promise { + const shimPath = join(workDir, 'fake-marimo-e2e'); + const script = [ + '#!/usr/bin/env bun', + "import { writeFileSync } from 'node:fs';", + 'const args = process.argv.slice(2);', + `const htmlContent = ${JSON.stringify(htmlContent)};`, + 'if (args[0] === "check") {', + ' process.stdout.write(JSON.stringify({ issues: [], summary: { errored: false, total_files: 1 } }));', + ' process.exit(0);', + '}', + 'if (args[0] === "export" && args[1] === "html") {', + ' writeFileSync(args[4], htmlContent, "utf8");', + ' process.exit(0);', + '}', + 'process.stderr.write("unexpected args: " + JSON.stringify(args));', + 'process.exit(2);', + ].join('\n'); + await writeFile(shimPath, `${script}\n`, 'utf8'); + await chmod(shimPath, 0o755); + return shimPath; +} + +async function runSnapshotSubprocess( + notebookPath: string, + outputPath: string, + marimoShimPath: string +): Promise { + const proc = Bun.spawn( + [ + process.execPath, + 'run', + SNAPSHOT_CLI_PATH, + '--notebook', + notebookPath, + '--out', + outputPath, + '--marimo', + marimoShimPath, + ], + { + cwd: REPO_ROOT, + stdin: 'ignore', + stdout: 'pipe', + stderr: 'pipe', + } + ); + const [exitCode, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]); + expect(exitCode).toBe(0); + expect(stderr).toBe(''); + return JSON.parse(stdout.trim()) as NotebookSnapshotReceipt; +} + +interface E2eRunSummary { + readonly fundExpressionHash: string; + readonly fundRankIcMean: number | null; + readonly shortsExpressionHash: string; + readonly shortsRankIcMean: number | null; + readonly eventExpressionHash: string; + readonly eventCarMean: number | null; + readonly snapshotSha256: string; +} + +describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () => { + let workDir = ''; + + beforeEach(async () => { + const rawDir = await mkdtemp(join(tmpdir(), 'research-copilot-mcp-e2e-')); + workDir = await realpath(rawDir); + }); + + afterEach(async () => { + if (workDir) { + await rm(workDir, { recursive: true, force: true }); + workDir = ''; + } + }); + + test('executes full Vault-fenced study + notebook snapshot + finding + knowledge pipeline with deterministic replay', async () => { + const curatedRoot = join(workDir, 'curated'); + const libraryRoot = join(workDir, 'library'); + const duckdbTmpDir = join(workDir, 'duckdb-tmp'); + const notebookDir = join(workDir, 'notebooks'); + const snapshotDir = join(workDir, 'snapshots'); + await Promise.all([ + mkdir(curatedRoot, { recursive: true }), + mkdir(libraryRoot, { recursive: true }), + mkdir(duckdbTmpDir, { recursive: true }), + mkdir(notebookDir, { recursive: true }), + mkdir(snapshotDir, { recursive: true }), + ]); + + const { restatedQ1TtmNetIncome } = await writeCuratedParquetFixtures(curatedRoot); + await writeLibraryFixture(libraryRoot); + + const notebookPath = join(notebookDir, 'ec1-study.py'); + const snapshotHtml = `

${DATASET_ID}

\n`; + await writeFile(notebookPath, '# synthetic EC1 marimo notebook fixture\n', 'utf8'); + const marimoShimPath = await writeCleanFakeMarimoShim(workDir, snapshotHtml); + + const buildEnv = (): Record => ({ + PATH: process.env.PATH, + NODE_ENV: 'test', + RESEARCH_MCP_POSTGRES_URL: + 'postgresql://research_ro:hermetic@127.0.0.1:5433/trading_bot_dev?sslmode=disable', + RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro', + RESEARCH_MCP_CURATED_ROOT: curatedRoot, + RESEARCH_MCP_VAULT_CUTOFF_TS: VAULT_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: libraryRoot, + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), + STOCKBOT_DUCKDB_TEMP_DIRECTORY: duckdbTmpDir, + STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', + STOCKBOT_DUCKDB_THREADS: '2', + }); + + // Verify PIT fundamentals semantics directly via openResearchCopilotStore: + // restated Q1 (effective_known_at 2024-05-20 > Q2 2024-05-10) updates ttm_net_income + // without overwriting Q2 period_end ('2024-04-30'), and estimated-lag listing 108 is excluded. + const pitCheckStore = await openResearchCopilotStore( + { + postgresUrl: 'postgresql://research_ro:hermetic@127.0.0.1:5433/trading_bot_dev', + curatedRoot, + vaultCutoffTs: VAULT_CUTOFF_TS, + principalId: AGENT_PRINCIPAL, + libraryRoot, + referenceListingIds: { XNYS: [101] }, + }, + { env: buildEnv() } + ); + try { + const pitTable = await pitCheckStore.store.fundamentalsAsOf({ + listingIds: [101, 108], + fields: ['ttm_net_income'], + asOf: '2024-05-25', + allowEstimatedLag: false, + }); + expect(pitTable.rows).toHaveLength(1); + expect(pitTable.rows[0]?.listing_id).toBe(101); + expect(pitTable.rows[0]?.period_end).toBe('2024-04-30'); + expect(pitTable.rows[0]?.ttm_net_income).toBe(restatedQ1TtmNetIncome); + } finally { + await pitCheckStore.close(); + } + + const executeFullPipeline = async (runTag: string): Promise => { + const db = createInMemoryCopilotDatabase(); + const stdio = createInteractiveStdioHarness(); + let executorClosed = false; + let idSeq = 0; + + const serverPromise = runResearchCopilotMcp({ + env: buildEnv(), + input: stdio.input, + output: stdio.output, + stderr: stdio.stderr, + openExecutor: () => ({ + executor: db.executor, + close: () => { + executorClosed = true; + }, + }), + newId: () => { + idSeq += 1; + return `00000000-0000-4000-8000-${String(idSeq).padStart(12, '0')}`; + }, + now: () => FIXED_NOW_MS, + }); + + // 1. initialize + notifications/initialized + tools/list + const initResp = await stdio.request('initialize', { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: 'ec1-e2e-client', version: '1.0.0' }, + }); + expect(initResp.error).toBeUndefined(); + stdio.notify('notifications/initialized'); + + const listResp = await stdio.request('tools/list', {}); + const listedTools = (listResp.result as { tools: Array<{ name: string }> }).tools.map( + t => t.name + ); + expect(listedTools).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + + // 2. search_symbols: post-cutoff delistedAt masked, lastBarDate clamped, post-cutoff listing 109 excluded + const searchRes = await stdio.callTool('search_symbols', { + query: 'ACME', + country: 'US', + includeDelisted: true, + }); + expect(searchRes.isError).toBe(false); + const searchPayload = searchRes.parsed as { + scope: string; + rowCount: number; + rows: Array<{ + listingId: number; + ticker: string; + lastBarDate: string | null; + delistedAt: string | null; + }>; + }; + expect(searchPayload.scope).toBe('vault_fenced'); + expect(searchPayload.rowCount).toBe(1); + expect(searchPayload.rows[0]?.listingId).toBe(101); + expect(searchPayload.rows[0]?.delistedAt).toBeNull(); + expect(searchPayload.rows[0]?.lastBarDate).toBe('2024-06-30'); + + // 3. query_data: straddling `to` clamped, 9999.0 Vault sentinel bars excluded + const queryStraddle = await stdio.callTool('query_data', { + listingIds: [101], + from: '2024-06-20', + to: '2024-07-10', + timeframe: '1d', + adjustment: 'raw', + }); + expect(queryStraddle.isError).toBe(false); + const queryPayload = queryStraddle.parsed as { + clampedTo: boolean; + rowCount: number; + rows: Array<{ close: number; ts: number }>; + }; + expect(queryPayload.clampedTo).toBe(true); + expect(queryPayload.rowCount).toBeGreaterThan(0); + expect(queryPayload.rows.every(r => r.close !== 9999.0 && r.ts < VAULT_CUTOFF_TS)).toBe(true); + + // query_data: from >= Vault cutoff rejected with VaultHoldoutFenceError + const queryVaultRejected = await stdio.callTool('query_data', { + listingIds: [101], + from: VAULT_CUTOFF_DATE, + to: '2024-07-10', + timeframe: '1d', + adjustment: 'raw', + }); + expect(queryVaultRejected.isError).toBe(true); + expect(queryVaultRejected.text).toContain('VaultHoldoutFenceError'); + + // 4. analyze_signal #1: PIT fundamentals (ttm_net_income, allowEstimatedLag: false) + const fundRes = await stdio.callTool('analyze_signal', { + listingIds: [...PRE_CUTOFF_LISTING_IDS], + from: '2024-04-01', + to: '2024-07-10', + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + signal: { + source: 'fundamentals', + field: 'ttm_net_income', + allowEstimatedLag: false, + }, + }); + expect(fundRes.isError).toBe(false); + const fundPayload = fundRes.parsed as { + status: string; + clampedTo: boolean; + analysis: { rankIc: { mean: number | null } }; + trial: { trialId: number; expressionHash: string; sampleEnd: string }; + deflatedSharpe: { clusterSize: number; dsr: number | null }; + }; + expect(fundPayload.status).toBe('ok'); + expect(fundPayload.clampedTo).toBe(true); + expect(fundPayload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); + expect(fundPayload.deflatedSharpe.clusterSize).toBe(1); + + // 5. analyze_signal #2: shorts alt-data (pct_float) in same relatedness cluster + const shortsRes = await stdio.callTool('analyze_signal', { + listingIds: [...PRE_CUTOFF_LISTING_IDS], + from: '2024-04-01', + to: '2024-07-10', + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + signal: { + source: 'shorts', + field: 'pct_float', + }, + }); + expect(shortsRes.isError).toBe(false); + const shortsPayload = shortsRes.parsed as { + status: string; + clampedTo: boolean; + analysis: { rankIc: { mean: number | null } }; + trial: { trialId: number; expressionHash: string; sampleEnd: string }; + deflatedSharpe: { clusterSize: number; dsr: number | null }; + }; + expect(shortsPayload.status).toBe('ok'); + expect(shortsPayload.clampedTo).toBe(true); + expect(shortsPayload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); + expect(shortsPayload.deflatedSharpe.clusterSize).toBe(2); + expect( + shortsPayload.deflatedSharpe.dsr !== null && + Number.isFinite(shortsPayload.deflatedSharpe.dsr) + ).toBe(true); + + // 6. event_study #3: ceo_post (subtype: newswire) + const eventRes = await stdio.callTool('event_study', { + listingIds: [...PRE_CUTOFF_LISTING_IDS], + from: '2024-04-01', + to: '2024-07-10', + event: { + kinds: ['ceo_post'], + subtypes: ['newswire'], + }, + preDays: 2, + postDays: 3, + benchmark: 'equal_weight', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(eventRes.isError).toBe(false); + const eventPayload = eventRes.parsed as { + status: string; + clampedTo: boolean; + eventCount: number; + study: { clustered: { carMean: number } | null; diagnostics: { usedEvents: number } }; + trial: { trialId: number; expressionHash: string; sampleEnd: string }; + deflatedSharpe: { clusterSize: number; dsr: number | null }; + }; + expect(eventPayload.status).toBe('ok'); + expect(eventPayload.clampedTo).toBe(true); + // Only the 8 pre-cutoff newswire ceo_post events are included (retail + Vault rows excluded). + expect(eventPayload.eventCount).toBe(8); + expect(eventPayload.study.diagnostics.usedEvents).toBe(8); + expect(eventPayload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); + expect(eventPayload.deflatedSharpe.clusterSize).toBe(3); + + // Verify every recorded research trial_ledger row satisfies Vault cutoff and trialMoments parity. + const recordedResearchTrials = db.trials.filter(t => t.trial_id !== VAULT_ONLY_TRIAL_ID); + expect(recordedResearchTrials).toHaveLength(3); + for (const row of recordedResearchTrials) { + expect(row.sample_end < VAULT_CUTOFF_DATE).toBe(true); + const expectedMoments = trialMoments(row.daily_series); + expect(expectedMoments).not.toBeNull(); + expect(row.n_obs).toBe(expectedMoments?.nObs); + expect(row.sharpe_unann).toBeCloseTo(expectedMoments?.sharpeUnann ?? Number.NaN, 4); + expect(row.skewness).toBeCloseTo(expectedMoments?.skewness ?? Number.NaN, 4); + expect(row.kurtosis).toBeCloseTo(expectedMoments?.kurtosis ?? Number.NaN, 4); + } + + // 7. Real subprocess invocation of scripts/export-notebook-snapshot.ts + const snapshotOutPath = join(snapshotDir, `ec1-${runTag}.html`); + const receipt = await runSnapshotSubprocess(notebookPath, snapshotOutPath, marimoShimPath); + const diskBytes = await readFile(snapshotOutPath); + expect(receipt.bytes).toBe(diskBytes.byteLength); + expect(receipt.sha256).toBe(createHash('sha256').update(diskBytes).digest('hex')); + + // 8. file_finding: Vault-only trial ref fails closed with zero findings inserts + const vaultRefAttempt = await stdio.callTool('file_finding', { + kind: 'finding', + title: 'Should Fail On Vault Trial Ref', + summary: 'Must fail closed when referencing a Vault-only trial.', + trialRefs: [String(VAULT_ONLY_TRIAL_ID)], + evidenceRefs: [DATASET_ID], + }); + expect(vaultRefAttempt.isError).toBe(true); + expect(vaultRefAttempt.text).toContain(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(db.findings).toHaveLength(0); + + // 9. file_finding: valid filing with 3 research-visible trialRefs + snapshot sha256 + idempotency + const researchTrialRefs = [ + String(fundPayload.trial.trialId), + String(shortsPayload.trial.trialId), + String(eventPayload.trial.trialId), + ]; + const findingArgs = { + kind: 'finding', + title: 'EC1 PIT Fundamentals, Shorts, and Newswire Event Study', + summary: + 'Synthetic EC1 study combining PIT fundamentals, +4d shorts, and ceo_post newswire events under zero modeled costs.', + trialRefs: researchTrialRefs, + evidenceRefs: [DATASET_ID, `sha256:${receipt.sha256}`], + idempotencyKey: 'ec1-study-finding-v1', + }; + + const filedFirst = await stdio.callTool('file_finding', findingArgs); + expect(filedFirst.isError).toBe(false); + const filedFirstPayload = filedFirst.parsed as { + id: string; + createdAt: string; + created: boolean; + }; + expect(filedFirstPayload.created).toBe(true); + expect(db.findings).toHaveLength(1); + + // Identical replay with same idempotencyKey -> created: false, identical id/createdAt + const filedReplay = await stdio.callTool('file_finding', findingArgs); + expect(filedReplay.isError).toBe(false); + const filedReplayPayload = filedReplay.parsed as { + id: string; + createdAt: string; + created: boolean; + }; + expect(filedReplayPayload.created).toBe(false); + expect(filedReplayPayload.id).toBe(filedFirstPayload.id); + expect(filedReplayPayload.createdAt).toBe(filedFirstPayload.createdAt); + expect(db.findings).toHaveLength(1); + + // Mutated payload with same idempotencyKey -> conflict error + const filedConflict = await stdio.callTool('file_finding', { + ...findingArgs, + summary: 'Mutated summary for conflict check.', + }); + expect(filedConflict.isError).toBe(true); + expect(filedConflict.text).toContain(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); + expect(db.findings).toHaveLength(1); + + // 10. read_knowledge (source: 'all') returns pending_review finding, library card, and provider_caveats + const knowledgeRes = await stdio.callTool('read_knowledge', { + source: 'all', + }); + expect(knowledgeRes.isError).toBe(false); + const knowledgePayload = knowledgeRes.parsed as { + rows: Array<{ source: string; id: string; status?: string }>; + sources: { library: number; findings: number; provider_caveats: number }; + }; + expect(knowledgePayload.sources.library).toBe(1); + expect(knowledgePayload.sources.findings).toBe(1); + expect(knowledgePayload.sources.provider_caveats).toBe(1); + + const findingRow = knowledgePayload.rows.find(r => r.source === 'findings'); + expect(findingRow?.id).toBe(filedFirstPayload.id); + expect(findingRow?.status).toBe('pending_review'); + expect( + knowledgePayload.rows.some( + r => r.source === 'library' && r.id === 'research_lib:methodology/pit-event-studies' + ) + ).toBe(true); + expect( + knowledgePayload.rows.some( + r => r.source === 'provider_caveats' && r.id === 'caveat-ceo-shorts-lag' + ) + ).toBe(true); + + // 11. Clean EOF shutdown + stdio.closeInput(); + const exitCode = await serverPromise; + expect(exitCode).toBe(0); + expect(stdio.stderr.text()).toBe(''); + expect(executorClosed).toBe(true); + + return { + fundExpressionHash: fundPayload.trial.expressionHash, + fundRankIcMean: fundPayload.analysis.rankIc.mean, + shortsExpressionHash: shortsPayload.trial.expressionHash, + shortsRankIcMean: shortsPayload.analysis.rankIc.mean, + eventExpressionHash: eventPayload.trial.expressionHash, + eventCarMean: eventPayload.study.clustered?.carMean ?? null, + snapshotSha256: receipt.sha256, + }; + }; + + const run1 = await executeFullPipeline('run1'); + const run2 = await executeFullPipeline('run2'); + + // Deterministic replay parity across runs + expect(run2).toEqual(run1); + }); +}); diff --git a/studio.config.json b/studio.config.json index ccc87b53..95ba0cc9 100644 --- a/studio.config.json +++ b/studio.config.json @@ -43,15 +43,15 @@ "docs": { "pitch": "design/pitch.md", "pillars": "design/pillars.md", - "brand": "docs/marketing/brand.md", + "brand": "design/marketing/brand.md", "agents": "AGENTS.md", - "index": "docs/README.md", - "plan": "docs/PLATFORM-PLAN.md", - "milestones": "docs/MILESTONES.md", - "dataContracts": "docs/DATA-CONTRACTS.md", - "validation": "docs/VALIDATION-AND-RIGOR.md", - "dataPipeline": "docs/data-pipeline/phase1-investigation.md", - "servers": "docs/servers.md" + "index": "design/README.md", + "plan": "design/PLATFORM-PLAN.md", + "milestones": "design/MILESTONES.md", + "dataContracts": "design/DATA-CONTRACTS.md", + "validation": "design/VALIDATION-AND-RIGOR.md", + "dataPipeline": "design/data-pipeline/phase1-investigation.md", + "servers": "design/servers.md" }, "modules": { "data-pipeline": [ diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 6f9c9176..55969f32 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (three exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`, the `M1.2ak` read-only MongoDB URI safety guard (`mongo_safety`), and the `M1.2al` driver-independent read-only MongoDB raw-BSON cursor seam (`mongo_stream`). +Dedicated Rust crate (four exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `mongodb` `=3.10.2` with `default-features = false, features = ["compat-3-3-0", "bson-3", "sync", "rustls-tls", "dns-resolver"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`, the `M1.2ak` read-only MongoDB URI safety guard (`mongo_safety`), the `M1.2al` read-only MongoDB raw-BSON cursor seam (`mongo_stream`) + M1 `--from-mongo` runners (`run_mongo`), and the M2 `curate-posts`, `curate-fundamentals`, `curate-macro`, `curate-bars-1m`, `curate-qm-bars-1m`, `curate-fx-1m`, and `send-ilp` commands. ## Scope & Sign Conventions @@ -92,7 +92,7 @@ Rules: - Merge: `rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod == eod_rows_out + te_rows_out` - Overlap: `overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod` -Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation policy (the `M1.2l` Parquet writer accepts caller-supplied timestamps; derivation belongs to the Mongo-streaming wiring task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends. +Deferred out of `src/fx.rs`: `CADUSD.FOREX` inversion and wiring FX into `src/adj.rs` cross-currency dividends (`ts`/`known_at` `23:59:59.999999 UTC` stamping is implemented in `src/curate_fx.rs`, and `fx_1m` intraday FX lives in `src/curate_fx_1m.rs` / `curate-fx-1m`). ## `shorts` Builder (`M1.2f`) @@ -478,8 +478,8 @@ Rules: - Never panics on untrusted input. `BsonEodPriceError` names the offending field on every field-level error: `MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, `TruncatedDocument`, `CorruptDocumentLength`, and `CorruptBson`. - `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`). - `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`. -5. **Deferred out of `M1.2o`:** - - MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, and decoders for remaining collections (`eodIntraday1M`). (`qmSplits`/`qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, and `qmFilings`/`qmEarnings` decoders are now implemented alongside all six M1 `curate-*` file-to-Parquet commands.) +5. **Status of follow-ups from `M1.2o`:** + - All six M1 `curate-*` commands (file mode and `--from-mongo` via `mongodb = "=3.10.2"` in `src/mongo_stream.rs` + `src/run_mongo.rs`), `rayon` year-sharded parallel `bars_1d` Parquet writes, and the `eodIntraday1M` decoder (`src/bson_eod_intraday.rs`) are now implemented. Direct PostgreSQL `provider_mapping` preload (replacing TSV export) remains out of scope. ## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`) @@ -1152,7 +1152,7 @@ Single-threaded baseline measured locally (`2026-11-29`, prior to `rayon` parall ### Known Limits - **Full in-RAM buffering of mapped bars (and optional QM volumes) + parallel year-bucketing RAM:** `curate-bars-1d` buffers every mapped bar in `Vec>>` before sorting (`64 B/bar` struct size; measured `68.5–109.6 B/bar` including `Vec` geometric growth headroom, plus ~200 B/row peak during `curate_bars_1d` while `built.rows` and `Bars1dParquetRow` briefly coexist), plus `32 B/row` for mapped `QmRawVolume>` when `--qm-prices` is supplied (~1.6 GiB worst case if all 51.5M QM rows map). When `--threads > 1`, Pass 1 of `write_bars_1d_dataset` buckets validated `Bars1dParquetRow`s by year (`~136 B/row` struct size plus `Vec` growth slack, `~180–200 B/row` transient overhead before the caller's `curated.rows` vector drops) and holds up to `min(threads, years)` concurrent `RowGroupBuffer`s during parallel Zstd encoding (each year's bucket drops as soon as its worker finishes). Pass `--threads 1` to use the bounded-RAM single-pass streaming writer. For the US+CA subset (~100–150M rows of the 846M-row `eodPrices` collection), this implies roughly **20–30 GiB peak RAM** (viable on a 64 GiB workstation, tight on 32 GiB); running all 846M global rows unsharded would exceed 160 GiB. -- **Parallelism scope & direct MongoDB cursors:** `rayon` year-sharded parallelism currently covers the `curate-bars-1d` Parquet write stage (`--threads`); parallel BSON decode, parallel curate/sort, other `curate-*` commands, and direct MongoDB cursors remain deferred to follow-up tasks. +- **Parallelism scope & direct MongoDB cursors:** `rayon` year-sharded parallelism covers the `curate-bars-1d` Parquet write stage (`--threads`), and `--from-mongo` read-only streaming is wired for all six M1 `curate-*` commands (`src/run_mongo.rs`); parallel BSON decode, parallel curate/sort, and `--from-mongo` on M2 commands remain deferred to follow-up tasks. - **Ticker-reuse split keying caveat:** because `curate_bars_1d` takes `SplitTable` keyed by `eodSearchCode` rather than `listing_id`, attaching a split to every `"eod"` `source_id` pointing at a `listing_id` means a later split on a reused `eodSearchCode` could affect an earlier listing that previously held that same `eodSearchCode`. - **Partition-level replacement on `--out` reuse:** `write_bars_1d_dataset` atomically replaces only the `bars_1d/year=YYYY/part.parquet` partitions emitted by the current run. Reusing an existing `--out` directory for a narrower year range leaves older year partitions intact on disk; use a fresh `--out` directory for a complete rebuild. @@ -1657,7 +1657,7 @@ Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mo ### Dependencies -- **No new dependency added:** `tools/curate-etl/Cargo.toml` and `Cargo.lock` are unchanged (still three exact-pinned direct dependencies: `bson = "=3.1.0"`, `parquet = "=60.2.0"`, and `rayon = "=1.12.0"`). `src/mongo_stream.rs` contains no `mongodb::` driver paths yet. +- **Exact-pinned direct dependencies (`tools/curate-etl/Cargo.toml`):** `bson = "=3.1.0"`, `mongodb = "=3.10.2"` (`compat-3-3-0`, `bson-3`, `sync`, `rustls-tls`, `dns-resolver`), `parquet = "=60.2.0"`, and `rayon = "=1.12.0"`. `src/mongo_stream.rs` implements both the offline driver-independent `RawDocumentSource` seam and the read-only `mongodb`-backed `ReadOnlyMongoClient` / `MongoRawDocumentSource`, wired into all six M1 `curate-*` commands via `src/run_mongo.rs`. ### Public API & Sealing Guarantees @@ -1679,10 +1679,9 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code - **Run 1:** plain `264.49 ms` (`3,780,816 docs/s`, `1,029.92 MiB/s`) vs. `RawBsonCursorReader` `263.32 ms` (`3,797,634 docs/s`, `1,034.50 MiB/s`, ratio `1.004x`, `peak_pending_capacity=271 bytes`) - **Run 2:** plain `281.99 ms` (`3,546,241 docs/s`, `966.02 MiB/s`) vs. `RawBsonCursorReader` `270.90 ms` (`3,691,390 docs/s`, `1,005.56 MiB/s`, ratio `1.041x`, `peak_pending_capacity=271 bytes`) -### Not Done / Not Verified +### Live-Host Verification Pending -- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress. -- **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks). +- **Live QA MongoDB cursor throughput on `quant`:** all tests and benchmarks run 100% offline with zero network connections; `ReadOnlyMongoClient` / `MongoRawDocumentSource` (`src/mongo_stream.rs`) and M1 `--from-mongo` runners (`src/run_mongo.rs`) are implemented and unit-tested offline, while live cursor throughput against read-only QA MongoDB on `quant` awaits host-side execution. ## Zero-Copy `eodIntraday1M` BSON Decoder (`M2.3d`) @@ -1694,7 +1693,7 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code ## Point-in-Time Fundamentals Core (`M2.2a`) -Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. BSON decoding, Zstd Parquet writing, CLI `curate-*` wiring, and `MarketDataStore.fundamentalsAsOf` are deferred to follow-up tasks. +Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. Downstream wiring now lives in `src/bson_qm_financials.rs` (BSON decoding), `src/parquet_fundamentals.rs` (Zstd Parquet writing), `src/run_curate_fundamentals.rs` / `curate-fundamentals` (CLI), and `libs/research/src/market-data-store-duckdb.ts` (`MarketDataStore.fundamentalsAsOf`). ### Public API & Field Set @@ -1749,7 +1748,7 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m - **Explicit field paths & fiscal policy (no unverified defaults):** `CurateFundamentalsArgs::with_verified_defaults(...)` populates only the four verified `qmFinancials` defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. Callers must explicitly supply the `currency` path, all six numeric metric `Option` paths, `CurateFundamentalsFiscalPeriod` (`Fixed(FiscalPeriod)` or `ByTokens { quarterly, annual }`), `filings_form_type_field`, and snapshot period limit `k >= 1`. - **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_idvenue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number. -- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up. +- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `/fundamentals_pit` or modifying pre-existing partitions. File-mode CLI wiring is available via `curate-fundamentals` above. ## `run_curate_bars_1m` Bounded-Memory File-to-File Runner (`M2.3k`) @@ -1824,7 +1823,7 @@ curate-etl send-ilp \ - **Bounded-memory chunking & raw OHLCV passthrough:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_qm_intraday_buffer` directly, borrowing `qmSearchCode` per chunk and curating without split un-adjustment (no splits input; raw `qmIntraday` OHLCV passes through bit-identical aside from `-0.0 -> +0.0` volume normalization) into one shared `IlpShardedWriter` with `finish()` called once after clean EOF. `mapping_source` rejects blank values and forwards any nonblank namespace verbatim (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`). - **Cross-chunk semantics, table/file separation & reporting:** Sorting and collision collapse/drop apply per chunk; cross-chunk duplicates rely on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`, and `curate_stats.listings_out` / `curate_stats.builder.keys_out` sum per-chunk counts. Emitted ILP v2 rows target table `bars_1m` with `source=qm_raw` and caller-supplied `known_at_micros`, while output files use the `bars_1m_qm.shard-.ilp` prefix so QM and EOD (`bars_1m.shard-.ilp`) exports can share `out_dir` safely. -- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. CLI wiring, `--from-mongo`, and live QuestDB ingestion remain follow-ups. +- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. File-mode CLI wiring is available via `curate-qm-bars-1m`; `--from-mongo` and live QuestDB ingestion remain follow-ups. ## Lagged Macro Regime Series Builder (`M2.2n`) From 4ff4f7ef0a014296b2b9179fb58609a2d6b33b09 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 5 Dec 2026 13:52:30 -0500 Subject: [PATCH 2/3] =?UTF-8?q?T-214:=20M2.1w=20=E2=80=94=20Add=20notebook?= =?UTF-8?q?=20snapshot=20CLI,=20MCP=20end-to-end=20study+snapshot+finding?= =?UTF-8?q?=20test,=20and=20fix=20docs/->design/=20path=20drift?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/research-copilot-mcp.ts | 7 +++---- scripts/test/research-copilot-mcp-e2e.test.ts | 12 ++++++------ 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/scripts/research-copilot-mcp.ts b/scripts/research-copilot-mcp.ts index 69234067..20160108 100644 --- a/scripts/research-copilot-mcp.ts +++ b/scripts/research-copilot-mcp.ts @@ -60,10 +60,9 @@ async function defaultOpenStore( config: ResearchCopilotHostConfig, env?: Readonly> ): Promise { - const { openResearchCopilotStore } = await import( - '../libs/data/duckdb/src/research-copilot-store' - ); - return openResearchCopilotStore(config, env !== undefined ? { env } : undefined); + const mod = await import('../libs/data/duckdb/src/research-copilot-store'); + const opts = env !== undefined ? { env } : undefined; + return mod.openResearchCopilotStore(config, opts); } function defaultCreateLibraryCardReader( diff --git a/scripts/test/research-copilot-mcp-e2e.test.ts b/scripts/test/research-copilot-mcp-e2e.test.ts index db813601..746c8e09 100644 --- a/scripts/test/research-copilot-mcp-e2e.test.ts +++ b/scripts/test/research-copilot-mcp-e2e.test.ts @@ -401,7 +401,7 @@ function createInMemoryCopilotDatabase(): InMemoryCopilotDatabase { for (let offset = 0; offset < params.length; offset += 14) { const id = nextTrialId; nextTrialId += 1; - const createdAt = new Date(FIXED_NOW_MS + id * 1000).toISOString(); + const createdAt = `${new Date(FIXED_NOW_MS + id * 1000).toISOString().slice(0, -1)}000Z`; const rawSeries = params[offset + 13] as readonly number[]; // Round-trip through Float32Array to mirror PostgreSQL `real[]`. const storedSeries = Array.from(Float32Array.from(rawSeries)); @@ -453,13 +453,13 @@ function createInMemoryCopilotDatabase(): InMemoryCopilotDatabase { ) { const market = String(params[0]); const bucket = String(params[1]); - const asOf = params[2] !== undefined ? String(params[2]) : undefined; + const asOfMs = params[2] !== undefined ? Date.parse(String(params[2])) : undefined; const found = trials .filter( row => row.universe_market === market && row.horizon_bucket === bucket && - (asOf === undefined || row.created_at <= asOf) + (asOfMs === undefined || Date.parse(row.created_at) <= asOfMs) ) .sort((a, b) => a.trial_id - b.trial_id); return { rows: found as unknown as readonly Row[] }; @@ -1079,7 +1079,7 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = expect(searchPayload.rowCount).toBe(1); expect(searchPayload.rows[0]?.listingId).toBe(101); expect(searchPayload.rows[0]?.delistedAt).toBeNull(); - expect(searchPayload.rows[0]?.lastBarDate).toBe('2024-06-30'); + expect(searchPayload.rows[0]?.lastBarDate).toBe(VAULT_CUTOFF_DATE); // 3. query_data: straddling `to` clamped, 9999.0 Vault sentinel bars excluded const queryStraddle = await stdio.callTool('query_data', { @@ -1187,7 +1187,7 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = status: string; clampedTo: boolean; eventCount: number; - study: { clustered: { carMean: number } | null; diagnostics: { usedEvents: number } }; + study: { clustered: { carMean: number } | null; diagnostics: { eventsUsed: number } }; trial: { trialId: number; expressionHash: string; sampleEnd: string }; deflatedSharpe: { clusterSize: number; dsr: number | null }; }; @@ -1195,7 +1195,7 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = expect(eventPayload.clampedTo).toBe(true); // Only the 8 pre-cutoff newswire ceo_post events are included (retail + Vault rows excluded). expect(eventPayload.eventCount).toBe(8); - expect(eventPayload.study.diagnostics.usedEvents).toBe(8); + expect(eventPayload.study.diagnostics.eventsUsed).toBe(8); expect(eventPayload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); expect(eventPayload.deflatedSharpe.clusterSize).toBe(3); From 2fcab86610c5e434ca367e9fe075c74f74d438dc Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 5 Dec 2026 14:04:34 -0500 Subject: [PATCH 3/3] T-214: edits made in the worktree --- scripts/test/research-copilot-mcp-e2e.test.ts | 326 +++++++++++++++++- studio.config.json | 1 - 2 files changed, 307 insertions(+), 20 deletions(-) diff --git a/scripts/test/research-copilot-mcp-e2e.test.ts b/scripts/test/research-copilot-mcp-e2e.test.ts index 746c8e09..0f57a72d 100644 --- a/scripts/test/research-copilot-mcp-e2e.test.ts +++ b/scripts/test/research-copilot-mcp-e2e.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { trialMoments } from '@stock-bot/calculations'; -import type { NotebookSnapshotReceipt } from '@stock-bot/research'; +import type { MarketDataStore, NotebookSnapshotReceipt } from '@stock-bot/research'; import { FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, @@ -526,7 +526,10 @@ function createInMemoryCopilotDatabase(): InMemoryCopilotDatabase { async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{ readonly preCutoffSessions: readonly string[]; + readonly q2PreRestatementTtmNetIncome: number; readonly restatedQ1TtmNetIncome: number; + readonly shortsApril15PctFloat: number; + readonly shortsApril30PctFloat: number; }> { const barsDir = join(curatedRoot, 'bars_1d', 'year=2024'); const fundDir = join(curatedRoot, 'fundamentals_pit', 'year=2024'); @@ -624,6 +627,7 @@ async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{ `); const fundValues: string[] = []; + const q2PreRestatementTtmNetIncome = 13_500_000.0; const restatedQ1TtmNetIncome = 42_500_000.0; // Verified Q1 + Q2 snapshots for listings 101..107 (7 listings >= DEFAULT_MIN_CROSS_SECTION = 5). for (let i = 0; i < 7; i += 1) { @@ -820,6 +824,17 @@ async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{ subtype: 'retail', payload: '{"spiel_id":"rt-101","is_edited":false}', }, + // Pre-cutoff ts with post-cutoff known_at (June 28 post edited after July 1 Vault cutoff): + // proves the DuckDB events scan fences on known_at as well as ts. + { + listingId: 102, + ts: '2024-06-28T14:00:00Z', + knownAt: '2024-07-02T14:00:00Z', + knownAtSource: 'post_edited', + kind: 'ceo_post', + subtype: 'newswire', + payload: '{"spiel_id":"nw-vault-edited-102","is_edited":true}', + }, // Post-cutoff Vault ceo_post (must be excluded by Vault fence) { listingId: 101, @@ -841,7 +856,13 @@ async function writeCuratedParquetFixtures(curatedRoot: string): Promise<{ `COPY (SELECT * FROM events ORDER BY listing_id ASC, ts ASC, kind ASC, subtype ASC, payload_json ASC, known_at ASC, known_at_source ASC) TO ${sqlString(join(eventsDir, 'part.parquet'))} (FORMAT PARQUET);` ); - return { preCutoffSessions, restatedQ1TtmNetIncome }; + return { + preCutoffSessions, + q2PreRestatementTtmNetIncome, + restatedQ1TtmNetIncome, + shortsApril15PctFloat: 0.02, + shortsApril30PctFloat: 0.035, + }; } finally { await builder.close(); } @@ -930,8 +951,10 @@ async function runSnapshotSubprocess( interface E2eRunSummary { readonly fundExpressionHash: string; readonly fundRankIcMean: number | null; + readonly fundFirstSeriesPoint: { readonly date: string; readonly value: number } | null; readonly shortsExpressionHash: string; readonly shortsRankIcMean: number | null; + readonly shortsFirstSeriesPoint: { readonly date: string; readonly value: number } | null; readonly eventExpressionHash: string; readonly eventCarMean: number | null; readonly snapshotSha256: string; @@ -966,14 +989,14 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = mkdir(snapshotDir, { recursive: true }), ]); - const { restatedQ1TtmNetIncome } = await writeCuratedParquetFixtures(curatedRoot); + const { + q2PreRestatementTtmNetIncome, + restatedQ1TtmNetIncome, + shortsApril15PctFloat, + shortsApril30PctFloat, + } = await writeCuratedParquetFixtures(curatedRoot); await writeLibraryFixture(libraryRoot); - const notebookPath = join(notebookDir, 'ec1-study.py'); - const snapshotHtml = `

${DATASET_ID}

\n`; - await writeFile(notebookPath, '# synthetic EC1 marimo notebook fixture\n', 'utf8'); - const marimoShimPath = await writeCleanFakeMarimoShim(workDir, snapshotHtml); - const buildEnv = (): Record => ({ PATH: process.env.PATH, NODE_ENV: 'test', @@ -990,9 +1013,8 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = STOCKBOT_DUCKDB_THREADS: '2', }); - // Verify PIT fundamentals semantics directly via openResearchCopilotStore: - // restated Q1 (effective_known_at 2024-05-20 > Q2 2024-05-10) updates ttm_net_income - // without overwriting Q2 period_end ('2024-04-30'), and estimated-lag listing 108 is excluded. + // Verify PIT fundamentals, shorts +4d release, and events known_at Vault boundaries + // directly via openResearchCopilotStore before running the stdio pipeline. const pitCheckStore = await openResearchCopilotStore( { postgresUrl: 'postgresql://research_ro:hermetic@127.0.0.1:5433/trading_bot_dev', @@ -1005,16 +1027,76 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = { env: buildEnv() } ); try { - const pitTable = await pitCheckStore.store.fundamentalsAsOf({ + // Fundamentals BEFORE Q1 restatement (effective_known_at 2024-05-20): returns Q2 value, + // excludes estimated-lag listing 108. + const preRestatementTable = await pitCheckStore.store.fundamentalsAsOf({ + listingIds: [101, 108], + fields: ['ttm_net_income'], + asOf: '2024-05-19', + allowEstimatedLag: false, + }); + expect(preRestatementTable.rows).toHaveLength(1); + expect(preRestatementTable.rows[0]?.listing_id).toBe(101); + expect(preRestatementTable.rows[0]?.period_end).toBe('2024-04-30'); + expect(preRestatementTable.rows[0]?.ttm_net_income).toBe(q2PreRestatementTtmNetIncome); + + // Fundamentals AFTER Q1 restatement (effective_known_at 2024-05-20 > Q2 2024-05-10): + // updates ttm_net_income without overwriting Q2 period_end ('2024-04-30'). + const postRestatementTable = await pitCheckStore.store.fundamentalsAsOf({ listingIds: [101, 108], fields: ['ttm_net_income'], asOf: '2024-05-25', allowEstimatedLag: false, }); - expect(pitTable.rows).toHaveLength(1); - expect(pitTable.rows[0]?.listing_id).toBe(101); - expect(pitTable.rows[0]?.period_end).toBe('2024-04-30'); - expect(pitTable.rows[0]?.ttm_net_income).toBe(restatedQ1TtmNetIncome); + expect(postRestatementTable.rows).toHaveLength(1); + expect(postRestatementTable.rows[0]?.listing_id).toBe(101); + expect(postRestatementTable.rows[0]?.period_end).toBe('2024-04-30'); + expect(postRestatementTable.rows[0]?.ttm_net_income).toBe(restatedQ1TtmNetIncome); + + // Shorts ON report_date (2024-04-30, before +4 TSX business-day known_at 2024-05-06T21:00Z): + // only the 2024-04-15 observation is visible; 2024-04-30 is NOT usable on its report date. + const shortsOnReportDate = await pitCheckStore.store.shortsAsOf({ + listingIds: [101], + from: '2024-04-01', + to: '2024-05-10', + asOf: '2024-04-30', + }); + expect(shortsOnReportDate.rows).toHaveLength(1); + expect(shortsOnReportDate.rows[0]?.report_date).toBe('2024-04-15'); + expect(shortsOnReportDate.rows[0]?.pct_float).toBe(shortsApril15PctFloat); + + // Shorts AFTER release (2024-05-07): 2024-04-30 observation becomes visible. + const shortsAfterRelease = await pitCheckStore.store.shortsAsOf({ + listingIds: [101], + from: '2024-04-01', + to: '2024-05-10', + asOf: '2024-05-07', + }); + expect(shortsAfterRelease.rows).toHaveLength(2); + expect(shortsAfterRelease.rows[1]?.report_date).toBe('2024-04-30'); + expect(shortsAfterRelease.rows[1]?.pct_float).toBe(shortsApril30PctFloat); + + // Events DuckDB boundary: excludes both post-cutoff ts/known_at (nw-vault-101) AND + // pre-cutoff ts (2024-06-28) with post-cutoff known_at (2024-07-02, nw-vault-edited-102). + const ceoPostEvents = await pitCheckStore.store.events({ + kinds: ['ceo_post'], + listingIds: [...PRE_CUTOFF_LISTING_IDS], + from: '2024-04-01', + to: '2024-07-10', + }); + expect(ceoPostEvents.rows).toHaveLength(9); + expect( + ceoPostEvents.rows.every( + r => Number(r.ts) < VAULT_CUTOFF_TS && Number(r.known_at) < VAULT_CUTOFF_TS + ) + ).toBe(true); + expect( + ceoPostEvents.rows.some( + r => + String(r.payload_json).includes('nw-vault-101') || + String(r.payload_json).includes('nw-vault-edited-102') + ) + ).toBe(false); } finally { await pitCheckStore.close(); } @@ -1128,7 +1210,12 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = const fundPayload = fundRes.parsed as { status: string; clampedTo: boolean; - analysis: { rankIc: { mean: number | null } }; + analysis: { + rankIc: { mean: number | null }; + ledgerSeries: { + points: Array<{ date: string; value: number }>; + }; + }; trial: { trialId: number; expressionHash: string; sampleEnd: string }; deflatedSharpe: { clusterSize: number; dsr: number | null }; }; @@ -1136,6 +1223,12 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = expect(fundPayload.clampedTo).toBe(true); expect(fundPayload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); expect(fundPayload.deflatedSharpe.clusterSize).toBe(1); + expect(fundPayload.analysis.ledgerSeries.points.length).toBeGreaterThan(0); + expect( + fundPayload.analysis.ledgerSeries.points.every( + pt => pt.date < VAULT_CUTOFF_DATE && Number.isFinite(pt.value) + ) + ).toBe(true); // 5. analyze_signal #2: shorts alt-data (pct_float) in same relatedness cluster const shortsRes = await stdio.callTool('analyze_signal', { @@ -1154,7 +1247,12 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = const shortsPayload = shortsRes.parsed as { status: string; clampedTo: boolean; - analysis: { rankIc: { mean: number | null } }; + analysis: { + rankIc: { mean: number | null }; + ledgerSeries: { + points: Array<{ date: string; value: number }>; + }; + }; trial: { trialId: number; expressionHash: string; sampleEnd: string }; deflatedSharpe: { clusterSize: number; dsr: number | null }; }; @@ -1166,6 +1264,16 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = shortsPayload.deflatedSharpe.dsr !== null && Number.isFinite(shortsPayload.deflatedSharpe.dsr) ).toBe(true); + // First shorts report (2024-04-15) has known_at 2024-04-19T21:00Z (after 20:00Z close), + // so the earliest eligible signal session is Monday 2024-04-22, never 2024-04-15. + expect(shortsPayload.analysis.ledgerSeries.points.length).toBeGreaterThan(0); + expect(shortsPayload.analysis.ledgerSeries.points[0]?.date).toBe('2024-04-22'); + expect(Number.isFinite(shortsPayload.analysis.ledgerSeries.points[0]?.value)).toBe(true); + expect( + shortsPayload.analysis.ledgerSeries.points.every( + pt => pt.date >= '2024-04-22' && pt.date < VAULT_CUTOFF_DATE && Number.isFinite(pt.value) + ) + ).toBe(true); // 6. event_study #3: ceo_post (subtype: newswire) const eventRes = await stdio.callTool('event_study', { @@ -1213,11 +1321,63 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = } // 7. Real subprocess invocation of scripts/export-notebook-snapshot.ts + // Render a deterministic fixture manifest containing study settings, baselines, + // trial hashes, and results so the filed sha256 evidence digest binds to the study. + const snapshotManifest = { + datasetId: DATASET_ID, + vaultCutoffIso: VAULT_CUTOFF_ISO, + modeledCosts: 'zero', + baselines: { + signal: 'zero_ic', + eventStudy: 'equal_weight', + }, + studies: { + fundamentals: { + field: 'ttm_net_income', + allowEstimatedLag: false, + horizonSessions: 5, + expressionHash: fundPayload.trial.expressionHash, + rankIcMean: fundPayload.analysis.rankIc.mean, + firstSeriesPoint: fundPayload.analysis.ledgerSeries.points[0] ?? null, + }, + shorts: { + field: 'pct_float', + horizonSessions: 5, + expressionHash: shortsPayload.trial.expressionHash, + rankIcMean: shortsPayload.analysis.rankIc.mean, + firstSeriesPoint: shortsPayload.analysis.ledgerSeries.points[0] ?? null, + }, + eventStudy: { + kinds: ['ceo_post'], + subtypes: ['newswire'], + preDays: 2, + postDays: 3, + expressionHash: eventPayload.trial.expressionHash, + eventCount: eventPayload.eventCount, + carMean: eventPayload.study.clustered?.carMean ?? null, + }, + }, + }; + const manifestJson = JSON.stringify(snapshotManifest); + const expectedSnapshotHtml = `

${DATASET_ID}

\n`; + const runWorkDir = join(workDir, `snapshot-run-${runTag}`); + await mkdir(runWorkDir, { recursive: true }); + const notebookPath = join(notebookDir, `ec1-study-${runTag}.py`); + await writeFile(notebookPath, `# synthetic EC1 manifest: ${manifestJson}\n`, 'utf8'); + const marimoShimPath = await writeCleanFakeMarimoShim(runWorkDir, expectedSnapshotHtml); + const snapshotOutPath = join(snapshotDir, `ec1-${runTag}.html`); const receipt = await runSnapshotSubprocess(notebookPath, snapshotOutPath, marimoShimPath); const diskBytes = await readFile(snapshotOutPath); + const diskHtml = diskBytes.toString('utf8'); + expect(diskHtml).toBe(expectedSnapshotHtml); + expect(diskHtml).toContain(fundPayload.trial.expressionHash); + expect(diskHtml).toContain(shortsPayload.trial.expressionHash); + expect(diskHtml).toContain(eventPayload.trial.expressionHash); expect(receipt.bytes).toBe(diskBytes.byteLength); - expect(receipt.sha256).toBe(createHash('sha256').update(diskBytes).digest('hex')); + expect(receipt.sha256).toBe( + createHash('sha256').update(expectedSnapshotHtml, 'utf8').digest('hex') + ); // 8. file_finding: Vault-only trial ref fails closed with zero findings inserts const vaultRefAttempt = await stdio.callTool('file_finding', { @@ -1256,6 +1416,7 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = }; expect(filedFirstPayload.created).toBe(true); expect(db.findings).toHaveLength(1); + expect(db.findings[0]?.evidence_refs).toContain(`sha256:${receipt.sha256}`); // Identical replay with same idempotencyKey -> created: false, identical id/createdAt const filedReplay = await stdio.callTool('file_finding', findingArgs); @@ -1316,8 +1477,10 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = return { fundExpressionHash: fundPayload.trial.expressionHash, fundRankIcMean: fundPayload.analysis.rankIc.mean, + fundFirstSeriesPoint: fundPayload.analysis.ledgerSeries.points[0] ?? null, shortsExpressionHash: shortsPayload.trial.expressionHash, shortsRankIcMean: shortsPayload.analysis.rankIc.mean, + shortsFirstSeriesPoint: shortsPayload.analysis.ledgerSeries.points[0] ?? null, eventExpressionHash: eventPayload.trial.expressionHash, eventCarMean: eventPayload.study.clustered?.carMean ?? null, snapshotSha256: receipt.sha256, @@ -1330,4 +1493,129 @@ describe('MCP research copilot Exit Criterion 1 end-to-end stdio workflow', () = // Deterministic replay parity across runs expect(run2).toEqual(run1); }); + + test('reports vaultExcludedEvents when a controlled store returns a post-cutoff fenced event', async () => { + const curatedRoot = join(workDir, 'curated'); + const libraryRoot = join(workDir, 'library'); + const duckdbTmpDir = join(workDir, 'duckdb-tmp'); + await Promise.all([ + mkdir(curatedRoot, { recursive: true }), + mkdir(libraryRoot, { recursive: true }), + mkdir(duckdbTmpDir, { recursive: true }), + ]); + + await writeCuratedParquetFixtures(curatedRoot); + await writeLibraryFixture(libraryRoot); + + const env: Record = { + PATH: process.env.PATH, + NODE_ENV: 'test', + RESEARCH_MCP_POSTGRES_URL: + 'postgresql://research_ro:hermetic@127.0.0.1:5433/trading_bot_dev?sslmode=disable', + RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro', + RESEARCH_MCP_CURATED_ROOT: curatedRoot, + RESEARCH_MCP_VAULT_CUTOFF_TS: VAULT_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: libraryRoot, + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), + STOCKBOT_DUCKDB_TEMP_DIRECTORY: duckdbTmpDir, + STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB', + STOCKBOT_DUCKDB_THREADS: '2', + }; + + const db = createInMemoryCopilotDatabase(); + const stdio = createInteractiveStdioHarness(); + let storeClosed = false; + + const serverPromise = runResearchCopilotMcp({ + env, + input: stdio.input, + output: stdio.output, + stderr: stdio.stderr, + openExecutor: () => ({ + executor: db.executor, + close: () => {}, + }), + openStore: async hostConfig => { + const real = await openResearchCopilotStore(hostConfig, { env }); + const wrappedStore: MarketDataStore = { + bars: q => real.store.bars(q), + async events(q) { + const base = await real.store.events(q); + return { + columns: base.columns, + rows: [ + ...base.rows, + { + listing_id: 102, + ts: Date.parse('2024-06-28T14:00:00Z'), + known_at: Date.parse('2024-07-02T14:00:00Z'), + known_at_source: 'post_edited', + kind: 'ceo_post', + subtype: 'newswire', + payload_json: '{"spiel_id":"nw-vault-leaked-102","is_edited":true}', + }, + ], + }; + }, + shortsAsOf: q => real.store.shortsAsOf(q), + fx: q => real.store.fx(q), + crossSection: q => real.store.crossSection(q), + fundamentalsAsOf: q => real.store.fundamentalsAsOf(q), + macroAsOf: q => real.store.macroAsOf(q), + universe: q => real.store.universe(q), + }; + return { + store: wrappedStore, + close: async () => { + storeClosed = true; + await real.close(); + }, + }; + }, + now: () => FIXED_NOW_MS, + }); + + const initResp = await stdio.request('initialize', { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: 'ec1-vault-diag-client', version: '1.0.0' }, + }); + expect(initResp.error).toBeUndefined(); + stdio.notify('notifications/initialized'); + + const eventRes = await stdio.callTool('event_study', { + listingIds: [...PRE_CUTOFF_LISTING_IDS], + from: '2024-04-01', + to: '2024-07-10', + event: { + kinds: ['ceo_post'], + subtypes: ['newswire'], + }, + preDays: 2, + postDays: 3, + benchmark: 'equal_weight', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(eventRes.isError).toBe(false); + const eventPayload = eventRes.parsed as { + status: string; + eventCount: number; + vaultExcludedEvents: number; + panelDiagnostics: { vaultExcludedEvents: number }; + study: { diagnostics: { eventsUsed: number } }; + }; + expect(eventPayload.status).toBe('ok'); + expect(eventPayload.eventCount).toBe(8); + expect(eventPayload.vaultExcludedEvents).toBe(1); + expect(eventPayload.panelDiagnostics.vaultExcludedEvents).toBe(1); + expect(eventPayload.study.diagnostics.eventsUsed).toBe(8); + + stdio.closeInput(); + const exitCode = await serverPromise; + expect(exitCode).toBe(0); + expect(stdio.stderr.text()).toBe(''); + expect(storeClosed).toBe(true); + }); }); diff --git a/studio.config.json b/studio.config.json index 95ba0cc9..4e56a017 100644 --- a/studio.config.json +++ b/studio.config.json @@ -43,7 +43,6 @@ "docs": { "pitch": "design/pitch.md", "pillars": "design/pillars.md", - "brand": "design/marketing/brand.md", "agents": "AGENTS.md", "index": "design/README.md", "plan": "design/PLATFORM-PLAN.md",