invariant-biosynthesis 0.0.3

Biosynthesis safety engine for Invariant: synthesis bundles, D/P/C invariants, hazard screening, attestation. As of 0.2.0 this crate ships from the unified Invariant workspace at https://github.com/clay-good/invariant — the standalone invariant-biosynthesis repo has been merged in.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Protocol-payload invariants PR1–PR4.
//!
//! Step 9 wires the previously-ignored `SynthesisPayload::Protocol` variant
//! into the validator pipeline. The four invariants here focus on the
//! *structure* of a lab-automation protocol — step count, vocabulary,
//! nesting, and aggregate volume — rather than on biology / chemistry per
//! se. They run for every bundle but always pass for non-protocol payloads.
//!
//! ## Allowed-vocabulary policy
//!
//! Profiles do not yet carry a per-installation step whitelist. PR2 falls
//! back to a conservative built-in vocabulary covering common ECL / Opentrons
//! / synthesizer verbs. The profile field can be added later without
//! breaking PR2's contract: any new vocabulary entries simply replace this
//! built-in list.

use serde::{Deserialize, Serialize};

use super::{Invariant, InvariantContext, InvariantId, InvariantStatus};
use crate::models::bundle::{SynthesisBundle, SynthesisPayload};

/// Vocabulary version for the built-in allowed verb list.
///
/// Increment this constant whenever the built-in verb list changes. All
/// deployed profiles must re-validate after a version bump because existing
/// `allowed_protocol_steps` entries may reference verbs that were removed.
/// New verbs can only be added via an RFC process — see `docs/rfcs/README.md`.
pub const PROTOCOL_STEP_VOCAB_VERSION: u32 = 1;

/// Hard upper bound on protocol step count, regardless of profile.
const MAX_STEPS: usize = 256;

/// Built-in allowed step verbs. Each protocol step is matched
/// case-insensitively against the first whitespace-delimited token.
const ALLOWED_VERBS: &[&str] = &[
    "aspirate",
    "dispense",
    "mix",
    "incubate",
    "centrifuge",
    "transfer",
    "wash",
    "elute",
    "heat",
    "cool",
    "shake",
    "vortex",
    "ligate",
    "digest",
    "amplify",
    "anneal",
    "denature",
    "extend",
    "couple",
    "deprotect",
    "cleave",
    "wait",
    "measure",
    "image",
    "log",
];

/// Tokens that indicate a nested protocol invocation.
const NESTED_TOKENS: &[&str] = &["protocol:", "include:", "subprotocol:", "run-protocol"];

/// Returns `true` if `verb` is in the built-in allowed verb list.
pub fn is_builtin_verb(verb: &str) -> bool {
    ALLOWED_VERBS.contains(&verb)
}

fn protocol_steps(bundle: &SynthesisBundle) -> Option<&[String]> {
    match &bundle.payload {
        SynthesisPayload::Protocol { steps } => Some(steps.as_slice()),
        _ => None,
    }
}

fn fail(reason: impl Into<String>) -> InvariantStatus {
    InvariantStatus::Fail {
        reason: reason.into(),
    }
}

fn advisory(note: impl Into<String>) -> InvariantStatus {
    InvariantStatus::Advisory { note: note.into() }
}

// ---------------------------------------------------------------------------
// PR1 — Step count bound
// ---------------------------------------------------------------------------

/// PR1 — Step-count bound.
///
/// Empty protocols are infeasible (no work). Protocols longer than the
/// internal `MAX_STEPS` constant (256) are rejected as runaway and almost
/// always indicate a planner loop or copy-paste error rather than
/// legitimate research.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProtocolStepCount;

impl Invariant for ProtocolStepCount {
    fn id(&self) -> InvariantId {
        InvariantId::Pr1
    }
    fn name(&self) -> &'static str {
        "protocol_step_count"
    }
    fn evaluate(&self, bundle: &SynthesisBundle) -> InvariantStatus {
        let Some(steps) = protocol_steps(bundle) else {
            return InvariantStatus::Pass;
        };
        if steps.is_empty() {
            return fail("protocol has zero steps".to_string());
        }
        if steps.len() > MAX_STEPS {
            return fail(format!(
                "protocol has {} steps (cap {MAX_STEPS})",
                steps.len()
            ));
        }
        InvariantStatus::Pass
    }
}

