From b23722f151d488db02b83695010525f83effb6f1 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 15:50:23 -0500 Subject: [PATCH] =?UTF-8?q?T-177:=20M2.1o=20=E2=80=94=20`marimo=20check`-g?= =?UTF-8?q?ated=20static=20HTML=20snapshot=20exporter=20for=20research=20n?= =?UTF-8?q?otebooks:=20`exportNotebookSnapshot`=20over=20an=20injected=20c?= =?UTF-8?q?ommand-runner=20port=20in=20`libs/research/src/notebook-snapsho?= =?UTF-8?q?t.ts`=20(check=20must=20pass=20before=20`marimo=20export=20html?= =?UTF-8?q?`,=20fail-closed,=20atomic=20output,=20no=20new=20deps,=20no=20?= =?UTF-8?q?real=20marimo=20in=20tests)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 21 + libs/research/src/index.ts | 1 + libs/research/src/notebook-snapshot.ts | 809 +++++++++++++++++++ libs/research/test/notebook-snapshot.test.ts | 765 ++++++++++++++++++ 4 files changed, 1596 insertions(+) create mode 100644 libs/research/src/notebook-snapshot.ts create mode 100644 libs/research/test/notebook-snapshot.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index 96a62b74..b22d581a 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -305,3 +305,24 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/feature-librar - **Executor & directory requirements:** Callers running plans against DuckDB must configure the executor session timezone to UTC (`TZ=UTC`) and ensure output parent directories (`/features//v/year=YYYY/`) exist before executing `COPY`. - **Point-in-time & `adj_factors` snapshots:** Feature definitions own per-observation availability (`knownAtRule` and projected `known_at`). Because `adj_factors` stores cumulative suffix products, features referencing `{{input:adj_factors}}` require a caller-verified, immutable point-in-time snapshot compatible with `vaultCutoffDate`. - **Economic ownership & evidence:** The Quant research role owns each feature's economic specification. `RET_1D_V1` uses a zero-return comparison baseline with no execution or transaction cost model. Any future research claim built on materialized features must retain the feature `ref` and `definitionHash`, immutable dataset identifier, sample window, `vaultCutoffDate`, baseline, and execution assumptions. + +## `marimo check`-Gated Notebook Snapshot Exporter + +Exported from `@stock-bot/research` (`libs/research/src/notebook-snapshot.ts`). Subprocess execution and filesystem access are injected via `NotebookCommandRunner` and `NotebookSnapshotFs`, and `node:crypto` is loaded lazily at call time so the shared package barrel remains browser-bundleable. Command flags and JSON report validation are confirmed against **marimo `0.26.0`** (pinned in `python/uv.lock`). + +### API & Ports + +- **`exportNotebookSnapshot(options)`** — Validates options and paths, confirms `notebookPath` is an existing regular `.py` file, gates on `marimo check --format=json `, and only on a clean check reserves a unique sibling `.html` temp file via `fs.createExclusive` and runs `marimo export html -o --force` before computing byte length and lowercase SHA-256 and atomically publishing via `fs.rename(tempPath, outputPath)`. +- **Frozen receipt (`NotebookSnapshotReceipt`)** — Returns `Object.freeze({ notebookPath, outputPath, bytes, sha256, checkDiagnostics })`, where `checkDiagnostics` is the deep-frozen marimo JSON report (or `null` when `marimo check` exits `0` with empty stdout). +- **`NotebookCommandRunner`** — Must execute `command` directly with `args` as an argv array (never a shell string). On timeout (default `120_000` ms per command), implementations must terminate the subprocess and reject with `code: 'ETIMEDOUT'` **only after the process has exited and stopped writing** so cleanup cannot race with late writes. +- **`NotebookSnapshotFs`** — Minimal port requiring `stat`, `createExclusive` (must throw `code: 'EEXIST'` on collision), `readBytes`, `rename`, and idempotent `remove`. On any export, read, or publish failure, only the owned temp file is removed and any pre-existing `outputPath` keeps its original bytes. +- **Fail-closed error codes (`NotebookSnapshotError`)** — `INVALID_OPTION`, `INVALID_PATH`, `NOTEBOOK_NOT_FOUND`, `CHECK_FAILED` (nonzero check exit, `summary.errored === true`, `type: 'error'`, or `severity: 'breaking'`), `CHECK_OUTPUT_INVALID` (non-JSON stdout on exit `0` or malformed `{ issues, summary }` / `summary.total_files !== 1`), `EXPORT_FAILED`, `EXPORT_EMPTY`, and `TIMEOUT`. Formatting and runtime advisories may accompany a clean check. +- **Lexical roots & execution notice:** `allowedNotebookRoot` and `allowedOutputRoot` enforce lexical POSIX path-component containment (blocking `..` traversal and same-prefix sibling escapes); callers must supply trusted directories and keep the notebook file stable between check and export. Note that `marimo export html` **executes notebook cells**. + +### Manual Host Smoke Check (Director / Host Only) + +Automated tests use fakes and never spawn `marimo`. On a host with the pinned `python/` `uv` environment (`marimo 0.26.0`): + +1. Ensure `STOCK_BOT_TRIAL_LEDGER_DSN` is **unset** so the smoke check does not append trial rows to `trial_ledger`. +2. Target `research/notebooks/ca_shorts_filings_study.py` against a fixed Vault-fenced dataset and run `exportNotebookSnapshot` (or the two commands it issues: `uv run --project python marimo check --format=json research/notebooks/ca_shorts_filings_study.py` followed by `uv run --project python marimo export html research/notebooks/ca_shorts_filings_study.py -o --force`). +3. Record the pinned inputs, whether `marimo check` reported 0 errors, and whether the exported HTML opens cleanly. Quant owns any research claims (including notebook revision, dataset ID, sample window, Vault cutoff, baseline, and cost assumptions); any paper or live write access requires a separate scope decision. diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index bb5e7062..b2e95446 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -6,6 +6,7 @@ export * from './market-data-store'; export * from './market-data-store-duckdb'; export * from './market-data-store-questdb'; export * from './market-data-store-routed'; +export * from './notebook-snapshot'; export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/notebook-snapshot.ts b/libs/research/src/notebook-snapshot.ts new file mode 100644 index 00000000..f7ed610d --- /dev/null +++ b/libs/research/src/notebook-snapshot.ts @@ -0,0 +1,809 @@ +/** + * `marimo check`-gated static HTML snapshot exporter for research notebooks. + * + * Enforces the D9 rule (`design/PLATFORM-PLAN.md`): a notebook must pass + * `marimo check --format=json` with zero errors before `marimo export html` + * runs, and exported HTML is published atomically via a sibling temp file. + * + * All subprocess execution and filesystem access are injected via ports + * (`NotebookCommandRunner`, `NotebookSnapshotFs`). `node:crypto` is loaded + * lazily at call time so `@stock-bot/research` remains browser-bundleable. + * + * Command flags and JSON diagnostic shape are confirmed against marimo 0.26.0 + * (pinned in `python/uv.lock`). + */ + +export const DEFAULT_MARIMO_COMMAND = 'marimo'; +export const DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS = 120_000; + +const MAX_TEMP_RESERVATION_ATTEMPTS = 16; +let tempSequence = 0; + +/** Stable machine-readable error codes thrown by {@link NotebookSnapshotError}. */ +export type NotebookSnapshotErrorCode = + | 'INVALID_OPTION' + | 'INVALID_PATH' + | 'NOTEBOOK_NOT_FOUND' + | 'CHECK_FAILED' + | 'CHECK_OUTPUT_INVALID' + | 'EXPORT_FAILED' + | 'EXPORT_EMPTY' + | 'TIMEOUT'; + +export interface NotebookSnapshotErrorOptions { + readonly details?: unknown; + readonly cause?: unknown; +} + +/** Typed fail-closed error thrown by {@link exportNotebookSnapshot}. */ +export class NotebookSnapshotError extends Error { + readonly code: NotebookSnapshotErrorCode; + readonly details?: unknown; + override readonly cause?: unknown; + + constructor( + code: NotebookSnapshotErrorCode, + message: string, + options?: NotebookSnapshotErrorOptions + ) { + super(message); + this.name = 'NotebookSnapshotError'; + this.code = code; + if (options && 'details' in options) { + this.details = options.details; + } + if (options && 'cause' in options) { + this.cause = options.cause; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export interface NotebookCommandRunOptions { + readonly cwd?: string; + readonly timeoutMs: number; +} + +export interface NotebookCommandResult { + readonly exitCode: number; + readonly stdout: string; + readonly stderr: string; +} + +/** + * Injected command-runner port. + * + * Implementations MUST execute `command` directly with `args` as an argv array + * (never via a shell string or shell interpolation). + * + * Timeout contract: on timeout, implementations MUST terminate the subprocess + * and settle (rejecting with an error carrying `code: 'ETIMEDOUT'`) only after + * the process has exited and stopped writing to disk. + */ +export interface NotebookCommandRunner { + run( + command: string, + args: readonly string[], + options: NotebookCommandRunOptions + ): Promise; +} + +export interface NotebookSnapshotFileStat { + readonly isFile: boolean; + readonly size: number; +} + +/** + * Minimal injected filesystem port for {@link exportNotebookSnapshot}. + */ +export interface NotebookSnapshotFs { + /** Returns file metadata for `path`, or `null` when `path` does not exist. */ + stat(path: string): Promise; + /** + * Exclusively creates an empty file at `path` (`O_CREAT | O_EXCL`). + * MUST throw an error carrying `code: 'EEXIST'` if `path` already exists. + */ + createExclusive(path: string): Promise; + /** Reads the complete byte contents of `path`. */ + readBytes(path: string): Promise; + /** Atomically replaces `destinationPath` with `sourcePath`. */ + rename(sourcePath: string, destinationPath: string): Promise; + /** Idempotently removes `path` (succeeds as a no-op if already absent). */ + remove(path: string): Promise; +} + +/** Parsed marimo 0.26.0 `marimo check --format=json` summary object. */ +export interface MarimoCheckSummary { + readonly errored: boolean; + readonly total_files: number; + readonly [key: string]: unknown; +} + +/** Parsed marimo 0.26.0 `marimo check --format=json` report object. */ +export interface MarimoCheckReport { + readonly issues: readonly Readonly>[]; + readonly summary: MarimoCheckSummary; + readonly [key: string]: unknown; +} + +export interface ExportNotebookSnapshotOptions { + readonly notebookPath: string; + readonly outputPath: string; + readonly runner: NotebookCommandRunner; + readonly fs: NotebookSnapshotFs; + /** Executable name or path for marimo (default `'marimo'`). */ + readonly marimoCommand?: string; + /** Per-command timeout in milliseconds (default `120_000`). */ + readonly timeoutMs?: number; + /** Optional working directory passed to `runner.run`. */ + readonly cwd?: string; + /** Optional absolute root directory that `notebookPath` must lexically reside within. */ + readonly allowedNotebookRoot?: string; + /** Optional absolute root directory that `outputPath` must lexically reside within. */ + readonly allowedOutputRoot?: string; +} + +/** Frozen receipt returned when a notebook snapshot is cleanly checked and published. */ +export interface NotebookSnapshotReceipt { + readonly notebookPath: string; + readonly outputPath: string; + readonly bytes: number; + readonly sha256: string; + readonly checkDiagnostics: MarimoCheckReport | null; +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +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; +} + +function normalizePosixAbsolutePath(rawPath: string): string { + const segments = rawPath.split('/'); + const stack: string[] = []; + for (let i = 0; i < segments.length; i += 1) { + const seg = segments[i]; + if (seg === undefined || seg === '' || seg === '.') { + continue; + } + if (seg === '..') { + if (stack.length > 0) { + stack.pop(); + } + continue; + } + stack.push(seg); + } + return `/${stack.join('/')}`; +} + +function validateAbsolutePath( + rawPath: unknown, + label: string, + options?: { readonly requiredExtension?: string } +): string { + if (typeof rawPath !== 'string' || rawPath.length === 0) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: expected a non-empty string.` + ); + } + if (rawPath.includes('\0')) { + throw new NotebookSnapshotError('INVALID_PATH', `Invalid ${label}: NUL bytes are not allowed.`); + } + if (rawPath.startsWith('-')) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: path must not start with '-'.` + ); + } + if (!rawPath.startsWith('/')) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: path must be an absolute POSIX path.` + ); + } + + if (options?.requiredExtension !== undefined) { + if (rawPath.endsWith('/')) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: path must reference a ${options.requiredExtension} file, not a directory.` + ); + } + } + + const normalized = normalizePosixAbsolutePath(rawPath); + + if (options?.requiredExtension !== undefined) { + const ext = options.requiredExtension; + if (!normalized.endsWith(ext) || normalized === `/${ext}` || normalized.endsWith(`/${ext}`)) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${label}: path must end with '${ext}'.` + ); + } + } + + return normalized; +} + +function assertWithinRoot( + normalizedPath: string, + rawRoot: unknown, + pathLabel: string, + rootLabel: string +): void { + const normalizedRoot = validateAbsolutePath(rawRoot, rootLabel); + if (normalizedRoot === '/') { + return; + } + const requiredPrefix = `${normalizedRoot}/`; + if (!normalizedPath.startsWith(requiredPrefix)) { + throw new NotebookSnapshotError( + 'INVALID_PATH', + `Invalid ${pathLabel}: resolved path '${normalizedPath}' escapes ${rootLabel} '${normalizedRoot}'.` + ); + } +} + +function splitDirAndBase(normalizedFilePath: string): { + readonly dir: string; + readonly base: string; +} { + const lastSlash = normalizedFilePath.lastIndexOf('/'); + const dir = lastSlash <= 0 ? '/' : normalizedFilePath.slice(0, lastSlash); + const base = normalizedFilePath.slice(lastSlash + 1); + return { dir, base }; +} + +function validatePortsAndOptions(options: ExportNotebookSnapshotOptions): { + readonly notebookPath: string; + readonly outputPath: string; + readonly runner: NotebookCommandRunner; + readonly fs: NotebookSnapshotFs; + readonly marimoCommand: string; + readonly timeoutMs: number; + readonly cwd?: string; +} { + if (!isPlainObject(options)) { + throw new NotebookSnapshotError('INVALID_OPTION', 'Invalid options: expected an object.'); + } + + const { runner, fs } = options; + if (!isPlainObject(runner) || typeof runner.run !== 'function') { + throw new NotebookSnapshotError( + 'INVALID_OPTION', + 'Invalid runner: expected an object with a callable run(command, args, options) method.' + ); + } + if ( + !isPlainObject(fs) || + typeof fs.stat !== 'function' || + typeof fs.createExclusive !== 'function' || + typeof fs.readBytes !== 'function' || + typeof fs.rename !== 'function' || + typeof fs.remove !== 'function' + ) { + throw new NotebookSnapshotError( + 'INVALID_OPTION', + 'Invalid fs: expected an object implementing stat, createExclusive, readBytes, rename, and remove.' + ); + } + + const marimoCommand = + options.marimoCommand === undefined ? DEFAULT_MARIMO_COMMAND : options.marimoCommand; + if ( + typeof marimoCommand !== 'string' || + marimoCommand.trim().length === 0 || + marimoCommand.includes('\0') || + marimoCommand.startsWith('-') + ) { + throw new NotebookSnapshotError( + 'INVALID_OPTION', + 'Invalid marimoCommand: expected a non-empty command name or path without NUL bytes or leading "-".' + ); + } + + const timeoutMs = + options.timeoutMs === undefined ? DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS : options.timeoutMs; + if (typeof timeoutMs !== 'number' || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) { + throw new NotebookSnapshotError( + 'INVALID_OPTION', + 'Invalid timeoutMs: expected a positive safe integer.' + ); + } + + const notebookPath = validateAbsolutePath(options.notebookPath, 'notebookPath', { + requiredExtension: '.py', + }); + const outputPath = validateAbsolutePath(options.outputPath, 'outputPath', { + requiredExtension: '.html', + }); + + if (options.allowedNotebookRoot !== undefined) { + assertWithinRoot( + notebookPath, + options.allowedNotebookRoot, + 'notebookPath', + 'allowedNotebookRoot' + ); + } + if (options.allowedOutputRoot !== undefined) { + assertWithinRoot(outputPath, options.allowedOutputRoot, 'outputPath', 'allowedOutputRoot'); + } + + let cwd: string | undefined; + if (options.cwd !== undefined) { + cwd = validateAbsolutePath(options.cwd, 'cwd'); + } + + return { + notebookPath, + outputPath, + runner, + fs, + marimoCommand, + timeoutMs, + ...(cwd !== undefined ? { cwd } : {}), + }; +} + +function validateCommandResult(result: unknown, phase: 'check' | 'export'): NotebookCommandResult { + if ( + !isPlainObject(result) || + typeof result.exitCode !== 'number' || + !Number.isSafeInteger(result.exitCode) || + typeof result.stdout !== 'string' || + typeof result.stderr !== 'string' + ) { + throw new NotebookSnapshotError( + phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED', + `Invalid runner result for marimo ${phase}: expected { exitCode, stdout, stderr }.` + ); + } + return { + exitCode: result.exitCode, + stdout: result.stdout, + stderr: result.stderr, + }; +} + +function issueHasBlockingError(issue: Record): boolean { + if (issue.type === 'error' || issue.severity === 'breaking') { + return true; + } + const nested = issue.diagnostics; + if (Array.isArray(nested)) { + for (let i = 0; i < nested.length; i += 1) { + const diag = nested[i]; + if (isPlainObject(diag) && (diag.type === 'error' || diag.severity === 'breaking')) { + return true; + } + } + } + return false; +} + +function parseAndValidateCheckReport(parsed: unknown): { + readonly report: MarimoCheckReport; + readonly hasBlockingError: boolean; +} { + if (!isPlainObject(parsed)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + 'marimo check JSON output must be an object with { issues, summary }.' + ); + } + + const { issues, summary } = parsed; + if (!Array.isArray(issues) || !isPlainObject(summary)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + 'marimo check JSON output must contain an issues array and a summary object.' + ); + } + + if ( + typeof summary.errored !== 'boolean' || + typeof summary.total_files !== 'number' || + !Number.isSafeInteger(summary.total_files) + ) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + 'marimo check summary must include boolean errored and integer total_files.' + ); + } + + if (summary.total_files !== 1) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check reported summary.total_files=${summary.total_files}; expected exactly 1 checked file.`, + { details: { diagnostics: parsed } } + ); + } + + let hasBlockingError = summary.errored; + + for (let i = 0; i < issues.length; i += 1) { + const issue = issues[i]; + if (!isPlainObject(issue)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}] must be an object.`, + { details: { diagnostics: parsed } } + ); + } + if (issue.type !== undefined && typeof issue.type !== 'string') { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].type must be a string when present.`, + { details: { diagnostics: parsed } } + ); + } + if (issue.severity !== undefined && typeof issue.severity !== 'string') { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].severity must be a string when present.`, + { details: { diagnostics: parsed } } + ); + } + if (issue.diagnostics !== undefined) { + if (!Array.isArray(issue.diagnostics)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].diagnostics must be an array when present.`, + { details: { diagnostics: parsed } } + ); + } + for (let j = 0; j < issue.diagnostics.length; j += 1) { + const diag = issue.diagnostics[j]; + if (!isPlainObject(diag)) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].diagnostics[${j}] must be an object.`, + { details: { diagnostics: parsed } } + ); + } + if (diag.type !== undefined && typeof diag.type !== 'string') { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].diagnostics[${j}].type must be a string when present.`, + { details: { diagnostics: parsed } } + ); + } + if (diag.severity !== undefined && typeof diag.severity !== 'string') { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + `marimo check issues[${i}].diagnostics[${j}].severity must be a string when present.`, + { details: { diagnostics: parsed } } + ); + } + } + } + + if (issueHasBlockingError(issue)) { + hasBlockingError = true; + } + } + + return { + report: parsed as MarimoCheckReport, + hasBlockingError, + }; +} + +function deepFreeze(value: T): T { + if (typeof value !== 'object' || value === null || Object.isFrozen(value)) { + return value; + } + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + deepFreeze(value[i]); + } + return Object.freeze(value); + } + const record = value as Record; + const keys = Object.keys(record); + for (let i = 0; i < keys.length; i += 1) { + const key = keys[i] as string; + deepFreeze(record[key]); + } + return Object.freeze(value); +} + +function generateTempToken(): string { + tempSequence += 1; + const randomPart = + typeof globalThis.crypto !== 'undefined' && typeof globalThis.crypto.randomUUID === 'function' + ? globalThis.crypto.randomUUID().replace(/-/g, '') + : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; + return `${tempSequence}-${randomPart}`; +} + +async function reserveSiblingTempHtml(fs: NotebookSnapshotFs, outputPath: string): Promise { + const { dir, base } = splitDirAndBase(outputPath); + const dirPrefix = dir === '/' ? '' : dir; + + for (let attempt = 0; attempt < MAX_TEMP_RESERVATION_ATTEMPTS; attempt += 1) { + const candidate = `${dirPrefix}/.${base}.${generateTempToken()}.tmp.html`; + try { + await fs.createExclusive(candidate); + return candidate; + } catch (err) { + if (getErrorCode(err) === 'EEXIST') { + continue; + } + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to reserve temporary HTML sibling for '${outputPath}'.`, + { cause: err } + ); + } + } + + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to reserve a unique temporary HTML sibling for '${outputPath}' after ${MAX_TEMP_RESERVATION_ATTEMPTS} attempts.` + ); +} + +async function sha256HexNodeCrypto(bytes: Uint8Array): Promise { + // Keep the Node built-in specifier non-literal so browser bundlers do not try + // to statically resolve `node:crypto` when bundling `@stock-bot/research`. + const cryptoSpecifier = 'node:crypto'; + const nodeCrypto = (await import(cryptoSpecifier)) as typeof import('node:crypto'); + return nodeCrypto.createHash('sha256').update(bytes).digest('hex'); +} + +async function runPhaseCommand( + runner: NotebookCommandRunner, + command: string, + args: readonly string[], + runOptions: NotebookCommandRunOptions, + phase: 'check' | 'export' +): Promise { + let rawResult: unknown; + try { + rawResult = await runner.run(command, args, runOptions); + } catch (err) { + if (getErrorCode(err) === 'ETIMEDOUT') { + throw new NotebookSnapshotError( + 'TIMEOUT', + `marimo ${phase} timed out after ${runOptions.timeoutMs}ms.`, + { cause: err, details: { phase, timeoutMs: runOptions.timeoutMs } } + ); + } + throw new NotebookSnapshotError( + phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED', + `marimo ${phase} command failed to execute.`, + { cause: err, details: { phase } } + ); + } + return validateCommandResult(rawResult, phase); +} + +/** + * Validates a marimo notebook with `marimo check --format=json` and, only when + * the check is clean, exports a static HTML snapshot via `marimo export html` + * and publishes it atomically via sibling temp-file rename. + */ +export async function exportNotebookSnapshot( + options: ExportNotebookSnapshotOptions +): Promise { + const { notebookPath, outputPath, runner, fs, marimoCommand, timeoutMs, cwd } = + validatePortsAndOptions(options); + + let notebookStat: NotebookSnapshotFileStat | null; + try { + notebookStat = await fs.stat(notebookPath); + } catch (err) { + if (getErrorCode(err) === 'ENOENT') { + notebookStat = null; + } else { + throw new NotebookSnapshotError( + 'NOTEBOOK_NOT_FOUND', + `Unable to stat notebook '${notebookPath}'.`, + { cause: err } + ); + } + } + + if (notebookStat === null || !notebookStat.isFile) { + throw new NotebookSnapshotError( + 'NOTEBOOK_NOT_FOUND', + `Notebook file not found or is not a regular file: '${notebookPath}'.` + ); + } + + const runOptions: NotebookCommandRunOptions = + cwd !== undefined ? { cwd, timeoutMs } : { timeoutMs }; + + // Step 1: Gate on `marimo check --format=json `. + const checkResult = await runPhaseCommand( + runner, + marimoCommand, + ['check', '--format=json', notebookPath], + runOptions, + 'check' + ); + + const trimmedCheckStdout = checkResult.stdout.trim(); + let parsedCheckJson: unknown = undefined; + let checkJsonParseError: unknown = undefined; + if (trimmedCheckStdout.length > 0) { + try { + parsedCheckJson = JSON.parse(trimmedCheckStdout); + } catch (err) { + checkJsonParseError = err; + } + } + + if (checkResult.exitCode !== 0) { + throw new NotebookSnapshotError( + 'CHECK_FAILED', + `marimo check exited with code ${checkResult.exitCode}.`, + { + details: { + exitCode: checkResult.exitCode, + stderr: checkResult.stderr, + stdout: checkResult.stdout, + ...(checkJsonParseError === undefined && parsedCheckJson !== undefined + ? { diagnostics: parsedCheckJson } + : {}), + }, + } + ); + } + + let checkDiagnostics: MarimoCheckReport | null = null; + if (trimmedCheckStdout.length > 0) { + if (checkJsonParseError !== undefined) { + throw new NotebookSnapshotError( + 'CHECK_OUTPUT_INVALID', + 'marimo check exited 0 but emitted non-JSON stdout.', + { + cause: checkJsonParseError, + details: { stdout: checkResult.stdout, stderr: checkResult.stderr }, + } + ); + } + + const { report, hasBlockingError } = parseAndValidateCheckReport(parsedCheckJson); + if (hasBlockingError) { + throw new NotebookSnapshotError( + 'CHECK_FAILED', + 'marimo check reported blocking errors in diagnostics.', + { + details: { + exitCode: checkResult.exitCode, + stderr: checkResult.stderr, + diagnostics: report, + }, + } + ); + } + checkDiagnostics = deepFreeze(report); + } + + // Step 2: Reserve an exclusive sibling `.html` temp file and run `marimo export html`. + const tempPath = await reserveSiblingTempHtml(fs, outputPath); + let tempOwned = true; + + try { + const exportResult = await runPhaseCommand( + runner, + marimoCommand, + ['export', 'html', notebookPath, '-o', tempPath, '--force'], + runOptions, + 'export' + ); + + if (exportResult.exitCode !== 0) { + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `marimo export html exited with code ${exportResult.exitCode}.`, + { + details: { + exitCode: exportResult.exitCode, + stderr: exportResult.stderr, + stdout: exportResult.stdout, + }, + } + ); + } + + let tempStat: NotebookSnapshotFileStat | null; + try { + tempStat = await fs.stat(tempPath); + } catch (err) { + if (getErrorCode(err) === 'ENOENT') { + tempStat = null; + } else { + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to stat exported snapshot temp file '${tempPath}'.`, + { cause: err } + ); + } + } + + if (tempStat === null || !tempStat.isFile || tempStat.size <= 0) { + throw new NotebookSnapshotError( + 'EXPORT_EMPTY', + `marimo export html produced missing or empty output at '${tempPath}'.` + ); + } + + let exportedBytes: Uint8Array; + try { + exportedBytes = await fs.readBytes(tempPath); + } catch (err) { + if (getErrorCode(err) === 'ENOENT') { + throw new NotebookSnapshotError( + 'EXPORT_EMPTY', + `Exported snapshot temp file '${tempPath}' disappeared before read.`, + { cause: err } + ); + } + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to read exported snapshot temp file '${tempPath}'.`, + { cause: err } + ); + } + + if (!(exportedBytes instanceof Uint8Array) || exportedBytes.byteLength === 0) { + throw new NotebookSnapshotError( + 'EXPORT_EMPTY', + `marimo export html produced zero bytes at '${tempPath}'.` + ); + } + + const sha256 = await sha256HexNodeCrypto(exportedBytes); + const receipt: NotebookSnapshotReceipt = Object.freeze({ + notebookPath, + outputPath, + bytes: exportedBytes.byteLength, + sha256, + checkDiagnostics, + }); + + try { + await fs.rename(tempPath, outputPath); + tempOwned = false; + } catch (err) { + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + `Failed to atomically publish snapshot from '${tempPath}' to '${outputPath}'.`, + { cause: err } + ); + } + + return receipt; + } catch (err) { + if (tempOwned) { + try { + await fs.remove(tempPath); + } catch { + // Preserve the primary error if temp cleanup also fails. + } + } + if (err instanceof NotebookSnapshotError) { + throw err; + } + throw new NotebookSnapshotError( + 'EXPORT_FAILED', + 'Unexpected failure during notebook snapshot export.', + { cause: err } + ); + } +} diff --git a/libs/research/test/notebook-snapshot.test.ts b/libs/research/test/notebook-snapshot.test.ts new file mode 100644 index 00000000..04531912 --- /dev/null +++ b/libs/research/test/notebook-snapshot.test.ts @@ -0,0 +1,765 @@ +import { createHash } from 'node:crypto'; +import { describe, expect, test } from 'bun:test'; +import { exportNotebookSnapshot as barrelExportNotebookSnapshot } from '../src/index'; +import { + DEFAULT_MARIMO_COMMAND, + DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS, + exportNotebookSnapshot, + NotebookSnapshotError, + type NotebookCommandResult, + type NotebookCommandRunner, + type NotebookCommandRunOptions, + type NotebookSnapshotFileStat, + type NotebookSnapshotFs, +} from '../src/notebook-snapshot'; + +interface RecordedCall { + readonly command: string; + readonly args: readonly string[]; + readonly options: NotebookCommandRunOptions; +} + +interface FakeFsEntry { + readonly isFile: boolean; + bytes: Uint8Array; +} + +class InMemoryNotebookFs implements NotebookSnapshotFs { + readonly entries = new Map(); + readonly createdTempPaths: string[] = []; + readonly removedPaths: string[] = []; + readonly renames: Array<{ readonly from: string; readonly to: string }> = []; + failRenameError: Error | null = null; + failRemoveError: Error | null = null; + + putFile(path: string, content: string | Uint8Array): void { + const bytes = + typeof content === 'string' ? new TextEncoder().encode(content) : new Uint8Array(content); + this.entries.set(path, { isFile: true, bytes }); + } + + putDirectory(path: string): void { + this.entries.set(path, { isFile: false, bytes: new Uint8Array(0) }); + } + + getBytes(path: string): Uint8Array | undefined { + const entry = this.entries.get(path); + return entry?.isFile ? entry.bytes : undefined; + } + + getText(path: string): string | undefined { + const bytes = this.getBytes(path); + return bytes ? new TextDecoder().decode(bytes) : undefined; + } + + async stat(path: string): Promise { + const entry = this.entries.get(path); + if (!entry) { + return null; + } + return { isFile: entry.isFile, size: entry.bytes.byteLength }; + } + + async createExclusive(path: string): Promise { + if (this.entries.has(path)) { + const err = new Error(`EEXIST: file already exists '${path}'`) as Error & { code: string }; + err.code = 'EEXIST'; + throw err; + } + this.entries.set(path, { isFile: true, bytes: new Uint8Array(0) }); + this.createdTempPaths.push(path); + } + + async readBytes(path: string): Promise { + const entry = this.entries.get(path); + if (!entry || !entry.isFile) { + const err = new Error(`ENOENT: no such file '${path}'`) as Error & { code: string }; + err.code = 'ENOENT'; + throw err; + } + return new Uint8Array(entry.bytes); + } + + async rename(sourcePath: string, destinationPath: string): Promise { + if (this.failRenameError) { + throw this.failRenameError; + } + const entry = this.entries.get(sourcePath); + if (!entry) { + const err = new Error(`ENOENT: no such file '${sourcePath}'`) as Error & { code: string }; + err.code = 'ENOENT'; + throw err; + } + this.entries.delete(sourcePath); + this.entries.set(destinationPath, entry); + this.renames.push({ from: sourcePath, to: destinationPath }); + } + + async remove(path: string): Promise { + this.removedPaths.push(path); + if (this.failRemoveError) { + throw this.failRemoveError; + } + this.entries.delete(path); + } +} + +type RunnerHandler = ( + command: string, + args: readonly string[], + options: NotebookCommandRunOptions, + callIndex: number +) => Promise; + +function createRecordingRunner(handler: RunnerHandler): { + readonly runner: NotebookCommandRunner; + readonly calls: RecordedCall[]; +} { + const calls: RecordedCall[] = []; + const runner: NotebookCommandRunner = { + async run(command, args, options) { + const callIndex = calls.length; + calls.push({ command, args: [...args], options: { ...options } }); + return handler(command, args, options, callIndex); + }, + }; + return { runner, calls }; +} + +function makeTimeoutError(message = 'Command timed out'): Error & { code: string } { + const err = new Error(message) as Error & { code: string }; + err.code = 'ETIMEDOUT'; + return err; +} + +async function expectSnapshotError( + promise: Promise, + expectedCode: NotebookSnapshotError['code'] +): Promise { + try { + await promise; + } catch (err) { + expect(err).toBeInstanceOf(NotebookSnapshotError); + const snapshotErr = err as NotebookSnapshotError; + expect(snapshotErr.code).toBe(expectedCode); + return snapshotErr; + } + throw new Error(`Expected NotebookSnapshotError(${expectedCode}), but promise resolved.`); +} + +describe('exportNotebookSnapshot', () => { + test('is re-exported from the @stock-bot/research barrel', () => { + expect(barrelExportNotebookSnapshot).toBe(exportNotebookSnapshot); + }); + + test('happy path: runs check then export html with exact argv, publishes via sibling temp rename, and returns frozen receipt with exact non-ASCII bytes and sha256', async () => { + const fs = new InMemoryNotebookFs(); + const notebookPath = '/workspace/research/notebooks/study.py'; + const outputPath = '/workspace/artifacts/study.html'; + fs.putFile(notebookPath, 'import marimo\n'); + + const nonAsciiHtml = + '

CA Shorts — €100 / 日本語

'; + const expectedBytes = new TextEncoder().encode(nonAsciiHtml); + const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex'); + + const cleanReport = { + issues: [], + summary: { errored: false, total_files: 1 }, + }; + + const { runner, calls } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: JSON.stringify(cleanReport), stderr: '' }; + } + const outFlagIdx = args.indexOf('-o'); + const tempPath = args[outFlagIdx + 1] as string; + fs.putFile(tempPath, expectedBytes); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const receipt = await exportNotebookSnapshot({ + notebookPath, + outputPath, + runner, + fs, + allowedNotebookRoot: '/workspace/research/notebooks', + allowedOutputRoot: '/workspace/artifacts', + }); + + expect(calls).toHaveLength(2); + expect(calls[0]).toEqual({ + command: DEFAULT_MARIMO_COMMAND, + args: ['check', '--format=json', notebookPath], + options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS }, + }); + + expect(fs.createdTempPaths).toHaveLength(1); + const tempPath = fs.createdTempPaths[0] as string; + expect(tempPath.startsWith('/workspace/artifacts/')).toBe(true); + expect(tempPath.endsWith('.html')).toBe(true); + expect(tempPath).not.toBe(outputPath); + + expect(calls[1]).toEqual({ + command: DEFAULT_MARIMO_COMMAND, + args: ['export', 'html', notebookPath, '-o', tempPath, '--force'], + options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS }, + }); + + expect(fs.renames).toEqual([{ from: tempPath, to: outputPath }]); + expect(fs.getBytes(tempPath)).toBeUndefined(); + expect(fs.getBytes(outputPath)).toEqual(expectedBytes); + + expect(Object.isFrozen(receipt)).toBe(true); + expect(Object.isFrozen(receipt.checkDiagnostics)).toBe(true); + expect(receipt).toEqual({ + notebookPath, + outputPath, + bytes: expectedBytes.byteLength, + sha256: expectedSha256, + checkDiagnostics: cleanReport, + }); + }); + + test('passes custom marimoCommand, timeoutMs, cwd, and notebook paths with spaces and shell metacharacters as single unmodified argv elements', async () => { + const fs = new InMemoryNotebookFs(); + const trickyNotebook = "/work/my notebooks/study $(rm -rf) & 'quote'; echo hi | cat.py"; + const outputPath = '/work/out/report snapshot.html'; + fs.putFile(trickyNotebook, 'import marimo\n'); + + const { runner, calls } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'ok'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const receipt = await exportNotebookSnapshot({ + notebookPath: trickyNotebook, + outputPath, + runner, + fs, + marimoCommand: '/opt/uv/bin/marimo', + timeoutMs: 45_000, + cwd: '/work', + }); + + expect(calls).toHaveLength(2); + expect(calls[0]?.command).toBe('/opt/uv/bin/marimo'); + expect(calls[0]?.args).toEqual(['check', '--format=json', trickyNotebook]); + expect(calls[0]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 }); + expect(calls[1]?.command).toBe('/opt/uv/bin/marimo'); + expect(calls[1]?.args[2]).toBe(trickyNotebook); + expect(calls[1]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 }); + expect(receipt.checkDiagnostics).toBeNull(); + }); + + test('accepts formatting and runtime advisories on clean exit 0', async () => { + const fs = new InMemoryNotebookFs(); + const notebookPath = '/work/nb.py'; + const outputPath = '/work/out.html'; + fs.putFile(notebookPath, 'import marimo\n'); + + const advisoryReport = { + issues: [ + { code: 'MF001', severity: 'formatting', message: 'Formatting suggestion' }, + { code: 'MR001', severity: 'runtime', message: 'Runtime advisory' }, + ], + summary: { errored: false, total_files: 1 }, + }; + + const { runner, calls } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: JSON.stringify(advisoryReport), stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'advisory ok'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const receipt = await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }); + expect(calls).toHaveLength(2); + expect(receipt.checkDiagnostics).toEqual(advisoryReport); + expect(Object.isFrozen(receipt.checkDiagnostics?.issues)).toBe(true); + }); + + test('never invokes export when marimo check exits non-zero and preserves parsed diagnostics', async () => { + const fs = new InMemoryNotebookFs(); + const notebookPath = '/work/bad.py'; + const outputPath = '/work/out.html'; + fs.putFile(notebookPath, 'def broken(:\n'); + + const failureReport = { + issues: [{ code: 'MB001', severity: 'breaking', message: 'Syntax error' }], + summary: { errored: true, total_files: 1 }, + }; + + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 1, + stdout: JSON.stringify(failureReport), + stderr: 'check failed', + })); + + const err = await expectSnapshotError( + exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }), + 'CHECK_FAILED' + ); + + expect(calls).toHaveLength(1); + expect(calls[0]?.args[0]).toBe('check'); + expect(fs.createdTempPaths).toHaveLength(0); + expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(failureReport); + }); + + test('nonzero check exit takes precedence as CHECK_FAILED even when stdout is non-JSON', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/bad.py', 'import marimo\n'); + + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 2, + stdout: 'not json at all', + stderr: 'fatal error', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/bad.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'CHECK_FAILED' + ); + expect(calls).toHaveLength(1); + }); + + test('never invokes export when check exits 0 with malformed JSON or invalid report shape', async () => { + const badOutputs = [ + '{not-valid-json', + '[]', + '{}', + JSON.stringify({ issues: 'not-an-array', summary: { errored: false, total_files: 1 } }), + JSON.stringify({ issues: [], summary: { errored: 'false', total_files: 1 } }), + JSON.stringify({ issues: [], summary: { errored: false, total_files: 0 } }), + JSON.stringify({ issues: [], summary: { errored: false, total_files: 2 } }), + JSON.stringify({ issues: [123], summary: { errored: false, total_files: 1 } }), + ]; + + for (const stdout of badOutputs) { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout, + stderr: '', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'CHECK_OUTPUT_INVALID' + ); + expect(calls).toHaveLength(1); + expect(fs.createdTempPaths).toHaveLength(0); + } + }); + + test('never invokes export when check exits 0 with summary.errored, file error, or breaking diagnostic', async () => { + const blockingReports = [ + { issues: [], summary: { errored: true, total_files: 1 } }, + { + issues: [{ type: 'error', message: 'Failed to parse notebook' }], + summary: { errored: false, total_files: 1 }, + }, + { + issues: [{ code: 'MB002', severity: 'breaking', message: 'Cycle detected' }], + summary: { errored: false, total_files: 1 }, + }, + { + issues: [ + { + file: '/work/nb.py', + diagnostics: [{ code: 'MB003', severity: 'breaking', message: 'Multiple definitions' }], + }, + ], + summary: { errored: false, total_files: 1 }, + }, + ]; + + for (const report of blockingReports) { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout: JSON.stringify(report), + stderr: '', + })); + + const err = await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'CHECK_FAILED' + ); + expect(calls).toHaveLength(1); + expect(fs.createdTempPaths).toHaveLength(0); + expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(report); + } + }); + + test('maps check timeout to TIMEOUT and never invokes export', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'original'); + + const { runner, calls } = createRecordingRunner(async () => { + throw makeTimeoutError('check timed out'); + }); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + timeoutMs: 5_000, + }), + 'TIMEOUT' + ); + + expect(calls).toHaveLength(1); + expect(fs.createdTempPaths).toHaveLength(0); + expect(fs.getText('/work/out.html')).toBe('original'); + }); + + test('fail-closed export: nonzero exit after partial HTML write removes temp and preserves existing destination', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'original-good-snapshot'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'partial-broken-cell-output'); + return { exitCode: 1, stdout: '', stderr: 'ZeroDivisionError in cell 3' }; + }); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'EXPORT_FAILED' + ); + + expect(fs.createdTempPaths).toHaveLength(1); + const tempPath = fs.createdTempPaths[0] as string; + expect(fs.removedPaths).toContain(tempPath); + expect(fs.getBytes(tempPath)).toBeUndefined(); + expect(fs.getText('/work/out.html')).toBe('original-good-snapshot'); + }); + + test('fail-closed export: missing or zero-byte temp output throws EXPORT_EMPTY, cleans temp, and preserves destination', async () => { + for (const mode of ['zero-byte', 'missing'] as const) { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'keep-me'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + if (mode === 'missing') { + fs.entries.delete(tempPath); + } + // In 'zero-byte' mode, tempPath stays at 0 bytes from createExclusive. + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'EXPORT_EMPTY' + ); + + const tempPath = fs.createdTempPaths[0] as string; + expect(fs.removedPaths).toContain(tempPath); + expect(fs.getBytes(tempPath)).toBeUndefined(); + expect(fs.getText('/work/out.html')).toBe('keep-me'); + } + }); + + test('fail-closed export: export timeout after partial write throws TIMEOUT, removes temp, and preserves destination', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'keep-original'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'partial-before-timeout'); + throw makeTimeoutError('export timed out'); + }); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + timeoutMs: 1_000, + }), + 'TIMEOUT' + ); + + const tempPath = fs.createdTempPaths[0] as string; + expect(fs.removedPaths).toContain(tempPath); + expect(fs.getBytes(tempPath)).toBeUndefined(); + expect(fs.getText('/work/out.html')).toBe('keep-original'); + }); + + test('fail-closed export: rename failure throws EXPORT_FAILED, removes temp, preserves destination, and preserves primary error if cleanup fails', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'prior-snapshot'); + fs.failRenameError = new Error('EXDEV: cross-device link not permitted'); + fs.failRemoveError = new Error('EIO: cleanup failed'); + + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + const tempPath = args[args.indexOf('-o') + 1] as string; + fs.putFile(tempPath, 'new-snapshot'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const err = await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'EXPORT_FAILED' + ); + + expect(err.cause).toBe(fs.failRenameError); + expect(fs.removedPaths).toContain(fs.createdTempPaths[0] as string); + expect(fs.getText('/work/out.html')).toBe('prior-snapshot'); + }); + + test('overlapping exports to the same outputPath reserve separate temp files without partial publication', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + fs.putFile('/work/out.html', 'initial'); + + let releaseFirstExport: (() => void) | null = null; + const firstExportStarted = new Promise(resolve => { + releaseFirstExport = resolve; + }); + let unblockFirstExport: (() => void) | null = null; + const gateFirstExport = new Promise(resolve => { + unblockFirstExport = resolve; + }); + + let exportCount = 0; + const { runner } = createRecordingRunner(async (_cmd, args) => { + if (args[0] === 'check') { + return { exitCode: 0, stdout: '', stderr: '' }; + } + exportCount += 1; + const myExport = exportCount; + const tempPath = args[args.indexOf('-o') + 1] as string; + if (myExport === 1) { + fs.putFile(tempPath, 'snapshot-A'); + releaseFirstExport?.(); + await gateFirstExport; + return { exitCode: 0, stdout: '', stderr: '' }; + } + fs.putFile(tempPath, 'snapshot-B'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + + const firstPromise = exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }); + await firstExportStarted; + + const secondReceipt = await exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }); + expect(fs.getText('/work/out.html')).toBe('snapshot-B'); + + unblockFirstExport?.(); + const firstReceipt = await firstPromise; + + expect(fs.createdTempPaths).toHaveLength(2); + expect(fs.createdTempPaths[0]).not.toBe(fs.createdTempPaths[1]); + expect(firstReceipt.bytes).toBe(new TextEncoder().encode('snapshot-A').byteLength); + expect(secondReceipt.bytes).toBe( + new TextEncoder().encode('snapshot-B').byteLength + ); + expect(fs.getText('/work/out.html')).toBe('snapshot-A'); + }); + + test('rejects invalid paths before any runner call', async () => { + const cases: Array<{ + readonly name: string; + readonly notebookPath: string; + readonly outputPath: string; + readonly allowedNotebookRoot?: string; + readonly allowedOutputRoot?: string; + }> = [ + { name: 'non-.py notebook', notebookPath: '/work/nb.txt', outputPath: '/work/out.html' }, + { name: 'bare .py filename', notebookPath: '/work/.py', outputPath: '/work/out.html' }, + { + name: 'trailing slash notebook', + notebookPath: '/work/nb.py/', + outputPath: '/work/out.html', + }, + { name: 'non-.html output', notebookPath: '/work/nb.py', outputPath: '/work/out.htm' }, + { name: 'bare .html filename', notebookPath: '/work/nb.py', outputPath: '/work/.html' }, + { name: 'relative notebook', notebookPath: 'research/nb.py', outputPath: '/work/out.html' }, + { name: 'relative output', notebookPath: '/work/nb.py', outputPath: './out.html' }, + { name: 'leading dash notebook', notebookPath: '-nb.py', outputPath: '/work/out.html' }, + { name: 'leading dash output', notebookPath: '/work/nb.py', outputPath: '--out.html' }, + { name: 'NUL in notebook', notebookPath: '/work/nb\0.py', outputPath: '/work/out.html' }, + { name: 'NUL in output', notebookPath: '/work/nb.py', outputPath: '/work/out\0.html' }, + { + name: '.. escape outside allowedNotebookRoot', + notebookPath: '/work/notebooks/../secret.py', + outputPath: '/work/out/report.html', + allowedNotebookRoot: '/work/notebooks', + }, + { + name: '.. escape outside allowedOutputRoot', + notebookPath: '/work/notebooks/nb.py', + outputPath: '/work/out/../evil.html', + allowedOutputRoot: '/work/out', + }, + { + name: 'same-prefix sibling notebook root', + notebookPath: '/work/notebooks-other/nb.py', + outputPath: '/work/out/report.html', + allowedNotebookRoot: '/work/notebooks', + }, + { + name: 'same-prefix sibling output root', + notebookPath: '/work/notebooks/nb.py', + outputPath: '/work/out-other/report.html', + allowedOutputRoot: '/work/out', + }, + ]; + + for (const tc of cases) { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout: '', + stderr: '', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: tc.notebookPath, + outputPath: tc.outputPath, + runner, + fs, + ...(tc.allowedNotebookRoot !== undefined + ? { allowedNotebookRoot: tc.allowedNotebookRoot } + : {}), + ...(tc.allowedOutputRoot !== undefined + ? { allowedOutputRoot: tc.allowedOutputRoot } + : {}), + }), + 'INVALID_PATH' + ); + expect(calls).toHaveLength(0); + } + }); + + test('rejects missing notebook or directory in place of notebook with NOTEBOOK_NOT_FOUND and zero runner calls', async () => { + for (const setup of ['missing', 'directory'] as const) { + const fs = new InMemoryNotebookFs(); + if (setup === 'directory') { + fs.putDirectory('/work/nb.py'); + } + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout: '', + stderr: '', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + }), + 'NOTEBOOK_NOT_FOUND' + ); + expect(calls).toHaveLength(0); + } + }); + + test('rejects invalid timeoutMs or marimoCommand with INVALID_OPTION and zero runner calls', async () => { + const fs = new InMemoryNotebookFs(); + fs.putFile('/work/nb.py', 'import marimo\n'); + const { runner, calls } = createRecordingRunner(async () => ({ + exitCode: 0, + stdout: '', + stderr: '', + })); + + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + timeoutMs: 0, + }), + 'INVALID_OPTION' + ); + await expectSnapshotError( + exportNotebookSnapshot({ + notebookPath: '/work/nb.py', + outputPath: '/work/out.html', + runner, + fs, + marimoCommand: '-evil', + }), + 'INVALID_OPTION' + ); + expect(calls).toHaveLength(0); + }); +});