diff --git a/README.md b/README.md index 7837eec..db7d38b 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,27 @@ npm run bioflow -- report --format markdown --out ./reports ## Clean a sample sheet +Check the file and review proposed corrections before writing any output: + +```bash +npm run bioflow -- validate-sample-sheet ./SampleSheet.csv +npm run bioflow -- preview-sample-sheet ./SampleSheet.csv +# For the complete proposed file and a machine-readable review: +npm run bioflow -- preview-sample-sheet ./SampleSheet.csv --json +``` + +These commands are read-only and use the built-in `sample-sheet-v1` profile. Validation reports whether cleanup accepts the input and whether it would change it. Preview shows header and cell changes, warnings, and a review hash. Invalid files produce an error instead of partial proposed output. + +Preview displays up to 1,000 cell changes and warns when the list is capped. JSON includes the complete proposed file in `cleanedText`, which should be reviewed before accepting a large cleanup. + +To accept a reviewed preview, pass its hash to cleanup: + +```bash +npm run bioflow -- tidy ./SampleSheet.csv --accept-preview --out ./cleaned/run-001 +``` + +Cleanup refuses the hash if the input, profile, or proposed output has changed. It uses the reviewed input bytes for the accepted run. Running `tidy` without this option retains its existing direct-cleanup behavior. + Normalize sample IDs, indexes, and lane values while retaining other metadata: ```bash diff --git a/docs/LOCAL_SAMPLE_SHEET.md b/docs/LOCAL_SAMPLE_SHEET.md index bd6d5a5..c121669 100644 --- a/docs/LOCAL_SAMPLE_SHEET.md +++ b/docs/LOCAL_SAMPLE_SHEET.md @@ -24,6 +24,28 @@ Public Nix validation and Conventional Commit checks run on hosted GitHub runner ## Run, verify, and report +### Review before cleanup + +```bash +bioflow validate-sample-sheet ./SampleSheet.csv --json +bioflow preview-sample-sheet ./SampleSheet.csv --json +bioflow tidy ./SampleSheet.csv --accept-preview --base-dir ./evidence --out ./cleaned/run-001 +``` + +Validation and preview do not create runs, configuration, exports, or audit records, and do not modify the input. They use the local built-in `sample-sheet-v1` profile, with no remote requests. `--profile sample-sheet-v1` may be supplied explicitly; other profiles are not supported by these two commands. + +A validation success means the file is accepted by cleanup, not that it is already normalized or compatible with a particular instrument. `needsChanges` reports whether the resulting file bytes would differ. Invalid input reports the first blocking error and returns status 1. Syntax errors return 2. Correctable changes and warnings return 0 with `valid: true`. + +The preview includes original and proposed headers, cell changes, warnings, complete proposed text (`cleanedText` in JSON), and input/output/profile hashes. Rows are numbered from 1 in the nonblank data records, matching the cleanup ID map; these are not physical line numbers. Added or removed empty cells are represented by header changes. Formatting changes such as delimiter, BOM removal, quoting, blank records, and line endings can change the file even when the cell-change list is empty. Human output escapes cell values; use `--json` to inspect the complete proposed text and all formatting. + +The preview hash binds the exact input bytes, validated profile rules, and complete review including the proposed output. `tidy --accept-preview` recomputes the review before creating a run and rejects a mismatch. It stores the matching input snapshot, so later edits to the source cannot change that accepted run. After an input edit, profile change, or implementation upgrade that changes the review, generate and review a fresh preview. The hash verifies a matching review; it is not a signature or evidence of a particular person's approval. + +`tidy` without `--accept-preview` keeps its direct-cleanup behavior. Review commands are new source-checkout capabilities and are not present in the previously published v0.0.2 package. + +Validation counts cell changes without retaining a detailed list. Preview retains at most 1,000 cell changes in row order and reports the full `changeCount` and `changesTruncated` flag. Human output explicitly warns when details are capped. JSON still contains the complete proposed file in `cleanedText`; inspect it before accepting a capped review. Header and formatting changes are separate from the cell count. Acceptance applies to the complete proposed cleanup; to change only selected values, edit the input and generate a fresh preview. + +### Execute and verify + Choose a fresh export directory for each invocation: ```bash diff --git a/flake.nix b/flake.nix index 795e127..c4d19d9 100644 --- a/flake.nix +++ b/flake.nix @@ -130,7 +130,12 @@ cd "$TMPDIR" printf 'Sample_ID,Index,Note\nalpha-1,acgt,"quoted, metadata"\n' > sample.csv bioflow --help | grep -F 'Usage:' - bioflow tidy sample.csv --base-dir ./evidence --run-id nix-installed-smoke --out ./cleaned + bioflow validate-sample-sheet sample.csv --json > validation.json + bioflow preview-sample-sheet sample.csv --json > preview.json + test ! -e .bioflow + preview_hash="$(node -e 'process.stdout.write(require("./preview.json").previewSha256)')" + bioflow tidy sample.csv --accept-preview "$preview_hash" --base-dir ./evidence --run-id nix-installed-smoke --out ./cleaned + node -e 'const fs = require("fs"); const expected = require("./preview.json").cleanedText; if (fs.readFileSync("cleaned/tidy.sample-sheet-v1.clean.csv", "utf8") !== expected) throw new Error("Accepted output differs from preview");' bioflow verify nix-installed-smoke --base-dir ./evidence bioflow report nix-installed-smoke --base-dir ./evidence --out ./reports grep -F 'ALPHA_1,ACGT,"quoted, metadata"' cleaned/tidy.sample-sheet-v1.data.csv diff --git a/src/clean/review.ts b/src/clean/review.ts new file mode 100644 index 0000000..85ee609 --- /dev/null +++ b/src/clean/review.ts @@ -0,0 +1,63 @@ +import { open } from "node:fs/promises"; +import { sha256Hex, sha256Json } from "../core/hash.js"; +import { MAX_SAMPLE_SHEET_BYTES, reviewSampleSheetText, SampleSheetProfileSchema } from "./sample-sheet.js"; + +export async function readSampleSheetBytes(filePath: string): Promise { + const file = await open(filePath, "r"); + try { + const info = await file.stat(); + if (!info.isFile()) throw new Error("Sample sheet input must be a regular file"); + if (info.size > MAX_SAMPLE_SHEET_BYTES) throw new Error("Sample sheet exceeds the 10 MiB input limit"); + const chunks: Buffer[] = []; + for await (const chunk of file.createReadStream({ start: 0, end: MAX_SAMPLE_SHEET_BYTES, autoClose: false })) { + chunks.push(Buffer.from(chunk)); + } + const bytes = Buffer.concat(chunks); + if (bytes.length > MAX_SAMPLE_SHEET_BYTES) throw new Error("Sample sheet exceeds the 10 MiB input limit"); + return bytes; + } finally { await file.close(); } +} + +function buildReview(bytes: Uint8Array, profile: unknown, maxChanges: number) { + if (bytes.byteLength > MAX_SAMPLE_SHEET_BYTES) throw new Error("Sample sheet exceeds the 10 MiB input limit"); + let text: string; + try { + // Retain the BOM for the before/after comparison; cleanup removes it. + text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); + } catch { + throw new Error("Sample sheet must be valid UTF-8; convert the input encoding before cleanup"); + } + const parsedProfile = SampleSheetProfileSchema.parse(profile); + const result = reviewSampleSheetText(text, parsedProfile, maxChanges); + const inputSha256 = sha256Hex(bytes); + const outputSha256 = sha256Hex(new TextEncoder().encode(result.cleaned.cleanedText)); + const preview = { + schemaVersion: "sample-sheet-preview.v1", + valid: true as const, + needsChanges: inputSha256 !== outputSha256, + inputSha256, + outputSha256, + profile: { id: parsedProfile.id, version: parsedProfile.version, sha256: sha256Json(parsedProfile) }, + kind: result.cleaned.kind, + rowCount: result.cleaned.idMappings.length, + columns: { before: result.inputColumns, after: result.cleaned.outputColumns }, + changes: result.changes, + changeCount: result.changeCount, + changesTruncated: result.changeCount > result.changes.length, + warnings: result.cleaned.warnings, + // Formatting changes can exist even when no cell values change. + formatting: { utf8BomRemoved: text.startsWith("\uFEFF"), outputDelimiter: ",", outputRecordNewline: "CRLF" }, + cleanedText: result.cleaned.cleanedText + }; + return preview; +} + +export function previewSampleSheet(bytes: Uint8Array, profile: unknown) { + const preview = buildReview(bytes, profile, 1_000); + return { ...preview, previewSha256: sha256Json(preview) }; +} + +export function validateSampleSheet(bytes: Uint8Array, profile: unknown) { + const result = buildReview(bytes, profile, 0); + return { schemaVersion: "sample-sheet-validation.v1", valid: true as const, needsChanges: result.needsChanges, rowCount: result.rowCount, changeCount: result.changeCount, warnings: result.warnings, errors: [] }; +} diff --git a/src/clean/sample-sheet.ts b/src/clean/sample-sheet.ts index 3f27e2e..d2a5f02 100644 --- a/src/clean/sample-sheet.ts +++ b/src/clean/sample-sheet.ts @@ -46,6 +46,42 @@ export interface CleanSampleSheetResult { } export function cleanSampleSheetText(input: string, profile: SampleSheetProfile): CleanSampleSheetResult { + return processSampleSheetText(input, profile).cleaned; +} + +export function reviewSampleSheetText(input: string, profile: SampleSheetProfile, maxChanges = 1_000): { + cleaned: CleanSampleSheetResult; + inputColumns: string[]; + changes: Array<{ row: number; column: string; before: string | null; after: string | null }>; + changeCount: number; +} { + if (!Number.isSafeInteger(maxChanges) || maxChanges < 0 || maxChanges > 1_000) throw new Error("Detailed change limit must be between 0 and 1,000"); + const { cleaned, parsed, rows } = processSampleSheetText(input, profile); + const changes: Array<{ row: number; column: string; before: string | null; after: string | null }> = []; + let changeCount = 0; + const columns = [...new Set([...parsed.header, ...cleaned.outputColumns])]; + const inputIndexes = new Map(parsed.header.map((column, index) => [column, index])); + const outputColumns = new Set(cleaned.outputColumns); + rows.forEach((row, index) => { + for (const column of columns) { + const inputIndex = inputIndexes.get(column); + const before = inputIndex === undefined ? null : parsed.rawDataRows[index]![inputIndex] ?? ""; + const after = outputColumns.has(column) ? row[column] ?? "" : null; + // Empty added/removed cells are represented by the header change. + if (before !== after && !(before === null && after === "") && !(before === "" && after === null)) { + changeCount++; + if (changes.length < maxChanges) changes.push({ row: index + 1, column, before, after }); + } + } + }); + return { cleaned, inputColumns: parsed.rawHeader, changes, changeCount }; +} + +function processSampleSheetText(input: string, profile: SampleSheetProfile): { + cleaned: CleanSampleSheetResult; + parsed: ParsedSampleSheet; + rows: Record[]; +} { if (Buffer.byteLength(input, "utf8") > MAX_SAMPLE_SHEET_BYTES) { throw new Error("Sample sheet exceeds the 10 MiB input limit"); } @@ -71,14 +107,14 @@ export function cleanSampleSheetText(input: string, profile: SampleSheetProfile) }) : cleanedDataCsv; - return { + return { parsed, rows, cleaned: { kind: parsed.kind, cleanedText, cleanedDataCsv, outputColumns, idMappings, warnings - }; + } }; } function normalizeText(input: string): string { @@ -94,11 +130,15 @@ type ParsedSampleSheet = suffixLines: string[]; header: string[]; dataRows: Record[]; + rawHeader: string[]; + rawDataRows: string[][]; } | { kind: "simple"; header: string[]; dataRows: Record[]; + rawHeader: string[]; + rawDataRows: string[][]; }; function parseSampleSheet(text: string): ParsedSampleSheet { @@ -116,7 +156,7 @@ function parseSampleSheet(text: string): ParsedSampleSheet { const delimiter = detectDelimiter(tableLines[0]!); const table = parseDelimited(tableLines.join("\n") + "\n", delimiter); - const { header, dataRows } = tableToRecords(table); + const records = tableToRecords(table); const suffixLines = lines.slice(endIdx).filter((l) => l !== undefined); let suffixInQuotes = false; for (const line of suffixLines) { @@ -126,14 +166,13 @@ function parseSampleSheet(text: string): ParsedSampleSheet { suffixInQuotes = quoteStateAfter(line, suffixInQuotes); } - return { kind: "illumina", preludeLines, suffixLines, header, dataRows }; + return { kind: "illumina", preludeLines, suffixLines, ...records }; } // Simple delimited file with a header row. const delimiter = detectDelimiter(lines[0] ?? ""); const table = parseDelimited(text + (text.endsWith("\n") ? "" : "\n"), delimiter); - const { header, dataRows } = tableToRecords(table); - return { kind: "simple", header, dataRows }; + return { kind: "simple", ...tableToRecords(table) }; } function findDataTableBounds( @@ -270,7 +309,7 @@ function parseDelimited(text: string, delimiter: "," | "\t"): string[][] { return rows; } -function tableToRecords(table: string[][]): { header: string[]; dataRows: Record[] } { +function tableToRecords(table: string[][]): { header: string[]; dataRows: Record[]; rawHeader: string[]; rawDataRows: string[][] } { const rawHeader = table[0] ?? []; if (rawHeader.length === 0) throw new Error("Missing header row"); @@ -281,6 +320,7 @@ function tableToRecords(table: string[][]): { header: string[]; dataRows: Record } const dataRows: Record[] = []; + const rawDataRows: string[][] = []; for (let r = 1; r < table.length; r++) { const row = table[r]!; const allEmpty = row.every((c) => String(c ?? "").trim().length === 0); @@ -294,9 +334,10 @@ function tableToRecords(table: string[][]): { header: string[]; dataRows: Record obj[key] = String(row[c] ?? "").trim(); } dataRows.push(obj); + rawDataRows.push(row); } - return { header, dataRows }; + return { header, dataRows, rawHeader, rawDataRows }; } function canonicalizeColumnName(name: string): string { diff --git a/src/cli/main.ts b/src/cli/main.ts index d24d97b..d7d0908 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -13,6 +13,7 @@ import { sha256Json } from "../core/hash.js"; import { stableStringify } from "../core/stable-json.js"; import { sampleSheetV1Profile } from "../clean/profiles/sample-sheet-v1.js"; import { MAX_SAMPLE_SHEET_BYTES } from "../clean/sample-sheet.js"; +import { previewSampleSheet, readSampleSheetBytes, validateSampleSheet } from "../clean/review.js"; import { loadCliConfig, resolveRemoteDefaults, saveCliConfig } from "./config.js"; import { runBioFlowMcp } from "../mcp/main.js"; import type { Workflow } from "../core/types.js"; @@ -135,6 +136,7 @@ type Command = } | { kind: "init"; outPath: string } | { kind: "validate"; workflowPath: string } + | { kind: "sample-sheet-review"; mode: "validate" | "preview"; inputPath: string; json: boolean } | { kind: "run"; workflowPath: string; inputs: string[] } | { kind: "verify"; runId: string; baseDir: string } | { @@ -152,6 +154,7 @@ type Command = outDir?: string | undefined; profileName: string; runId?: string | undefined; + acceptPreview?: string | undefined; remote?: RemoteConfig | undefined; } | { @@ -356,6 +359,46 @@ async function main(): Promise { if (res.outputPath) console.log(`Wrote: ${res.outputPath}`); return; } + case "sample-sheet-review": { + try { + const bytes = await readSampleSheetBytes(path.resolve(cmd.inputPath)); + if (cmd.mode === "validate") { + const validation = validateSampleSheet(bytes, sampleSheetV1Profile); + if (cmd.json) printJson(validation); + else { + console.log(`Valid sample sheet: ${validation.rowCount} data row(s)`); + console.log(validation.needsChanges ? "Cleanup would change this file." : "Cleanup would leave this file unchanged."); + for (const warning of validation.warnings) console.log(`Warning: ${JSON.stringify(warning)}`); + } + return; + } + const preview = previewSampleSheet(bytes, sampleSheetV1Profile); + if (cmd.json) { + printJson(preview); + } else { + console.log(`Valid sample sheet: ${preview.rowCount} data row(s)`); + console.log(preview.needsChanges ? "Cleanup would change this file." : "Cleanup would leave this file unchanged."); + for (const warning of preview.warnings) console.log(`Warning: ${JSON.stringify(warning)}`); + if (cmd.mode === "preview") { + console.log(`Columns before: ${JSON.stringify(preview.columns.before)}`); + console.log(`Columns after: ${JSON.stringify(preview.columns.after)}`); + for (const change of preview.changes) { + console.log(`Row ${change.row}, ${JSON.stringify(change.column)}: ${JSON.stringify(change.before)} -> ${JSON.stringify(change.after)}`); + } + if (preview.changesTruncated) console.log(`Showing ${preview.changes.length} of ${preview.changeCount} cell changes. Before accepting, inspect the complete proposed file using --json (cleanedText).`); + if (preview.needsChanges) console.log("Output uses comma-separated UTF-8 without a BOM and CRLF record endings; blank records and quoting may be normalized. Use --json to inspect the complete proposed file."); + console.log(`Preview SHA-256: ${preview.previewSha256}`); + console.log(`To accept this review, run tidy on the same file with --accept-preview ${preview.previewSha256} and a fresh --out directory.`); + } + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (cmd.json) printJson({ schemaVersion: cmd.mode === "preview" ? "sample-sheet-preview.v1" : "sample-sheet-validation.v1", valid: false, errors: [message] }); + else console.error(`Invalid sample sheet: ${message}`); + process.exitCode = 1; + } + return; + } case "tidy": { const baseDir = cmd.baseDir; const store = new LocalArtifactStore(baseDir); @@ -372,8 +415,18 @@ async function main(): Promise { if (["__workflow.json", "gxp-report.md", "tidy.sample-sheet-v1.clean.csv", "tidy.sample-sheet-v1.data.csv", "tidy.sample-sheet-v1.idmap.json", "tidy.sample-sheet-v1.report.json"].includes(path.basename(inputPath))) { throw new Error("Input filename is reserved for run evidence; rename the input file before cleanup"); } + let approvedBytes: Buffer | undefined; + if (cmd.acceptPreview) { + approvedBytes = await readSampleSheetBytes(inputPath); + const preview = previewSampleSheet(approvedBytes, profile); + if (preview.previewSha256 !== cmd.acceptPreview) { + throw new Error("Preview no longer matches this input, profile, or proposed output; generate and review a new preview before accepting"); + } + } await claimTidyRun(baseDir, runId); - const input = await store.importFile(runId, inputPath); + const input = approvedBytes + ? await store.putBytes({ runId, name: path.basename(inputPath), bytes: approvedBytes, mediaType: path.extname(inputPath).toLowerCase() === ".csv" ? "text/csv" : "application/octet-stream", kind: "input" }) + : await store.importFile(runId, inputPath); const workflow = makeTidyWorkflow({ profile }); const { execution, executionPath } = await runWorkflow({ workflow, @@ -663,6 +716,18 @@ function parseArgs(argv: string[]): Command | null { return { kind: "report", runId, ...opts }; } + if (sub === "validate-sample-sheet" || sub === "preview-sample-sheet") { + const inputPath = rest[0]; + if (!inputPath || inputPath.startsWith("--")) return null; + let json = false; + for (let i = 1; i < rest.length; i++) { + if (rest[i] === "--json") { json = true; continue; } + if (rest[i] === "--profile" && rest[i + 1] === "sample-sheet-v1") { i++; continue; } + return null; + } + return { kind: "sample-sheet-review", mode: sub === "validate-sample-sheet" ? "validate" : "preview", inputPath, json }; + } + if (sub === "tidy") { const inputPath = rest[0]; if (!inputPath) return null; @@ -675,6 +740,7 @@ function parseArgs(argv: string[]): Command | null { outDir: opts.outDir, profileName: opts.profileName, runId: opts.runId, + acceptPreview: opts.acceptPreview, remote: opts.remote }; } @@ -807,10 +873,12 @@ Usage: bioflow autopilot:gate [file] [--max-duration-ms ] [--min-progress-completed ] [--min-progress-ratio <0..1>] [--require-persisted-auth ] [--required-checklist-ids a,b,c] [--json] bioflow init bioflow validate + bioflow validate-sample-sheet [--profile sample-sheet-v1] [--json] + bioflow preview-sample-sheet [--profile sample-sheet-v1] [--json] bioflow run --input [--input ...] bioflow verify [--base-dir ] bioflow report [--format markdown] [--out ] [--base-dir ] [--no-replay] - bioflow tidy [--profile ] [--out ] [--run-id ] [--remote-url ] [--org-id ] [--token ] + bioflow tidy [--profile ] [--out ] [--run-id ] [--accept-preview ] [--remote-url ] [--org-id ] [--token ] bioflow push [--remote-url ] [--org-id ] [--token ] [--dry-run] [--profile-id ] [--tags a,b] [--visibility ] bioflow pull [--remote-url ] [--org-id ] [--token ] [--force] bioflow ls-remote [--remote-url ] [--org-id ] [--token ] [--limit ] [--cursor ] [--profile-id ] [--tags a,b] [--visibility ] @@ -2276,6 +2344,7 @@ function parseTidyOpts(argv: string[]): { outDir?: string | undefined; profileName: string; runId?: string | undefined; + acceptPreview?: string | undefined; remote?: RemoteConfig | undefined; } | null { const remoteDefaults = resolveRemoteDefaults(); @@ -2288,12 +2357,20 @@ function parseTidyOpts(argv: string[]): { let outDir: string | undefined; let profileName = "sample-sheet-v1"; let runId: string | undefined; + let acceptPreview: string | undefined; let remoteUrl = remoteUrlDefault; let token = tokenDefault; let orgId = orgIdDefault; for (let i = 0; i < argv.length; i++) { const arg = argv[i]!; + if (arg === "--accept-preview") { + const value = argv[i + 1]; + if (!value || !/^[a-f0-9]{64}$/.test(value)) return null; + acceptPreview = value; + i++; + continue; + } if (arg === "--base-dir") { const v = argv[i + 1]; if (!v) return null; @@ -2351,6 +2428,7 @@ function parseTidyOpts(argv: string[]): { outDir: outDir ? path.resolve(outDir) : undefined, profileName, runId, + acceptPreview, remote: token || orgId ? { url: remoteUrl, token, orgId } : undefined }; } diff --git a/test/cli-sample-sheet-review.test.ts b/test/cli-sample-sheet-review.test.ts new file mode 100644 index 0000000..d3838f8 --- /dev/null +++ b/test/cli-sample-sheet-review.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from "vitest"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { bioflowCommand } from "../scripts/lib/process-command.js"; +import { sha256Hex } from "../src/core/hash.js"; + +async function workspace() { + const root = await mkdtemp(path.resolve(".bioflow_review_cli_")); + const input = path.join(root, "sample.csv"); + const bytes = Buffer.from('Sample_ID,Index,Note\nalpha-1,acgt,"quoted, metadata"\nalpha 1,TGCA,second\n'); + await writeFile(input, bytes); + const run = (args: string[]) => spawnSync(...bioflowCommand(args), { + cwd: root, encoding: "utf8", env: {...process.env, BIOFLOW_BASE_DIR: path.join(root, "store"), BIOFLOW_CONFIG_PATH: path.join(root, "config.json")} + }); + return { root, input, bytes, run }; +} + +describe("read-only sample-sheet CLI review and acceptance", () => { + it.each(["validate-sample-sheet", "preview-sample-sheet"])("%s leaves input, config and evidence untouched", async command => { + const w = await workspace(); + try { + const result = w.run([command, w.input, "--json"]); + expect(result.status, result.stderr).toBe(0); + const report = JSON.parse(result.stdout); + expect(report.valid).toBe(true); + expect(report.needsChanges).toBe(true); + expect(report.rowCount).toBe(2); + expect(await readFile(w.input)).toEqual(w.bytes); + expect(await readdir(w.root)).toEqual(["sample.csv"]); + if (command === "preview-sample-sheet") { + expect(report.changes).toContainEqual({row: 2, column: "Sample_ID", before: "alpha 1", after: "ALPHA_1_001"}); + expect(report.previewSha256).toMatch(/^[a-f0-9]{64}$/); + } + } finally { await rm(w.root, {recursive: true, force: true}); } + }); + + it("writes exactly the reviewed output when the preview is accepted, then verifies the run", async () => { + const w = await workspace(); + try { + const preview = JSON.parse(w.run(["preview-sample-sheet", w.input, "--json"]).stdout); + const out = path.join(w.root, "cleaned"); + const accepted = w.run(["tidy", w.input, "--accept-preview", preview.previewSha256, "--out", out]); + expect(accepted.status, accepted.stderr).toBe(0); + const bytes = await readFile(path.join(out, "tidy.sample-sheet-v1.clean.csv")); + expect(bytes.toString()).toBe(preview.cleanedText); + expect(sha256Hex(bytes)).toBe(preview.outputSha256); + const runId = accepted.stdout.match(/Run ([\w-]+) -> completed/)?.[1]; + expect(runId).toBeTruthy(); + const verified = w.run(["verify", runId!]); + expect(verified.status, verified.stderr).toBe(0); + expect(await readFile(w.input)).toEqual(w.bytes); + } finally { await rm(w.root, {recursive: true, force: true}); } + }, 20_000); + + it("rejects changed input before creating a run or exports", async () => { + const w = await workspace(); + try { + const preview = JSON.parse(w.run(["preview-sample-sheet", w.input, "--json"]).stdout); + await writeFile(w.input, 'Sample_ID,Index\nDIFFERENT,ACGT\n'); + const result = w.run(["tidy", w.input, "--accept-preview", preview.previewSha256, "--out", path.join(w.root, "cleaned")]); + expect(result.status).toBe(1); + expect(result.stderr).toContain("Preview no longer matches"); + expect(await readdir(w.root)).toEqual(["sample.csv"]); + } finally { await rm(w.root, {recursive: true, force: true}); } + }); + + it.each(["validate-sample-sheet", "preview-sample-sheet"])("%s reports invalid input as JSON with no writes", async command => { + const w = await workspace(); + try { + await writeFile(w.input, 'Sample_ID,Index\nalpha,ACGT,extra\n'); + const result = w.run([command, w.input, "--json"]); + expect(result.status).toBe(1); + expect(result.stderr).toBe(""); + expect(JSON.parse(result.stdout)).toMatchObject({valid: false, errors: [expect.stringContaining("Expected at most")]}); + expect(await readdir(w.root)).toEqual(["sample.csv"]); + } finally { await rm(w.root, {recursive: true, force: true}); } + }); + + it("reports missing files, invalid UTF-8 and oversized files without creating state", async () => { + const w = await workspace(); + try { + expect(w.run(["validate-sample-sheet", path.join(w.root, "missing.csv"), "--json"]).status).toBe(1); + await writeFile(w.input, Buffer.from([0xff])); + expect(JSON.parse(w.run(["preview-sample-sheet", w.input, "--json"]).stdout).errors[0]).toContain("valid UTF-8"); + await writeFile(w.input, Buffer.alloc(10 * 1024 * 1024 + 1)); + expect(JSON.parse(w.run(["preview-sample-sheet", w.input, "--json"]).stdout).errors[0]).toContain("10 MiB"); + expect(await readdir(w.root)).toEqual(["sample.csv"]); + } finally { await rm(w.root, {recursive: true, force: true}); } + }); + + it("escapes multiline and terminal control characters in human-readable cell changes", async () => { + const w = await workspace(); + try { + await writeFile(w.input, 'Sample_ID,Index,Note\nalpha,ACGT," \u001b[31mfirst\nsecond "\n'); + const result = w.run(["preview-sample-sheet", w.input]); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('\\u001b[31mfirst\\nsecond'); + expect(result.stdout).not.toContain('\u001b'); + expect(result.stdout).toContain("--accept-preview"); + } finally { await rm(w.root, {recursive: true, force: true}); } + }); + + it("returns syntax status 2 for write flags, unknown profiles or invalid acceptance hashes", async () => { + const w = await workspace(); + try { + for (const args of [ + ["preview-sample-sheet", w.input, "--out", "writes"], + ["validate-sample-sheet", w.input, "--profile", "remote"], + ["tidy", w.input, "--accept-preview"], + ["tidy", w.input, "--accept-preview", "not-a-hash"] + ]) expect(w.run(args).status).toBe(2); + expect(await readdir(w.root)).toEqual(["sample.csv"]); + } finally { await rm(w.root, {recursive: true, force: true}); } + }); + + it("makes capped details explicit in human and JSON previews and retains the complete proposed file", async () => { + const w = await workspace(); + try { + const header = ['Sample_ID', 'Index', ...Array.from({length: 254}, (_, i) => `Note${i}`)].join(','); + const rows = Array.from({length: 5}, (_, i) => [`ROW_${i}`, 'ACGT', ...Array(254).fill(' value ')].join(',')); + await writeFile(w.input, header + '\n' + rows.join('\n') + '\n'); + const human = w.run(['preview-sample-sheet', w.input]); + expect(human.status, human.stderr).toBe(0); + expect(human.stdout).toContain('Showing 1000 of 1270 cell changes'); + const json = JSON.parse(w.run(['preview-sample-sheet', w.input, '--json']).stdout); + expect(json.changesTruncated).toBe(true); + expect(json.changeCount).toBe(1270); + expect(json.changes).toHaveLength(1000); + expect(json.cleanedText.split('\r\n')[5]).toBe(['ROW_4', 'ACGT', ...Array(254).fill('value')].join(',')); + const validation = JSON.parse(w.run(['validate-sample-sheet', w.input, '--json']).stdout); + expect(validation.changeCount).toBe(1270); + expect(validation).not.toHaveProperty('changes'); + expect(await readdir(w.root)).toEqual(['sample.csv']); + } finally { await rm(w.root, {recursive: true, force: true}); } + }); +}); diff --git a/test/docs-commands.test.ts b/test/docs-commands.test.ts index 09f783f..93b29ec 100644 --- a/test/docs-commands.test.ts +++ b/test/docs-commands.test.ts @@ -24,6 +24,8 @@ const LOCAL_BIOFLOW_SUBCOMMANDS = new Set([ "autopilot:gate", "init", "validate", + "validate-sample-sheet", + "preview-sample-sheet", "run", "verify", "report", diff --git a/test/fixtures/sample-sheet-review-limits.ts b/test/fixtures/sample-sheet-review-limits.ts new file mode 100644 index 0000000..704bd02 --- /dev/null +++ b/test/fixtures/sample-sheet-review-limits.ts @@ -0,0 +1,16 @@ +import assert from "node:assert/strict"; +import { previewSampleSheet, validateSampleSheet } from "../../src/clean/review.js"; +import { sampleSheetV1Profile } from "../../src/clean/profiles/sample-sheet-v1.js"; + +const rows = 8_000; +const header = ["Sample_ID", "Index", ...Array.from({ length: 254 }, (_, i) => `Note${i}`)].join(","); +const row = ["ROW", "ACGT", ...Array(254).fill(" x ")].join(",") + "\n"; +const bytes = Buffer.from(header + "\n" + row.repeat(rows)); +assert.ok(bytes.length < 10 * 1024 * 1024); +const validation = validateSampleSheet(bytes, sampleSheetV1Profile); +assert.equal(validation.changeCount, rows * 254 + rows - 1); +const preview = previewSampleSheet(bytes, sampleSheetV1Profile); +assert.equal(preview.changeCount, validation.changeCount); +assert.equal(preview.changes.length, 1_000); +assert.equal(preview.changesTruncated, true); +console.log(JSON.stringify({ inputBytes: bytes.length, rows, totalCellChanges: preview.changeCount, retainedChanges: preview.changes.length })); diff --git a/test/packaged-cli.test.ts b/test/packaged-cli.test.ts index 399a73d..b2c47b8 100644 --- a/test/packaged-cli.test.ts +++ b/test/packaged-cli.test.ts @@ -115,7 +115,13 @@ describe("packaged CLI", () => { const localStore = path.join(tempDir, "local-store"); const localOut = path.join(tempDir, "cleaned"); await writeFile(samplePath, 'Sample_ID,Index,Note\nalpha-1,acgt,"quoted, metadata"\n'); - const tidy = await runPackagedCli(["tidy", samplePath, "--base-dir", localStore, "--out", localOut], tempDir); + const validation = await runPackagedCli(["validate-sample-sheet", samplePath, "--json"], tempDir); + expect(validation.status, validation.stderr).toBe(0); + expect(JSON.parse(validation.stdout)).toMatchObject({valid: true, needsChanges: true}); + const previewResult = await runPackagedCli(["preview-sample-sheet", samplePath, "--json"], tempDir); + expect(previewResult.status, previewResult.stderr).toBe(0); + const preview = JSON.parse(previewResult.stdout); + const tidy = await runPackagedCli(["tidy", samplePath, "--accept-preview", preview.previewSha256, "--base-dir", localStore, "--out", localOut], tempDir); expect(tidy.status, tidy.stderr).toBe(0); const localRunId = tidy.stdout.match(/Run ([\w-]+) -> completed/)?.[1]; expect(localRunId).toBeTruthy(); @@ -125,11 +131,15 @@ describe("packaged CLI", () => { expect(report.status, report.stderr).toBe(0); const csv = await readFile(path.join(localOut, "tidy.sample-sheet-v1.data.csv"), "utf8"); expect(csv).toContain('ALPHA_1,ACGT,"quoted, metadata"'); + expect(csv).toBe(preview.cleanedText); const collision = await runPackagedCli(["tidy", samplePath, "--base-dir", localStore, "--out", localOut], tempDir); expect(collision.status).toBe(1); expect(collision.stderr).toContain("Refusing to overwrite export"); expect(await readFile(path.join(localOut, "tidy.sample-sheet-v1.data.csv"), "utf8")).toBe(csv); await writeFile(samplePath, "Sample_ID,Index\nalpha,ACGT,extra\n"); + const invalidReview = await runPackagedCli(["validate-sample-sheet", samplePath, "--json"], tempDir); + expect(invalidReview.status).toBe(1); + expect(JSON.parse(invalidReview.stdout).valid).toBe(false); const rejected = await runPackagedCli(["tidy", samplePath, "--base-dir", localStore], tempDir); expect(rejected.status).toBe(1); expect(rejected.stderr).toContain("Expected at most 2 fields"); diff --git a/test/sample-sheet-review.test.ts b/test/sample-sheet-review.test.ts new file mode 100644 index 0000000..5f122a6 --- /dev/null +++ b/test/sample-sheet-review.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from "vitest"; +import { previewSampleSheet, validateSampleSheet } from "../src/clean/review.js"; +import { reviewSampleSheetText } from "../src/clean/sample-sheet.js"; +import { sampleSheetV1Profile } from "../src/clean/profiles/sample-sheet-v1.js"; +import { sha256Hex } from "../src/core/hash.js"; +import { spawnSync } from "node:child_process"; +import { sourceCommand } from "../scripts/lib/process-command.js"; + +const preview = (text: string) => previewSampleSheet(Buffer.from(text), sampleSheetV1Profile); + +describe("sample-sheet correction review", () => { + it("shows exact header, normalization, duplicate-ID, derived-index and metadata changes", () => { + const input = ' Sample Id ,i7 index,Lanes,Project Name\n sample-1 ,acgt+tgca,"3,2,2", project \n sample 1 ,ttaa,1,other\n'; + const result = preview(input); + expect(result.columns).toEqual({before: [" Sample Id ", "i7 index", "Lanes", "Project Name"], after: ["Sample_ID", "Index", "Index2", "Index_Dual", "Lane", "Project_Name"]}); + expect(result.changes).toEqual(expect.arrayContaining([ + {row: 1, column: "Sample_ID", before: " sample-1 ", after: "SAMPLE_1"}, + {row: 2, column: "Sample_ID", before: " sample 1 ", after: "SAMPLE_1_001"}, + {row: 1, column: "Index", before: "acgt+tgca", after: "ACGT"}, + {row: 1, column: "Index2", before: null, after: "TGCA"}, + {row: 1, column: "Index_Dual", before: null, after: "ACGT+TGCA"}, + {row: 1, column: "Lane", before: "3,2,2", after: "2,3"}, + {row: 1, column: "Project_Name", before: " project ", after: "project"} + ])); + expect(result.cleanedText).toBe('Sample_ID,Index,Index2,Index_Dual,Lane,Project_Name\r\nSAMPLE_1,ACGT,TGCA,ACGT+TGCA,"2,3",project\r\nSAMPLE_1_001,TTAA,,,1,other\r\n'); + expect(result.outputSha256).toBe(sha256Hex(result.cleanedText)); + expect(result.inputSha256).toBe(sha256Hex(input)); + expect(result.warnings).toEqual(["Row 1: Lane list contained duplicates; normalized"]); + }); + + it("marks a canonical simple sheet unchanged", () => { + const result = preview('Sample_ID,Index\r\nALPHA,ACGT\r\n'); + expect(result.needsChanges).toBe(false); + expect(result.changes).toEqual([]); + expect(result.inputSha256).toBe(result.outputSha256); + }); + + it("reports formatting-only TSV/BOM/newline changes without inventing cell changes", () => { + const result = preview('\uFEFFSample_ID\tIndex\nALPHA\tACGT\n'); + expect(result.needsChanges).toBe(true); + expect(result.changes).toEqual([]); + expect(result.formatting.utf8BomRemoved).toBe(true); + expect(result.cleanedText).toBe('Sample_ID,Index\r\nALPHA,ACGT\r\n'); + }); + + it("preserves quoted multiline metadata and section-looking text", () => { + const result = preview('[Header]\nVersion,4\n[Data]\nSample_ID,Index,Note\nalpha,ACGT,"first\n\n[Settings]\nlast"\n[Settings]\nsetting,value\n'); + expect(result.changes).toEqual([{row: 1, column: "Sample_ID", before: "alpha", after: "ALPHA"}]); + expect(result.cleanedText).toContain('"first\r\n\r\n[Settings]\r\nlast"'); + expect(result.cleanedText).toContain('[Settings]\r\nsetting,value'); + }); + + it("gives the same review hash for the same bytes and rules, and different hashes for changed metadata or rules", () => { + const input = Buffer.from('Sample_ID,Index,Note\nalpha,ACGT,first\n'); + const result = previewSampleSheet(input, sampleSheetV1Profile); + expect(previewSampleSheet(input, structuredClone(sampleSheetV1Profile)).previewSha256).toBe(result.previewSha256); + expect(preview('Sample_ID,Index,Note\nalpha,ACGT,second\n').previewSha256).not.toBe(result.previewSha256); + const profile = structuredClone(sampleSheetV1Profile); + profile.rules.sampleId.maxLen = 31; // Even rules that leave these rows unchanged must be bound. + expect(previewSampleSheet(input, profile).previewSha256).not.toBe(result.previewSha256); + }); + + it.each([ + ['Sample_ID,Index\nalpha,ACGT,extra\n', /Expected at most/], + ['Sample_ID,Index,Note\nalpha,ACGT,"unfinished\n', /Unterminated/], + ['Sample_ID,Index\nalpha,1234\n', /IUPAC/], + ['Sample_ID,Index\n,ACGT\n', /Sample_ID is required/] + ])("rejects invalid input instead of proposing partial output", (input, error) => { + expect(() => preview(input)).toThrow(error); + }); + + it("rejects invalid UTF-8 and oversized inputs", () => { + expect(() => previewSampleSheet(Buffer.from([0xff]), sampleSheetV1Profile)).toThrow("valid UTF-8"); + expect(() => previewSampleSheet(Buffer.alloc(10 * 1024 * 1024 + 1), sampleSheetV1Profile)).toThrow("10 MiB"); + }); + + it("bounds details on a wide file while counting every change and preserving complete proposed output", () => { + const header = ["Sample_ID", "Index", ...Array.from({length: 254}, (_, i) => `Note${i}`)].join(','); + const row = (index: number) => [`ROW_${index}`, "ACGT", ...Array(254).fill(' value ')].join(','); + const input = header + '\r\n' + Array.from({length: 20}, (_, i) => row(i)).join('\r\n') + '\r\n'; + const summary = reviewSampleSheetText(input, sampleSheetV1Profile, 0); + expect(summary.changes).toEqual([]); + expect(summary.changeCount).toBe(20 * 254); + const validation = validateSampleSheet(Buffer.from(input), sampleSheetV1Profile); + expect(validation.changeCount).toBe(20 * 254); + expect(validation).not.toHaveProperty("changes"); + const result = preview(input); + expect(result.changes).toHaveLength(1_000); + expect(result.changeCount).toBe(20 * 254); + expect(result.changesTruncated).toBe(true); + expect(result.cleanedText.split('\r\n')[20]).toBe(['ROW_19', 'ACGT', ...Array(254).fill('value')].join(',')); + expect(result.outputSha256).toBe(sha256Hex(result.cleanedText)); + }); + + it("handles an 8 MB, two-million-change review within a 512 MB Node heap", () => { + const [command, args] = sourceCommand("test/fixtures/sample-sheet-review-limits.ts"); + const result = spawnSync(command, ["--max-old-space-size=512", ...args], { encoding: "utf8", timeout: 20_000 }); + expect(result.error).toBeUndefined(); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({rows: 8000, totalCellChanges: 2039999, retainedChanges: 1000}); + }, 25_000); +});