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
9 changes: 9 additions & 0 deletions .changeset/loose-ducks-lay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@platforma-open/milaboratories.immune-assay-data.workflow": minor
"@platforma-open/milaboratories.immune-assay-data": minor
"@platforma-open/milaboratories.immune-assay-data.model": minor
"@platforma-open/milaboratories.immune-assay-data.kind": minor
"@platforma-open/milaboratories.immune-assay-data.ui": minor
---

Fix trace gap
1 change: 1 addition & 0 deletions block/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"devDependencies": {
"@milaboratories/ts-builder": "catalog:",
"@milaboratories/ts-configs": "catalog:",
"@platforma-open/milaboratories.immune-assay-data.kind": "workspace:*",
"@platforma-open/milaboratories.immune-assay-data.model": "workspace:*",
"@platforma-open/milaboratories.immune-assay-data.ui": "workspace:*",
"@platforma-open/milaboratories.immune-assay-data.workflow": "workspace:*",
Expand Down
4 changes: 4 additions & 0 deletions kind/.oxfmtrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": ["node_modules/@milaboratories/ts-builder/configs/oxfmt.json"],
"ignorePatterns": ["dist", "coverage", "CHANGELOG.md"]
}
3 changes: 3 additions & 0 deletions kind/.oxlintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": ["node_modules/@milaboratories/ts-builder/dist/configs/oxlint-node.json"]
}
38 changes: 38 additions & 0 deletions kind/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "@platforma-open/milaboratories.immune-assay-data.kind",
"version": "1.0.0",
"private": true,
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"sources": "./src/index.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"default": "./dist/index.js"
}
},
"scripts": {
"fmt": "ts-builder format",
"watch": "ts-builder build --target block-kind --watch",
"build": "ts-builder build --target block-kind && block-tools build-kind-manifest",
"check": "ts-builder check --target block-kind"
},
"dependencies": {
"@milaboratories/pl-model-common": "catalog:",
"@platforma-sdk/block-kind": "catalog:",
"es-toolkit": "catalog:"
},
"devDependencies": {
"@milaboratories/ts-builder": "catalog:",
"@milaboratories/ts-configs": "catalog:",
"@platforma-sdk/block-tools": "catalog:"
},
"peerDependencies": {
"@types/node": "*",
"typescript": "*"
}
}
146 changes: 146 additions & 0 deletions kind/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import type { ImportFileHandle, PlRef, SUniversalPColumnId } from "@milaboratories/pl-model-common";
import { isColumnUniversalId, isPlRef } from "@milaboratories/pl-model-common";
import { assertParamsObject, defineBlockKind } from "@platforma-sdk/block-kind";
import { isBoolean, isPlainObject, isString } from "es-toolkit";
import { isArray, isNumber } from "es-toolkit/compat";
import { name, version } from "../package.json" with { type: "json" };

/**
* Matching method and thresholds.
*/
export type Settings = {
coverageThreshold: number;
identity: number;
/**
* `alignment-score` / `sequence-identity` run MMseqs2; `exact-match` reports only
* byte-identical sequences and ignores identity/coverage/fast-mode.
*/
similarityType: "sequence-identity" | "alignment-score" | "exact-match";
};

/** Which upstream the block is pointed at. Lives here for the same reason as {@link Settings}. */
export type Modality = "antibody_tcr" | "peptide";