// ---------------------------------------------------------------------------
// PR2 — Allowed step vocabulary
// ---------------------------------------------------------------------------

/// PR2 — Step-vocabulary check.
///
/// Each step's first token (case-insensitive) must appear in the built-in
/// allowed verb list. Steps with verbs outside that list fail; advisories
/// are out of scope here because executor platforms reject unknown verbs
/// hard.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProtocolAllowedVocabulary;

impl Invariant for ProtocolAllowedVocabulary {
    fn id(&self) -> InvariantId {
        InvariantId::Pr2
    }
    fn name(&self) -> &'static str {
        "protocol_allowed_vocabulary"
    }
    fn evaluate(&self, bundle: &SynthesisBundle) -> InvariantStatus {
        let Some(steps) = protocol_steps(bundle) else {
            return InvariantStatus::Pass;
        };
        let mut bad: Vec<(usize, String)> = Vec::new();
        for (i, step) in steps.iter().enumerate() {
            let verb = step
                .split_whitespace()
                .next()
                .map(|s| s.to_ascii_lowercase())
                .unwrap_or_default();
            if verb.is_empty() {
                bad.push((i, "<empty>".to_string()));
                continue;
            }
            // Strip trailing punctuation (e.g. "aspirate," → "aspirate").
            let verb = verb.trim_end_matches([',', ':', ';', '(']);
            if !ALLOWED_VERBS.contains(&verb) {
                bad.push((i, verb.to_string()));
            }
        }
        if bad.is_empty() {
            InvariantStatus::Pass
        } else {
            let summary = bad
                .iter()
                .map(|(i, v)| format!("step {i}: {v:?}"))
                .collect::<Vec<_>>()
                .join("; ");
            fail(format!("disallowed step verbs: {summary}"))
        }
    }

    fn evaluate_with(
        &self,
        bundle: &SynthesisBundle,
        ctx: &InvariantContext<'_>,
    ) -> InvariantStatus {
        let Some(steps) = protocol_steps(bundle) else {
            return InvariantStatus::Pass;
        };
        // Use profile-supplied list if present, otherwise fall back to built-in default.
        let allowed_verbs: Vec<&str> =
            if let Some(ref profile_steps) = ctx.profile.allowed_protocol_steps {
                profile_steps.iter().map(|s| s.as_str()).collect()
            } else {
                ALLOWED_VERBS.to_vec()
            };

        let mut bad: Vec<(usize, String)> = Vec::new();
        for (i, step) in steps.iter().enumerate() {
            let verb = step
                .split_whitespace()
                .next()
                .map(|s| s.to_ascii_lowercase())
                .unwrap_or_default();
            if verb.is_empty() {
                bad.push((i, "<empty>".to_string()));
                continue;
            }
            let verb = verb.trim_end_matches([',', ':', ';', '(']);
            if !allowed_verbs.contains(&verb) {
                bad.push((i, verb.to_string()));
            }
        }
        if bad.is_empty() {
            InvariantStatus::Pass
        } else {
            let summary = bad
                .iter()
                .map(|(i, v)| format!("step {i}: {v:?}"))
                .collect::<Vec<_>>()
                .join("; ");
            fail(format!("disallowed step verbs: {summary}"))
        }
    }
}

// ---------------------------------------------------------------------------
// PR3 — No nested protocols
// ---------------------------------------------------------------------------

/// PR3 — No-nested-protocol rule.
///
/// Protocol steps must not invoke other protocols (e.g. via `protocol:foo`
/// or `include:bar` directives). Nested protocols circumvent the
/// per-bundle invariant pipeline and are therefore rejected.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProtocolNoNested;

