T-214: M2.1w — Add notebook snapshot CLI, MCP end-to-end study+snapshot+finding test, and fix docs/->design/ path drift
This commit is contained in:
commit
40548adddb
10 changed files with 2481 additions and 46 deletions
12
AGENTS.md
12
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).
|
||||
|
|
|
|||
12
CLAUDE.md
12
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`).
|
||||
|
|
|
|||
16
README.md
16
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
|
||||
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
310
scripts/export-notebook-snapshot.ts
Normal file
310
scripts/export-notebook-snapshot.ts
Normal file
|
|
@ -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<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
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<Record<string, string | undefined>>;
|
||||
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 <path.py> --out <path.html> [options]',
|
||||
'',
|
||||
'Options:',
|
||||
' --notebook <path.py> Required marimo notebook file (.py)',
|
||||
' --out <path.html> Required output HTML snapshot path (.html)',
|
||||
` --marimo <cmd> marimo executable (default: $MARIMO_COMMAND or ${DEFAULT_MARIMO_COMMAND})`,
|
||||
` --timeout-ms <positive-int> Per-command timeout in ms (default: ${DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS})`,
|
||||
' --cwd <dir> Working directory passed to marimo subprocesses',
|
||||
' --allowed-notebook-root <dir> Optional root directory bounding --notebook',
|
||||
' --allowed-output-root <dir> 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<string, string>();
|
||||
|
||||
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 <path.py>.');
|
||||
}
|
||||
const rawOut = seen.get('--out');
|
||||
if (rawOut === undefined) {
|
||||
throw new ExportNotebookSnapshotCliError('Missing required flag --out <path.html>.');
|
||||
}
|
||||
|
||||
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<number> {
|
||||
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();
|
||||
}
|
||||
|
|
@ -57,12 +57,12 @@ async function defaultOpenExecutor(
|
|||
}
|
||||
|
||||
async function defaultOpenStore(
|
||||
config: ResearchCopilotHostConfig
|
||||
config: ResearchCopilotHostConfig,
|
||||
env?: Readonly<Record<string, string | undefined>>
|
||||
): Promise<ManagedMarketDataStore> {
|
||||
const { openResearchCopilotStore } = await import(
|
||||
'../libs/data/duckdb/src/research-copilot-store'
|
||||
);
|
||||
return openResearchCopilotStore(config);
|
||||
const mod = await import('../libs/data/duckdb/src/research-copilot-store');
|
||||
const opts = env !== undefined ? { env } : undefined;
|
||||
return mod.openResearchCopilotStore(config, opts);
|
||||
}
|
||||
|
||||
function defaultCreateLibraryCardReader(
|
||||
|
|
@ -91,7 +91,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,
|
||||
|
|
|
|||
505
scripts/test/export-notebook-snapshot.test.ts
Normal file
505
scripts/test/export-notebook-snapshot.test.ts
Normal file
|
|
@ -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<Record<string, string | undefined>>;
|
||||
}
|
||||
): Promise<SpawnCliResult> {
|
||||
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<string> {
|
||||
const shimPath = join(workDir, name);
|
||||
const htmlContent = extra?.htmlContent ?? '<!doctype html><html><body>Snapshot OK</body></html>\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, "<html>partial-failure", "utf8");',
|
||||
' process.stderr.write("export crashed\\n");',
|
||||
' process.exit(2);',
|
||||
' }',
|
||||
' if (mode === "export_hang") {',
|
||||
' writeFileSync(outPath, "<html>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<string, string>;
|
||||
};
|
||||
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 = '<!doctype html><html><body><h1>Study Snapshot</h1></body></html>\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 = '<!doctype html><html><body>Relative OK</body></html>\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 = '<!doctype html><html><body>Prior Verified Snapshot</body></html>\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 = '<!doctype html><html><body>Preserved</body></html>\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 = '<!doctype html><html><body>Stable Prior</body></html>\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 = '<!doctype html><html><body>Stable Before Timeout</body></html>\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:');
|
||||
});
|
||||
});
|
||||
1621
scripts/test/research-copilot-mcp-e2e.test.ts
Normal file
1621
scripts/test/research-copilot-mcp-e2e.test.ts
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -43,15 +43,14 @@
|
|||
"docs": {
|
||||
"pitch": "design/pitch.md",
|
||||
"pillars": "design/pillars.md",
|
||||
"brand": "docs/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": [
|
||||
|
|
|
|||
|
|
@ -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<EodDailyBar<Arc<str>>>` 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<Arc<str>>` 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<K>` 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<String>` 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_id<TAB>venue`, 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 `<out_dir>/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 `<out_dir>/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-<NN>.ilp` prefix so QM and EOD (`bars_1m.shard-<NN>.ilp`) exports can share `out_dir` safely.
|
||||
- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-<digits>.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-<digits>.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`)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue