dsh-molbio-tools 0.25.0 → 0.27.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.
@@ -185,12 +185,56 @@ async function checkRow(row, packages, harnessRoot, presetBase) {
185
185
  if (typeof Config !== 'function') {
186
186
  return { ...result, status: 'ok', detail: 'package exports no Config schema (config passed through unvalidated)' };
187
187
  }
188
- try {
189
- Config(row.config);
190
- return { ...result, status: 'ok' };
191
- } catch (error) {
192
- return { ...result, status: 'config-invalid', detail: String(error.message ?? error).split('\n')[0] };
188
+ // A '!!js' scalar parses to { __jsExpr: <source> } (the Loader's own tag).
189
+ // The Loader EVALUATES those before a package's Config sees a value; this
190
+ // guard holds the unevaluated node, and the expression's runtime type is not
191
+ // knowable here (baseUrl, ctx and dshHomePath exist only at mount). So it
192
+ // validates with each scalar placeholder in turn and reports invalid only
193
+ // when NO placeholder satisfies the schema - a shape error, the thing this
194
+ // guard exists for, still fails all three. 0.2.2-rc.2's customSkillDirs is
195
+ // the first upstream row that needs this: its value is a '!!js' path string.
196
+ const configs = hasJsExpr(row.config) ? jsExprPlaceholderVariants(row.config) : [row.config];
197
+ let lastError;
198
+ for (const config of configs) {
199
+ try {
200
+ Config(config);
201
+ return { ...result, status: 'ok', ...(configs.length > 1 ? { detail: 'config validated with !!js placeholders' } : {}) };
202
+ } catch (error) {
203
+ lastError = error;
204
+ }
205
+ }
206
+ return { ...result, status: 'config-invalid', detail: String(lastError?.message ?? lastError).split('\n')[0] };
207
+ }
208
+
209
+ /** Is this node a Loader '!!js' expression ({ __jsExpr: <source> })? */
210
+ function isJsExpr(value) {
211
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
212
+ && typeof value.__jsExpr === 'string' && Object.keys(value).length === 1;
213
+ }
214
+
215
+ /** Does any value in this config tree carry an unevaluated '!!js' node? */
216
+ function hasJsExpr(value) {
217
+ if (isJsExpr(value)) return true;
218
+ if (Array.isArray(value)) return value.some(hasJsExpr);
219
+ if (value !== null && typeof value === 'object') return Object.values(value).some(hasJsExpr);
220
+ return false;
221
+ }
222
+
223
+ /** Replace every '!!js' node with one scalar placeholder, recursively. */
224
+ function withJsExprPlaceholder(value, placeholder) {
225
+ if (isJsExpr(value)) return placeholder;
226
+ if (Array.isArray(value)) return value.map((entry) => withJsExprPlaceholder(entry, placeholder));
227
+ if (value !== null && typeof value === 'object') {
228
+ const out = {};
229
+ for (const [key, entry] of Object.entries(value)) out[key] = withJsExprPlaceholder(entry, placeholder);
230
+ return out;
193
231
  }
232
+ return value;
233
+ }
234
+
235
+ /** The three placeholder types a schema could require for an evaluated '!!js'. */
236
+ function jsExprPlaceholderVariants(config) {
237
+ return ['', 0, false].map((placeholder) => withJsExprPlaceholder(config, placeholder));
194
238
  }
195
239
 
196
240
  /** Rows, in composition order, with nested group children flattened inline. */
@@ -356,6 +400,17 @@ async function main() {
356
400
  const packages = packagesDir(harnessRoot);
357
401
  const version = JSON.parse(await readFile(join(harnessRoot, 'package.json'), 'utf8')).version;
358
402
  console.log(`harness : ${harnessRoot} (dsh ${version})`);
403
+ // The DECLARATION must follow the harness this run actually used. Nothing
404
+ // else in the suite reads `dshReleases`, so a harness bump the manifests
405
+ // never record is silent: every guard is green while the store still calls
406
+ // the build `unknown` (0.25.2).
407
+ const declaredProblems = compatibilityProblems(
408
+ [
409
+ JSON.parse(await readFile(join(repoRoot, 'package.json'), 'utf8')),
410
+ JSON.parse(await readFile(join(repoRoot, 'packages', 'molbio-panel', 'package.json'), 'utf8')),
411
+ ],
412
+ version,
413
+ );
359
414
  console.log(`composition: ${composition}`);
360
415
 
361
416
  const rows = flattenRows(presetPlugins(await readComposition(composition, harnessRoot)));
@@ -483,7 +538,7 @@ async function main() {
483
538
  }
484
539
  }
485
540
 
486
- if (failures.length > 0 || drift.length > 0 || relativeRows.length > 0 || countDrift.length > 0 || orderDrift.length > 0) {
541
+ if (failures.length > 0 || drift.length > 0 || relativeRows.length > 0 || countDrift.length > 0 || orderDrift.length > 0 || declaredProblems.length > 0) {
487
542
  if (failures.length > 0) {
488
543
  console.error(`preset-health FAILED: ${failures.length} row(s) cannot mount on dsh ${version}`);
489
544
  for (const failure of failures) console.error(` - ${failure.id} [${failure.status}]: ${failure.detail}`);
@@ -501,13 +556,46 @@ async function main() {
501
556
  console.error(`preset-health FAILED: ${orderDrift.length} preset order collision(s) with a shipped preset`);
502
557
  for (const line of orderDrift) console.error(` - ${line}`);
503
558
  }
559
+ if (declaredProblems.length > 0) {
560
+ console.error(`preset-health FAILED: ${declaredProblems.length} package manifest(s) do not declare dsh ${version} compatible`);
561
+ for (const problem of declaredProblems) console.error(` - ${problem}`);
562
+ }
504
563
  process.exit(1);
505
564
  }
506
- console.log(`preset-health OK: all ${rows.length} rows load on dsh ${version}, and the preset is the shipped standard plus the molbio rows`);
565
+ console.log(`preset-health OK: all ${rows.length} rows load on dsh ${version}, the preset is the shipped standard plus the molbio rows, and both manifests declare that version compatible`);
507
566
  console.log(`specifier OK: the preset names the package (${selfName}), so Node resolves it from the profile — no copied directory to keep in sync`);
508
567
  console.log(`order OK: ${ownOrder} collides with no shipped preset`);
509
568
  }
510
569
 
570
+ /**
571
+ * The declared compatibility of EVERY package manifest for the harness a run
572
+ * actually used.
573
+ *
574
+ * `engines.dsh` says "this range may work"; `dsh.compatibility.dshReleases`
575
+ * says "this exact build was run". The store reads the second one, and nothing
576
+ * else in this suite reads it — so a harness bump that the manifests never
577
+ * record is silent: the guards are green while the store still calls the
578
+ * build `unknown`, or omits it. 0.25.2 makes the declaration part of
579
+ * `preset-health`, which already knows which harness it validated.
580
+ *
581
+ * Exported so `test/drift-probe.mjs` can drive it with a mutated manifest —
582
+ * rules.md rule 9: a guard nobody has seen fail is not a guard.
583
+ *
584
+ * @param {object[]} manifests parsed `package.json` documents.
585
+ * @param {string} version the installed harness version.
586
+ * @returns {string[]} one line per manifest that does not say `compatible`.
587
+ */
588
+ export function compatibilityProblems(manifests, version) {
589
+ const problems = [];
590
+ for (const manifest of manifests) {
591
+ const state = manifest?.dsh?.compatibility?.dshReleases?.[version];
592
+ if (state !== 'compatible') {
593
+ problems.push(`${manifest?.name ?? '(unnamed manifest)'} declares dsh ${version} as ${state === undefined ? 'absent' : JSON.stringify(state)}`);
594
+ }
595
+ }
596
+ return problems;
597
+ }
598
+
511
599
  /**
512
600
  * Relative plugin specifiers in a composition.
513
601
  *
package/test/smoke.mjs CHANGED
@@ -4554,6 +4554,53 @@ if (savedNcbiEnv.MOLBIO_NCBI_API_KEY !== undefined) process.env.MOLBIO_NCBI_API_
4554
4554
  await assert.rejects(() => run('molbio_fastq_trim', { path: at('trim-in.fq'), output_path: at('x.fq'), adapter: 'ACGTX' }), /invalid/);
4555
4555
  }
4556
4556
 
4557
+ // ── duplex thermodynamics (survey #9) ──────────────────────────────────────
4558
+
4559
+ {
4560
+ const seq = 'GTAAAACGACGGCCAGTGCC';
4561
+ const thermo = await run('molbio_duplex_thermo', { sequence: seq });
4562
+ assert.equal(thermo.length, 20);
4563
+ assert.equal(thermo.gc_percent, 60);
4564
+ assert.equal(
4565
+ thermo.duplex.tm_celsius,
4566
+ lib.primerTm(seq, { naMm: 50, mgMm: 1.5, dntpMm: 0.8, primerNm: 250 }).tm_celsius,
4567
+ 'molbio_duplex_thermo and molbio_primer_tm agree on the same sequence and conditions',
4568
+ );
4569
+ assert.ok(thermo.duplex.delta_g37_kcal < 0, 'a stable duplex has a negative ΔG°37');
4570
+ assert.ok(thermo.duplex.delta_h_kcal < 0);
4571
+ assert.ok(thermo.duplex.delta_s_salt_cal < thermo.duplex.delta_s_cal, 'the salt correction lowers the entropy');
4572
+ assert.equal(thermo.model, 'santalucia-1998-nn');
4573
+ assert.deepEqual(
4574
+ Object.keys(thermo.conditions).sort(),
4575
+ ['dntp_mm', 'mg_mm', 'na_equivalent_mm', 'na_mm', 'oligo_nm'],
4576
+ );
4577
+ assert.ok(Array.isArray(thermo.hairpins));
4578
+ assert.equal(thermo.dimers.homodimer_any_tm, 0);
4579
+ assert.equal(thermo.dimers.heterodimer_any_tm, undefined, 'no heterodimer fields without a partner');
4580
+
4581
+ // An exact reverse complement enables the heterodimer check.
4582
+ const partner = reverseComplementOf(seq);
4583
+ const paired = await run('molbio_duplex_thermo', { sequence: seq, partner });
4584
+ assert.equal(paired.partner, partner);
4585
+ assert.ok(paired.dimers.heterodimer_any_tm > 0);
4586
+
4587
+ // A mismatched partner is REFUSED (no Watson–Crick estimate for it).
4588
+ await assert.rejects(
4589
+ () => run('molbio_duplex_thermo', { sequence: seq, partner: 'A'.repeat(20) }),
4590
+ /not the reverse complement/,
4591
+ );
4592
+ await assert.rejects(() => run('molbio_duplex_thermo', { sequence: 'ACGTNACGT' }), /A\/C\/G\/T/);
4593
+ await assert.rejects(() => run('molbio_duplex_thermo', { sequence: seq, hairpins: 11 }), /hairpins/);
4594
+ await assert.rejects(() => run('molbio_duplex_thermo', { sequence: seq, na_mm: -1 }), /na_mm/);
4595
+
4596
+ // The rendered projection carries the values a user asked for.
4597
+ const tool = registered.find((entry) => entry.name === 'molbio_duplex_thermo');
4598
+ const text = tool.output.render({}, thermo)[0].text;
4599
+ assert.match(text, /Tm 63\.92 °C/);
4600
+ assert.match(text, /ΔG°37 -23\.17 kcal\/mol/);
4601
+ assert.match(text, /dimers: homodimer Tm any/);
4602
+ }
4603
+
4557
4604
  // ── plugin surface ──────────────────────────────────────────────────────────
4558
4605
 
4559
4606
  assert.equal(plugin.name, 'dsh-molbio-tools');
package/thermo.mjs ADDED
@@ -0,0 +1,180 @@
1
+ /**
2
+ * dsh-molbio-tools/thermo.mjs
3
+ *
4
+ * Duplex thermodynamics beyond a single Tm: for one DNA oligo this module
5
+ * reports the nearest-neighbour enthalpy, entropy (raw and salt-corrected),
6
+ * ΔG at 37 °C and Tm, plus the two structure checks the primer tools already
7
+ * score — hairpin stems and self/hetero dimers.
8
+ *
9
+ * ── What this module will NOT do ────────────────────────────────────────────
10
+ * Mismatched duplexes have their own published parameter sets (Allawi &
11
+ * SantaLucia 1997/1998) and this module does not carry them. Rather than
12
+ * silently feeding a mismatch through Watson–Crick parameters — which yields a
13
+ * plausible-looking number that is wrong by several kcal/mol — a supplied
14
+ * `partner` that is not the exact reverse complement is REFUSED, with the
15
+ * mismatching positions named. Same for ambiguity codes: IUPAC symbols have no
16
+ * nearest-neighbour parameters, so they are refused rather than guessed.
17
+ *
18
+ * The salt/concentration model is deliberately the SAME one `lib.primerTm`
19
+ * uses (von Ahsen 2001 magnesium equivalence, SantaLucia 1998 entropy
20
+ * correction), so this tool can never disagree with the primer tools about a
21
+ * sequence both of them see.
22
+ */
23
+ import {
24
+ DNA_BASES,
25
+ MolbioInputError,
26
+ dimerThermo,
27
+ duplexThermodynamics,
28
+ endStability5,
29
+ hairpinThermo,
30
+ normalizeSequence,
31
+ reverseComplement,
32
+ } from './lib.mjs';
33
+
34
+ /** Defaults shared by the tool and its tests. */
35
+ export const DUPLEX_THERMO_DEFAULTS = Object.freeze({
36
+ naMm: 50,
37
+ mgMm: 1.5,
38
+ dntpMm: 0.8,
39
+ oligoNm: 250,
40
+ hairpins: 3,
41
+ });
42
+
43
+ /** Longest oligo this model is offered for (structure enumeration is quadratic). */
44
+ const MAX_OLIGO_LENGTH = 200;
45
+
46
+ function round2(value) {
47
+ return Math.round(value * 100) / 100;
48
+ }
49
+
50
+ function finiteOrUndefined(value, field) {
51
+ if (value === undefined) return undefined;
52
+ const parsed = typeof value === 'number' ? value : Number(value);
53
+ if (!Number.isFinite(parsed)) throw new MolbioInputError(`${field} must be a finite number`);
54
+ return parsed;
55
+ }
56
+
57
+ /**
58
+ * Validate and default the condition knobs. Every value is range-checked here
59
+ * so a mistyped concentration fails loudly instead of producing a Tm that looks
60
+ * plausible and is not.
61
+ */
62
+ export function resolveThermoOptions(raw = {}) {
63
+ const na_mm = finiteOrUndefined(raw.na_mm, 'na_mm') ?? DUPLEX_THERMO_DEFAULTS.naMm;
64
+ const mg_mm = finiteOrUndefined(raw.mg_mm, 'mg_mm') ?? DUPLEX_THERMO_DEFAULTS.mgMm;
65
+ const dntp_mm = finiteOrUndefined(raw.dntp_mm, 'dntp_mm') ?? DUPLEX_THERMO_DEFAULTS.dntpMm;
66
+ const oligo_nm = finiteOrUndefined(raw.oligo_nm, 'oligo_nm') ?? DUPLEX_THERMO_DEFAULTS.oligoNm;
67
+ const hairpins = raw.hairpins ?? DUPLEX_THERMO_DEFAULTS.hairpins;
68
+ if (na_mm < 0 || na_mm > 1000) throw new MolbioInputError('na_mm must be between 0 and 1000 mM');
69
+ if (mg_mm < 0 || mg_mm > 500) throw new MolbioInputError('mg_mm must be between 0 and 500 mM');
70
+ if (dntp_mm < 0 || dntp_mm > 500) throw new MolbioInputError('dntp_mm must be between 0 and 500 mM');
71
+ if (oligo_nm < 0.01 || oligo_nm > 1e6) throw new MolbioInputError('oligo_nm must be between 0.01 and 1,000,000 nM');
72
+ if (!Number.isInteger(hairpins) || hairpins < 0 || hairpins > 10) {
73
+ throw new MolbioInputError('hairpins must be an integer between 0 and 10 (0 disables the structure scan)');
74
+ }
75
+ return { naMm: na_mm, mgMm: mg_mm, dntpMm: dntp_mm, oligoNm: oligo_nm, hairpins };
76
+ }
77
+
78
+ /**
79
+ * Normalize one oligo and refuse anything the nearest-neighbour model cannot
80
+ * represent (ambiguity codes, too short, too long).
81
+ */
82
+ export function canonicalOligo(raw, label = 'sequence') {
83
+ const seq = normalizeSequence(raw, label);
84
+ if (seq.length < 4) {
85
+ throw new MolbioInputError(`${label} must be at least 4 bases for a nearest-neighbour estimate (got ${seq.length})`);
86
+ }
87
+ if (seq.length > MAX_OLIGO_LENGTH) {
88
+ throw new MolbioInputError(`${label} must be at most ${MAX_OLIGO_LENGTH} bases (got ${seq.length}); this is a duplex/structure estimator, not a genome-scale model`);
89
+ }
90
+ for (let i = 0; i < seq.length; i++) {
91
+ if (!DNA_BASES.has(seq[i])) {
92
+ throw new MolbioInputError(`${label} contains ${seq[i]} at position ${i + 1}; the nearest-neighbour model covers A/C/G/T only — ambiguity codes have no thermodynamic parameters`);
93
+ }
94
+ }
95
+ return seq;
96
+ }
97
+
98
+ /**
99
+ * Thermodynamics and structure checks for one duplex.
100
+ *
101
+ * @param {string} rawSequence one strand, 5'→3'.
102
+ * @param {object} [rawOptions] partner + condition knobs (see resolveThermoOptions).
103
+ * @returns {object} the tool's structured value (schema in index.mjs).
104
+ */
105
+ export function analyzeDuplex(rawSequence, rawOptions = {}) {
106
+ const sequence = canonicalOligo(rawSequence);
107
+ const opts = resolveThermoOptions(rawOptions);
108
+ const partnerRaw = rawOptions.partner;
109
+ let partner;
110
+ if (partnerRaw !== undefined && partnerRaw !== null && String(partnerRaw).trim() !== '') {
111
+ partner = canonicalOligo(partnerRaw, 'partner');
112
+ if (partner.length !== sequence.length) {
113
+ throw new MolbioInputError(`partner is ${partner.length} bases but sequence is ${sequence.length}; a duplex partner must be the reverse complement of the same length`);
114
+ }
115
+ const expected = reverseComplement(sequence);
116
+ const mismatches = [];
117
+ for (let i = 0; i < sequence.length; i++) {
118
+ if (partner[i] !== expected[i]) mismatches.push(i + 1);
119
+ }
120
+ if (mismatches.length > 0) {
121
+ const shown = mismatches.slice(0, 8).join(', ') + (mismatches.length > 8 ? ', …' : '');
122
+ throw new MolbioInputError(`partner is not the reverse complement of sequence (${mismatches.length} mismatch(es) at position(s) ${shown}); this tool models Watson–Crick duplexes only, so no estimate is given for a mismatched duplex`);
123
+ }
124
+ }
125
+
126
+ const ct = opts.oligoNm * 1e-9;
127
+ const thermo = duplexThermodynamics(sequence, {
128
+ naMm: opts.naMm,
129
+ mgMm: opts.mgMm,
130
+ dntpMm: opts.dntpMm,
131
+ primerNm: opts.oligoNm,
132
+ });
133
+ let gc = 0;
134
+ for (const base of sequence) if (base === 'G' || base === 'C') gc++;
135
+
136
+ const hairpins = opts.hairpins === 0
137
+ ? []
138
+ : hairpinThermo(sequence, ct).slice(0, opts.hairpins).map((hit) => ({
139
+ start: hit.start,
140
+ stem: hit.stem,
141
+ loop: hit.loop,
142
+ tm_celsius: hit.tm,
143
+ delta_g37_kcal: hit.dg37_kcal,
144
+ }));
145
+
146
+ const self = dimerThermo(sequence, sequence, ct);
147
+ const dimers = {
148
+ homodimer_any_tm: self.any_tm,
149
+ homodimer_end_tm: self.end_tm,
150
+ ...partner === undefined ? {} : (() => {
151
+ const hetero = dimerThermo(sequence, partner, ct);
152
+ return { heterodimer_any_tm: hetero.any_tm, heterodimer_end_tm: hetero.end_tm };
153
+ })(),
154
+ };
155
+
156
+ return {
157
+ sequence,
158
+ ...partner === undefined ? {} : { partner },
159
+ length: sequence.length,
160
+ gc_percent: round2((gc / sequence.length) * 100),
161
+ conditions: {
162
+ na_mm: opts.naMm,
163
+ mg_mm: opts.mgMm,
164
+ dntp_mm: opts.dntpMm,
165
+ oligo_nm: opts.oligoNm,
166
+ na_equivalent_mm: round2(thermo.na_equivalent_mm),
167
+ },
168
+ duplex: {
169
+ delta_h_kcal: round2(thermo.dh_kcal),
170
+ delta_s_cal: round2(thermo.ds_cal),
171
+ delta_s_salt_cal: round2(thermo.ds_salt_cal),
172
+ delta_g37_kcal: round2(thermo.delta_g37_kcal),
173
+ tm_celsius: round2(thermo.tm_celsius),
174
+ },
175
+ end_stability_3p_kcal: endStability5(sequence),
176
+ hairpins,
177
+ dimers,
178
+ model: 'santalucia-1998-nn',
179
+ };
180
+ }