impl Invariant for ProtocolNoNested {
    fn id(&self) -> InvariantId {
        InvariantId::Pr3
    }
    fn name(&self) -> &'static str {
        "protocol_no_nested"
    }
    fn evaluate(&self, bundle: &SynthesisBundle) -> InvariantStatus {
        let Some(steps) = protocol_steps(bundle) else {
            return InvariantStatus::Pass;
        };
        for (i, step) in steps.iter().enumerate() {
            let lower = step.to_ascii_lowercase();
            for tok in NESTED_TOKENS {
                if lower.contains(tok) {
                    return fail(format!("step {i} invokes nested protocol token {tok:?}"));
                }
            }
        }
        InvariantStatus::Pass
    }
}

// ---------------------------------------------------------------------------
// PR4 — Aggregate volume vs profile cap
// ---------------------------------------------------------------------------

/// PR4 — Aggregate-volume budget.
///
/// Sums any explicit volume tokens of the form `<number>(uL|ul|mL|ml|L)`
/// embedded in step strings and compares the total (in mL) against the
/// profile's `max_synthesis_volume_ml`. Steps without parsable volumes are
/// ignored — this is a fail-safe upper-bound check, not a planner.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProtocolAggregateVolume;

impl Invariant for ProtocolAggregateVolume {
    fn id(&self) -> InvariantId {
        InvariantId::Pr4
    }
    fn name(&self) -> &'static str {
        "protocol_aggregate_volume"
    }
    fn evaluate(&self, _bundle: &SynthesisBundle) -> InvariantStatus {
        InvariantStatus::Pass
    }
    fn evaluate_with(
        &self,
        bundle: &SynthesisBundle,
        ctx: &InvariantContext<'_>,
    ) -> InvariantStatus {
        let Some(steps) = protocol_steps(bundle) else {
            return InvariantStatus::Pass;
        };
        let cap_ml = ctx.profile.max_synthesis_volume_ml;
        let mut total_ml = 0.0f64;
        for step in steps {
            for vol_ml in extract_volumes_ml(step) {
                total_ml += vol_ml;
            }
        }
        if total_ml > cap_ml {
            fail(format!(
                "aggregate volume {:.3} mL exceeds profile cap {:.3} mL",
                total_ml, cap_ml
            ))
        } else if total_ml > 0.5 * cap_ml {
            advisory(format!(
                "aggregate volume {:.3} mL is over half of profile cap {:.3} mL",
                total_ml, cap_ml
            ))
        } else {
            InvariantStatus::Pass
        }
    }
}

