Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,27 @@ npm run bioflow -- report <runId> --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 <previewSha256> --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
Expand Down
22 changes: 22 additions & 0 deletions docs/LOCAL_SAMPLE_SHEET.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <previewSha256> --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
Expand Down
7 changes: 6 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
63 changes: 63 additions & 0 deletions src/clean/review.ts
Original file line number Diff line number Diff line change
@@ -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<Buffer> {
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: [] };
}
57 changes: 49 additions & 8 deletions src/clean/sample-sheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>[];
} {
if (Buffer.byteLength(input, "utf8") > MAX_SAMPLE_SHEET_BYTES) {
throw new Error("Sample sheet exceeds the 10 MiB input limit");
}
Expand All @@ -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 {
Expand All @@ -94,11 +130,15 @@ type ParsedSampleSheet =
suffixLines: string[];
header: string[];
dataRows: Record<string, string>[];
rawHeader: string[];
rawDataRows: string[][];
}
| {
kind: "simple";
header: string[];
dataRows: Record<string, string>[];
rawHeader: string[];
rawDataRows: string[][];
};

function parseSampleSheet(text: string): ParsedSampleSheet {
Expand All @@ -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) {
Expand All @@ -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(
Expand Down Expand Up @@ -270,7 +309,7 @@ function parseDelimited(text: string, delimiter: "," | "\t"): string[][] {
return rows;
}

function tableToRecords(table: string[][]): { header: string[]; dataRows: Record<string, string>[] } {
function tableToRecords(table: string[][]): { header: string[]; dataRows: Record<string, string>[]; rawHeader: string[]; rawDataRows: string[][] } {
const rawHeader = table[0] ?? [];
if (rawHeader.length === 0) throw new Error("Missing header row");

Expand All @@ -281,6 +320,7 @@ function tableToRecords(table: string[][]): { header: string[]; dataRows: Record
}

const dataRows: Record<string, string>[] = [];
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);
Expand All @@ -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 {
Expand Down
Loading
Loading