@biolibs/bionet 1.3.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/merge.ts CHANGED
@@ -27,7 +27,7 @@
27
27
  import { Dseq } from "@biolibs/dseq";
28
28
  import { Dseqrecord } from "@biolibs/dseqrecord";
29
29
  import type { SignOptions, SigningKey } from "@biolibs/opencloning";
30
- import { entryId, readEntry, verifyEntry, writeEntry, type Operation, type PartEnds, type PartFeature, type Role, type RunInput, type StandingMm,
30
+ import { entryId, readEntry, verifyEntry, writeEntry, type Operation, type PartEnds, type PartFeature, type PlanInput, type Role, type RunInput, type StandingMm,
31
31
  type SignedEntry } from "./log.js";
32
32
  import { INVENTORY_VERSION, type InventoryDocument, type InventoryPart, type LabModel,
33
33
  type PeerModel } from "./model.js";
@@ -148,6 +148,35 @@ export interface RunState {
148
148
  added: string;
149
149
  }
150
150
 
151
+ /** A run somebody has proposed, as the lab holds it. */
152
+ export interface PlanState {
153
+ /** Its ID. */
154
+ plan: string;
155
+ /** What kind of run it would be: `pcr`. */
156
+ kind: string;
157
+ /** The place to do it at, or `null`. */
158
+ instrument: string | null;
159
+ /** What it would use: a tube, or a part there is no tube of yet. */
160
+ inputs: PlanInput[];
161
+ /** What it is expected to make, each with the checksum that would be its identity. */
162
+ expects: { name: string; sequence: string; circular: boolean; ends: PartEnds; length: number; checksum: string }[];
163
+ /** How to set it up. */
164
+ settings: Record<string, string | number>;
165
+ /** Why, and anything else said about it. */
166
+ note: string | null;
167
+ /** The key that proposed it. */
168
+ by: string;
169
+ /** What became of it: the run that carried it out, or `null` for that if it was set aside. `null` while it is open. */
170
+ settled: { run: string | null; by: string; entry: string } | null;
171
+ /**
172
+ * For a plan still open: the tubes it counts on that have since been retired or hold less than it
173
+ * would use. The plan is kept and shown; somebody has to look before carrying it out.
174
+ */
175
+ wanting: string[];
176
+ /** The entry that proposed it. */
177
+ added: string;
178
+ }
179
+
151
180
  /** One position of one box that the log says holds more than one item. */
152
181
  export interface Crowded {
153
182
  /** The box. */
@@ -209,6 +238,8 @@ export interface LabState {
209
238
  crowded: Crowded[];
210
239
  /** Everything done at the bench that was recorded, in the order the merge settled on. */
211
240
  runs: RunState[];
241
+ /** Every run that has been proposed, open or settled, in the order the merge settled on. */
242
+ plans: PlanState[];
212
243
  /** Every entry that could be placed, in order, with what became of it. */
213
244
  entries: Placed[];
214
245
  /** Entries that are waiting on others that have not arrived. */
@@ -232,6 +263,8 @@ interface Node {
232
263
  op: Operation;
233
264
  /** How far into each log this entry had seen, itself included. Set when it is placed. */
234
265
  vc: Map<string, number>;
266
+ /** Whether its key was an adviser when it was placed. Set when it is placed. */
267
+ adviser?: boolean;
235
268
  }
236
269
 
237
270
  const KEY = /^[A-Za-z0-9_-]{43}$/;
@@ -304,9 +337,146 @@ function areFeatures(value: unknown, length: number): value is PartFeature[] {
304
337
  && piece.start >= 0 && piece.end > piece.start && piece.end <= length));
305
338
  }
306
339
 
340
+ /**
341
+ * What a value in a change may be, for the purpose of knowing it: `true` for anything at all, an
342
+ * object for something whose fields are listed, and a list of one shape for a list of those.
343
+ */
344
+ type Known = true | { readonly [field: string]: Known } | readonly [Known];
345
+
346
+ /**
347
+ * Every field each kind of change may carry, and every field inside those.
348
+ *
349
+ * This exists because of what happened when parts learned to have ends. A version that did not know
350
+ * `ends` took such an entry, ignored them, and worked the part's checksum out from the bases alone —
351
+ * so two machines read one entry differently, which is the one thing the merge must never do. A kind
352
+ * of change a version does not know is refused and said so; a *field* it does not know used to pass
353
+ * unnoticed. Now it does not: anything not listed here is as unreadable as an unknown change.
354
+ *
355
+ * So adding a field is a breaking change for older readers, and it is meant to be. They will set the
356
+ * entry aside and say why, which a person can act on, instead of quietly disagreeing about the lab.
357
+ *
358
+ * `true` means the value is not looked into: `settings` on a run and `value` on a field are open by
359
+ * design, and `at`, `size` and a feature's strand are numbers rather than things with fields.
360
+ */
361
+ const KNOWN: Readonly<Record<string, Readonly<Record<string, Known>>>> = {
362
+ "roster.found": { name: true, person: true },
363
+ "roster.add": { key: true, person: true, role: true },
364
+ "roster.remove": { key: true, cutoff: true },
365
+ "roster.role": { key: true, role: true },
366
+ "part.add": { sequence: true, circular: true, name: true, ends: { left: true, right: true } },
367
+ "part.annotate": { part: true, features: [{ type: true, label: true, strand: true, parts: [{ start: true, end: true }] }] },
368
+ "part.offer": { part: true, available: true },
369
+ "item.add": { item: true, part: true, amount: true, unit: true },
370
+ "item.adjust": { item: true, by: true },
371
+ "item.recount": { item: true, amount: true },
372
+ "item.retire": { item: true },
373
+ "item.put": { item: true, place: true, slot: { row: true, column: true } },
374
+ "place.add": { place: true, kind: true, name: true, parent: true, grid: { rows: true, columns: true } },
375
+ "place.move": { place: true, parent: true },
376
+ "place.stand": { place: true, standing: { at: true, size: true, turn: true } },
377
+ "place.retire": { place: true },
378
+ "run.record": {
379
+ run: true, kind: true, instrument: true, settings: true, outcome: true, note: true,
380
+ inputs: [{ item: true, amount: true, role: true }],
381
+ outputs: [{ item: true, sequence: true, circular: true, ends: { left: true, right: true }, name: true, amount: true, unit: true }],
382
+ },
383
+ "plan.add": {
384
+ plan: true, kind: true, instrument: true, settings: true, note: true,
385
+ inputs: [{ item: true, part: true, amount: true, role: true }],
386
+ expects: [{ sequence: true, circular: true, ends: { left: true, right: true }, name: true }],
387
+ },
388
+ "plan.settle": { plan: true, run: true },
389
+ "field.set": { on: true, id: true, field: true, value: true },
390
+ };
391
+
392
+ /** What an adviser may write. Everything else from one is refused. */
393
+ const ADVISER_MAY = new Set(["part.add", "plan.add", "plan.settle"]);
394
+
395
+ /**
396
+ * The first field in a change that this version does not know, if there is one.
397
+ *
398
+ * @param value - What to look at.
399
+ * @param known - What its fields may be.
400
+ * @param where - What to call it in the answer, such as `outputs`.
401
+ * @returns The field's name, said as a path, or `null` if every field is one this version knows.
402
+ */
403
+ function strayIn(value: unknown, known: Known, where: string): string | null {
404
+ if (known === true || value === null || typeof value !== "object") return null;
405
+ if (Array.isArray(known)) {
406
+ if (!Array.isArray(value)) return null; // that it is not a list is settled by the checks below
407
+ for (const [at, one] of value.entries()) {
408
+ const stray = strayIn(one, known[0]!, `${where}[${at}]`);
409
+ if (stray !== null) return stray;
410
+ }
411
+ return null;
412
+ }
413
+ if (Array.isArray(value)) return null;
414
+ // Not a list, so it is the object form; TypeScript cannot see that through the tuple in the union.
415
+ const fields = known as Readonly<Record<string, Known>>;
416
+ for (const [field, held] of Object.entries(value as Record<string, unknown>)) {
417
+ const path = where === "" ? field : `${where}.${field}`;
418
+ if (!Object.hasOwn(fields, field)) return path;
419
+ const stray = strayIn(held, fields[field]!, path);
420
+ if (stray !== null) return stray;
421
+ }
422
+ return null;
423
+ }
424
+
425
+ /**
426
+ * The first field a change carries that this version does not know.
427
+ *
428
+ * @param op - The change.
429
+ * @returns The field's name, or `null` if this version knows every field it carries, or does not
430
+ * know the kind of change at all — which is settled elsewhere, and said differently.
431
+ */
432
+ export function strayField(op: Operation): string | null {
433
+ const known = Object.hasOwn(KNOWN, op.type) ? KNOWN[op.type]! : undefined;
434
+ if (known === undefined) return null;
435
+ const { type: _type, ...rest } = op as Record<string, unknown>;
436
+ void _type;
437
+ return strayIn(rest, known, "");
438
+ }
439
+
307
440
  /** The most items that may go into one run or come out of it, and the most settings it may carry. */
308
441
  const MOST_IN_A_RUN = 50;
309
442
 
443
+ /** Whether something is a run's settings: whole numbers and short text, by name. */
444
+ const areSettings = (settings: unknown): settings is Record<string, string | number> =>
445
+ typeof settings === "object" && settings !== null && !Array.isArray(settings) && Object.keys(settings).length <= MOST_IN_A_RUN
446
+ && Object.entries(settings).every(([name, value]) => FIELD.test(name) && (amountOf(value) || (typeof value === "string" && value.length <= 200)));
447
+
448
+ /**
449
+ * Why a plan cannot be kept, or `null` if it can.
450
+ *
451
+ * Only its form is checked: that it names things the lab has and that what it expects is a
452
+ * molecule. Whether the run would really make that is not the log's to say. Each reader's own
453
+ * tools work it out again, which is why the plan carries its claim and not its working.
454
+ */
455
+ function planProblem(op: Operation, items: ReadonlyMap<string, unknown>, parts: ReadonlyMap<string, unknown>, places: ReadonlyMap<string, unknown>,
456
+ plans: ReadonlyMap<string, unknown>): string | null {
457
+ if (!(typeof op["plan"] === "string" && ITEM_ID.test(op["plan"])) || !text(op["kind"], 40)) return "It does not carry a plan ID and what kind of run it would be.";
458
+ if (plans.has(op["plan"])) return "A plan with that ID already exists.";
459
+ if (!(op["instrument"] === null || (typeof op["instrument"] === "string" && places.has(op["instrument"])))) return "The place it would be done at is not one the lab has.";
460
+ if (!(op["note"] === null || text(op["note"], 2_000))) return "Its note is not some text.";
461
+ if (!areSettings(op["settings"])) return "Its settings are not whole numbers and short text, by name.";
462
+ const inputs = op["inputs"];
463
+ if (!Array.isArray(inputs) || inputs.length > MOST_IN_A_RUN) return "It does not list what it would use.";
464
+ for (const input of inputs as Partial<PlanInput>[]) {
465
+ if (typeof input !== "object" || input === null || !amountOf(input.amount) || input.amount < 0 || !text(input.role, 40)) return "It does not say how many whole units of each thing it would use, and as what.";
466
+ if ((input.item === undefined) === (input.part === undefined)) return "Each thing it would use has to be a tube or a part, and not both.";
467
+ if (input.item !== undefined && !(typeof input.item === "string" && items.has(input.item))) return "A tube it would use is not an item the lab has.";
468
+ if (input.part !== undefined && !(typeof input.part === "string" && parts.has(input.part))) return "A part it would use is not one the lab has.";
469
+ }
470
+ const expects = op["expects"];
471
+ if (!Array.isArray(expects) || expects.length > MOST_IN_A_RUN) return "It does not list what it expects to make.";
472
+ for (const expect of expects as Record<string, unknown>[]) {
473
+ if (typeof expect !== "object" || expect === null || !text(expect["sequence"], LONGEST_SEQUENCE) || typeof expect["circular"] !== "boolean" || !text(expect["name"], 200)) {
474
+ return "It does not give each thing it expects a sequence, a name and whether it is a circle.";
475
+ }
476
+ }
477
+ return null;
478
+ }
479
+
310
480
  /**
311
481
  * Why a run cannot be recorded, or `null` if it can.
312
482
  *
@@ -347,7 +517,7 @@ function runProblem(op: Operation, items: ReadonlyMap<string, unknown>, places:
347
517
  }
348
518
 
349
519
  const amountOf = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value);
350
- const role = (value: unknown): value is Role => value === "member" || value === "keeper";
520
+ const role = (value: unknown): value is Role => value === "member" || value === "keeper" || value === "adviser";
351
521
 
352
522
  /** Whether `later` was written by somebody who held `earlier`. */
353
523
  const hadSeen = (later: Node, earlier: Node): boolean => (later.vc.get(earlier.author) ?? -1) >= earlier.seq;
@@ -372,7 +542,7 @@ const hadSeen = (later: Node, earlier: Node): boolean => (later.vc.get(earlier.a
372
542
  * ```
373
543
  */
374
544
  export async function mergeLog(entries: readonly unknown[], options: { lab?: string } = {}): Promise<LabState> {
375
- const state: LabState = { lab: options.lab ?? null, name: null, roster: [], parts: [], items: [], places: [], crowded: [], runs: [], entries: [],
545
+ const state: LabState = { lab: options.lab ?? null, name: null, roster: [], parts: [], items: [], places: [], crowded: [], runs: [], plans: [], entries: [],
376
546
  waiting: [], discarded: [], overlaps: [], heads: {}, knows: {} };
377
547
 
378
548
  // Read and check every entry on its own, before any of them is believed about the others.
@@ -535,6 +705,14 @@ function walk(founding: Node, chains: Map<string, Node[]>, chained: Map<string,
535
705
  };
536
706
  const op = node.op;
537
707
 
708
+ // Before any of it is read: a field this version does not know makes the whole change
709
+ // unreadable, because what it would change about the rest cannot be guessed.
710
+ const stray = strayField(op);
711
+ if (stray !== null) {
712
+ say("not understood", `It carries ${JSON.stringify(stray)}, which this version does not know, so it could be read differently from the way its author meant it.`);
713
+ continue;
714
+ }
715
+
538
716
  if (node === founding) {
539
717
  roster.set(node.author, { key: node.author, person: text(op["person"], 200) ? op["person"] : "",
540
718
  role: "keeper", founder: true, added: node.id, removed: null });
@@ -549,6 +727,12 @@ function walk(founding: Node, chains: Map<string, Node[]>, chained: Map<string,
549
727
  if (cut !== undefined && node.seq > cut) { say("set aside", "It comes after the point at which its key was removed."); continue; }
550
728
 
551
729
  if (!op.type.startsWith("roster.")) {
730
+ // An adviser proposes and describes. It is turned away here, where the roster is known as it
731
+ // stood when the entry was written, from anything that would change what the lab holds.
732
+ if (author.role === "adviser") {
733
+ if (!ADVISER_MAY.has(op.type)) { say("refused", "Its key is an adviser, which may add parts and propose runs and nothing else."); continue; }
734
+ node.adviser = true;
735
+ }
552
736
  say("applied"); // whether the change itself makes sense is settled when the inventory is folded
553
737
  continue;
554
738
  }
@@ -585,7 +769,7 @@ function walk(founding: Node, chains: Map<string, Node[]>, chained: Map<string,
585
769
  const target = typeof op["key"] === "string" ? roster.get(op["key"]) : undefined;
586
770
  if (target === undefined || target.removed !== null || !role(op["role"])) {
587
771
  say("refused", "It does not name a key on the roster and a role to give it.");
588
- } else if (target.role === "keeper" && op["role"] === "member" && liveKeepers() === 1) {
772
+ } else if (target.role === "keeper" && op["role"] !== "keeper" && liveKeepers() === 1) {
589
773
  say("refused", "A lab cannot be left without a keeper.");
590
774
  } else {
591
775
  if (op["role"] === "keeper" && target.role !== "keeper") since.set(target.key, since.size);
@@ -620,6 +804,8 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
620
804
  };
621
805
 
622
806
  const places = new Map<string, { place: PlaceState; set: Map<string, Register> }>();
807
+ /** Each plan, with the entry that settled it, if one has. */
808
+ const plans = new Map<string, { plan: PlanState; settled: Node | null }>();
623
809
  /** Where each item was last put. */
624
810
  const put = new Map<string, Map<string, Register>>();
625
811
 
@@ -783,6 +969,44 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
783
969
  settings: { ...(op["settings"] as Record<string, string | number>) }, outcome: op["outcome"] as "worked" | "failed",
784
970
  note: op["note"] as string | null, added: node.id,
785
971
  });
972
+ } else if (op.type === "plan.add") {
973
+ const problem = planProblem(op, items, parts, places, plans);
974
+ if (problem !== null) { refuse(problem); continue; }
975
+ const expects: PlanState["expects"] = [];
976
+ try {
977
+ for (const expect of op["expects"] as { sequence: string; circular: boolean; name: string; ends?: unknown }[]) {
978
+ const molecule = moleculeOf(expect.sequence, expect.circular, expect.ends);
979
+ expects.push({ name: expect.name, sequence: expect.sequence, circular: expect.circular, ends: molecule.ends, length: molecule.length, checksum: molecule.checksum });
980
+ }
981
+ } catch {
982
+ refuse("Something it expects to make is not a sequence, with ends a molecule of that length can have.");
983
+ continue;
984
+ }
985
+ plans.set(op["plan"] as string, {
986
+ settled: null,
987
+ plan: {
988
+ plan: op["plan"] as string, kind: op["kind"] as string, instrument: op["instrument"] as string | null,
989
+ inputs: (op["inputs"] as PlanInput[]).map((input) => ({ ...(input.item === undefined ? { part: input.part! } : { item: input.item }), amount: input.amount, role: input.role })),
990
+ expects, settings: { ...(op["settings"] as Record<string, string | number>) }, note: op["note"] as string | null,
991
+ by: node.author, settled: null, wanting: [], added: node.id,
992
+ },
993
+ });
994
+ } else if (op.type === "plan.settle") {
995
+ const held = typeof op["plan"] === "string" ? plans.get(op["plan"]) : undefined;
996
+ const run = op["run"];
997
+ if (held === undefined) { refuse("It does not name a plan the lab has."); continue; }
998
+ if (!(run === null || (typeof run === "string" && state.runs.some((one) => one.run === run)))) { refuse("The run it says carried the plan out is not one the lab has."); continue; }
999
+ // Only somebody who can do a run can say one was done; an adviser can take back what it proposed.
1000
+ if (node.adviser === true && (run !== null || held.plan.by !== node.author)) { refuse("An adviser may only set aside a plan of its own."); continue; }
1001
+ const settle = (): void => { held.settled = node; held.plan.settled = { run: run as string | null, by: node.author, entry: node.id }; };
1002
+ if (held.settled === null) settle();
1003
+ else if (hadSeen(node, held.settled)) refuse("That plan is already settled.");
1004
+ else {
1005
+ // Two people settled it without knowing of each other. One stands, and the overlap is shown.
1006
+ const wins = node.id < held.settled.id;
1007
+ state.overlaps.push({ what: `what became of plan ${held.plan.plan.slice(0, 12)}`, kept: wins ? node.id : held.settled.id, dropped: wins ? held.settled.id : node.id });
1008
+ if (wins) settle();
1009
+ }
786
1010
  } else if (op.type === "field.set") {
787
1011
  const field = op["field"];
788
1012
  const value = op["value"];
@@ -820,6 +1044,17 @@ function fold(state: LabState, placed: Placed[], chained: Map<string, Node>): vo
820
1044
  item.where = (put.get(item.item)?.get("where")?.value ?? null) as ItemState["where"];
821
1045
  state.items.push(item);
822
1046
  }
1047
+ // A plan counts on tubes that go on being used after it is written. It is not refused for that:
1048
+ // it is kept, and says which of them are no longer what it needs.
1049
+ for (const { plan } of plans.values()) {
1050
+ if (plan.settled === null) {
1051
+ plan.wanting = plan.inputs.flatMap((input) => {
1052
+ const held = input.item === undefined ? undefined : items.get(input.item)?.item;
1053
+ return held !== undefined && (held.retired || held.amount < input.amount) ? [held.item] : [];
1054
+ });
1055
+ }
1056
+ state.plans.push(plan);
1057
+ }
823
1058
  for (const { place, set } of places.values()) {
824
1059
  for (const [field, held] of set) {
825
1060
  if (field === "name") place.name = held.value as string;