/// Pull every `<number><unit>` volume token from `step`, normalizing to mL.
/// Recognised units: `uL`, `ul`, `µL`, `mL`, `ml`, `L`. Unknown / missing
/// units yield no contribution.
fn extract_volumes_ml(step: &str) -> Vec<f64> {
    let bytes = step.as_bytes();
    let mut out = Vec::new();
    let mut i = 0usize;
    while i < bytes.len() {
        // Find a digit start.
        if !bytes[i].is_ascii_digit() {
            i += 1;
            continue;
        }
        let num_start = i;
        while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') {
            i += 1;
        }
        let num_end = i;
        // Skip whitespace between number and unit.
        while i < bytes.len() && bytes[i] == b' ' {
            i += 1;
        }
        let unit_start = i;
        while i < bytes.len() && bytes[i].is_ascii_alphabetic() {
            i += 1;
        }
        let unit = &step[unit_start..i];
        let Some(num_str) = step.get(num_start..num_end) else {
            continue;
        };
        let Ok(num) = num_str.parse::<f64>() else {
            continue;
        };
        let factor_to_ml = match unit.to_ascii_lowercase().as_str() {
            "ul" => Some(0.001),
            "ml" => Some(1.0),
            "l" => Some(1000.0),
            _ => None,
        };
        if let Some(f) = factor_to_ml {
            out.push(num * f);
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::bundle::{BundleAuthority, SynthesisPayload};
    use crate::models::profile::BioProfile;
    use chrono::Utc;

    fn protocol(steps: Vec<&str>) -> SynthesisBundle {
        SynthesisBundle {
            timestamp: Utc::now(),
            source: "t".into(),
            sequence: 0,
            payload: SynthesisPayload::Protocol {
                steps: steps.into_iter().map(String::from).collect(),
            },
            delta_time: 0.0,
            authority: BundleAuthority {
                pca_chain: String::new(),
                required_ops: vec![],
            },
            metadata: Default::default(),
        }
    }

    fn dna_bundle() -> SynthesisBundle {
        SynthesisBundle {
            timestamp: Utc::now(),
            source: "t".into(),
            sequence: 0,
            payload: SynthesisPayload::Dna {
                sequence: "ATGCGT".into(),
            },
            delta_time: 0.0,
            authority: BundleAuthority {
                pca_chain: String::new(),
                required_ops: vec![],
            },
            metadata: Default::default(),
        }
    }

    fn profile(cap_ml: f64) -> BioProfile {
        BioProfile {
            name: "t".into(),
            version: "0.1.0".into(),
            bsl_level: 2,
            allowed_substrates: vec!["protocol".into()],
            max_synthesis_volume_ml: cap_ml,
            export_controlled: false,
            profile_signature: None,
            profile_signer_kid: None,
            codon_usage_organism: None,
            codon_entropy_band: None,
            protein_kmer_k: None,
            protein_kmer_threshold: None,
            allowed_protocol_steps: None,
            allow_stale_screening: false,
            stale_screening_max_days: None,
            max_authority_chain_depth: 5,
            max_dna_length_bp: None,
            max_peptide_length_aa: None,
            max_smiles_length_chars: None,
        }
    }

    fn ctx<'a>(prof: &'a BioProfile) -> InvariantContext<'a> {
        InvariantContext {
            screening_hits: &[],
            profile: prof,
        }
    }

    // ---- PR1 ----
    #[test]
    fn pr1_empty_protocol_fails() {
        assert!(matches!(
            ProtocolStepCount.evaluate(&protocol(vec![])),
            InvariantStatus::Fail { .. }
        ));
    }
    #[test]
    fn pr1_oversized_protocol_fails() {
        let many: Vec<&str> = (0..MAX_STEPS + 1).map(|_| "aspirate 10uL").collect();
        assert!(matches!(
            ProtocolStepCount.evaluate(&protocol(many)),
            InvariantStatus::Fail { .. }
        ));
    }
    #[test]
    fn pr1_normal_protocol_passes() {
        assert!(matches!(
            ProtocolStepCount.evaluate(&protocol(vec!["aspirate 10uL"])),
            InvariantStatus::Pass
        ));
    }
    #[test]
    fn pr1_non_protocol_passes() {
        assert!(matches!(
            ProtocolStepCount.evaluate(&dna_bundle()),
            InvariantStatus::Pass
        ));
    }

    // ---- PR2 ----
    #[test]
    fn pr2_allowed_verbs_pass() {
        let p = protocol(vec!["aspirate 10uL", "dispense 10uL", "mix 5"]);
        assert!(matches!(
            ProtocolAllowedVocabulary.evaluate(&p),
            InvariantStatus::Pass
        ));
    }
    #[test]
    fn pr2_disallowed_verb_fails() {
        let p = protocol(vec!["aspirate 10uL", "explode chamber"]);
        assert!(matches!(
            ProtocolAllowedVocabulary.evaluate(&p),
            InvariantStatus::Fail { .. }
        ));
    }
    #[test]
    fn pr2_empty_step_fails() {
        let p = protocol(vec!["aspirate 10uL", ""]);
        assert!(matches!(
            ProtocolAllowedVocabulary.evaluate(&p),
            InvariantStatus::Fail { .. }
        ));
    }

    // ---- PR3 ----
    #[test]
    fn pr3_clean_passes() {
        let p = protocol(vec!["aspirate 10uL"]);
        assert!(matches!(
            ProtocolNoNested.evaluate(&p),
            InvariantStatus::Pass
        ));
    }
    #[test]
    fn pr3_protocol_token_fails() {
        let p = protocol(vec!["protocol:foo"]);
        assert!(matches!(
            ProtocolNoNested.evaluate(&p),
            InvariantStatus::Fail { .. }
        ));
    }
    #[test]
    fn pr3_include_token_fails() {
        let p = protocol(vec!["include:other-protocol"]);
        assert!(matches!(
            ProtocolNoNested.evaluate(&p),
            InvariantStatus::Fail { .. }
        ));
    }

    // ---- PR4 ----
    #[test]
    fn pr4_under_cap_passes() {
        let prof = profile(10.0);
        let p = protocol(vec!["aspirate 100uL", "dispense 200uL"]);
        assert!(matches!(
            ProtocolAggregateVolume.evaluate_with(&p, &ctx(&prof)),
            InvariantStatus::Pass
        ));
    }
    #[test]
    fn pr4_over_cap_fails() {
        let prof = profile(0.5);
        let p = protocol(vec!["aspirate 600uL"]);
        assert!(matches!(
            ProtocolAggregateVolume.evaluate_with(&p, &ctx(&prof)),
            InvariantStatus::Fail { .. }
        ));
    }
    #[test]
    fn pr4_over_half_advisory() {
        let prof = profile(1.0);
        // 600 uL = 0.6 mL, > 0.5 * 1.0
        let p = protocol(vec!["aspirate 600uL"]);
        assert!(matches!(
            ProtocolAggregateVolume.evaluate_with(&p, &ctx(&prof)),
            InvariantStatus::Advisory { .. }
        ));
    }
    #[test]
    fn pr4_no_volumes_passes() {
        let prof = profile(1.0);
        let p = protocol(vec!["mix"]);
        assert!(matches!(
            ProtocolAggregateVolume.evaluate_with(&p, &ctx(&prof)),
            InvariantStatus::Pass
        ));
    }
    #[test]
    fn pr4_unit_aware() {
        let prof = profile(0.5);
        // 1 mL > 0.5 mL cap.
        let p = protocol(vec!["dispense 1mL"]);
        assert!(matches!(
            ProtocolAggregateVolume.evaluate_with(&p, &ctx(&prof)),
            InvariantStatus::Fail { .. }
        ));
    }

    // ---- PR2 profile-driven vocabulary ----
    #[test]
    fn pr2_profile_restricted_list_rejects_default_verb() {
        // Profile only allows "aspirate" and "dispense"
        let mut prof = profile(10.0);
        prof.allowed_protocol_steps = Some(vec!["aspirate".into(), "dispense".into()]);
        let c = ctx(&prof);
        let p = protocol(vec!["aspirate 10uL", "mix 5"]); // "mix" not in restricted list
        assert!(matches!(
            ProtocolAllowedVocabulary.evaluate_with(&p, &c),
            InvariantStatus::Fail { .. }
        ));
    }

    #[test]
    fn pr2_empty_profile_list_rejects_everything() {
        let mut prof = profile(10.0);
        prof.allowed_protocol_steps = Some(vec![]);
        let c = ctx(&prof);
        let p = protocol(vec!["aspirate 10uL"]);
        assert!(matches!(
            ProtocolAllowedVocabulary.evaluate_with(&p, &c),
            InvariantStatus::Fail { .. }
        ));
    }

    #[test]
    fn pr2_no_profile_field_uses_default() {
        let prof = profile(10.0);
        let c = ctx(&prof);
        let p = protocol(vec!["aspirate 10uL", "dispense 10uL"]);
        assert!(matches!(
            ProtocolAllowedVocabulary.evaluate_with(&p, &c),
            InvariantStatus::Pass
        ));
    }

    #[test]
    fn pr2_non_subset_profile_fails_validation() {
        use crate::models::error::Validate;
        let mut prof = profile(10.0);
        prof.allowed_protocol_steps = Some(vec!["aspirate".into(), "nuke_it".into()]);
        assert!(prof.validate().is_err());
    }

    // ---- Volume parser ----
    #[test]
    fn extract_volumes_ml_handles_common_units() {
        assert_eq!(extract_volumes_ml("aspirate 100uL"), vec![0.1]);
        assert_eq!(extract_volumes_ml("dispense 2.5 mL"), vec![2.5]);
        assert_eq!(extract_volumes_ml("transfer 1L"), vec![1000.0]);
        assert!(extract_volumes_ml("mix").is_empty());
        assert!(extract_volumes_ml("incubate at 37C").is_empty()); // 37C is not a volume unit.
    }
}