/**
* This block's init-params contract — everything a creator or a project template chooses,
* and nothing derived. Excluded on purpose: state the block recomputes from the assay file's
* own bytes (`importColumns`, `detectedXsvType`, `fileImportError`) and pure view state
* (`tableState`, `alignmentModel`).
*
* `mem` / `cpu` are excluded deliberately and permanently: resource allocation belongs to
* the machine a block runs on, not to configuration a template carries between machines.
*
* `fileHandle` travels only when it is an `index://` handle — that is `{storageId, path}`,
* which resolves for anyone whose server registers that storage. An `upload://` handle
* carries a signature bound to the instance that made it and will not resolve elsewhere.
* The model's `templateParams` projection is what drops an `upload://` handle, so one never
* reaches a template by export. It is still accepted here rather than rejected: a parser
* stricter than the states the UI reaches would make the block refuse its own exports, and a
* hand-written entry naming a local file is the author's call to make.
*
* Every field is optional: a block may be created without a template, and a template need
* not set all of them.
*/
export type BlockParams = {
customBlockLabel?: string;
datasetRef?: PlRef;
targetRef?: SUniversalPColumnId;
targetColumnLabel?: string;
fileHandle?: ImportFileHandle;
fileExtension?: string;
sequenceColumnHeader?: string;
selectedColumns?: string[];
settings?: Settings;
lessSensitive?: boolean;
maxSeqs?: number;
/**
* Carried on purpose, like the rest of the recipe. The UI reapplies modality threshold
* defaults whenever the resolved modality differs from this field, so a template that
* carried `settings` without it would land, see `undefined`, and have its thresholds
* overwritten. Carrying it also stays correct when a template lands on the other
* modality: the values then differ, the watcher fires, and the new defaults win.
*/
lastAppliedModality?: Modality;
};

type Guard<T> = (v: unknown) => v is T;
type Check<T> = { is: Guard<T>; must: string };

function check<T>(is: Guard<T>, must: string): Check<T> {
return { is, must };
}

/** Both handle forms are `<scheme>://<scheme>/<urlencoded JSON>`; the scheme is the envelope. */
const isImportFileHandle: Guard<ImportFileHandle> = (v): v is ImportFileHandle =>
isString(v) && (v.startsWith("upload://") || v.startsWith("index://"));

const isStringArray: Guard<string[]> = (v): v is string[] => isArray(v) && v.every(isString);

const isModality: Guard<Modality> = (v): v is Modality => v === "antibody_tcr" || v === "peptide";

/**
* A whole number of at least `min`. `Number.isInteger` rather than es-toolkit's `isInteger`,
* which returns a plain boolean and so leaves the value un-narrowed for the comparison after it.
*/
function isIntAtLeast(min: number): Guard<number> {
return (v): v is number => isNumber(v) && Number.isInteger(v) && v >= min;
}

const SIMILARITY_TYPES: readonly Settings["similarityType"][] = [
"sequence-identity",
"alignment-score",
"exact-match",
];

const isSettings: Guard<Settings> = (v): v is Settings =>
isPlainObject(v) &&
isNumber(v.coverageThreshold) &&
isNumber(v.identity) &&
SIMILARITY_TYPES.includes(v.similarityType as Settings["similarityType"]);
Comment on lines +95 to +99

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Threshold bounds are unenforced

When a hand-written or externally generated template supplies identity or coverageThreshold outside 0.1–1.0, isSettings accepts it and the model forwards it unchanged to alignment processing, causing invalid matching behavior or a failed run.

Suggested change
const isSettings: Guard<Settings> = (v): v is Settings =>
isPlainObject(v) &&
isNumber(v.coverageThreshold) &&
isNumber(v.identity) &&
SIMILARITY_TYPES.includes(v.similarityType as Settings["similarityType"]);
const isSettings: Guard<Settings> = (v): v is Settings =>
isPlainObject(v) &&
isNumber(v.coverageThreshold) &&
v.coverageThreshold >= 0.1 &&
v.coverageThreshold <= 1 &&
isNumber(v.identity) &&
v.identity >= 0.1 &&
v.identity <= 1 &&
SIMILARITY_TYPES.includes(v.similarityType as Settings["similarityType"]);

Knowledge Base Used: Assay domain model

Fix in Claude Code

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agree


/**
* The runtime half of the contract. The `satisfies` clause is what stops it drifting: every
* field `BlockParams` declares must appear here, and each guard must narrow to that field's
* own type — so adding a param without a check stops compiling.
*/
const CONTRACT = {
customBlockLabel: check(isString, "a string"),
datasetRef: check(isPlRef, "a reference to an input dataset"),
targetRef: check(isColumnUniversalId, "a sequence column identifier"),
targetColumnLabel: check(isString, "a string"),
fileHandle: check(isImportFileHandle, "an upload:// or index:// file handle"),
fileExtension: check(isString, "a string"),
sequenceColumnHeader: check(isString, "a string"),
selectedColumns: check(isStringArray, "an array of column names"),
settings: check(isSettings, "an object with coverageThreshold, identity and similarityType"),
lessSensitive: check(isBoolean, "a boolean"),
maxSeqs: check(isIntAtLeast(0), "a whole number of 0 or more, where 0 means no limit"),
lastAppliedModality: check(isModality, '"antibody_tcr" or "peptide"'),
} satisfies { [K in keyof Required<BlockParams>]: Check<NonNullable<BlockParams[K]>> };

/**
* The contract at runtime, for params arriving from a template file rather than typed code.
* An absent field is always allowed — every param is optional and the block's own default
* takes over — so each guard runs only on what is present. Keys the contract does not name
* are dropped by never being read.
*/
function parseInitializationParams(value: unknown): BlockParams {
assertParamsObject(value);

const params: Record<string, unknown> = {};
for (const [field, { is, must }] of Object.entries(CONTRACT)) {
const v = value[field];
if (v === undefined) continue;
if (!is(v)) throw new Error(`'${field}' must be ${must}.`);
params[field] = v;
}
return params as BlockParams;
}

// Identity comes from this package's own package.json, so the on-wire `{name}@{version}`
// reference can never drift from what is published; the bundler inlines the JSON import.
export const kind = defineBlockKind<BlockParams>({
name,
version,
parseInitializationParams,
});
10 changes: 10 additions & 0 deletions kind/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "@milaboratories/ts-configs/block/facade",
"compilerOptions": {
"outDir": "./dist",
"rootDir": ".",
"resolveJsonModule": true
},
"include": ["src/**/*", "package.json"],
"exclude": ["dist", "node_modules"]
}
2 changes: 1 addition & 1 deletion model/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
"check": "ts-builder check --target block-model"
},
"dependencies": {
"@milaboratories/graph-maker": "catalog:",
"@milaboratories/helpers": "catalog:",
"@platforma-open/milaboratories.immune-assay-data.kind": "workspace:*",
"@platforma-sdk/model": "catalog:"
},
"devDependencies": {
Expand Down
71 changes: 54 additions & 17 deletions model/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Modality, Settings } from "@platforma-open/milaboratories.immune-assay-data.kind";
import { kind } from "@platforma-open/milaboratories.immune-assay-data.kind";
import type {
InferOutputsType,
PColumn,
Expand All @@ -12,6 +14,7 @@ import {
createPlDataTableV2,
DataModelBuilder,
getFileNameFromHandle,
isImportFileHandleIndex,
} from "@platforma-sdk/model";
import { getDefaultBlockLabel } from "./label";
import type {
Expand All @@ -20,8 +23,6 @@ import type {
BlockPrerunArgs,
LegacyBlockArgs,
LegacyBlockUiState,
Modality,
Settings,
} from "./types";

// `undefined` is part of the data union on purpose: `getAnchoredPColumns` returns
Expand All @@ -36,12 +37,13 @@ const defaultSettings = (): Settings => ({
similarityType: "alignment-score",
});

const blockDataModel = new DataModelBuilder()
const blockDataModel = new DataModelBuilder({ kind })
.from<BlockData>("V20260519")
.upgradeLegacy<LegacyBlockArgs, LegacyBlockUiState>(({ args, uiState }) => ({
customBlockLabel: args?.customBlockLabel ?? "",
datasetRef: args?.datasetRef,
targetRef: args?.targetRef,
targetColumnLabel: undefined,
fileHandle: args?.fileHandle,
fileExtension: args?.fileExtension,
detectedXsvType: args?.detectedXsvType,
Expand All @@ -60,30 +62,40 @@ const blockDataModel = new DataModelBuilder()
// the modality-reset watcher from clobbering user-tuned thresholds on reopen.
lastAppliedModality: "antibody_tcr",
}))
.init(() => ({
customBlockLabel: "",
datasetRef: undefined,
targetRef: undefined,
fileHandle: undefined,
fileExtension: undefined,
// `params` is absent when a block is created by hand rather than from a
// template, so every field the contract carries keeps its own default.
.init(({ params }) => ({
customBlockLabel: params?.customBlockLabel ?? "",
datasetRef: params?.datasetRef,
targetRef: params?.targetRef,
targetColumnLabel: params?.targetColumnLabel,
fileHandle: params?.fileHandle,
fileExtension: params?.fileExtension,
detectedXsvType: undefined,
importColumns: undefined,
sequenceColumnHeader: undefined,
selectedColumns: [],
settings: defaultSettings(),
lessSensitive: false,
maxSeqs: 10000,
sequenceColumnHeader: params?.sequenceColumnHeader,
selectedColumns: params?.selectedColumns ?? [],
settings: params?.settings ?? defaultSettings(),
lessSensitive: params?.lessSensitive ?? false,
maxSeqs: params?.maxSeqs ?? 10000,
mem: undefined,
cpu: undefined,
fileImportError: undefined,
tableState: createPlDataTableStateV2(),
alignmentModel: {},
lastAppliedModality: undefined,
lastAppliedModality: params?.lastAppliedModality,
}));

function deriveDefaultLabel(data: BlockData): string {
/** The block's file handle when it can resolve on another machine, else undefined. */
function shareableFileHandle(data: BlockData): BlockData["fileHandle"] {
const handle = data.fileHandle;
return handle !== undefined && isImportFileHandleIndex(handle) ? handle : undefined;
}

export function deriveDefaultLabel(data: BlockData): string {
return getDefaultBlockLabel({
fileName: data.fileHandle ? getFileNameFromHandle(data.fileHandle) : undefined,
targetColumnLabel: data.targetColumnLabel,
similarityType: data.settings.similarityType,
identity: data.settings.identity,
coverageThreshold: data.settings.coverageThreshold,
Expand Down Expand Up @@ -121,7 +133,7 @@ function getAnchoredClonotypeProps(
).filter((p) => p.spec.annotations?.["pl7.app/sequence/isAnnotation"] !== "true");
}

export const platforma = BlockModelV3.create(blockDataModel)
export const platforma = BlockModelV3.create({ dataModel: blockDataModel, kind })

.args<BlockArgs>((data) => {
if (data.datasetRef === undefined) throw new Error("Dataset is required");
Expand Down Expand Up @@ -157,6 +169,31 @@ export const platforma = BlockModelV3.create(blockDataModel)
};
})

// The inverse of `init`: exactly the fields BlockParams declares, so exporting a block to
// a template and applying that template round-trip.
.templateParams((data) => {
// The assay file and everything describing it travel together, or not at all. An
// `upload://` handle is signed by the desktop that opened the file dialog and resolves
// nowhere else, so it is dropped — and with it the extension read off its filename and the
// column picks. Sending them alone would land picks that `setFile` wipes the moment a
// file is chosen.
const file = shareableFileHandle(data);
return {
customBlockLabel: data.customBlockLabel,
datasetRef: data.datasetRef,
targetRef: data.targetRef,
targetColumnLabel: data.targetColumnLabel,
fileHandle: file,
fileExtension: file === undefined ? undefined : data.fileExtension,
sequenceColumnHeader: file === undefined ? undefined : data.sequenceColumnHeader,
selectedColumns: file === undefined ? undefined : data.selectedColumns,
settings: data.settings,
lessSensitive: data.lessSensitive,
maxSeqs: data.maxSeqs,
lastAppliedModality: data.lastAppliedModality,
};
})

.prerunArgs(
(data): BlockPrerunArgs => ({
fileHandle: data.fileHandle,
Expand Down
6 changes: 6 additions & 0 deletions model/src/label.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export function getDefaultBlockLabel(data: {
fileName?: string;
targetColumnLabel?: string;
similarityType: "alignment-score" | "sequence-identity" | "exact-match";
identity: number;
coverageThreshold: number;
Expand All @@ -11,6 +12,11 @@ export function getDefaultBlockLabel(data: {
parts.push(data.fileName);
}

// The matched sequence column
if (data.targetColumnLabel) {
parts.push(data.targetColumnLabel);
}

// Sequence Match mode has no identity/coverage thresholds — they are meaningless.
if (data.similarityType === "exact-match") {
parts.push("Sequence match");
Expand Down
Loading
Loading