Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Update PyLabRobot safety workflows
Timothy Kassis70a0d595e54b
diff --git a/skills/pylabrobot/SKILL.md b/skills/pylabrobot/SKILL.mdindex 12976af4..cd2274b5 100644--- a/skills/pylabrobot/SKILL.md+++ b/skills/pylabrobot/SKILL.md@@ -1,182 +1,220 @@---name: pylabrobot-description: Vendor-agnostic lab automation framework. Use when controlling multiple equipment types (Hamilton, Tecan, Opentrons, plate readers, pumps) or needing unified programming across different vendors. Best for complex workflows, multi-vendor setups, simulation. For Opentrons-only protocols with official API, opentrons-integration may be simpler.-license: MIT license-metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}+description: Develop and review PyLabRobot lab-automation resources, liquid-handling plans, offline simulations, and supported-device integrations. Use for PyLabRobot protocols or API questions; keep physical execution behind an explicit operator safety gate.+license: MIT+compatibility: Verified against PyLabRobot 0.2.1 on Python 3.9+. Bundled planning CLIs require only Python 3.11+ and make no serial, USB, or network connections. Physical devices need model-specific extras, configuration, calibration, and trained operator approval.+allowed-tools:+ - Read+ - Write+ - Edit+ - Bash+metadata:+ version: "1.1"+ skill-author: "K-Dense Inc."+ pylabrobot-version: "0.2.1"+ researched: "2026-07-23"---# PyLabRobot-## Overview--PyLabRobot is a hardware-agnostic, pure Python Software Development Kit for automated and autonomous laboratories. Use this skill to control liquid handling robots, plate readers, pumps, heater shakers, incubators, centrifuges, and other laboratory automation equipment through a unified Python interface that works across platforms (Windows, macOS, Linux).--## When to Use This Skill--Use this skill when:-- Programming liquid handling robots (Hamilton STAR/STARlet, Opentrons OT-2, Tecan EVO)-- Automating laboratory workflows involving pipetting, sample preparation, or analytical measurements-- Managing deck layouts and laboratory resources (plates, tips, containers, troughs)-- Integrating multiple lab devices (liquid handlers, plate readers, heater shakers, pumps)-- Creating reproducible laboratory protocols with state management-- Simulating protocols before running on physical hardware-- Reading plates using BMG CLARIOstar or other supported plate readers-- Controlling temperature, shaking, centrifugation, or other material handling operations-- Working with laboratory automation in Python--## Core Capabilities--PyLabRobot provides comprehensive laboratory automation through six main capability areas, each detailed in the references/ directory:--### 1. Liquid Handling (`references/liquid-handling.md`)--Control liquid handling robots for aspirating, dispensing, and transferring liquids. Key operations include:-- **Basic Operations**: Aspirate, dispense, transfer liquids between wells-- **Tip Management**: Pick up, drop, and track pipette tips automatically-- **Advanced Techniques**: Multi-channel pipetting, serial dilutions, plate replication-- **Volume Tracking**: Automatic tracking of liquid volumes in wells-- **Hardware Support**: Hamilton STAR/STARlet, Opentrons OT-2, Tecan EVO, and others--### 2. Resource Management (`references/resources.md`)--Manage laboratory resources in a hierarchical system:-- **Resource Types**: Plates, tip racks, troughs, tubes, carriers, and custom labware-- **Deck Layout**: Assign resources to deck positions with coordinate systems-- **State Management**: Track tip presence, liquid volumes, and resource states-- **Serialization**: Save and load deck layouts and states from JSON files-- **Resource Discovery**: Access wells, tips, and containers through intuitive APIs--### 3. Hardware Backends (`references/hardware-backends.md`)--Connect to diverse laboratory equipment through backend abstraction:-- **Liquid Handlers**: Hamilton STAR (full support), Opentrons OT-2, Tecan EVO-- **Simulation**: ChatterboxBackend for protocol testing without hardware-- **Platform Support**: Works on Windows, macOS, Linux, and Raspberry Pi-- **Backend Switching**: Change robots by swapping backend without rewriting protocols--### 4. Analytical Equipment (`references/analytical-equipment.md`)--Integrate plate readers and analytical instruments:-- **Plate Readers**: BMG CLARIOstar for absorbance, luminescence, fluorescence-- **Scales**: Mettler Toledo integration for mass measurements-- **Integration Patterns**: Combine liquid handlers with analytical equipment-- **Automated Workflows**: Move plates between devices automatically+Use PyLabRobot's hardware-agnostic frontends, resource tree, trackers, and+device-specific backends to develop laboratory automation. Default to local+manifest validation, bookkeeping, and the software-only chatterbox backend.++## Verified snapshot++- PyPI stable: **`PyLabRobot==0.2.1`**, released **2026-03-23**.+- Upstream requirement: **Python >=3.9**. This skill uses Python 3.11 for its+ reproducible smoke tests.+- `/stable/` documentation identifies itself as 0.2.1. `/dev/` and repository+ `main` describe unreleased work and must not be assumed available in 0.2.1.+- Stable liquid-handler backends include `STARBackend`, `VantageBackend`,+ `EVOBackend`, `OpentronsOT2Backend`, and the offline+ `LiquidHandlerChatterboxBackend`.+- PyLabRobot's GitHub Releases page has no 0.2.x software release entry; use+ the PyPI history, `v0.2.1` tag, and changelog as release evidence.++## Non-negotiable hardware boundary++Never connect to, initialize, home, move, heat, shake, spin, pump, open/close,+or otherwise command physical equipment automatically. Do not turn a simulation+plan into a live backend merely by changing an environment variable, config+value, or import.++Before any separately authorized live run, require a trained human to:++1. Explicitly confirm the exact backend, device identity, firmware, transport,+ deck, and protocol revision.+2. Reconcile the physical deck against the resource tree, including carriers,+ adapters, lids, plates, tip racks, waste, labware orientation, barcodes, and+ every occupied coordinate.+3. Verify calibration, teaching, motion envelopes, collision risks, gripper or+ channel clearances, and all aspiration/dispense coordinates.+4. Review source identity and actual fill volume, dead volume, destination+ capacity, tip type/capacity/filter compatibility, channel mapping, units,+ heights, rates, liquid class, blowout/mixing, and contamination boundaries.+5. Confirm guards, doors, waste capacity, containment, emergency stop readiness,+ PPE, biosafety/chemical controls, and a safe abort/recovery procedure.+6. Approve a slow dry run or nonhazardous commissioning run when anything is+ new or changed.++Tracker state is **bookkeeping**, not sensing. It cannot prove that liquid or a+tip is physically present. The Visualizer renders resource/tracker events; it+does not model physics. Chatterbox prints planned operations; it does not prove+calibration, reachability, collision freedom, liquid behavior, or device state.++## Required intake++Do not guess any of these:++- Exact device model, installed options, firmware, computer/OS, and transport.+- Stable PyLabRobot version and required extras.+- Deck/deck origin, carriers, adapters, resource definitions, dimensions,+ coordinates, orientations, and motion clearances.+- Plate/tube/reservoir capacities and dead volumes; initial physical volumes.+- Tip model, filter, fitting, capacity, rack state, channel count, and channel+ mapping.+- Transfer units (`uL`, `mm`, `uL/s`, `s`), heights, rates, mixing, air gaps,+ blowout, liquid properties, and validated vendor liquid class.+- Contamination policy, controls, waste handling, operator interventions,+ acceptance criteria, and recovery procedure.++If information is missing, produce an assumptions/blockers list and an offline+draft only.++## Reproducible install++For offline API inspection and chatterbox simulation:++```bash+uv venv --python 3.11 .venv-pylabrobot+uv pip install --python .venv-pylabrobot/bin/python "PyLabRobot==0.2.1"+```-### 5. Material Handling (`references/material-handling.md`)+On Windows, use `.venv-pylabrobot\Scripts\python.exe`. Do not install hardware+extras until the user names the device and explicitly approves its transport+dependencies. Then inspect the matching stable device page before considering a+pin such as `"PyLabRobot[serial]==0.2.1"` or `"PyLabRobot[usb]==0.2.1"`.-Control environmental and material handling equipment:-- **Heater Shakers**: Hamilton HeaterShaker, Inheco ThermoShake-- **Incubators**: Inheco and Thermo Fisher incubators with temperature control-- **Centrifuges**: Agilent VSpin with bucket positioning and spin control-- **Pumps**: Cole Parmer Masterflex for fluid pumping operations-- **Temperature Control**: Set and monitor temperatures during protocols+## Offline-first workflow-### 6. Visualization & Simulation (`references/visualization.md`)+Run from the repository root. Every bundled CLI uses strict, bounded UTF-8+JSON/CSV, local non-symlink paths, fixed allowlists, and JSON output. None can+select a live backend.-Visualize and simulate laboratory protocols:-- **Browser Visualizer**: Real-time 3D visualization of deck state-- **Simulation Mode**: Test protocols without physical hardware-- **State Tracking**: Monitor tip presence and liquid volumes visually-- **Deck Editor**: Graphical tool for designing deck layouts-- **Protocol Validation**: Verify protocols before running on hardware+```bash+python3 skills/pylabrobot/scripts/validate_manifest.py \+ --input skills/pylabrobot/tests/fixtures/protocol_manifest.json-## Quick Start+python3 skills/pylabrobot/scripts/check_deck_geometry.py \+ --input skills/pylabrobot/tests/fixtures/protocol_manifest.json-To get started with PyLabRobot, install the package and initialize a liquid handler:+python3 skills/pylabrobot/scripts/plan_transfers.py \+ --manifest skills/pylabrobot/tests/fixtures/protocol_manifest.json \+ --transfers skills/pylabrobot/tests/fixtures/transfers.csv-```python-# Install PyLabRobot-# uv pip install pylabrobot+python3 skills/pylabrobot/scripts/generate_simulation_plan.py \+ --manifest skills/pylabrobot/tests/fixtures/protocol_manifest.json \+ --transfers skills/pylabrobot/tests/fixtures/transfers.csv-# Basic liquid handling setup-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import STAR-from pylabrobot.resources import STARLetDeck--# Initialize liquid handler-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-await lh.setup()--# Basic operations-await lh.pick_up_tips(tip_rack["A1:H1"])-await lh.aspirate(plate["A1"], vols=100)-await lh.dispense(plate["A2"], vols=100)-await lh.drop_tips()+python3 skills/pylabrobot/scripts/inspect_backends.py \+ --expected-version 0.2.1 --strict```-## Working with References--This skill organizes detailed information across multiple reference files. Load the relevant reference when:-- **Liquid Handling**: Writing pipetting protocols, tip management, transfers-- **Resources**: Defining deck layouts, managing plates/tips, custom labware-- **Hardware Backends**: Connecting to specific robots, switching platforms-- **Analytical Equipment**: Integrating plate readers, scales, or analytical devices-- **Material Handling**: Using heater shakers, incubators, centrifuges, pumps-- **Visualization**: Simulating protocols, visualizing deck states--All reference files can be found in the `references/` directory and contain comprehensive examples, API usage patterns, and best practices.--## Best Practices--When creating laboratory automation protocols with PyLabRobot:--1. **Start with Simulation**: Use ChatterboxBackend and the visualizer to test protocols before running on hardware-2. **Enable Tracking**: Turn on tip tracking and volume tracking for accurate state management-3. **Resource Naming**: Use clear, descriptive names for all resources (plates, tip racks, containers)-4. **State Serialization**: Save deck layouts and states to JSON for reproducibility-5. **Error Handling**: Implement proper async error handling for hardware operations-6. **Temperature Control**: Set temperatures early as heating/cooling takes time-7. **Modular Protocols**: Break complex workflows into reusable functions-8. **Documentation**: Reference official docs at https://docs.pylabrobot.org for latest features--## Common Workflows+The geometry checker uses conservative static axis-aligned boxes; it is not a+motion planner. The transfer planner requires one new tip per row and checks+source/dead/destination volumes, tip capacity, wells, channels, heights, rates,+units, and allowlists. Review+`assets/protocol-manifest.schema.json` and the synthetic fixtures before making+a project-specific manifest.-### Liquid Transfer Protocol+## Verified software-only example-```python-# Setup-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-await lh.setup()--# Define resources-tip_rack = TIP_CAR_480_A00(name="tip_rack")-source_plate = Cos_96_DW_1mL(name="source")-dest_plate = Cos_96_DW_1mL(name="dest")--lh.deck.assign_child_resource(tip_rack, rails=1)-lh.deck.assign_child_resource(source_plate, rails=10)-lh.deck.assign_child_resource(dest_plate, rails=15)--# Transfer protocol-await lh.pick_up_tips(tip_rack["A1:H1"])-await lh.transfer(source_plate["A1:H12"], dest_plate["A1:H12"], vols=100)-await lh.drop_tips()-```--### Plate Reading Workflow+The exact backend below is software-only. Do not substitute a hardware backend.```python-# Setup plate reader-from pylabrobot.plate_reading import PlateReader-from pylabrobot.plate_reading.clario_star_backend import CLARIOstarBackend--pr = PlateReader(name="CLARIOstar", backend=CLARIOstarBackend())-await pr.setup()--# Set temperature and read-await pr.set_temperature(37)-await pr.open()-# (manually or robotically load plate)-await pr.close()-data = await pr.read_absorbance(wavelength=450)+from pylabrobot.liquid_handling import LiquidHandler+from pylabrobot.liquid_handling.backends import LiquidHandlerChatterboxBackend+from pylabrobot.resources import (+ Cor_96_wellplate_360ul_Fb,+ PLT_CAR_L5AC_A00,+ TIP_CAR_480_A00,+ hamilton_96_tiprack_1000uL_filter,+ set_tip_tracking,+ set_volume_tracking,+)+from pylabrobot.resources.hamilton import STARLetDeck++set_tip_tracking(True)+set_volume_tracking(True)++deck = STARLetDeck()+tip_carrier = TIP_CAR_480_A00(name="tip_carrier")+tips = hamilton_96_tiprack_1000uL_filter(name="tips")+tip_carrier[0] = tips+plate_carrier = PLT_CAR_L5AC_A00(name="plate_carrier")+source = Cor_96_wellplate_360ul_Fb(name="source")+destination = Cor_96_wellplate_360ul_Fb(name="destination")+plate_carrier[0] = source+plate_carrier[1] = destination+deck.assign_child_resource(tip_carrier, rails=3)+deck.assign_child_resource(plate_carrier, rails=15)+source.get_well("A1").tracker.set_volume(100.0) # planned state, not sensing++lh = LiquidHandler(backend=LiquidHandlerChatterboxBackend(), deck=deck)+await lh.setup() # safe here only because the backend above is software-only+try:+ await lh.pick_up_tips(tips["A1"])+ await lh.aspirate(source["A1"], vols=[10.0])+ await lh.dispense(destination["A1"], vols=[10.0])+ await lh.return_tips()+finally:+ await lh.stop()```-## Additional Resources--- **Official Documentation**: https://docs.pylabrobot.org-- **GitHub Repository**: https://github.com/PyLabRobot/pylabrobot-- **Community Forum**: https://discuss.pylabrobot.org-- **PyPI Package**: https://pypi.org/project/PyLabRobot/--For detailed usage of specific capabilities, refer to the corresponding reference file in the `references/` directory.-+## API rules that prevent stale code++- Current names are `STARBackend`, `VantageBackend`, `EVOBackend`, and+ `OpentronsOT2Backend`; do not use stale `STAR`, `TecanBackend`,+ `OpentronsBackend`, or `ChatterboxBackend` imports.+- Use `LiquidHandlerChatterboxBackend` for generic offline liquid-handler+ testing. `ChatterBoxBackend` is a separate legacy-named export; do not+ conflate the two.+- `Visualizer(resource=...)` is valid, followed by `await vis.setup()` and+ `await vis.stop()`; it starts localhost HTTP/WebSocket servers and may open a+ browser.+- There is no generic `from pylabrobot.liquid_handling import LiquidClass` in+ 0.2.1. Stable liquid classes are vendor-specific, for example+ `pylabrobot.liquid_handling.liquid_classes.hamilton.HamiltonLiquidClass`.+- Most frontend methods are async. Backend kwargs and capabilities are+ vendor/model specific; a shared frontend does not imply identical behavior.++## References++- [Liquid handling](references/liquid-handling.md) — operations, tips, tracking,+ liquid classes, units, and validation.+- [Resources](references/resources.md) — decks, coordinates, plates, tip racks,+ collisions, state, and serialization.+- [Hardware backends](references/hardware-backends.md) — verified names,+ support levels, capabilities, and live-run gate.+- [Analytical equipment](references/analytical-equipment.md) — plate readers+ and scales.+- [Material handling](references/material-handling.md) — pumps, heaters,+ shakers, temperature control, storage, and centrifuges.+- [Visualization](references/visualization.md) — chatterbox, Visualizer,+ localhost services, and simulation limits.++## Dated upstream sources++Checked **2026-07-23**:++- [PyPI 0.2.1](https://pypi.org/project/PyLabRobot/) — released 2026-03-23;+ Python >=3.9; extras and artifacts.+- [Stable installation guide](https://docs.pylabrobot.org/stable/user_guide/_getting-started/installation.html)+ — stable versus source/dev install and optional transport groups.+- [Stable API](https://docs.pylabrobot.org/stable/api/pylabrobot.html) and+ [supported machines](https://docs.pylabrobot.org/stable/user_guide/machines.html)+ — 0.2.1 API and model-specific support labels.+- [`v0.2.1` source tag](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1)+ and [changelog](https://github.com/PyLabRobot/pylabrobot/blob/main/CHANGELOG.md)+ — tag dated 2026-03-23; `Unreleased` is development-only.diff --git a/skills/pylabrobot/assets/protocol-manifest.schema.json b/skills/pylabrobot/assets/protocol-manifest.schema.jsonnew file mode 100644index 00000000..41ac1b14--- /dev/null+++ b/skills/pylabrobot/assets/protocol-manifest.schema.json@@ -0,0 +1,367 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "urn:pylabrobot-skill:protocol-manifest:1.0",+ "title": "Offline PyLabRobot protocol manifest",+ "description": "Documentation schema for the dependency-free validator. The bundled Python validator additionally enforces numeric bounds, unique names, well bounds, allowlists, and safety invariants without fetching this URI or any remote reference.",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "schema_version",+ "protocol_id",+ "mode",+ "units",+ "deck",+ "resources",+ "constraints"+ ],+ "properties": {+ "schema_version": {+ "const": "1.0"+ },+ "protocol_id": {+ "$ref": "#/$defs/name"+ },+ "mode": {+ "const": "offline"+ },+ "units": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "volume",+ "length",+ "rate",+ "time"+ ],+ "properties": {+ "volume": {+ "const": "uL"+ },+ "length": {+ "const": "mm"+ },+ "rate": {+ "const": "uL/s"+ },+ "time": {+ "const": "s"+ }+ }+ },+ "deck": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "size_mm"+ ],+ "properties": {+ "name": {+ "$ref": "#/$defs/name"+ },+ "size_mm": {+ "$ref": "#/$defs/positive_xyz"+ }+ }+ },+ "resources": {+ "type": "array",+ "minItems": 1,+ "maxItems": 256,+ "items": {+ "oneOf": [+ {+ "$ref": "#/$defs/liquid_resource"+ },+ {+ "$ref": "#/$defs/tip_rack"+ },+ {+ "$ref": "#/$defs/waste"+ }+ ]+ }+ },+ "constraints": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "allowed_liquid_classes",+ "allowed_tip_types",+ "channels",+ "requires_human_confirmation",+ "max_transfer_uL",+ "max_rate_uL_s"+ ],+ "properties": {+ "allowed_liquid_classes": {+ "$ref": "#/$defs/name_list"+ },+ "allowed_tip_types": {+ "$ref": "#/$defs/name_list"+ },+ "channels": {+ "type": "integer",+ "minimum": 1,+ "maximum": 96+ },+ "requires_human_confirmation": {+ "const": true+ },+ "max_transfer_uL": {+ "$ref": "#/$defs/positive_volume"+ },+ "max_rate_uL_s": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 10000+ }+ }+ }+ },+ "$defs": {+ "name": {+ "type": "string",+ "pattern": "^[A-Za-z][A-Za-z0-9_-]{0,63}$"+ },+ "well": {+ "type": "string",+ "pattern": "^[A-Z]{1,2}[1-9][0-9]{0,2}$"+ },+ "positive_volume": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 1000000+ },+ "name_list": {+ "type": "array",+ "minItems": 1,+ "maxItems": 256,+ "uniqueItems": true,+ "items": {+ "$ref": "#/$defs/name"+ }+ },+ "location_xyz": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "x",+ "y",+ "z"+ ],+ "properties": {+ "x": {+ "type": "number",+ "minimum": 0,+ "maximum": 5000+ },+ "y": {+ "type": "number",+ "minimum": 0,+ "maximum": 5000+ },+ "z": {+ "type": "number",+ "minimum": 0,+ "maximum": 5000+ }+ }+ },+ "positive_xyz": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "x",+ "y",+ "z"+ ],+ "properties": {+ "x": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 5000+ },+ "y": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 5000+ },+ "z": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 5000+ }+ }+ },+ "liquid_grid": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "rows",+ "columns",+ "well_capacity_uL",+ "dead_volume_uL",+ "well_depth_mm"+ ],+ "properties": {+ "rows": {+ "type": "integer",+ "minimum": 1,+ "maximum": 384+ },+ "columns": {+ "type": "integer",+ "minimum": 1,+ "maximum": 384+ },+ "well_capacity_uL": {+ "$ref": "#/$defs/positive_volume"+ },+ "dead_volume_uL": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "well_depth_mm": {+ "type": "number",+ "exclusiveMinimum": 0,+ "maximum": 5000+ }+ }+ },+ "tip_grid": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "rows",+ "columns",+ "tip_capacity_uL"+ ],+ "properties": {+ "rows": {+ "type": "integer",+ "minimum": 1,+ "maximum": 384+ },+ "columns": {+ "type": "integer",+ "minimum": 1,+ "maximum": 384+ },+ "tip_capacity_uL": {+ "$ref": "#/$defs/positive_volume"+ }+ }+ },+ "liquid_resource": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "kind",+ "location_mm",+ "size_mm",+ "grid",+ "initial_volumes_uL"+ ],+ "properties": {+ "name": {+ "$ref": "#/$defs/name"+ },+ "kind": {+ "enum": [+ "plate",+ "reservoir",+ "tube_rack"+ ]+ },+ "location_mm": {+ "$ref": "#/$defs/location_xyz"+ },+ "size_mm": {+ "$ref": "#/$defs/positive_xyz"+ },+ "grid": {+ "$ref": "#/$defs/liquid_grid"+ },+ "initial_volumes_uL": {+ "type": "object",+ "propertyNames": {+ "$ref": "#/$defs/well"+ },+ "additionalProperties": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ }+ }+ }+ },+ "tip_rack": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "kind",+ "location_mm",+ "size_mm",+ "grid",+ "tip_type",+ "tips_available"+ ],+ "properties": {+ "name": {+ "$ref": "#/$defs/name"+ },+ "kind": {+ "const": "tip_rack"+ },+ "location_mm": {+ "$ref": "#/$defs/location_xyz"+ },+ "size_mm": {+ "$ref": "#/$defs/positive_xyz"+ },+ "grid": {+ "$ref": "#/$defs/tip_grid"+ },+ "tip_type": {+ "$ref": "#/$defs/name"+ },+ "tips_available": {+ "type": "array",+ "minItems": 1,+ "uniqueItems": true,+ "items": {+ "$ref": "#/$defs/well"+ }+ }+ }+ },+ "waste": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "kind",+ "location_mm",+ "size_mm"+ ],+ "properties": {+ "name": {+ "$ref": "#/$defs/name"+ },+ "kind": {+ "const": "waste"+ },+ "location_mm": {+ "$ref": "#/$defs/location_xyz"+ },+ "size_mm": {+ "$ref": "#/$defs/positive_xyz"+ }+ }+ }+ }+}diff --git a/skills/pylabrobot/references/analytical-equipment.md b/skills/pylabrobot/references/analytical-equipment.mdindex 307b51fb..1c664020 100644--- a/skills/pylabrobot/references/analytical-equipment.md+++ b/skills/pylabrobot/references/analytical-equipment.md@@ -1,464 +1,200 @@-# Analytical Equipment in PyLabRobot+# Analytical equipment-## Overview+Verified against **PyLabRobot 0.2.1** on **2026-07-23**. This reference describes+APIs without connecting to or commanding instruments.-PyLabRobot integrates with analytical equipment including plate readers, scales, and other measurement devices. This allows automated workflows that combine liquid handling with analytical measurements.+## Plate-reader frontend-## Plate Readers--### BMG CLARIOstar (Plus)--The BMG Labtech CLARIOstar and CLARIOstar Plus are microplate readers that measure absorbance, luminescence, and fluorescence.--#### Hardware Setup--**Physical Connections:**-1. IEC C13 power cord to mains power-2. USB-B cable to computer (with security screws on device end)-3. Optional: RS-232 port for plate stacking units--**Communication:**-- Serial connection through FTDI/USB-A at firmware level-- Cross-platform support (Windows, macOS, Linux)--#### Software Setup+Stable imports include:```python-from pylabrobot.plate_reading import PlateReader-from pylabrobot.plate_reading.clario_star_backend import CLARIOstarBackend--# Create backend-backend = CLARIOstarBackend()--# Initialize plate reader-pr = PlateReader(- name="CLARIOstar",- backend=backend,- size_x=0.0, # Physical dimensions not critical for plate readers- size_y=0.0,- size_z=0.0+from pylabrobot.plate_reading import (+ CLARIOstarBackend,+ Cytation5Backend,+ PlateReader,+ PlateReaderChatterboxBackend,)--# Setup (initializes device)-await pr.setup()--# When done-await pr.stop()-```--#### Basic Operations--**Opening and Closing:**--```python-# Open loading tray-await pr.open()--# (Load plate manually or robotically)--# Close loading tray-await pr.close()```-**Temperature Control:**--```python-# Set temperature (in Celsius)-await pr.set_temperature(37)+`PlateReader` is a resource and requires dimensions plus a backend:-# Note: Reaching temperature is slow-# Set temperature early in protocol+```text+PlateReader(name, size_x, size_y, size_z, backend, rotation=None,+ category="plate_reader", model=None,+ child_location=Coordinate(...), preferred_pickup_location=None)```-**Reading Measurements:**--```python-# Absorbance reading-data = await pr.read_absorbance(wavelength=450) # nm--# Luminescence reading-data = await pr.read_luminescence()--# Fluorescence reading-data = await pr.read_fluorescence(- excitation_wavelength=485, # nm- emission_wavelength=535 # nm-)+Do not copy the stale constructor+`PlateReader(name="CLARIOstar", backend=CLARIOstarBackend())`; the stable+frontend requires `size_x`, `size_y`, and `size_z`.++Verified frontend methods include:++```text+open(**backend_kwargs)+close(**backend_kwargs)+read_absorbance(wavelength, wells=None, use_new_return_type=False,+ **backend_kwargs)+read_fluorescence(excitation_wavelength, emission_wavelength, focal_height,+ wells=None, use_new_return_type=False, **backend_kwargs)+read_luminescence(focal_height, wells=None, use_new_return_type=False,+ **backend_kwargs)```-#### Data Format--Plate reader methods return array data:+The old examples in this skill incorrectly treated return values as a guaranteed+NumPy `8x12` array and omitted required focal height. In 0.2.1 the annotated+return is `List[Dict]`; backend and `use_new_return_type` affect the concrete+shape. Record the exact method arguments, plate/well mapping, instrument+settings, raw response, and package/backend version before analysis.-```python-import numpy as np+`PlateReader` does not expose a universal `set_temperature` method in the+verified 0.2.1 frontend. Temperature, shaking, injectors, kinetics, pathlength,+read mode, and optics are backend/model-specific; do not infer them from another+reader.-# Read absorbance-data = await pr.read_absorbance(wavelength=450)+## Offline interface checks-# data is typically a 2D array (8x12 for 96-well plate)-print(f"Data shape: {data.shape}")-print(f"Well A1: {data[0][0]}")-print(f"Well H12: {data[7][11]}")+`PlateReaderChatterboxBackend` is available for software-only frontend testing.+It can exercise method calls and resource state without an instrument, but it+does not simulate optics, plate seating, thermal behavior, gain, focus,+measurement noise, or assay chemistry.-# Convert to DataFrame for easier handling-import pandas as pd-df = pd.DataFrame(data)-```+For import and method-presence checks without backend construction:-#### Integration with Liquid Handler--Combine plate reading with liquid handling:--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import STAR-from pylabrobot.resources import STARLetDeck-from pylabrobot.plate_reading import PlateReader-from pylabrobot.plate_reading.clario_star_backend import CLARIOstarBackend--# Initialize liquid handler-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-await lh.setup()--# Initialize plate reader-pr = PlateReader(name="CLARIOstar", backend=CLARIOstarBackend())-await pr.setup()--# Set temperature early-await pr.set_temperature(37)--try:- # Prepare samples with liquid handler- tip_rack = TIP_CAR_480_A00(name="tips")- reagent_plate = Cos_96_DW_1mL(name="reagents")- assay_plate = Cos_96_DW_1mL(name="assay")-- lh.deck.assign_child_resource(tip_rack, rails=1)- lh.deck.assign_child_resource(reagent_plate, rails=10)- lh.deck.assign_child_resource(assay_plate, rails=15)-- # Transfer samples- await lh.pick_up_tips(tip_rack["A1:H1"])- await lh.transfer(- reagent_plate["A1:H12"],- assay_plate["A1:H12"],- vols=100- )- await lh.drop_tips()-- # Move plate to reader (manual or robotic arm)- print("Move assay plate to plate reader")- input("Press Enter when plate is loaded...")-- # Read plate- await pr.open()- # (plate loaded here)- await pr.close()-- data = await pr.read_absorbance(wavelength=450)- print(f"Absorbance data: {data}")--finally:- await lh.stop()- await pr.stop()+```bash+python3 skills/pylabrobot/scripts/inspect_backends.py \+ --expected-version 0.2.1 --strict```-#### Advanced Features--**Development Status:**--Some CLARIOstar features are under development:-- Spectral scanning-- Injector needle control-- Detailed measurement parameter configuration-- Well-specific reading patterns--Check current documentation for latest feature support.--#### Best Practices--1. **Temperature Control**: Set temperature early as heating is slow-2. **Plate Loading**: Ensure plate is properly seated before closing-3. **Measurement Selection**: Choose appropriate wavelengths for your assay-4. **Data Validation**: Check measurement quality and expected ranges-5. **Error Handling**: Handle timeout and communication errors-6. **Maintenance**: Keep optics clean per manufacturer guidelines--#### Example: Complete Plate Reading Workflow--```python-async def run_plate_reading_assay():- """Complete workflow with sample prep and reading"""-- # Initialize equipment- lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())- pr = PlateReader(name="CLARIOstar", backend=CLARIOstarBackend())-- await lh.setup()- await pr.setup()-- # Set plate reader temperature- await pr.set_temperature(37)-- try:- # Define resources- tip_rack = TIP_CAR_480_A00(name="tips")- samples = Cos_96_DW_1mL(name="samples")- assay_plate = Cos_96_DW_1mL(name="assay")- substrate = Trough_100ml(name="substrate")-- lh.deck.assign_child_resource(tip_rack, rails=1)- lh.deck.assign_child_resource(substrate, rails=5)- lh.deck.assign_child_resource(samples, rails=10)- lh.deck.assign_child_resource(assay_plate, rails=15)-- # Transfer samples- await lh.pick_up_tips(tip_rack["A1:H1"])- await lh.transfer(- samples["A1:H12"],- assay_plate["A1:H12"],- vols=50- )- await lh.drop_tips()-- # Add substrate- await lh.pick_up_tips(tip_rack["A2:H2"])- for col in range(1, 13):- await lh.transfer(- substrate["channel_1"],- assay_plate[f"A{col}:H{col}"],- vols=50- )- await lh.drop_tips()-- # Incubate (if needed)- # await asyncio.sleep(300) # 5 minutes-- # Move to plate reader- print("Transfer assay plate to CLARIOstar")- input("Press Enter when ready...")-- await pr.open()- input("Press Enter when plate is loaded...")- await pr.close()-- # Read absorbance- data = await pr.read_absorbance(wavelength=450)-- # Process results- import pandas as pd- df = pd.DataFrame(- data,- index=[f"{r}" for r in "ABCDEFGH"],- columns=[f"{c}" for c in range(1, 13)]- )-- print("Absorbance Results:")- print(df)-- # Save results- df.to_csv("plate_reading_results.csv")-- return df-- finally:- await lh.stop()- await pr.stop()--# Run assay-results = await run_plate_reading_assay()-```+The inspector does not call `setup()` and makes no transport connection.++## Stable plate-reader inventory++The stable 0.2.1 supported-machines page lists:++- **BMG Labtech CLARIOstar (Plus): Full** — absorbance, fluorescence,+ luminescence.+- **Agilent/BioTek Cytation 1 and Cytation 5: Full** — absorbance,+ fluorescence, luminescence, microscopy.+- **Agilent/BioTek Synergy H1: Full**.+- **Byonoy Absorbance 96 Automate: Full**.+- **Byonoy Luminescence 96 and Luminescence 96 Automate: Full**.+- **Molecular Devices SpectraMax M5e: Full**.+- **Molecular Devices SpectraMax 384plus: Full**.+- **Molecular Devices ImageXpress Pico: Basics**.+- **Tecan Infinite 200 PRO: Mostly**.++The installed 0.2.1 package also exports+`ExperimentalTecanInfinite200ProBackend` and `ExperimentalSparkBackend`; the+`Experimental` prefix is meaningful. The 0.2.1 changelog records Infinite 200+PRO and Spark backend additions, but do not upgrade that to a generic/full+support claim.++Support is model-specific. Confirm serial/FTDI/USB/SiLA/microscopy extras,+firmware, instrument options, plate types, optics, and methods on the exact+stable page.++## Plate-reader live-run checklist++Before a separately authorized connection or read:++1. Confirm instrument model, serial/device ID, firmware, approved transport,+ exclusive control, and current calibration/QC.+2. Confirm plate manufacturer/catalog, format, material, bottom, lid/seal,+ orientation, barcode, and correct seating.+3. Confirm read mode and units: wavelength(s), focal height, gain, flashes,+ integration, shaking, temperature, kinetics, injectors, well selection, and+ read direction as applicable.+4. Check tray/door state and robot/manual transfer path; prevent closing on an+ obstruction or moving a plate while a device is active.+5. Include blanks, standards, controls, expected ranges, saturation rules, and+ acceptance criteria.+6. Save raw data and complete settings before derived analysis.++Opening/closing a tray is physical motion. Never call it merely to test+connectivity.## Scales-### Mettler Toledo Scales--PyLabRobot supports Mettler Toledo scales for mass measurements.--#### Setup+Stable frontend:```pythonfrom pylabrobot.scales import Scale-from pylabrobot.scales.mettler_toledo_backend import MettlerToledoBackend--# Create scale-scale = Scale(- name="analytical_scale",- backend=MettlerToledoBackend()-)--await scale.setup()```-#### Operations+Verified methods are:-```python-# Get weight measurement-weight = await scale.get_weight() # Returns weight in grams-print(f"Weight: {weight} g")--# Tare (zero) the scale-await scale.tare()--# Get multiple measurements-weights = []-for i in range(5):- w = await scale.get_weight()- weights.append(w)- await asyncio.sleep(1)--average_weight = sum(weights) / len(weights)-print(f"Average weight: {average_weight} g")+```text+get_weight(**backend_kwargs) -> float+tare(**backend_kwargs)+zero(**backend_kwargs)```-#### Integration with Liquid Handler+The stable README shows the model-specific backend:```python-# Weigh samples during protocol-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-scale = Scale(name="scale", backend=MettlerToledoBackend())--await lh.setup()-await scale.setup()--try:- # Tare scale- await scale.tare()-- # Dispense liquid- await lh.pick_up_tips(tip_rack["A1"])- await lh.aspirate(reagent["A1"], vols=1000)-- # (Move to scale position)-- # Dispense and weigh- await lh.dispense(container, vols=1000)- weight = await scale.get_weight()-- print(f"Dispensed weight: {weight} g")-- # Calculate actual volume (assuming density = 1 g/mL for water)- actual_volume = weight * 1000 # Convert g to µL- print(f"Actual volume: {actual_volume} µL")-- await lh.drop_tips()--finally:- await lh.stop()- await scale.stop()+from pylabrobot.scales.mettler_toledo import MettlerToledoWXS205SDU```-## Other Analytical Devices+Do not instantiate it or call `setup()` during planning. Stable supported+machines lists the **Mettler Toledo WXS205SDU: Full**.-### Flow Cytometers+Before live weighing, verify:-Some flow cytometer integrations are in development. Check current documentation for support status.+- model, port, units, resolution, range, calibration, leveling, warm-up, and+ environmental limits;+- tare container, stability/status flags, vibration, drafts, static, and+ evaporation;+- whether returned values are stable/net/gross and how errors are represented;+- physical placement/removal route and collision clearance.-### Spectrophotometers+Mass is not automatically volume. Converting grams to microlitres requires a+validated density at the relevant temperature and uncertainty propagation. Do+not assume water density equals exactly `1 g/mL`.-Additional spectrophotometer models may be supported. Check documentation for current device compatibility.+## Coordinating liquid handlers and analytical devices-## Multi-Device Workflows+Treat each device as a separate state machine:-### Coordinating Multiple Devices+- never overlap motion unless the workcell has an approved interlock and+ scheduler;+- transfer ownership of a plate explicitly between deck, arm, reader, scale,+ and operator;+- verify doors/trays/buckets are in the required state;+- use unique plate IDs and record handoff timestamps;+- stop safely on partial failure; do not blindly retry a measurement or move;+- distinguish software resource assignment from physical plate location.-```python-async def multi_device_workflow():- """Coordinate liquid handler, plate reader, and scale"""-- # Initialize all devices- lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())- pr = PlateReader(name="CLARIOstar", backend=CLARIOstarBackend())- scale = Scale(name="scale", backend=MettlerToledoBackend())-- await lh.setup()- await pr.setup()- await scale.setup()-- try:- # 1. Weigh reagent- await scale.tare()- # (place container on scale)- reagent_weight = await scale.get_weight()-- # 2. Prepare samples with liquid handler- await lh.pick_up_tips(tip_rack["A1:H1"])- await lh.transfer(source["A1:H12"], dest["A1:H12"], vols=100)- await lh.drop_tips()-- # 3. Read plate- await pr.open()- # (load plate)- await pr.close()- data = await pr.read_absorbance(wavelength=450)-- return {- "reagent_weight": reagent_weight,- "absorbance_data": data- }-- finally:- await lh.stop()- await pr.stop()- await scale.stop()-```+An async Python call does not create a physical safety interlock.-## Best Practices+## Data integrity-1. **Device Initialization**: Setup all devices at start of protocol-2. **Error Handling**: Handle communication errors gracefully-3. **Cleanup**: Always call `stop()` on all devices-4. **Timing**: Account for device-specific timing (temperature equilibration, measurement time)-5. **Calibration**: Follow manufacturer calibration procedures-6. **Data Validation**: Verify measurements are within expected ranges-7. **Documentation**: Record device settings and parameters-8. **Integration Testing**: Test multi-device workflows thoroughly-9. **Concurrent Operations**: Use async to overlap operations when possible-10. **Data Storage**: Save raw data with metadata (timestamps, settings)+For every measurement, retain:-## Common Patterns+- protocol and manifest revisions;+- PyLabRobot/backend version and instrument identity/firmware;+- plate/barcode and well map;+- complete acquisition settings and units;+- calibration/QC status, blanks/controls, timestamps, and error/status fields;+- unmodified raw output plus checksums;+- transformation code/version and rejected/out-of-range values.-### Kinetic Plate Reading+Validate dimensions and well labels before joining measurement data to sample+metadata.-```python-async def kinetic_reading(num_reads: int, interval: int):- """Perform kinetic plate reading"""-- pr = PlateReader(name="CLARIOstar", backend=CLARIOstarBackend())- await pr.setup()-- try:- await pr.set_temperature(37)- await pr.open()- # (load plate)- await pr.close()-- results = []- for i in range(num_reads):- data = await pr.read_absorbance(wavelength=450)- timestamp = time.time()- results.append({- "read_number": i + 1,- "timestamp": timestamp,- "data": data- })-- if i < num_reads - 1:- await asyncio.sleep(interval)-- return results-- finally:- await pr.stop()--# Read every 30 seconds for 10 minutes-results = await kinetic_reading(num_reads=20, interval=30)-```+## Sources-## Additional Resources+Checked **2026-07-23**:-- Plate Reading Documentation: https://docs.pylabrobot.org/user_guide/02_analytical/-- BMG CLARIOstar Guide: https://docs.pylabrobot.org/user_guide/02_analytical/plate-reading/bmg-clariostar.html-- API Reference: https://docs.pylabrobot.org/api/pylabrobot.plate_reading.html-- Supported Equipment: https://docs.pylabrobot.org/user_guide/machines.html+- [Stable supported machines](https://docs.pylabrobot.org/stable/user_guide/machines.html)+ — analytical inventory and support labels (page metadata surfaced+ 2025-01-01; docs version 0.2.1).+- [Stable plate-reading guide](https://docs.pylabrobot.org/stable/user_guide/02_analytical/plate-reading/plate-reading.html)+ and [plate-reading API](https://docs.pylabrobot.org/stable/api/pylabrobot.plate_reading.html).+- [Stable scales guide](https://docs.pylabrobot.org/stable/user_guide/02_analytical/scales/scales.html)+ and [scales API](https://docs.pylabrobot.org/stable/api/pylabrobot.scales.html).+- [`v0.2.1` plate-reading source](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1/pylabrobot/plate_reading)+ and [scale source](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1/pylabrobot/scales)+ — exact constructors/methods; tag dated 2026-03-23.+- [0.2.1 changelog](https://github.com/PyLabRobot/pylabrobot/blob/main/CHANGELOG.md#021)+ — Tecan Infinite 200 PRO/Spark additions.diff --git a/skills/pylabrobot/references/hardware-backends.md b/skills/pylabrobot/references/hardware-backends.mdindex 3afa4da0..5a9e3d73 100644--- a/skills/pylabrobot/references/hardware-backends.md+++ b/skills/pylabrobot/references/hardware-backends.md@@ -1,480 +1,215 @@-# Hardware Backends in PyLabRobot+# Hardware backends and supported robots-## Overview+Verified against **PyLabRobot 0.2.1** on **2026-07-23**. Support labels below+come from the stable supported-machines page, not from marketing claims.-PyLabRobot uses a backend abstraction system that allows the same protocol code to run on different liquid handling robots and platforms. Backends handle device-specific communication while the `LiquidHandler` frontend provides a unified interface.+## Architecture-## Backend Architecture+PyLabRobot separates:-### How Backends Work+- a frontend such as `LiquidHandler`, which validates and records standard+ operations;+- a backend, which translates those operations for one device family;+- a resource/deck tree, which supplies geometry and state.-1. **Frontend**: `LiquidHandler` class provides high-level API-2. **Backend**: Device-specific class handles hardware communication-3. **Protocol**: Same code works across different backends+A common frontend does not guarantee identical channels, tools, operations,+parameters, calibration, error semantics, timing, or firmware support.+Backend-specific kwargs must be reviewed against the exact stable model page.-```python-# Same protocol code-await lh.pick_up_tips(tip_rack["A1"])-await lh.aspirate(plate["A1"], vols=100)-await lh.dispense(plate["A2"], vols=100)-await lh.drop_tips()--# Works with any backend (STAR, Opentrons, simulation, etc.)-```--### Backend Interface--All backends inherit from `LiquidHandlerBackend` and implement:-- `setup()`: Initialize connection to hardware-- `stop()`: Close connection and cleanup-- Device-specific command methods (aspirate, dispense, etc.)--## Supported Backends--### Hamilton STAR (Full Support)--The Hamilton STAR and STARlet liquid handling robots have full PyLabRobot support.--**Setup:**--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import STAR-from pylabrobot.resources import STARLetDeck--# Create STAR backend-backend = STAR()--# Initialize liquid handler-lh = LiquidHandler(backend=backend, deck=STARLetDeck())-await lh.setup()-```--**Platform Support:**-- Windows ✅-- macOS ✅-- Linux ✅-- Raspberry Pi ✅--**Communication:**-- USB connection to robot-- Direct firmware commands-- No Hamilton software required--**Features:**-- Full liquid handling operations-- CO-RE tip support-- 96-channel head support (if equipped)-- Temperature control-- Carrier and rail-based positioning--**Deck Types:**-```python-from pylabrobot.resources import STARLetDeck, STARDeck--# For STARlet (smaller deck)-deck = STARLetDeck()--# For STAR (full deck)-deck = STARDeck()-```--**Example:**+## Verified stable liquid-handler names```pythonfrom pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import STAR-from pylabrobot.resources import STARLetDeck, TIP_CAR_480_A00, Cos_96_DW_1mL--# Initialize-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-await lh.setup()--# Define resources-tip_rack = TIP_CAR_480_A00(name="tips")-plate = Cos_96_DW_1mL(name="plate")--# Assign to rails-lh.deck.assign_child_resource(tip_rack, rails=1)-lh.deck.assign_child_resource(plate, rails=10)--# Execute protocol-await lh.pick_up_tips(tip_rack["A1"])-await lh.transfer(plate["A1"], plate["A2"], vols=100)-await lh.drop_tips()--await lh.stop()-```--### Opentrons OT-2 (Supported)--The Opentrons OT-2 is supported through the Opentrons HTTP API.--**Setup:**--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import OpentronsBackend-from pylabrobot.resources import OTDeck--# Create Opentrons backend (requires robot IP address)-backend = OpentronsBackend(host="192.168.1.100") # Replace with your robot's IP--# Initialize liquid handler-lh = LiquidHandler(backend=backend, deck=OTDeck())-await lh.setup()-```--**Platform Support:**-- Any platform with network access to OT-2--**Communication:**-- HTTP API over network-- Requires robot IP address-- No Opentrons app required--**Features:**-- 8-channel pipette support-- Single-channel pipette support-- Standard OT-2 deck layout-- Coordinate-based positioning--**Limitations:**-- Uses older Opentrons HTTP API-- Some features may be limited compared to STAR--**Example:**--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import OpentronsBackend-from pylabrobot.resources import OTDeck--# Initialize with robot IP-lh = LiquidHandler(- backend=OpentronsBackend(host="192.168.1.100"),- deck=OTDeck()+from pylabrobot.liquid_handling.backends import (+ EVOBackend,+ LiquidHandlerChatterboxBackend,+ OpentronsOT2Backend,+ STARBackend,+ VantageBackend,)-await lh.setup()--# Load deck layout-lh.deck = Deck.load_from_json_file("opentrons_layout.json")--# Execute protocol-await lh.pick_up_tips(tip_rack["A1"])-await lh.transfer(plate["A1"], plate["A2"], vols=100)-await lh.drop_tips()--await lh.stop()-```--### Tecan EVO (Work in Progress)--Support for Tecan EVO liquid handling robots is under development.--**Current Status:**-- Work-in-progress-- Basic commands may be available-- Check documentation for current feature support--**Setup (when available):**--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import TecanBackend-from pylabrobot.resources import TecanDeck--backend = TecanBackend()-lh = LiquidHandler(backend=backend, deck=TecanDeck())```-### Hamilton Vantage (Mostly Supported)--Hamilton Vantage has "mostly" complete support.+Do not use stale names from older skill text:-**Setup:**--```python-from pylabrobot.liquid_handling.backends import Vantage-from pylabrobot.resources import VantageDeck--lh = LiquidHandler(backend=Vantage(), deck=VantageDeck())-```+- `STAR` is not the stable high-level backend name; use `STARBackend`.+- `TecanBackend` is not the 0.2.1 EVO backend; use `EVOBackend`.+- `OpentronsBackend` is stale; use `OpentronsOT2Backend`.+- `ChatterboxBackend` has incorrect naming/capitalization for the recommended+ generic liquid-handler testing backend; use+ `LiquidHandlerChatterboxBackend`.+- `ChatterBoxBackend` (capital `B`) is a separate exported legacy-named class.+ Avoid it when the stable docs specifically call for+ `LiquidHandlerChatterboxBackend`.-**Features:**-- Similar to STAR support-- Some advanced features may be limited--## Simulation Backend--### ChatterboxBackend (Simulation)--Test protocols without physical hardware using the simulation backend.--**Setup:**--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend-from pylabrobot.resources import STARLetDeck+## Stable liquid-handling support levels-# Create simulation backend-backend = ChatterboxBackend(num_channels=8)+- **Hamilton STAR(let): Full.** Stable class `STARBackend`; deck definitions+ include `STARDeck` and `STARLetDeck`.+- **Hamilton Vantage: Mostly.** Stable class `VantageBackend`; verify unsupported+ commands and installed options.+- **Hamilton Prep: WIP.**+- **Hamilton Nimbus: WIP.**+- **Tecan Freedom EVO: Basic.** Stable class `EVOBackend`; do not describe it as+ full or backend-equivalent to STAR.+- **Opentrons OT-2: Mostly.** Stable class `OpentronsOT2Backend(host, port=31950)`;+ network/API/firmware compatibility is model-specific.-# Initialize liquid handler-lh = LiquidHandler(backend=backend, deck=STARLetDeck())-await lh.setup()-```+Upstream defines:-**Features:**-- No hardware required-- Simulates all liquid handling operations-- Works with visualizer for real-time feedback-- Validates protocol logic-- Tracks tips and volumes+- **WIP**: work in progress;+- **Basics/Basic**: core functionality is integrated and documented;+- **Mostly**: most capabilities are available but known commands are missing;+- **Full**: upstream considers at least 90% of hardware/firmware capabilities+ supported with extensive documentation.-**Use Cases:**-- Protocol development and testing-- Training and education-- CI/CD pipeline testing-- Debugging without hardware access+These labels do not validate a particular firmware, attachment, computer,+transport, or protocol.-**Example:**+## Offline backend```pythonfrom pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend-from pylabrobot.resources import STARLetDeck, TIP_CAR_480_A00, Cos_96_DW_1mL-from pylabrobot.resources import set_tip_tracking, set_volume_tracking+from pylabrobot.liquid_handling.backends import LiquidHandlerChatterboxBackend+from pylabrobot.resources.hamilton import STARLetDeck-# Enable tracking for simulation-set_tip_tracking(True)-set_volume_tracking(True)--# Initialize with simulation backendlh = LiquidHandler(- backend=ChatterboxBackend(num_channels=8),- deck=STARLetDeck()+ backend=LiquidHandlerChatterboxBackend(num_channels=8),+ deck=STARLetDeck(),)await lh.setup()--# Define resources-tip_rack = TIP_CAR_480_A00(name="tips")-plate = Cos_96_DW_1mL(name="plate")--lh.deck.assign_child_resource(tip_rack, rails=1)-lh.deck.assign_child_resource(plate, rails=10)--# Set initial volumes-for well in plate.children:- well.tracker.set_liquids([(None, 200)])--# Run simulated protocol-await lh.pick_up_tips(tip_rack["A1:H1"])-await lh.transfer(plate["A1:H1"], plate["A2:H2"], vols=100)-await lh.drop_tips()--# Check results-print(f"A1 volume: {plate['A1'].tracker.get_volume()} µL") # 100 µL-print(f"A2 volume: {plate['A2'].tracker.get_volume()} µL") # 100 µL--await lh.stop()+try:+ # Build resources and exercise planned operations only.+ ...+finally:+ await lh.stop()```-## Switching Backends--### Backend-Agnostic Protocols+This backend prints operations and updates software state. It does not connect+to a robot and does not model robot physics. Keep the backend construction+literal; never choose a live class from a string, plugin, environment variable,+or untrusted config.-Write protocols that work with any backend:+## Capability/version inspection without connection-```python-def get_backend(robot_type: str):- """Factory function to create appropriate backend"""- if robot_type == "star":- from pylabrobot.liquid_handling.backends import STAR- return STAR()- elif robot_type == "opentrons":- from pylabrobot.liquid_handling.backends import OpentronsBackend- return OpentronsBackend(host="192.168.1.100")- elif robot_type == "simulation":- from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend- return ChatterboxBackend()- else:- raise ValueError(f"Unknown robot type: {robot_type}")--def get_deck(robot_type: str):- """Factory function to create appropriate deck"""- if robot_type == "star":- from pylabrobot.resources import STARLetDeck- return STARLetDeck()- elif robot_type == "opentrons":- from pylabrobot.resources import OTDeck- return OTDeck()- elif robot_type == "simulation":- from pylabrobot.resources import STARLetDeck- return STARLetDeck()- else:- raise ValueError(f"Unknown robot type: {robot_type}")--# Use in protocol-robot_type = "simulation" # Change to "star" or "opentrons" as needed-backend = get_backend(robot_type)-deck = get_deck(robot_type)--lh = LiquidHandler(backend=backend, deck=deck)-await lh.setup()--# Protocol code works with any backend-await lh.pick_up_tips(tip_rack["A1"])-await lh.transfer(plate["A1"], plate["A2"], vols=100)-await lh.drop_tips()+```bash+python3 skills/pylabrobot/scripts/inspect_backends.py \+ --expected-version 0.2.1 --strict```-### Development Workflow+The inspector:-1. **Develop**: Write protocol using ChatterboxBackend-2. **Test**: Run with visualizer to validate logic-3. **Verify**: Test on simulation with real deck layout-4. **Deploy**: Switch to hardware backend (STAR, Opentrons)+- imports a fixed allowlist of stable classes only after argument parsing;+- reads installed distribution metadata;+- inspects class signatures/method presence;+- creates zero backend instances;+- never calls `setup()`;+- performs no serial, USB, HID, FTDI, Modbus, or network operation.-```python-# Development-lh = LiquidHandler(backend=ChatterboxBackend(), deck=STARLetDeck())+Method presence is not proof that a model implements the operation; some+backends deliberately raise `NotImplementedError`.-# ... develop protocol ...+## Extras and transports-# Production (just change backend)-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-```+Base `PyLabRobot==0.2.1` keeps hardware dependencies optional. Stable+installation documentation lists extras including:++- `serial`+- `usb`+- `ftdi`+- `hid`+- `modbus`+- `opentrons`+- `sila`+- `microscopy`+- `pico`+- `all`++Install only the exact reviewed extra for a named device and keep the top-level+pin:++```bash+# Example form only; do not run until the device and transport are approved.+uv pip install "PyLabRobot[serial]==0.2.1"+```++`all` intentionally does not include microscopy in stable 0.2.1 because of its+separate NumPy/SDK constraints. Optional transport packages can enumerate or+communicate with devices; installation does not authorize their use.++## Live-run gate++Do not instantiate a live backend or call `setup()` until a trained operator has+explicitly confirmed:++1. Backend class, exact robot model/serial number, firmware, options, and+ transport.+2. Vendor/organization permission, warranty implications, maintenance state,+ access controls, and exclusive control of the device.+3. Deck definition, carriers/adapters, resources, coordinates, orientation,+ clearances, and collision/motion review.+4. Calibration, teaching, tip/head compatibility, channel mapping, units,+ heights, rates, liquid classes, and all backend kwargs.+5. Source/dead/destination volumes, physical liquid identity, tip state,+ contamination policy, waste, lids/seals, tubing/cables, and operator steps.+6. Guards/doors, emergency stop readiness, PPE, containment, dry-run plan,+ abort path, and recovery/resume rules.++Never make a live run conditional only on `USE_HARDWARE=true`, a CLI flag, or an+IP/serial value. Confirmation must be tied to the reviewed protocol and current+physical setup.++## Backend-specific cautions++### Hamilton STAR/Vantage++These are direct firmware drivers. Upstream states that PyLabRobot is not+endorsed or supported by robot manufacturers and that firmware-driver use may+affect warranty. Review USB permissions, device selection, cover/arm/head+configuration, firmware ranges, liquid-level detection, channels, CO-RE tips,+and all device-specific errors.++### Tecan EVO++Stable status is **Basic**, not full. Use `EVOBackend`; verify which LiHa/RoMa+commands, arms, tips, carriers, and firmware paths are implemented. Never infer+Hamilton behavior or liquid classes.++### Opentrons OT-2++`OpentronsOT2Backend` communicates with an explicitly configured host over+HTTP. Do not scan a network or probe a robot. Confirm robot software/API+compatibility and unsupported operations; stable source explicitly rejects+some features such as a 96 head and robotic-arm methods.-## Backend Configuration+## Stable versus development-### Custom Backend Parameters--Some backends accept configuration parameters:--```python-# Opentrons with custom parameters-backend = OpentronsBackend(- host="192.168.1.100",- port=31950 # Default Opentrons API port-)--# ChatterboxBackend with custom channels-backend = ChatterboxBackend(- num_channels=8 # 8-channel simulation-)-```--### Connection Troubleshooting--**Hamilton STAR:**-- Ensure USB cable is connected-- Check that no other software is using the robot-- Verify firmware is up to date-- On macOS/Linux, may need USB permissions--**Opentrons OT-2:**-- Verify robot IP address is correct-- Check network connectivity (ping robot)-- Ensure robot is powered on-- Confirm Opentrons app is not blocking API access--**General:**-- Use `await lh.setup()` to test connection-- Check error messages for specific issues-- Ensure proper permissions for device access--## Backend-Specific Features--### Hamilton STAR Specific--```python-# Access backend directly for hardware-specific features-star_backend = lh.backend--# Hamilton-specific commands (if needed)-# Most operations should go through LiquidHandler interface-```--### Opentrons Specific--```python-# Opentrons-specific configuration-ot_backend = lh.backend--# Access OT-2 API directly if needed (advanced)-# Most operations should go through LiquidHandler interface-```--## Best Practices--1. **Abstract Hardware**: Write backend-agnostic protocols when possible-2. **Test in Simulation**: Always test with ChatterboxBackend first-3. **Factory Pattern**: Use factory functions to create backends-4. **Error Handling**: Handle connection errors gracefully-5. **Documentation**: Document which backends your protocol supports-6. **Configuration**: Use config files for backend parameters-7. **Version Control**: Track backend versions and compatibility-8. **Cleanup**: Always call `await lh.stop()` to release hardware-9. **Single Connection**: Only one program should connect to hardware at a time-10. **Platform Testing**: Test on target platform before deployment--## Common Patterns--### Multi-Backend Support--```python-import asyncio-from typing import Literal--async def run_protocol(- robot_type: Literal["star", "opentrons", "simulation"],- visualize: bool = False-):- """Run protocol on specified backend"""-- # Create backend- if robot_type == "star":- from pylabrobot.liquid_handling.backends import STAR- backend = STAR()- deck = STARLetDeck()- elif robot_type == "opentrons":- from pylabrobot.liquid_handling.backends import OpentronsBackend- backend = OpentronsBackend(host="192.168.1.100")- deck = OTDeck()- elif robot_type == "simulation":- from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend- backend = ChatterboxBackend()- deck = STARLetDeck()-- # Initialize- lh = LiquidHandler(backend=backend, deck=deck)- await lh.setup()-- try:- # Load deck layout (backend-agnostic)- # lh.deck = Deck.load_from_json_file(f"{robot_type}_layout.json")-- # Execute protocol (backend-agnostic)- await lh.pick_up_tips(tip_rack["A1"])- await lh.transfer(plate["A1"], plate["A2"], vols=100)- await lh.drop_tips()-- print("Protocol completed successfully!")-- finally:- await lh.stop()--# Run on different backends-await run_protocol("simulation") # Test in simulation-await run_protocol("star") # Run on Hamilton STAR-await run_protocol("opentrons") # Run on Opentrons OT-2-```+The stable pin/tag is `v0.2.1`. Repository `main` continued changing through+2026-07-22 during this review. Development docs and `CHANGELOG.md`'s+`Unreleased` section may describe classes not in the wheel. For example,+HighRes MicroSpin support is unreleased and must not be presented as a stable+0.2.1 capability.-## Additional Resources+When considering a later release:-- Backend Documentation: https://docs.pylabrobot.org/user_guide/backends.html-- Supported Machines: https://docs.pylabrobot.org/user_guide/machines.html-- API Reference: https://docs.pylabrobot.org/api/pylabrobot.liquid_handling.backends.html-- GitHub Examples: https://github.com/PyLabRobot/pylabrobot/tree/main/examples+1. Confirm it exists on PyPI and is not a prerelease.+2. Compare `Requires-Python`, extras, tag, changelog, and source.+3. Run import/signature and software-only tests in an isolated environment.+4. Revalidate each target model/firmware and repeat commissioning.++## Sources++Checked **2026-07-23**:++- [Stable supported machines](https://docs.pylabrobot.org/stable/user_guide/machines.html)+ — model/status tables and status definitions (page metadata surfaced+ 2025-01-01; docs version 0.2.1).+- [Stable liquid-handling API](https://docs.pylabrobot.org/stable/api/pylabrobot.liquid_handling.html)+ — abstract, hardware, serializing, and testing backends.+- [Stable installation](https://docs.pylabrobot.org/stable/user_guide/_getting-started/installation.html)+ — optional extras and stable/source distinction.+- [`v0.2.1` backend source](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1/pylabrobot/liquid_handling/backends)+ — exact classes and limitations; tag commit dated 2026-03-23.+- [Project README](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1#readme)+ — supported robot families and manufacturer/warranty disclaimer.+- [Changelog](https://github.com/PyLabRobot/pylabrobot/blob/main/CHANGELOG.md)+ — stable 0.2.1 versus development-only `Unreleased`.diff --git a/skills/pylabrobot/references/liquid-handling.md b/skills/pylabrobot/references/liquid-handling.mdindex 2d087855..bdf51438 100644--- a/skills/pylabrobot/references/liquid-handling.md+++ b/skills/pylabrobot/references/liquid-handling.md@@ -1,403 +1,223 @@-# Liquid Handling with PyLabRobot+# Liquid handling-## Overview+Verified against **PyLabRobot 0.2.1** on **2026-07-23**. Examples in this+reference are planning or chatterbox-only. They are not authorization to connect+to a robot.-The liquid handling module (`pylabrobot.liquid_handling`) provides a unified interface for controlling liquid handling robots. The `LiquidHandler` class serves as the main interface for all pipetting operations, working across different hardware platforms through backend abstraction.--## Basic Setup--### Initializing a Liquid Handler+## Stable frontend and backend```pythonfrom pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import STAR-from pylabrobot.resources import STARLetDeck--# Create liquid handler with STAR backend-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-await lh.setup()--# When done-await lh.stop()-```--### Switching Between Backends+from pylabrobot.liquid_handling.backends import LiquidHandlerChatterboxBackend+from pylabrobot.resources.hamilton import STARLetDeck-Change robots by swapping the backend without rewriting protocols:--```python-# Hamilton STAR-from pylabrobot.liquid_handling.backends import STAR-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())--# Opentrons OT-2-from pylabrobot.liquid_handling.backends import OpentronsBackend-lh = LiquidHandler(backend=OpentronsBackend(host="192.168.1.100"), deck=OTDeck())--# Simulation (no hardware required)-from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend-lh = LiquidHandler(backend=ChatterboxBackend(), deck=STARLetDeck())+lh = LiquidHandler(+ backend=LiquidHandlerChatterboxBackend(num_channels=8),+ deck=STARLetDeck(),+)+await lh.setup() # prints operations; no hardware transport```-## Core Operations--### Tip Management--Picking up and dropping tips is fundamental to liquid handling operations:--```python-# Pick up tips from specific positions-await lh.pick_up_tips(tip_rack["A1"]) # Single tip-await lh.pick_up_tips(tip_rack["A1:H1"]) # Row of 8 tips-await lh.pick_up_tips(tip_rack["A1:A12"]) # Column of 12 tips--# Drop tips-await lh.drop_tips() # Drop at current location-await lh.drop_tips(waste) # Drop at specific location--# Return tips to original rack-await lh.return_tips()+For 0.2.1, the important frontend signatures are:++```text+pick_up_tips(tip_spots, use_channels=None, offsets=None, **backend_kwargs)+drop_tips(tip_spots, use_channels=None, offsets=None,+ allow_nonzero_volume=False, **backend_kwargs)+return_tips(use_channels=None, allow_nonzero_volume=False, offsets=None,+ **backend_kwargs)+aspirate(resources, vols, use_channels=None, flow_rates=None, offsets=None,+ liquid_height=None, blow_out_air_volume=None, spread="wide",+ mix=None, **backend_kwargs)+dispense(resources, vols, use_channels=None, flow_rates=None, offsets=None,+ liquid_height=None, blow_out_air_volume=None, spread="wide",+ mix=None, **backend_kwargs)```-**Tip Tracking**: Enable automatic tip tracking to monitor tip usage:--```python-from pylabrobot.resources import set_tip_tracking-set_tip_tracking(True) # Enable globally-```+Volumes are microlitres (`uL`), coordinates/heights are millimetres (`mm`), and+flow rates are `uL/s` unless the exact backend page says otherwise. Use lists+whose lengths agree with selected resources/channels; do not rely on scalar+broadcasting copied from an older example.-### Aspirating Liquids+## Safe operation shape-Draw liquid from wells or containers:+With the software-only backend and already assigned resources:```python-# Basic aspiration-await lh.aspirate(plate["A1"], vols=100) # 100 µL from A1+source.get_well("A1").tracker.set_volume(100.0) # bookkeeping only-# Multiple wells with same volume-await lh.aspirate(plate["A1:H1"], vols=100) # 100 µL from each well--# Multiple wells with different volumes-await lh.aspirate(- plate["A1:A3"],- vols=[100, 150, 200] # Different volumes-)--# Advanced parameters+await lh.pick_up_tips(tips["A1"])await lh.aspirate(- plate["A1"],- vols=100,- flow_rate=50, # µL/s- liquid_height=5, # mm from bottom- blow_out_air_volume=10 # µL air+ source["A1"],+ vols=[25.0],+ use_channels=[0],+ flow_rates=[50.0],+ liquid_height=[1.0],)-```--### Dispensing Liquids--Dispense liquid into wells or containers:--```python-# Basic dispensing-await lh.dispense(plate["A2"], vols=100) # 100 µL to A2--# Multiple wells-await lh.dispense(plate["A1:H1"], vols=100) # 100 µL to each--# Different volumesawait lh.dispense(- plate["A1:A3"],- vols=[100, 150, 200]-)--# Advanced parameters-await lh.dispense(- plate["A2"],- vols=100,- flow_rate=50, # µL/s- liquid_height=2, # mm from bottom- blow_out_air_volume=10 # µL air+ destination["A1"],+ vols=[25.0],+ use_channels=[0],+ flow_rates=[75.0],+ liquid_height=[2.0],)+await lh.return_tips()```-### Transferring Liquids+Before translating this to any physical system, verify:-Transfer combines aspirate and dispense in a single operation:+- resource and well identity, actual position, orientation, dimensions, and+ reachability;+- source fill volume **and dead volume**; destination capacity and headspace;+- tip model, fitting, filter, capacity, rack state, liquid compatibility, and+ channel compatibility;+- 0-based `use_channels` mapping against the physical head and mounted tools;+- volume, length, rate, and time units;+- aspiration/dispense height, offset, rate, settling, blowout, mixing, air gaps,+ surface behavior, and validated liquid class;+- contamination grouping, filtered-tip requirement, tip reuse prohibition or+ validated policy, waste route, and carryover controls.-```python-# Basic transfer-await lh.transfer(- source=source_plate["A1"],- dest=dest_plate["A1"],- vols=100-)+The bundled transfer planner makes the conservative choice of one new tip per+CSV row.-# Multiple transfers (same tips)-await lh.transfer(- source=source_plate["A1:H1"],- dest=dest_plate["A1:H1"],- vols=100-)+## `transfer()` is not the old plate-copy API-# Different volumes per well-await lh.transfer(- source=source_plate["A1:A3"],- dest=dest_plate["B1:B3"],- vols=[50, 100, 150]-)+In 0.2.1 the verified signature is:-# With tip handling-await lh.pick_up_tips(tip_rack["A1:H1"])-await lh.transfer(- source=source_plate["A1:H12"],- dest=dest_plate["A1:H12"],- vols=100-)-await lh.drop_tips()+```text+transfer(source: Well, targets: List[Well], source_vol=None, ratios=None,+ target_vols=None, aspiration_flow_rate=None,+ dispense_flow_rates=None, **backend_kwargs)```-## Advanced Techniques+It represents distribution from one source to multiple targets. Old examples+that pass parallel `source=source_plate["A1:H12"]`, `dest=...`, and `vols=...`+do not match this stable signature. For one-to-one transfers, plan explicit+aspirate/dispense pairs and validate channel/tip state.-### Serial Dilutions+## Tip tracking-Create serial dilutions across plate rows or columns:+Enable tracking before operations:```python-# 2-fold serial dilution-source_vols = [100, 50, 50, 50, 50, 50, 50, 50]-dest_vols = [0, 50, 50, 50, 50, 50, 50, 50]--# Add diluent first-await lh.pick_up_tips(tip_rack["A1"])-await lh.transfer(- source=buffer["A1"],- dest=plate["A2:A8"],- vols=50-)-await lh.drop_tips()--# Perform serial dilution-await lh.pick_up_tips(tip_rack["A2"])-for i in range(7):- await lh.aspirate(plate[f"A{i+1}"], vols=50)- await lh.dispense(plate[f"A{i+2}"], vols=50)- # Mix- await lh.aspirate(plate[f"A{i+2}"], vols=50)- await lh.dispense(plate[f"A{i+2}"], vols=50)-await lh.drop_tips()-```--### Plate Replication--Copy an entire plate layout to another plate:+from pylabrobot.resources import set_tip_tracking-```python-# Setup tips-await lh.pick_up_tips(tip_rack["A1:H1"])--# Replicate 96-well plate (12 columns)-for col in range(1, 13):- await lh.transfer(- source=source_plate[f"A{col}:H{col}"],- dest=dest_plate[f"A{col}:H{col}"],- vols=100- )--await lh.drop_tips()+set_tip_tracking(True)```-### Multi-Channel Pipetting--Use multiple channels simultaneously for parallel operations:--```python-# 8-channel transfer (entire row)-await lh.pick_up_tips(tip_rack["A1:H1"])-await lh.transfer(- source=source_plate["A1:H1"],- dest=dest_plate["A1:H1"],- vols=100-)-await lh.drop_tips()--# Process entire plate with 8-channel-for col in range(1, 13):- await lh.pick_up_tips(tip_rack[f"A{col}:H{col}"])- await lh.transfer(- source=source_plate[f"A{col}:H{col}"],- dest=dest_plate[f"A{col}:H{col}"],- vols=100- )- await lh.drop_tips()-```+Tip racks normally start populated; supported factories accept+`with_tips=False`, and `TipRack.fill()`, `empty()`, and `set_tip_state(...)`+modify planned state. `return_tips()` depends on operation history. Tip tracking+can catch inconsistent planned operations, but it cannot detect whether a tip+is physically present, seated, blocked, damaged, or the expected type.-### Mixing Liquids+Never disable tracking merely to bypass `NoTipError` or `HasTipError`. Reconcile+the physical deck and planned state instead.-Mix liquids by repeatedly aspirating and dispensing:+## Volume tracking is bookkeeping```python-# Mix by aspiration/dispensing-await lh.pick_up_tips(tip_rack["A1"])--# Mix 5 times-for _ in range(5):- await lh.aspirate(plate["A1"], vols=80)- await lh.dispense(plate["A1"], vols=80)+from pylabrobot.resources import set_volume_tracking-await lh.drop_tips()+set_volume_tracking(True)+well.tracker.set_volume(200.0)+used_uL = well.tracker.get_used_volume()+free_uL = well.tracker.get_free_volume()```-## Volume Tracking+The `VolumeTracker` updates planned volumes and can reject under-aspiration,+tip overfill, or well overfill. It does **not** measure a meniscus or confirm+liquid identity. Initial state must come from a trusted preparation record and+human reconciliation.-Track liquid volumes in wells automatically:+Keep dead volume separate from geometric capacity. The tracker may allow a+withdrawal that is physically unreliable because of vessel shape, tilt,+surface tension, foam, viscosity, or required submersion.-```python-from pylabrobot.resources import set_volume_tracking+### Physical liquid detection is backend-specific-# Enable volume tracking globally-set_volume_tracking(True)+Hamilton STAR liquid-level detection is a separate physical feature. Stable+STAR docs expose backend kwargs such as `lld_mode`, `immersion_depth`, and+`surface_following_distance`. It is not portable to all backends and is not+enabled by volume tracking. Validate the model, sensors, consumables, conductive+properties, firmware behavior, failure handling, and channel-specific values+before considering it.-# Set initial volumes-plate["A1"].tracker.set_liquids([(None, 200)]) # 200 µL+## Liquid classes-# After aspirating 100 µL-await lh.aspirate(plate["A1"], vols=100)-print(plate["A1"].tracker.get_volume()) # 100 µL+There is no stable generic import:-# Check remaining volume-remaining = plate["A1"].tracker.get_volume()+```python+# Invalid in 0.2.1:+# from pylabrobot.liquid_handling import LiquidClass```-## Liquid Classes--Define liquid properties for optimal pipetting:+Hamilton liquid classes are vendor-specific:```python-# Liquid classes control aspiration/dispense parameters-from pylabrobot.liquid_handling import LiquidClass--# Create custom liquid class-water = LiquidClass(- name="Water",- aspiration_flow_rate=100,- dispense_flow_rate=150,- aspiration_mix_flow_rate=100,- dispense_mix_flow_rate=100,- air_transport_retract_dist=10+from pylabrobot.liquid_handling.liquid_classes.hamilton import HamiltonLiquidClass+from pylabrobot.liquid_handling.liquid_classes.hamilton.star import (+ HighVolumeFilter_Water_DispenseSurface_Part,)-# Use with operationsawait lh.aspirate(- plate["A1"],- vols=100,- liquid_class=water+ source["A1"],+ vols=[100.0],+ hamilton_liquid_classes=[+ HighVolumeFilter_Water_DispenseSurface_Part+ ],)```-## Error Handling--Handle errors in liquid handling operations:--```python-try:- await lh.setup()- await lh.pick_up_tips(tip_rack["A1"])- await lh.transfer(source["A1"], dest["A1"], vols=100)- await lh.drop_tips()-except Exception as e:- print(f"Error during liquid handling: {e}")- # Attempt to drop tips if holding them- try:- await lh.drop_tips()- except:- pass-finally:- await lh.stop()-```--## Best Practices--1. **Always Setup and Stop**: Call `await lh.setup()` before operations and `await lh.stop()` when done-2. **Enable Tracking**: Use tip tracking and volume tracking for accurate state management-3. **Tip Management**: Always pick up tips before aspirating and drop them when done-4. **Flow Rates**: Adjust flow rates based on liquid viscosity and vessel type-5. **Liquid Height**: Set appropriate aspiration/dispense heights to avoid splashing-6. **Error Handling**: Use try/finally blocks to ensure proper cleanup-7. **Test in Simulation**: Use ChatterboxBackend to test protocols before running on hardware-8. **Volume Limits**: Respect tip volume limits and well capacities-9. **Mixing**: Mix after dispensing viscous liquids or when accuracy is critical-10. **Documentation**: Document liquid classes and custom parameters for reproducibility--## Common Patterns--### Complete Liquid Handling Protocol--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import STAR-from pylabrobot.resources import STARLetDeck, TIP_CAR_480_A00, Cos_96_DW_1mL-from pylabrobot.resources import set_tip_tracking, set_volume_tracking--# Enable tracking-set_tip_tracking(True)-set_volume_tracking(True)--# Initialize-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-await lh.setup()--try:- # Define resources- tip_rack = TIP_CAR_480_A00(name="tips")- source = Cos_96_DW_1mL(name="source")- dest = Cos_96_DW_1mL(name="dest")-- # Assign to deck- lh.deck.assign_child_resource(tip_rack, rails=1)- lh.deck.assign_child_resource(source, rails=10)- lh.deck.assign_child_resource(dest, rails=15)-- # Set initial volumes- for well in source.children:- well.tracker.set_liquids([(None, 200)])-- # Execute protocol- await lh.pick_up_tips(tip_rack["A1:H1"])- await lh.transfer(- source=source["A1:H12"],- dest=dest["A1:H12"],- vols=100- )- await lh.drop_tips()--finally:- await lh.stop()+The keyword above is a STAR backend kwarg, not a universal frontend contract.+`TecanLiquidClass` and `get_liquid_class` exist under+`pylabrobot.liquid_handling.liquid_classes.tecan`, but are a different+vendor-specific system.++Do not select a class from its name alone. Review liquid, tip, head, volume+range, jet/surface mode, vessel geometry, calibration curve, flow, settling,+transport air, blowout, and firmware/model applicability. Custom classes need+documented gravimetric or assay validation and operator approval.++## Mixing, serial dilution, and multichannel work++- Make every aspirate/dispense pair explicit in the plan.+- Check the tip's current planned volume before mixing.+- Keep the mix volume below both tip capacity and usable well volume.+- For serial dilutions, define where a tip may be reused and where a fresh tip+ is mandatory; do not infer contamination safety from row order.+- Confirm well order and channel order. A plate slice is not proof that the+ physical channels align with those wells.+- Include residual volume, pre-wet cycles, adsorption, foaming, and carryover in+ the acceptance criteria.++## Deterministic preflight++```bash+python3 skills/pylabrobot/scripts/plan_transfers.py \+ --manifest skills/pylabrobot/tests/fixtures/protocol_manifest.json \+ --transfers skills/pylabrobot/tests/fixtures/transfers.csv```-## Hardware-Specific Notes--### Hamilton STAR--- Supports full liquid handling capabilities-- Uses USB connection for communication-- Firmware commands executed directly-- Supports CO-RE (Compressed O-Ring Expansion) tips--### Opentrons OT-2--- Requires IP address for network connection-- Uses HTTP API for communication-- Limited to 8-channel and single-channel pipettes-- Simpler deck layout compared to STAR--### Tecan EVO--- Work-in-progress support-- Similar capabilities to Hamilton STAR-- Check current compatibility status in documentation--## Additional Resources--- Official Liquid Handling Guide: https://docs.pylabrobot.org/user_guide/basic.html-- API Reference: https://docs.pylabrobot.org/api/pylabrobot.liquid_handling.html-- Example Protocols: https://github.com/PyLabRobot/pylabrobot/tree/main/examples+The CSV header is exact and fixed. Unknown columns, duplicate IDs, unsupported+tip policies, missing source volumes, non-finite numbers, out-of-grid wells,+unallowlisted liquid classes/tips, excess rates/heights/volumes, channel+mismatches, dead-volume violations, destination overflow, and insufficient tips+fail closed.++## Sources++Checked **2026-07-23**:++- [Stable basic Hamilton tutorial](https://docs.pylabrobot.org/stable/user_guide/00_liquid-handling/hamilton-star/basic.html)+ — current imports, rails, tips, channels, and `uL` operations (page metadata+ surfaced 2025-01-01; docs version 0.2.1).+- [Stable liquid-handling API](https://docs.pylabrobot.org/stable/api/pylabrobot.liquid_handling.html)+ — frontend/backend split and `LiquidHandlerChatterboxBackend`.+- [Stable tracker guide](https://docs.pylabrobot.org/stable/user_guide/machine-agnostic-features/using-trackers.html)+ — tip/volume tracker behavior (page metadata surfaced 2025-01-01).+- [Stable Hamilton liquid classes](https://docs.pylabrobot.org/stable/user_guide/00_liquid-handling/hamilton-star/hamilton-liquid-classes.html)+ and [STAR liquid-level detection](https://docs.pylabrobot.org/stable/user_guide/00_liquid-handling/hamilton-star/star_lld.html).+- [`v0.2.1` liquid-handler source](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1/pylabrobot/liquid_handling)+ — signatures and import verification; tag dated 2026-03-23.diff --git a/skills/pylabrobot/references/material-handling.md b/skills/pylabrobot/references/material-handling.mdindex 231d208e..4f69b748 100644--- a/skills/pylabrobot/references/material-handling.md+++ b/skills/pylabrobot/references/material-handling.md@@ -1,620 +1,229 @@-# Material Handling Equipment in PyLabRobot+# Material handling, pumps, and environmental devices-## Overview+Verified against **PyLabRobot 0.2.1** on **2026-07-23**. Every operation in+this domain can create physical motion, pressure, heat, or stored energy. The+snippets below identify APIs only; they do not connect to devices.-PyLabRobot integrates with material handling equipment including heater shakers, incubators, centrifuges, and pumps. These devices enable environmental control, sample preparation, and automated workflows beyond basic liquid handling.--## Heater Shakers--### Hamilton HeaterShaker--The Hamilton HeaterShaker provides temperature control and orbital shaking for microplates.--#### Setup--```python-from pylabrobot.heating_shaking import HeaterShaker-from pylabrobot.heating_shaking.hamilton import HamiltonHeaterShakerBackend--# Create heater shaker-hs = HeaterShaker(- name="heater_shaker_1",- backend=HamiltonHeaterShakerBackend(),- size_x=156.0,- size_y= 156.0,- size_z=18.0-)--await hs.setup()-```--#### Operations--**Temperature Control:**--```python-# Set temperature (Celsius)-await hs.set_temperature(37)--# Get current temperature-temp = await hs.get_temperature()-print(f"Current temperature: {temp}°C")--# Turn off heating-await hs.set_temperature(None)-```+## Pumps-**Shaking Control:**+Stable frontend and one stable backend export:```python-# Start shaking (RPM)-await hs.set_shake_rate(300) # 300 RPM--# Stop shaking-await hs.set_shake_rate(0)+from pylabrobot.pumps import MasterflexBackend, Pump```-**Plate Operations:**--```python-# Lock plate in position-await hs.lock_plate()+Verified `Pump` methods:-# Unlock plate-await hs.unlock_plate()+```text+run_revolutions(num_revolutions)+run_continuously(speed)+run_for_duration(speed, duration)+halt()```-#### Integration with Liquid Handler--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import STAR-from pylabrobot.resources import STARLetDeck--# Initialize devices-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-hs = HeaterShaker(name="hs", backend=HamiltonHeaterShakerBackend())--await lh.setup()-await hs.setup()+The stale methods `start`, `stop` as a pumping command, `pump_volume`, and+`calibrate(duration=..., speed=..., volume=...)` are not the verified universal+0.2.1 frontend shown above. `stop()` belongs to machine lifecycle; `halt()` is+the pump-motion command.-try:- # Assign heater shaker to deck- lh.deck.assign_child_resource(hs, rails=8)+`MasterflexBackend(com_port)` is transport-specific. Do not instantiate it+during discovery. Stable supported machines labels Cole-Parmer Masterflex+L/S listed models and Agrowtek Pump Array as **Full**.- # Prepare samples- tip_rack = TIP_CAR_480_A00(name="tips")- plate = Cos_96_DW_1mL(name="plate")+### Pump safety- lh.deck.assign_child_resource(tip_rack, rails=1)+Before a separately authorized run, verify:- # Place plate on heater shaker- hs.assign_child_resource(plate, location=(0, 0, 0))+- exact pump/head/tubing model, material, inner diameter, direction, occlusion,+ fittings, valves, clamps, and destination;+- calibrated relationship among command speed/revolutions/time and delivered+ volume for the current fluid, tubing age, backpressure, and temperature;+- prime/purge route, bubbles, siphoning, dead volume, residual volume, maximum+ pressure/flow, leak containment, and waste capacity;+- chemical/biological compatibility, cross-contamination controls, and tubing+ change policy;+- an accessible stop and safe behavior on disconnect, timeout, or partial+ delivery.- # Transfer reagents to plate on heater shaker- await lh.pick_up_tips(tip_rack["A1:H1"])- await lh.transfer(reagent["A1:H1"], plate["A1:H1"], vols=100)- await lh.drop_tips()+A time/speed command is not a measured volume. Record the calibration and+uncertainty; use a validated scale/flow sensor if closed-loop confirmation is+required.- # Lock plate and start incubation- await hs.lock_plate()- await hs.set_temperature(37)- await hs.set_shake_rate(300)+## Heater shakers and shakers- # Incubate- import asyncio- await asyncio.sleep(600) # 10 minutes-- # Stop shaking and heating- await hs.set_shake_rate(0)- await hs.set_temperature(None)- await hs.unlock_plate()--finally:- await lh.stop()- await hs.stop()-```--#### Multiple Heater Shakers--The HamiltonHeaterShakerBackend handles multiple units:+Stable frontend imports:```python-# Backend automatically manages multiple heater shakers-hs1 = HeaterShaker(name="hs1", backend=HamiltonHeaterShakerBackend())-hs2 = HeaterShaker(name="hs2", backend=HamiltonHeaterShakerBackend())--await hs1.setup()-await hs2.setup()--# Assign to different deck positions-lh.deck.assign_child_resource(hs1, rails=8)-lh.deck.assign_child_resource(hs2, rails=12)--# Control independently-await hs1.set_temperature(37)-await hs2.set_temperature(42)-```--### Inheco ThermoShake--The Inheco ThermoShake provides temperature control and shaking.--#### Setup--```python-from pylabrobot.heating_shaking import HeaterShaker-from pylabrobot.heating_shaking.inheco import InhecoThermoShakeBackend--hs = HeaterShaker(- name="thermoshake",- backend=InhecoThermoShakeBackend(),- size_x=156.0,- size_y=156.0,- size_z=18.0+from pylabrobot.heating_shaking import (+ HamiltonHeaterShakerBackend,+ HeaterShaker,+ InhecoThermoshakeBackend,)--await hs.setup()+from pylabrobot.shaking import Shaker```-#### Operations--Similar to Hamilton HeaterShaker:+The stable class is `InhecoThermoshakeBackend` (lowercase `s` in+`Thermoshake`), not the stale `InhecoThermoShakeBackend`.-```python-# Temperature control-await hs.set_temperature(37)-temp = await hs.get_temperature()--# Shaking control-await hs.set_shake_rate(300)+Verified `HeaterShaker` methods:-# Plate locking-await hs.lock_plate()-await hs.unlock_plate()+```text+set_temperature(temperature, passive=False)+get_temperature()+shake(speed, duration=None, **backend_kwargs)+stop_shaking(**backend_kwargs)+lock_plate(**backend_kwargs)+unlock_plate(**backend_kwargs)```-## Incubators+The old names `set_shake_rate` and `set_temperature(None)` are not the verified+0.2.1 frontend signatures. Use the exact device page for deactivation/cooling+and do not substitute zero/`None` unless documented for that backend.-### Inheco Incubators+`HeaterShaker` construction requires `name`, dimensions, backend, and a+`child_location`. Backend construction is also device topology-specific:+`HamiltonHeaterShakerBackend(index, interface)` and+`InhecoThermoshakeBackend(index, control_box)` require approved shared+interfaces/controllers.-PyLabRobot supports various Inheco incubator models for temperature-controlled plate storage.+Stable supported machines lists:-#### Supported Models+- Inheco Thermoshake and Thermoshake AC: **Full**+- Opentrons Thermoshake: **Full**+- Hamilton Heater Shaker: **Full**+- QInstruments BioShake: **Full**-- Inheco Single Plate Incubator-- Inheco Multi-Plate Incubators-- Other Inheco temperature controllers+### Heater/shaker safety-#### Setup--```python-from pylabrobot.temperature_control import TemperatureController-from pylabrobot.temperature_control.inheco import InhecoBackend--# Create incubator-incubator = TemperatureController(- name="incubator",- backend=InhecoBackend(),- size_x=156.0,- size_y=156.0,- size_z=50.0-)+Confirm plate compatibility, mass, balance, lid/seal, locking, condensation,+spillage containment, orbit/speed limits, thermal limits, ramp/equilibration,+sensor calibration, and safe unlock temperature. Never unlock or move a plate+while shaking. Treat a requested setpoint as a command, not proof that the+sample has reached that temperature.-await incubator.setup()-```+## Temperature controllers-#### Operations+Stable frontend:```python-# Set temperature-await incubator.set_temperature(37)--# Get temperature-temp = await incubator.get_temperature()-print(f"Incubator temperature: {temp}°C")--# Turn off-await incubator.set_temperature(None)+from pylabrobot.temperature_controlling import TemperatureController```-### Thermo Fisher Cytomat Incubators+Verified methods:-Cytomat incubators provide automated plate storage with temperature and CO2 control.--#### Setup--```python-from pylabrobot.incubation import Incubator-from pylabrobot.incubation.cytomat_backend import CytomatBackend--incubator = Incubator(- name="cytomat",- backend=CytomatBackend()-)--await incubator.setup()+```text+set_temperature(temperature, passive=False)+get_temperature()+deactivate()```-#### Operations--```python-# Store plate-await incubator.store_plate(plate_id="plate_001", position=1)--# Retrieve plate-await incubator.retrieve_plate(position=1)--# Set environmental conditions-await incubator.set_temperature(37)-await incubator.set_co2(5.0) # 5% CO2-```+Stable support includes Inheco CPAC (**Full**) and Opentrons Temperature Module+(**Mostly** in the complete stable table). Validate active cooling, condensation,+plate/adapter contact, setpoint range, ramp, sensor placement, overshoot, and+sample-versus-block temperature.## Centrifuges-### Agilent VSpin--The Agilent VSpin is a vacuum-assisted centrifuge for plate processing.--#### Setup--```python-from pylabrobot.centrifuge import Centrifuge-from pylabrobot.centrifuge.vspin import VSpinBackend--centrifuge = Centrifuge(- name="vspin",- backend=VSpinBackend()-)--await centrifuge.setup()-```--#### Operations--**Door Control:**--```python-# Open door-await centrifuge.open_door()--# Close door-await centrifuge.close_door()--# Lock door-await centrifuge.lock_door()--# Unlock door-await centrifuge.unlock_door()-```--**Bucket Positioning:**--```python-# Move bucket to loading position-await centrifuge.move_bucket_to_loading()--# Move bucket to home position-await centrifuge.move_bucket_to_home()-```--**Spinning:**+Stable imports:```python-# Run centrifuge-await centrifuge.spin(- speed=2000, # RPM- duration=300 # seconds-)--# Stop spinning-await centrifuge.stop_spin()+from pylabrobot.centrifuge import Access2Backend, Centrifuge, VSpinBackend```-#### Integration Example+Verified frontend:-```python-async def centrifuge_workflow():- """Complete centrifugation workflow"""-- lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())- centrifuge = Centrifuge(name="vspin", backend=VSpinBackend())-- await lh.setup()- await centrifuge.setup()-- try:- # Prepare samples- await lh.pick_up_tips(tip_rack["A1:H1"])- await lh.transfer(samples["A1:H12"], plate["A1:H12"], vols=200)- await lh.drop_tips()-- # Load into centrifuge- print("Move plate to centrifuge")- await centrifuge.open_door()- await centrifuge.move_bucket_to_loading()- input("Press Enter when plate is loaded...")-- await centrifuge.move_bucket_to_home()- await centrifuge.close_door()- await centrifuge.lock_door()-- # Centrifuge- await centrifuge.spin(speed=2000, duration=300)-- # Unload- await centrifuge.unlock_door()- await centrifuge.open_door()- await centrifuge.move_bucket_to_loading()- input("Press Enter when plate is removed...")-- await centrifuge.move_bucket_to_home()- await centrifuge.close_door()-- finally:- await lh.stop()- await centrifuge.stop()+```text+open_door()+close_door()+lock_door()+unlock_door()+spin(g, duration, **backend_kwargs)```-## Pumps+The stable method takes relative centrifugal force `g`, not the stale+`speed=...` RPM argument. Converting RPM to RCF requires the correct rotor+radius; never guess it.-### Cole Parmer Masterflex+Stable supported machines labels:-PyLabRobot supports Cole Parmer Masterflex peristaltic pumps for fluid transfer.+- Agilent VSpin: **Mostly**+- Agilent VSpin Access2 Loader: **Full**-#### Setup+`VSpinBackend(device_id=None)` and `Access2Backend(device_id, timeout=60)` are+device-specific. Do not use placeholder IDs in a live script.-```python-from pylabrobot.pumps import Pump-from pylabrobot.pumps.cole_parmer import ColeParmerMasterflexBackend+The current changelog lists HighRes Biosolutions MicroSpin under+**Unreleased**. Although development `main` may expose `MicroSpin`, it is not a+stable 0.2.1 API and must not be imported in pinned examples.-pump = Pump(- name="masterflex",- backend=ColeParmerMasterflexBackend()-)+### Centrifuge safety-await pump.setup()-```+Require human verification of rotor/bucket/adapter model, plate rating,+orientation, balance, maximum RCF, duration, acceleration/deceleration, lid/door+interlocks, loading position, clearance, maintenance, and emergency procedure.+Never open/unlock while rotating or issue movement merely to test a connection.+On timeout or disconnect, assume the rotor may still be moving until physically+verified safe.-#### Operations+## Storage/incubation-**Running Pump:**+The stable machine inventory includes multiple Thermo Fisher/Heraeus Cytomat+models as **Full**, and Inheco Incubator Shaker/SCILA as **Mostly**. Their APIs+are model-specific; do not use stale generic examples such as+`from pylabrobot.incubation import Incubator` without verifying that exact+symbol in the pinned wheel.-```python-# Run for duration-await pump.run_for_duration(- duration=10, # seconds- speed=50 # % of maximum-)+Storage moves require explicit plate identity, slot mapping, occupancy state,+door/hatch/interlock state, orientation, environmental setpoints, and recovery+from an interrupted handoff. Software occupancy is not physical detection.-# Run continuously-await pump.start(speed=50)+## Multi-device orchestration-# Stop pump-await pump.stop()-```+Do not independently `gather()` hardware operations just because frontends are+async. Safe concurrency requires approved workcell interlocks and a scheduler+that owns:-**Volume-Based Pumping:**+- device and plate state;+- collision zones and transfer ownership;+- door/tray/bucket/lock preconditions;+- timeouts, retries, idempotency, and partial-completion handling;+- emergency stop and restart/reconciliation behavior.-```python-# Pump specific volume (requires calibration)-await pump.pump_volume(- volume=10, # mL- speed=50 # % of maximum-)-```+Default sequence:-#### Calibration+1. Validate manifests and transfers offline.+2. Generate a non-executable simulation plan.+3. Exercise software-only frontends where available.+4. Review every handoff with the operator.+5. Obtain explicit confirmation for the exact live protocol.+6. Commission one device/move at a time under site procedures.-```python-# Calibrate pump for volume accuracy-# (requires known volume measurement)-await pump.run_for_duration(duration=60, speed=50)-actual_volume = 25.3 # mL measured+## No-connection inspection-pump.calibrate(duration=60, speed=50, volume=actual_volume)+```bash+python3 skills/pylabrobot/scripts/inspect_backends.py \+ --expected-version 0.2.1 --strict```-### Agrowtek Pump Array+This checks a fixed set of frontend symbols and methods without constructing+devices or calling `setup()`.-Support for Agrowtek pump arrays for multiple simultaneous fluid transfers.--#### Setup--```python-from pylabrobot.pumps import PumpArray-from pylabrobot.pumps.agrowtek import AgrowtekBackend--pump_array = PumpArray(- name="agrowtek",- backend=AgrowtekBackend(),- num_pumps=8-)--await pump_array.setup()-```--#### Operations--```python-# Run specific pump-await pump_array.run_pump(- pump_number=1,- duration=10,- speed=50-)--# Run multiple pumps simultaneously-await pump_array.run_pumps(- pump_numbers=[1, 2, 3],- duration=10,- speed=50-)-```--## Multi-Device Protocols--### Complex Workflow Example--```python-async def complex_workflow():- """Multi-device automated workflow"""-- # Initialize all devices- lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())- hs = HeaterShaker(name="hs", backend=HamiltonHeaterShakerBackend())- centrifuge = Centrifuge(name="vspin", backend=VSpinBackend())- pump = Pump(name="pump", backend=ColeParmerMasterflexBackend())-- await lh.setup()- await hs.setup()- await centrifuge.setup()- await pump.setup()-- try:- # 1. Sample preparation- await lh.pick_up_tips(tip_rack["A1:H1"])- await lh.transfer(samples["A1:H12"], plate["A1:H12"], vols=100)- await lh.drop_tips()-- # 2. Add reagent via pump- await pump.pump_volume(volume=50, speed=50)-- # 3. Mix on heater shaker- await hs.lock_plate()- await hs.set_temperature(37)- await hs.set_shake_rate(300)- await asyncio.sleep(600) # 10 min incubation- await hs.set_shake_rate(0)- await hs.set_temperature(None)- await hs.unlock_plate()-- # 4. Centrifuge- await centrifuge.open_door()- # (load plate)- await centrifuge.close_door()- await centrifuge.spin(speed=2000, duration=180)- await centrifuge.open_door()- # (unload plate)-- # 5. Transfer supernatant- await lh.pick_up_tips(tip_rack["A2:H2"])- await lh.transfer(- plate["A1:H12"],- output_plate["A1:H12"],- vols=80- )- await lh.drop_tips()-- finally:- await lh.stop()- await hs.stop()- await centrifuge.stop()- await pump.stop()-```--## Best Practices--1. **Device Initialization**: Setup all devices at protocol start-2. **Sequential Operations**: Material handling often requires sequential steps-3. **Safety**: Always unlock/open doors before manual plate handling-4. **Temperature Equilibration**: Allow time for devices to reach temperature-5. **Error Handling**: Handle device errors gracefully with try/finally-6. **State Verification**: Check device state before operations-7. **Timing**: Account for device-specific delays (heating, centrifugation)-8. **Maintenance**: Follow manufacturer maintenance schedules-9. **Calibration**: Regularly calibrate pumps and temperature controllers-10. **Documentation**: Record all device settings and parameters--## Common Patterns--### Temperature-Controlled Incubation--```python-async def incubate_with_shaking(- plate,- temperature: float,- shake_rate: int,- duration: int-):- """Incubate plate with temperature and shaking"""-- hs = HeaterShaker(name="hs", backend=HamiltonHeaterShakerBackend())- await hs.setup()-- try:- # Assign plate to heater shaker- hs.assign_child_resource(plate, location=(0, 0, 0))-- # Start incubation- await hs.lock_plate()- await hs.set_temperature(temperature)- await hs.set_shake_rate(shake_rate)-- # Wait- await asyncio.sleep(duration)-- # Stop- await hs.set_shake_rate(0)- await hs.set_temperature(None)- await hs.unlock_plate()-- finally:- await hs.stop()--# Use in protocol-await incubate_with_shaking(- plate=assay_plate,- temperature=37,- shake_rate=300,- duration=600 # 10 minutes-)-```--### Automated Plate Processing--```python-async def process_plates(plate_list: list):- """Process multiple plates through workflow"""-- lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())- hs = HeaterShaker(name="hs", backend=HamiltonHeaterShakerBackend())-- await lh.setup()- await hs.setup()-- try:- for i, plate in enumerate(plate_list):- print(f"Processing plate {i+1}/{len(plate_list)}")-- # Transfer samples- await lh.pick_up_tips(tip_rack[f"A{i+1}:H{i+1}"])- await lh.transfer(- source[f"A{i+1}:H{i+1}"],- plate["A1:H1"],- vols=100- )- await lh.drop_tips()-- # Incubate- hs.assign_child_resource(plate, location=(0, 0, 0))- await hs.lock_plate()- await hs.set_temperature(37)- await hs.set_shake_rate(300)- await asyncio.sleep(300) # 5 min- await hs.set_shake_rate(0)- await hs.set_temperature(None)- await hs.unlock_plate()- hs.unassign_child_resource(plate)-- finally:- await lh.stop()- await hs.stop()-```+## Sources-## Additional Resources+Checked **2026-07-23**:-- Material Handling Documentation: https://docs.pylabrobot.org/user_guide/01_material-handling/-- Heater Shakers: https://docs.pylabrobot.org/user_guide/01_material-handling/heating_shaking/-- API Reference: https://docs.pylabrobot.org/api/-- Supported Equipment: https://docs.pylabrobot.org/user_guide/machines.html+- [Stable supported machines](https://docs.pylabrobot.org/stable/user_guide/machines.html)+ — pumps, centrifuges, heater shakers, storage, and temperature controllers+ with model-specific labels (page metadata surfaced 2025-01-01).+- [Stable pumps guide](https://docs.pylabrobot.org/stable/user_guide/00_liquid-handling/pumps/_pumps.html)+ and [pumps API](https://docs.pylabrobot.org/stable/api/pylabrobot.pumps.html).+- [Stable heating/shaking guide](https://docs.pylabrobot.org/stable/user_guide/01_material-handling/heating_shaking/heating_shaking.html)+ and [heating/shaking API](https://docs.pylabrobot.org/stable/api/pylabrobot.heating_shaking.html).+- [Stable centrifuge guide](https://docs.pylabrobot.org/stable/user_guide/01_material-handling/centrifuge/_centrifuge.html)+ and [centrifuge API](https://docs.pylabrobot.org/stable/api/pylabrobot.centrifuge.html).+- [`v0.2.1` pumps](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1/pylabrobot/pumps),+ [heating/shaking](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1/pylabrobot/heating_shaking),+ and [centrifuge](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1/pylabrobot/centrifuge)+ source — exact methods/classes; tag dated 2026-03-23.+- [Changelog `Unreleased`](https://github.com/PyLabRobot/pylabrobot/blob/main/CHANGELOG.md#unreleased)+ — development-only MicroSpin.diff --git a/skills/pylabrobot/references/resources.md b/skills/pylabrobot/references/resources.mdindex 17db928d..985b3ef3 100644--- a/skills/pylabrobot/references/resources.md+++ b/skills/pylabrobot/references/resources.md@@ -1,489 +1,238 @@-# Resource Management in PyLabRobot+# Resources, decks, state, and serialization-## Overview+Verified against **PyLabRobot 0.2.1** on **2026-07-23**.-Resources in PyLabRobot represent laboratory equipment, labware, or components used in protocols. The resource system provides a hierarchical structure for managing plates, tip racks, troughs, tubes, carriers, and other labware with precise spatial positioning and state tracking.+## Resource model-## Resource Basics+PyLabRobot represents a workcell as a resource tree. Typical nodes are:-### What is a Resource?+- `LiquidHandler` / `Deck`+- carriers, adapters, sites, and modules+- `Plate`, `TipRack`, reservoirs, tube racks, and `Trash`+- `Well`, `TipSpot`, and `Tip`-A resource represents:-- A piece of labware (plate, tip rack, trough, tube)-- Equipment (liquid handler, plate reader)-- A part of labware (well, tip)-- A container of labware (deck, carrier)--All resources inherit from the base `Resource` class and form a tree structure (arborescence) with parent-child relationships.--### Resource Attributes--Every resource requires:-- **name**: Unique identifier for the resource-- **size_x, size_y, size_z**: Dimensions in millimeters (cuboid representation)-- **location**: Coordinate relative to parent's origin (optional, set when assigned)+Every resource has a unique name, dimensions in millimetres, an optional+location relative to its parent, and parent/child relationships. Names are how+`Deck.get_resource(name)` resolves nested resources, so duplicates are unsafe.```python-from pylabrobot.resources import Resource+from pylabrobot.resources import Coordinate, Resource-# Create a basic resourceresource = Resource(- name="my_resource",- size_x=127.76, # mm- size_y=85.48, # mm- size_z=14.5 # mm+ name="fixture",+ size_x=100.0,+ size_y=50.0,+ size_z=20.0,)-```--## Resource Types--### Plates--Microplates with wells for holding liquids:--```python-from pylabrobot.resources import (- Cos_96_DW_1mL, # 96-well plate, 1mL deep well- Cos_96_DW_500ul, # 96-well plate, 500µL- Plate_384_Sq, # 384-well square plate- Cos_96_PCR # 96-well PCR plate+parent.assign_child_resource(+ resource,+ location=Coordinate(x=10.0, y=20.0, z=0.0),)--# Create plate-plate = Cos_96_DW_1mL(name="sample_plate")--# Access wells-well_a1 = plate["A1"] # Single well-row_a = plate["A1:H1"] # Entire row (A1-H1)-col_1 = plate["A1:A12"] # Entire column (A1-A12)-range_wells = plate["A1:C3"] # Range of wells-all_wells = plate.children # All wells as list-```--### Tip Racks--Containers holding pipette tips:--```python-from pylabrobot.resources import (- TIP_CAR_480_A00, # 96 standard tips- HTF_L, # Hamilton tips, filtered- TipRack # Generic tip rack-)--# Create tip rack-tip_rack = TIP_CAR_480_A00(name="tips")--# Access tips-tip_a1 = tip_rack["A1"] # Single tip position-tips_row = tip_rack["A1:H1"] # Row of tips-tips_col = tip_rack["A1:A12"] # Column of tips--# Check tip presence (requires tip tracking enabled)-from pylabrobot.resources import set_tip_tracking-set_tip_tracking(True)--has_tip = tip_rack["A1"].tracker.has_tip-```--### Troughs--Reservoir containers for reagents:--```python-from pylabrobot.resources import Trough_100ml--# Create trough-trough = Trough_100ml(name="buffer")--# Access channels-channel_1 = trough["channel_1"]-all_channels = trough.children```-### Tubes--Individual tubes or tube racks:--```python-from pylabrobot.resources import Tube, TubeRack--# Create tube rack-tube_rack = TubeRack(name="samples")--# Access tubes-tube_a1 = tube_rack["A1"]-```+The coordinate origin and usable envelope depend on the parent/deck definition.+Do not copy coordinates across robots, carriers, adapters, or labware revisions.-### Carriers+## Use stable built-in definitions-Platforms that hold plates, tips, or other labware:+Stable 0.2.1 exports vendor/model resource factories. The Hamilton getting+started tutorial uses:```pythonfrom pylabrobot.resources import (- PlateCarrier,- TipCarrier,- MFXCarrier+ Cor_96_wellplate_360ul_Fb,+ PLT_CAR_L5AC_A00,+ TIP_CAR_480_A00,+ hamilton_96_tiprack_1000uL_filter,)--# Carriers provide positions for labware-carrier = PlateCarrier(name="plate_carrier")--# Assign plate to carrier-plate = Cos_96_DW_1mL(name="plate")-carrier.assign_child_resource(plate, location=(0, 0, 0))+from pylabrobot.resources.hamilton import STARLetDeck```-## Deck Management--### Working with Decks+Names are case-sensitive. Old examples such as `Cos_96_DW_1mL` may not identify+the intended current factory. Search the installed 0.2.1 resource namespace or+stable resource docs and verify manufacturer, catalog number, dimensions,+bottom geometry, capacity, lid/adapter, and revision.-The deck represents the robot's work surface:+Carrier sites are commonly assigned before the carrier is placed on the deck:```python-from pylabrobot.resources import STARLetDeck, OTDeck+tip_carrier = TIP_CAR_480_A00(name="tip_carrier")+tip_carrier[0] = tips = hamilton_96_tiprack_1000uL_filter(name="tips")-# Hamilton STARlet deck-deck = STARLetDeck()+plate_carrier = PLT_CAR_L5AC_A00(name="plate_carrier")+plate_carrier[0] = plate = Cor_96_wellplate_360ul_Fb(name="plate")-# Opentrons OT-2 deck-deck = OTDeck()+deck = STARLetDeck()+deck.assign_child_resource(tip_carrier, rails=3)+deck.assign_child_resource(plate_carrier, rails=15)```-### Assigning Resources to Deck+Rail placement is Hamilton-specific. Other decks use their own sites,+coordinates, fixtures, and constraints.-Resources are assigned to specific deck positions using rails or coordinates:--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.resources import STARLetDeck, TIP_CAR_480_A00, Cos_96_DW_1mL+## Plates, wells, tip racks, and tips-lh = LiquidHandler(backend=backend, deck=STARLetDeck())--# Assign using rail positions (Hamilton STAR)-tip_rack = TIP_CAR_480_A00(name="tips")-source_plate = Cos_96_DW_1mL(name="source")-dest_plate = Cos_96_DW_1mL(name="dest")--lh.deck.assign_child_resource(tip_rack, rails=1)-lh.deck.assign_child_resource(source_plate, rails=10)-lh.deck.assign_child_resource(dest_plate, rails=15)--# Assign using coordinates (x, y, z in mm)-lh.deck.assign_child_resource(- resource=tip_rack,- location=(100, 200, 0)-)-```--### Unassigning Resources--Remove resources from deck:+Stable accessors include:```python-# Unassign specific resource-lh.deck.unassign_child_resource(tip_rack)--# Access assigned resources-all_resources = lh.deck.children-resource_names = [r.name for r in lh.deck.children]+well = plate.get_well("A1")+wells = plate.get_wells(["A1", "B1"])+selected_wells = plate["A1"] # list[Well], even for one identifier+tip_spot = tips.get_item("A1")+selected_tip_spots = tips["A1"] # list[TipSpot]+tip = tip_spot.get_tip()```-## Coordinate System+Relevant stable constructors/attributes include:-PyLabRobot uses a right-handed Cartesian coordinate system:+- `Well(..., max_volume=..., height_volume_data=...)`+- `Tip(has_filter, total_tip_length, maximal_volume, fitting_depth, ...)`+- `TipRack(..., with_tips=True)`+- `TipSpot(..., make_tip=...)`-- **X-axis**: Left to right (increasing rightward)-- **Y-axis**: Front to back (increasing toward back)-- **Z-axis**: Down to up (increasing upward)-- **Origin**: Bottom-front-left corner of parent+`Tip.maximal_volume` is only one compatibility dimension. Also validate fitting,+length, filter, head/tool, pickup/drop geometry, rack model, and vendor support.-### Location Calculations+Well capacity is geometric bookkeeping. Usable aspiration volume is smaller+when dead volume, well shape, tilt, liquid properties, required immersion, or+assay constraints apply. `height_volume_data` supports interpolation for+definitions that provide it; it is not a sensor and is only as accurate as the+definition/calibration.-```python-# Get absolute location (relative to deck/root)-absolute_loc = plate.get_absolute_location()+## Coordinate and collision checks-# Get location relative to another resource-relative_loc = well.get_location_wrt(deck)+For every resource, verify:-# Get location relative to parent-parent_relative = plate.location-```--## State Management--### Tracking Liquid Volumes--Track liquid volumes in wells and containers:--```python-from pylabrobot.resources import set_volume_tracking--# Enable volume tracking globally-set_volume_tracking(True)--# Set liquid in well-plate["A1"].tracker.set_liquids([- (None, 200) # (liquid_type, volume_in_uL)-])+1. Dimensions and units (`mm`).+2. Location relative to the correct parent and absolute location on the deck.+3. Orientation/rotation, lid, adapter, nesting, and stacking height.+4. Static overlap with neighboring resources.+5. Dynamic envelopes for channels, tips, grippers, arms, doors, trays, buckets,+ cables, tubing, and manually handled items.+6. Manufacturing tolerance, calibration, teaching, and clearance margin.-# Multiple liquids-plate["A2"].tracker.set_liquids([- ("water", 100),- ("ethanol", 50)-])+Hamilton deck assignment performs collision checks and exposes an+`ignore_collision` escape hatch. Do not set `ignore_collision=True` to make a+layout pass. Resolve the definition or placement and repeat physical review.+Generic resource assignment alone is not a complete collision or motion check.-# Get current volume-volume = plate["A1"].tracker.get_volume() # Returns total volume+The bundled checker provides an independent deterministic screen:-# Get liquids-liquids = plate["A1"].tracker.get_liquids() # Returns list of (type, vol) tuples+```bash+python3 skills/pylabrobot/scripts/check_deck_geometry.py \+ --input skills/pylabrobot/tests/fixtures/protocol_manifest.json```-### Tracking Tip Presence+It checks deck bounds and pairwise axis-aligned box overlap. It intentionally+does not claim to model rotation, motion, lids, tubing, cables, tolerances, or+vendor firmware paths.-Track which tips are present in tip racks:+## Tip and volume state```python-from pylabrobot.resources import set_tip_tracking+from pylabrobot.resources import set_tip_tracking, set_volume_tracking-# Enable tip tracking globallyset_tip_tracking(True)+set_volume_tracking(True)-# Check if tip is present-has_tip = tip_rack["A1"].tracker.has_tip--# Tips are automatically tracked when using pick_up_tips/drop_tips-await lh.pick_up_tips(tip_rack["A1"]) # Marks tip as absent-await lh.return_tips() # Marks tip as present-```--## Serialization--### Saving and Loading Resources--Save resource definitions and states to JSON:--```python-# Save resource definition-plate.save("plate_definition.json")--# Load resource from JSON-from pylabrobot.resources import Plate-plate = Plate.load_from_json_file("plate_definition.json")--# Save deck layout-lh.deck.save("deck_layout.json")--# Load deck layout-from pylabrobot.resources import Deck-deck = Deck.load_from_json_file("deck_layout.json")-```--### State Serialization--Save and restore resource states separately from definitions:--```python-# Save state (tip presence, liquid volumes)-state = plate.serialize_state()-with open("plate_state.json", "w") as f:- json.dump(state, f)--# Load state-with open("plate_state.json", "r") as f:- state = json.load(f)-plate.load_state(state)--# Save all states in hierarchy-all_states = lh.deck.serialize_all_state()--# Load all states-lh.deck.load_all_state(all_states)+tips.fill()+tips.get_item("A1").tracker.has_tip+plate.get_well("A1").tracker.set_volume(200.0)+plate.get_well("A1").tracker.get_used_volume()+plate.get_well("A1").tracker.get_free_volume()```-## Custom Resources--### Defining Custom Labware+Trackers model expected software state and operation history. They do not+physically detect tips, liquid, liquid identity, clogs, seals, lids, or+misloaded labware. Reconcile tracker state against a trusted preparation record+and the physical deck before any live run.-Create custom labware when built-in resources don't match your equipment:+Keep these separate:-```python-from pylabrobot.resources import Plate, Well--# Define custom plate-class CustomPlate(Plate):- def __init__(self, name: str):- super().__init__(- name=name,- size_x=127.76,- size_y=85.48,- size_z=14.5,- num_items_x=12, # 12 columns- num_items_y=8, # 8 rows- dx=9.0, # Well spacing X- dy=9.0, # Well spacing Y- dz=0.0, # Well spacing Z (usually 0)- item_dx=9.0, # Distance between well centers X- item_dy=9.0 # Distance between well centers Y- )--# Use custom plate-custom_plate = CustomPlate(name="my_custom_plate")-```+- maximum geometric well volume;+- declared initial volume;+- minimum dead/residual volume;+- transfer amount;+- maximum tip volume and currently held tip volume;+- destination headspace;+- physical liquid-level detection, if a particular backend supports it.-### Custom Wells+## Definition and state serialization-Define custom well geometry:+Verified 0.2.1 methods include:```python-from pylabrobot.resources import Well--# Create custom well-well = Well(- name="custom_well",- size_x=8.0,- size_y=8.0,- size_z=10.5,- max_volume=200, # µL- bottom_shape="flat" # or "v", "u"-)-```--## Resource Discovery--### Finding Resources--Navigate the resource hierarchy:--```python-# Get all wells in a plate-wells = plate.children--# Find resource by name-resource = lh.deck.get_resource("plate_name")--# Iterate through resources-for resource in lh.deck.children:- print(f"{resource.name}: {resource.get_absolute_location()}")+resource.save("deck.json", indent=2)+loaded = Resource.load_from_json_file("deck.json")-# Get wells by pattern-wells_a = [w for w in plate.children if w.name.startswith("A")]+state = resource.serialize_all_state()+resource.load_all_state(state)+resource.save_state_to_file("state.json", indent=2)+resource.load_state_from_file("state.json")```-### Resource Metadata+`Resource.serialize()` stores a definition; `serialize_state()` and+`serialize_all_state()` store tracker/resource state. Keep definition and state+with protocol version, PyLabRobot version, checksums, device/deck identity, and+preparation metadata.-Access resource information:+Treat serialized files as untrusted input:-```python-# Resource properties-print(f"Name: {plate.name}")-print(f"Size: {plate.size_x} x {plate.size_y} x {plate.size_z} mm")-print(f"Location: {plate.get_absolute_location()}")-print(f"Parent: {plate.parent.name if plate.parent else None}")-print(f"Children: {len(plate.children)}")--# Type checking-from pylabrobot.resources import Plate, TipRack-if isinstance(resource, Plate):- print("This is a plate")-elif isinstance(resource, TipRack):- print("This is a tip rack")-```+- accept only bounded UTF-8 JSON from an approved local path;+- reject duplicate/unknown keys and non-finite values;+- never load arbitrary Python, pickle, plugins, or user-selected classes;+- keep `Resource.deserialize(..., allow_marshal=False)` at its safe default;+- validate names, resource types, dimensions, locations, capacities, and state+ against an allowlist before constructing a workcell;+- do not let a saved state replace physical deck reconciliation.-## Best Practices+The bundled tools do not deserialize PyLabRobot classes. They use a small,+strict manifest schema:-1. **Unique Names**: Use descriptive, unique names for all resources-2. **Enable Tracking**: Turn on tip and volume tracking for accurate state management-3. **Coordinate Validation**: Verify resource positions don't overlap on deck-4. **State Serialization**: Save deck layouts and states for reproducible protocols-5. **Resource Cleanup**: Unassign resources when no longer needed-6. **Custom Resources**: Define custom labware when built-in options don't match-7. **Documentation**: Document custom resource dimensions and properties-8. **Type Checking**: Use isinstance() to verify resource types before operations-9. **Hierarchy Navigation**: Use parent/children relationships to navigate resource tree-10. **JSON Storage**: Store deck layouts in JSON for version control and sharing+- `assets/protocol-manifest.schema.json`+- `tests/fixtures/protocol_manifest.json`-## Common Patterns+The Python validator adds bounds and cross-field checks beyond the documentation+schema:-### Complete Deck Setup--```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends import STAR-from pylabrobot.resources import (- STARLetDeck,- TIP_CAR_480_A00,- Cos_96_DW_1mL,- Trough_100ml,- set_tip_tracking,- set_volume_tracking-)--# Enable tracking-set_tip_tracking(True)-set_volume_tracking(True)--# Initialize liquid handler-lh = LiquidHandler(backend=STAR(), deck=STARLetDeck())-await lh.setup()--# Define resources-tip_rack_1 = TIP_CAR_480_A00(name="tips_1")-tip_rack_2 = TIP_CAR_480_A00(name="tips_2")-source_plate = Cos_96_DW_1mL(name="source")-dest_plate = Cos_96_DW_1mL(name="dest")-buffer = Trough_100ml(name="buffer")--# Assign to deck-lh.deck.assign_child_resource(tip_rack_1, rails=1)-lh.deck.assign_child_resource(tip_rack_2, rails=2)-lh.deck.assign_child_resource(buffer, rails=5)-lh.deck.assign_child_resource(source_plate, rails=10)-lh.deck.assign_child_resource(dest_plate, rails=15)--# Set initial volumes-for well in source_plate.children:- well.tracker.set_liquids([(None, 200)])--buffer["channel_1"].tracker.set_liquids([(None, 50000)]) # 50 mL--# Save deck layout-lh.deck.save("my_protocol_deck.json")--# Save initial state-import json-with open("initial_state.json", "w") as f:- json.dump(lh.deck.serialize_all_state(), f)+```bash+python3 skills/pylabrobot/scripts/validate_manifest.py \+ --input skills/pylabrobot/tests/fixtures/protocol_manifest.json```-### Loading Saved Deck+Inputs must remain under the current working directory, be regular non-symlink+files, use the expected extension, and stay under 2 MB.-```python-from pylabrobot.resources import Deck+## Custom labware-# Load deck from file-deck = Deck.load_from_json_file("my_protocol_deck.json")+Do not invent a `Plate` or `Well` from nominal SBS footprint alone. Obtain and+review:-# Load state-import json-with open("initial_state.json", "r") as f:- state = json.load(f)-deck.load_all_state(state)+- exact manufacturer/catalog/revision;+- external dimensions, skirt and flange, nesting/stacking, lid and adapter;+- well centres, pitch, top/bottom geometry, depth, material thickness, and+ height/volume behavior;+- robot-specific pickup, gripping, carrier/site, and clearance data;+- empirical calibration and acceptance results.-# Use with liquid handler-lh = LiquidHandler(backend=STAR(), deck=deck)-await lh.setup()+Use upstream's current resource-definition contributor tooling and tests. Keep+custom definitions versioned and independently reviewed before commissioning.-# Access resources by name-source_plate = deck.get_resource("source")-dest_plate = deck.get_resource("dest")-```+## Sources-## Additional Resources+Checked **2026-07-23**:-- Resource Documentation: https://docs.pylabrobot.org/resources/introduction.html-- Custom Resources Guide: https://docs.pylabrobot.org/resources/custom-resources.html-- API Reference: https://docs.pylabrobot.org/api/pylabrobot.resources.html-- Deck Layouts: https://github.com/PyLabRobot/pylabrobot/tree/main/pylabrobot/resources/deck+- [Stable resource management](https://docs.pylabrobot.org/stable/resources/introduction.html)+ and [stable resources API](https://docs.pylabrobot.org/stable/api/pylabrobot.resources.html)+ — resource tree and current 0.2.1 classes.+- [Stable Hamilton tutorial](https://docs.pylabrobot.org/stable/user_guide/00_liquid-handling/hamilton-star/basic.html)+ — verified factories, carrier sites, rails, and deck summary (page metadata+ surfaced 2025-01-01).+- [Stable tracker guide](https://docs.pylabrobot.org/stable/user_guide/machine-agnostic-features/using-trackers.html)+ — tip/volume state and errors (page metadata surfaced 2025-01-01).+- [`v0.2.1` resources source](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1/pylabrobot/resources)+ — constructor, serialization, tracker, and collision signatures; tag dated+ 2026-03-23.+- [Changelog](https://github.com/PyLabRobot/pylabrobot/blob/main/CHANGELOG.md)+ — 0.2.1 added `height_volume_data`; plate `stacking_z_height` is listed under+ `Unreleased` and is not assumed stable.diff --git a/skills/pylabrobot/references/visualization.md b/skills/pylabrobot/references/visualization.mdindex 7ad3846b..9fec4e84 100644--- a/skills/pylabrobot/references/visualization.md+++ b/skills/pylabrobot/references/visualization.md@@ -1,532 +1,187 @@-# Visualization & Simulation in PyLabRobot+# Visualization and software-only simulation-## Overview+Verified against **PyLabRobot 0.2.1** on **2026-07-23**.-PyLabRobot provides visualization and simulation tools for developing, testing, and validating laboratory protocols without physical hardware. The visualizer offers real-time 3D visualization of deck state, while simulation backends enable protocol testing and validation.+## Three different layers-## The Visualizer+Do not conflate:-### What is the Visualizer?+1. **Manifest/ledger planning** — the bundled dependency-free CLIs validate+ bounded JSON/CSV and produce non-executable JSON.+2. **Chatterbox backend** — PyLabRobot validates frontend/tracker operations and+ prints them instead of sending hardware commands.+3. **Visualizer** — a browser renderer that receives resource and tracker events+ over localhost HTTP/WebSocket services.-The PyLabRobot Visualizer is a browser-based tool that:-- Displays 3D visualization of the deck layout-- Shows real-time tip presence and liquid volumes-- Works with both simulated and physical robots-- Provides interactive deck state inspection-- Enables visual protocol validation+None is a robot physics simulator, collision-motion planner, liquid-dynamics+model, or physical sensor.-### Starting the Visualizer+## Chatterbox backend-The visualizer runs as a web server and displays in your browser:--```python-from pylabrobot.visualizer import Visualizer--# Create visualizer-vis = Visualizer()--# Start web server (opens browser automatically)-await vis.start()--# Stop visualizer-await vis.stop()-```--**Default Settings:**-- Port: 1234 (http://localhost:1234)-- Opens browser automatically when started--### Connecting Liquid Handler to Visualizer+The verified stable import is:```pythonfrom pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend-from pylabrobot.resources import STARLetDeck-from pylabrobot.visualizer import Visualizer--# Create visualizer-vis = Visualizer()-await vis.start()+from pylabrobot.liquid_handling.backends import LiquidHandlerChatterboxBackend+from pylabrobot.resources.hamilton import STARLetDeck-# Create liquid handler with simulation backendlh = LiquidHandler(- backend=ChatterboxBackend(num_channels=8),- deck=STARLetDeck()+ backend=LiquidHandlerChatterboxBackend(num_channels=8),+ deck=STARLetDeck(),)--# Connect liquid handler to visualizer-lh.visualizer = vis-await lh.setup()--# Now all operations are visualized in real-time-await lh.pick_up_tips(tip_rack["A1:H1"])-await lh.aspirate(plate["A1:H1"], vols=100)-await lh.dispense(plate["A2:H2"], vols=100)-await lh.drop_tips()-```--### Tracking Features--#### Enable Tracking--For the visualizer to display tips and liquids, enable tracking:--```python-from pylabrobot.resources import set_tip_tracking, set_volume_tracking--# Enable globally (before creating resources)-set_tip_tracking(True)-set_volume_tracking(True)+try:+ # Assign resources, seed tracker state, and execute planned calls.+ ...+finally:+ await lh.stop()```-#### Setting Initial Liquids+`setup()` above is offline only because the backend is constructed literally as+`LiquidHandlerChatterboxBackend`. Never replace it from a config string,+environment variable, plugin, or auto-detected device.-Define initial liquid contents for visualization:+The stable docs sometimes use the generic phrase `ChatterboxBackend`, but the+verified liquid-handler class/import is `LiquidHandlerChatterboxBackend`.+`ChatterBoxBackend` (capital `B`) is a distinct exported legacy-named class.-```python-# Set liquid in a single well-plate["A1"].tracker.set_liquids([- (None, 200) # (liquid_type, volume_in_µL)-])--# Set multiple liquids in one well-plate["A2"].tracker.set_liquids([- ("water", 100),- ("ethanol", 50)-])--# Set liquids in multiple wells-for well in plate["A1:H1"]:- well.tracker.set_liquids([(None, 200)])--# Set liquids in entire plate-for well in plate.children:- well.tracker.set_liquids([("sample", 150)])-```--#### Visualizing Tip Presence--```python-# Tips are automatically tracked when using pick_up/drop operations-await lh.pick_up_tips(tip_rack["A1:H1"]) # Tips shown as absent in visualizer-await lh.return_tips() # Tips shown as present in visualizer-```+## Visualizer API-### Complete Visualizer Example+Current stable usage:```python-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend-from pylabrobot.resources import (- STARLetDeck,- TIP_CAR_480_A00,- Cos_96_DW_1mL,- set_tip_tracking,- set_volume_tracking-)from pylabrobot.visualizer import Visualizer-# Enable tracking-set_tip_tracking(True)-set_volume_tracking(True)--# Create visualizer-vis = Visualizer()-await vis.start()--# Create liquid handler-lh = LiquidHandler(- backend=ChatterboxBackend(num_channels=8),- deck=STARLetDeck()-)-lh.visualizer = vis-await lh.setup()--# Define resources-tip_rack = TIP_CAR_480_A00(name="tips")-source_plate = Cos_96_DW_1mL(name="source")-dest_plate = Cos_96_DW_1mL(name="dest")--# Assign to deck-lh.deck.assign_child_resource(tip_rack, rails=1)-lh.deck.assign_child_resource(source_plate, rails=10)-lh.deck.assign_child_resource(dest_plate, rails=15)--# Set initial volumes-for well in source_plate.children:- well.tracker.set_liquids([("sample", 200)])--# Execute protocol with visualization-await lh.pick_up_tips(tip_rack["A1:H1"])-await lh.transfer(- source_plate["A1:H12"],- dest_plate["A1:H12"],- vols=100+vis = Visualizer(+ resource=lh,+ host="127.0.0.1",+ ws_port=2121,+ fs_port=1337,+ open_browser=False,)-await lh.drop_tips()--# Keep visualizer open to inspect final state-input("Press Enter to close visualizer...")--# Cleanup-await lh.stop()-await vis.stop()-```--## Deck Layout Editor--### Using the Deck Editor--PyLabRobot includes a graphical deck layout editor:--**Features:**-- Visual deck design interface-- Drag-and-drop resource placement-- Edit initial liquid states-- Set tip presence-- Save/load layouts as JSON--**Usage:**-- Accessed through the visualizer interface-- Create layouts graphically instead of code-- Export to JSON for use in protocols--### Loading Deck Layouts--```python-from pylabrobot.resources import Deck--# Load deck from JSON file-deck = Deck.load_from_json_file("my_deck_layout.json")--# Use with liquid handler-lh = LiquidHandler(backend=backend, deck=deck)-await lh.setup()--# Resources are already assigned-source = deck.get_resource("source")-dest = deck.get_resource("dest")-tip_rack = deck.get_resource("tips")+await vis.setup()+try:+ # Exercise the software-only liquid handler.+ ...+finally:+ await vis.stop()```-## Simulation--### ChatterboxBackend--The ChatterboxBackend simulates liquid handling operations:--**Features:**-- No hardware required-- Validates protocol logic-- Tracks tips and volumes-- Supports all liquid handling operations-- Works with visualizer--**Setup:**--```python-from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend--# Create simulation backend-backend = ChatterboxBackend(- num_channels=8 # Simulate 8-channel pipette-)+Corrections to stale examples:-# Use with liquid handler-lh = LiquidHandler(backend=backend, deck=STARLetDeck())-```--### Simulation Use Cases+- `Visualizer` requires a root `resource`; `Visualizer()` alone is incomplete.+- Use `setup()` / `stop()`, not `start()`.+- Do not assign `lh.visualizer = vis`; pass `lh` as the Visualizer resource.+- Stable defaults are WebSocket port 2121 and file-server port 1337, not 1234.-#### Protocol Development+The Visualizer starts two local servers and can open a browser. It therefore+uses localhost networking even when the liquid handler is software-only.+Do not use it where the requirement is "no network." Bind only to loopback,+keep `open_browser=False` for controlled tests, avoid shared/untrusted hosts,+and stop both services reliably.-```python-async def develop_protocol():- """Develop protocol using simulation"""+The bundled CLIs and tests do **not** start the Visualizer or any socket.- # Use simulation for development- lh = LiquidHandler(- backend=ChatterboxBackend(),- deck=STARLetDeck()- )+## What the Visualizer does- # Connect visualizer- vis = Visualizer()- await vis.start()- lh.visualizer = vis+It:- await lh.setup()+- renders a `Resource` tree;+- receives assignment/unassignment callbacks;+- renders tracker state such as planned tips and volumes;+- updates as frontend operations change state.- try:- # Develop and test protocol- await lh.pick_up_tips(tip_rack["A1"])- await lh.transfer(plate["A1"], plate["A2"], vols=100)- await lh.drop_tips()+It does not:- print("Protocol development complete!")+- calculate physical trajectories or clearances;+- detect an incorrect/missing physical resource, tip, or liquid;+- model meniscus, viscosity, foam, pressure, carryover, or pipetting error;+- emulate firmware timing, sensors, interlocks, doors, arms, or failures;+- validate liquid classes or calibrations;+- authorize a live run.- finally:- await lh.stop()- await vis.stop()-```+Upstream's contributor guide explicitly describes the browser as passive: it+renders messages and does not perform simulation logic.-#### Protocol Validation+## Tracker setup```python-async def validate_protocol():- """Validate protocol logic without hardware"""-- set_tip_tracking(True)- set_volume_tracking(True)-- lh = LiquidHandler(- backend=ChatterboxBackend(),- deck=STARLetDeck()- )- await lh.setup()-- try:- # Setup resources- tip_rack = TIP_CAR_480_A00(name="tips")- plate = Cos_96_DW_1mL(name="plate")-- lh.deck.assign_child_resource(tip_rack, rails=1)- lh.deck.assign_child_resource(plate, rails=10)-- # Set initial state- for well in plate.children:- well.tracker.set_liquids([(None, 200)])-- # Execute protocol- await lh.pick_up_tips(tip_rack["A1:H1"])-- # Test different volumes- test_volumes = [50, 100, 150]- for i, vol in enumerate(test_volumes):- await lh.transfer(- plate[f"A{i+1}:H{i+1}"],- plate[f"A{i+4}:H{i+4}"],- vols=vol- )-- await lh.drop_tips()-- # Validate volumes- for i, vol in enumerate(test_volumes):- for row in "ABCDEFGH":- well = plate[f"{row}{i+4}"]- actual_vol = well.tracker.get_volume()- assert actual_vol == vol, f"Volume mismatch in {well.name}"-- print("✓ Protocol validation passed!")-- finally:- await lh.stop()-```--#### Testing Edge Cases+from pylabrobot.resources import set_tip_tracking, set_volume_tracking-```python-async def test_edge_cases():- """Test protocol edge cases in simulation"""-- lh = LiquidHandler(- backend=ChatterboxBackend(),- deck=STARLetDeck()- )- await lh.setup()-- try:- # Test 1: Empty well aspiration- try:- await lh.aspirate(empty_plate["A1"], vols=100)- print("✗ Should have raised error for empty well")- except Exception as e:- print(f"✓ Correctly raised error: {e}")-- # Test 2: Overfilling well- try:- await lh.dispense(small_well, vols=1000) # Too much- print("✗ Should have raised error for overfilling")- except Exception as e:- print(f"✓ Correctly raised error: {e}")-- # Test 3: Tip capacity- try:- await lh.aspirate(large_volume_well, vols=2000) # Exceeds tip capacity- print("✗ Should have raised error for tip capacity")- except Exception as e:- print(f"✓ Correctly raised error: {e}")-- finally:- await lh.stop()+set_tip_tracking(True)+set_volume_tracking(True)+source.get_well("A1").tracker.set_volume(100.0)```-### CI/CD Integration--Use simulation for automated testing:--```python-# test_protocols.py-import pytest-from pylabrobot.liquid_handling import LiquidHandler-from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend--async def test_transfer_protocol():- """Test liquid transfer protocol"""+Set initial state from a synthetic fixture for tests. For later live work,+reconcile planned state with the physical deck; do not infer physical presence+from what the browser draws.- lh = LiquidHandler(- backend=ChatterboxBackend(),- deck=STARLetDeck()- )- await lh.setup()+## Deterministic no-network plan- try:- # Setup- tip_rack = TIP_CAR_480_A00(name="tips")- plate = Cos_96_DW_1mL(name="plate")+Generate a JSON plan without importing PyLabRobot:- lh.deck.assign_child_resource(tip_rack, rails=1)- lh.deck.assign_child_resource(plate, rails=10)-- # Set initial volumes- plate["A1"].tracker.set_liquids([(None, 200)])-- # Execute- await lh.pick_up_tips(tip_rack["A1"])- await lh.transfer(plate["A1"], plate["A2"], vols=100)- await lh.drop_tips()-- # Assert- assert plate["A1"].tracker.get_volume() == 100- assert plate["A2"].tracker.get_volume() == 100-- finally:- await lh.stop()+```bash+python3 skills/pylabrobot/scripts/generate_simulation_plan.py \+ --manifest skills/pylabrobot/tests/fixtures/protocol_manifest.json \+ --transfers skills/pylabrobot/tests/fixtures/transfers.csv```-## Best Practices--1. **Always Use Simulation First**: Develop and test protocols in simulation before running on hardware-2. **Enable Tracking**: Turn on tip and volume tracking for accurate visualization-3. **Set Initial States**: Define initial liquid volumes for realistic simulation-4. **Visual Inspection**: Use visualizer to verify deck layout and protocol execution-5. **Validate Logic**: Test edge cases and error conditions in simulation-6. **Automated Testing**: Integrate simulation into CI/CD pipelines-7. **Save Layouts**: Use JSON to save and share deck layouts-8. **Document States**: Record initial states for reproducibility-9. **Interactive Development**: Keep visualizer open during development-10. **Protocol Refinement**: Iterate in simulation before hardware runs+The output:-## Common Patterns+- fixes the target at `PyLabRobot==0.2.1`;+- names only `LiquidHandlerChatterboxBackend`;+- marks live backends as forbidden;+- records zero connection attempts and no serial/USB/network access;+- expands each transfer into tip pickup, aspirate, dispense, and tip disposal;+- includes final planned volumes, tip counts, limitations, and a mandatory human+ review checklist.-### Development to Production Workflow+It intentionally produces data, not executable Python.-```python-import os--# Configuration-USE_HARDWARE = os.getenv("USE_HARDWARE", "false").lower() == "true"--# Create appropriate backend-if USE_HARDWARE:- from pylabrobot.liquid_handling.backends import STAR- backend = STAR()- print("Running on Hamilton STAR hardware")-else:- from pylabrobot.liquid_handling.backends.simulation import ChatterboxBackend- backend = ChatterboxBackend()- print("Running in simulation mode")--# Rest of protocol is identical-lh = LiquidHandler(backend=backend, deck=STARLetDeck())--if not USE_HARDWARE:- # Enable visualizer for simulation- vis = Visualizer()- await vis.start()- lh.visualizer = vis+## Test strategy-await lh.setup()+Use layers of evidence:-# Protocol execution-# ... (same code for hardware and simulation)+1. Strict manifest schema validation.+2. Static deck bounds and axis-aligned overlap screen.+3. Transfer/dead-volume/destination/tip/channel/rate/height ledger.+4. Non-executable simulation plan review.+5. Pinned 0.2.1 import/signature inspection with zero backend instances.+6. Chatterbox-only protocol smoke with synthetic resources.+7. Optional Visualizer review on an approved loopback host.+8. Independent physical commissioning only after explicit operator approval.-# Run with: USE_HARDWARE=false python protocol.py # Simulation-# Run with: USE_HARDWARE=true python protocol.py # Hardware-```+Test failures should be deterministic. Do not catch broad errors and continue;+do not disable trackers; do not mutate expected state to make a failed+assertion pass.-### Visual Protocol Verification+Run bundled tests without bytecode:-```python-async def visual_verification():- """Run protocol with visual verification pauses"""-- vis = Visualizer()- await vis.start()-- lh = LiquidHandler(- backend=ChatterboxBackend(),- deck=STARLetDeck()- )- lh.visualizer = vis- await lh.setup()-- try:- # Step 1- await lh.pick_up_tips(tip_rack["A1:H1"])- input("Press Enter to continue...")-- # Step 2- await lh.aspirate(source["A1:H1"], vols=100)- input("Press Enter to continue...")-- # Step 3- await lh.dispense(dest["A1:H1"], vols=100)- input("Press Enter to continue...")-- # Step 4- await lh.drop_tips()- input("Press Enter to finish...")-- finally:- await lh.stop()- await vis.stop()+```bash+PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover \+ -s skills/pylabrobot/tests -p "test_*.py" -v```-## Troubleshooting--### Visualizer Not Updating--- Ensure `lh.visualizer = vis` is set before operations-- Check that tracking is enabled globally-- Verify visualizer is running (`vis.start()`)-- Refresh browser if connection is lost--### Tracking Not Working--```python-# Must enable tracking BEFORE creating resources-set_tip_tracking(True)-set_volume_tracking(True)--# Then create resources-tip_rack = TIP_CAR_480_A00(name="tips")-plate = Cos_96_DW_1mL(name="plate")-```+## Stable versus development-### Simulation Errors+Use `/stable/` for pinned 0.2.1 behavior. `/dev/` and repository `main` may+change event payloads, resource serialization, supported devices, or+Visualizer UI. Do not copy development examples into a stable protocol without+installing and testing an actual later stable release.-- Simulation validates operations (e.g., can't aspirate from empty well)-- Use try/except to handle validation errors-- Check initial states are set correctly-- Verify volumes don't exceed capacities+## Sources-## Additional Resources+Checked **2026-07-23**:-- Visualizer Documentation: https://docs.pylabrobot.org/user_guide/using-the-visualizer.html (if available)-- Simulation Guide: https://docs.pylabrobot.org/user_guide/simulation.html (if available)-- API Reference: https://docs.pylabrobot.org/api/pylabrobot.visualizer.html-- GitHub Examples: https://github.com/PyLabRobot/pylabrobot/tree/main/examples+- [Stable Visualizer guide](https://docs.pylabrobot.org/stable/user_guide/machine-agnostic-features/using-the-visualizer.html)+ — current imports, `Visualizer(resource=lh)`, `setup()`, and localhost ports.+- [Visualizer contributor architecture](https://docs.pylabrobot.org/stable/contributor_guide/visualizer.html)+ — passive rendering, file server, WebSocket server, and callbacks.+- [Stable tracker guide](https://docs.pylabrobot.org/stable/user_guide/machine-agnostic-features/using-trackers.html)+ — planned tip/volume state (page metadata surfaced 2025-01-01).+- [Stable liquid-handling API](https://docs.pylabrobot.org/stable/api/pylabrobot.liquid_handling.html)+ — `LiquidHandlerChatterboxBackend`.+- [`v0.2.1` Visualizer source](https://github.com/PyLabRobot/pylabrobot/tree/v0.2.1/pylabrobot/visualizer)+ and [chatterbox source](https://github.com/PyLabRobot/pylabrobot/blob/v0.2.1/pylabrobot/liquid_handling/backends/chatterbox.py)+ — exact constructor/method verification; tag dated 2026-03-23.diff --git a/skills/pylabrobot/scripts/__init__.py b/skills/pylabrobot/scripts/__init__.pynew file mode 100644index 00000000..5a0d8ee5--- /dev/null+++ b/skills/pylabrobot/scripts/__init__.py@@ -0,0 +1 @@+"""Offline, deterministic helpers bundled with the PyLabRobot skill."""diff --git a/skills/pylabrobot/scripts/_common.py b/skills/pylabrobot/scripts/_common.pynew file mode 100644index 00000000..9807942a--- /dev/null+++ b/skills/pylabrobot/scripts/_common.py@@ -0,0 +1,718 @@+"""Dependency-free validation and planning helpers for the PyLabRobot skill.++These helpers never import PyLabRobot, open sockets, enumerate hardware, or access+serial/USB devices. All file inputs are bounded, local to the current working+directory, regular files, and non-symlinks.+"""++from __future__ import annotations++import csv+import json+import math+import re+import sys+from pathlib import Path+from typing import Any, Iterable, Sequence++SCHEMA_VERSION = "1.0"+PYLABROBOT_VERSION = "0.2.1"+MAX_FILE_BYTES = 2_000_000+MAX_RESOURCES = 256+MAX_TRANSFERS = 10_000+MAX_DIMENSION_MM = 5_000.0+MAX_VOLUME_UL = 1_000_000.0+MAX_RATE_UL_S = 10_000.0+MAX_CHANNELS = 96++NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")+WELL_RE = re.compile(r"^([A-Z]{1,2})([1-9][0-9]{0,2})$")+INT_TEXT_RE = re.compile(r"^(0|[1-9][0-9]*)$")++RESOURCE_KINDS = frozenset({"plate", "reservoir", "tube_rack", "tip_rack", "waste"})+LIQUID_KINDS = frozenset({"plate", "reservoir", "tube_rack"})+TRANSFER_HEADERS = (+ "transfer_id",+ "source",+ "destination",+ "volume_uL",+ "tip_policy",+ "tip_type",+ "liquid_class",+ "aspiration_height_mm",+ "dispense_height_mm",+ "aspiration_rate_uL_s",+ "dispense_rate_uL_s",+ "channel",+)+++class ValidationError(ValueError):+ """A deterministic, user-correctable validation failure."""+++def _reject_constant(value: str) -> None:+ raise ValidationError(f"non-finite JSON number is forbidden: {value}")+++def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, value in pairs:+ if key in result:+ raise ValidationError(f"duplicate JSON key: {key}")+ result[key] = value+ return result+++def safe_input_path(raw_path: str, allowed_suffixes: Sequence[str]) -> Path:+ """Resolve a bounded local input path and reject symlinks/path traversal."""+ base = Path.cwd().resolve()+ candidate = Path(raw_path)+ unresolved = candidate if candidate.is_absolute() else base / candidate+ try:+ lexical_relative = unresolved.relative_to(base)+ except ValueError as exc:+ raise ValidationError("input path must stay inside the current working directory") from exc+ if ".." in lexical_relative.parts:+ raise ValidationError("parent-directory traversal is forbidden")++ cursor = base+ for part in lexical_relative.parts:+ cursor = cursor / part+ if cursor.is_symlink():+ raise ValidationError(f"symlink paths are forbidden: {raw_path}")++ resolved = unresolved.resolve(strict=False)+ try:+ resolved.relative_to(base)+ except ValueError as exc:+ raise ValidationError("input path must stay inside the current working directory") from exc++ if resolved.suffix.lower() not in {suffix.lower() for suffix in allowed_suffixes}:+ allowed = ", ".join(sorted(allowed_suffixes))+ raise ValidationError(f"input must use one of these suffixes: {allowed}")+ if not resolved.exists() or not resolved.is_file():+ raise ValidationError(f"input is not a regular file: {raw_path}")+ size = resolved.stat().st_size+ if size > MAX_FILE_BYTES:+ raise ValidationError(f"input exceeds {MAX_FILE_BYTES} bytes")+ return resolved+++def load_json(raw_path: str) -> dict[str, Any]:+ path = safe_input_path(raw_path, (".json",))+ try:+ text = path.read_text(encoding="utf-8")+ except UnicodeDecodeError as exc:+ raise ValidationError("JSON input must be UTF-8") from exc+ try:+ data = json.loads(+ text,+ object_pairs_hook=_unique_object,+ parse_constant=_reject_constant,+ )+ except json.JSONDecodeError as exc:+ raise ValidationError(f"invalid JSON at line {exc.lineno}, column {exc.colno}") from exc+ if not isinstance(data, dict):+ raise ValidationError("JSON root must be an object")+ return data+++def load_csv(raw_path: str) -> list[dict[str, str]]:+ path = safe_input_path(raw_path, (".csv",))+ try:+ with path.open("r", encoding="utf-8", newline="") as handle:+ reader = csv.DictReader(handle)+ if tuple(reader.fieldnames or ()) != TRANSFER_HEADERS:+ raise ValidationError(+ "CSV header must exactly match: " + ",".join(TRANSFER_HEADERS)+ )+ rows: list[dict[str, str]] = []+ for line_number, row in enumerate(reader, start=2):+ if None in row:+ raise ValidationError(f"CSV line {line_number} has extra columns")+ normalized = {key: (value or "").strip() for key, value in row.items()}+ if any(value == "" for value in normalized.values()):+ raise ValidationError(f"CSV line {line_number} contains an empty field")+ rows.append(normalized)+ if len(rows) > MAX_TRANSFERS:+ raise ValidationError(f"CSV exceeds {MAX_TRANSFERS} transfer rows")+ except UnicodeDecodeError as exc:+ raise ValidationError("CSV input must be UTF-8") from exc+ if not rows:+ raise ValidationError("CSV must contain at least one transfer row")+ return rows+++def _exact_keys(+ obj: Any,+ required: Iterable[str],+ optional: Iterable[str],+ where: str,+) -> dict[str, Any]:+ if not isinstance(obj, dict):+ raise ValidationError(f"{where} must be an object")+ required_set = set(required)+ allowed = required_set | set(optional)+ missing = sorted(required_set - set(obj))+ unknown = sorted(set(obj) - allowed)+ if missing:+ raise ValidationError(f"{where} missing keys: {', '.join(missing)}")+ if unknown:+ raise ValidationError(f"{where} has unknown keys: {', '.join(unknown)}")+ return obj+++def _name(value: Any, where: str) -> str:+ if not isinstance(value, str) or NAME_RE.fullmatch(value) is None:+ raise ValidationError(f"{where} must match {NAME_RE.pattern}")+ return value+++def _number(+ value: Any,+ where: str,+ *,+ minimum: float = 0.0,+ maximum: float,+ minimum_inclusive: bool = True,+) -> float:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise ValidationError(f"{where} must be a number")+ result = float(value)+ if not math.isfinite(result):+ raise ValidationError(f"{where} must be finite")+ too_small = result < minimum if minimum_inclusive else result <= minimum+ if too_small or result > maximum:+ bracket = "[" if minimum_inclusive else "("+ raise ValidationError(f"{where} must be in {bracket}{minimum}, {maximum}]")+ return result+++def _integer(value: Any, where: str, minimum: int, maximum: int) -> int:+ if isinstance(value, bool) or not isinstance(value, int):+ raise ValidationError(f"{where} must be an integer")+ if value < minimum or value > maximum:+ raise ValidationError(f"{where} must be in [{minimum}, {maximum}]")+ return value+++def _string_list(value: Any, where: str, maximum_items: int = 256) -> list[str]:+ if not isinstance(value, list) or not value or len(value) > maximum_items:+ raise ValidationError(f"{where} must be a non-empty list with at most {maximum_items} items")+ result: list[str] = []+ for index, item in enumerate(value):+ result.append(_name(item, f"{where}[{index}]"))+ if len(set(result)) != len(result):+ raise ValidationError(f"{where} must not contain duplicates")+ return result+++def _xyz(value: Any, where: str, *, positive: bool) -> dict[str, float]:+ obj = _exact_keys(value, ("x", "y", "z"), (), where)+ minimum_inclusive = not positive+ return {+ axis: _number(+ obj[axis],+ f"{where}.{axis}",+ minimum=0.0,+ maximum=MAX_DIMENSION_MM,+ minimum_inclusive=minimum_inclusive,+ )+ for axis in ("x", "y", "z")+ }+++def row_index(row_letters: str) -> int:+ index = 0+ for character in row_letters:+ index = index * 26 + ord(character) - ord("A") + 1+ return index - 1+++def validate_well(well: str, rows: int, columns: int, where: str) -> str:+ match = WELL_RE.fullmatch(well)+ if match is None:+ raise ValidationError(f"{where} must be an uppercase well such as A1")+ row, column_text = match.groups()+ if row_index(row) >= rows or int(column_text) > columns:+ raise ValidationError(f"{where}={well} lies outside the declared grid")+ return well+++def _validate_grid(value: Any, kind: str, where: str) -> dict[str, Any]:+ if kind == "tip_rack":+ obj = _exact_keys(value, ("rows", "columns", "tip_capacity_uL"), (), where)+ return {+ "rows": _integer(obj["rows"], f"{where}.rows", 1, 384),+ "columns": _integer(obj["columns"], f"{where}.columns", 1, 384),+ "tip_capacity_uL": _number(+ obj["tip_capacity_uL"],+ f"{where}.tip_capacity_uL",+ maximum=MAX_VOLUME_UL,+ minimum_inclusive=False,+ ),+ }+ obj = _exact_keys(+ value,+ ("rows", "columns", "well_capacity_uL", "dead_volume_uL", "well_depth_mm"),+ (),+ where,+ )+ capacity = _number(+ obj["well_capacity_uL"],+ f"{where}.well_capacity_uL",+ maximum=MAX_VOLUME_UL,+ minimum_inclusive=False,+ )+ dead = _number(+ obj["dead_volume_uL"],+ f"{where}.dead_volume_uL",+ maximum=capacity,+ )+ if dead >= capacity:+ raise ValidationError(f"{where}.dead_volume_uL must be below well capacity")+ return {+ "rows": _integer(obj["rows"], f"{where}.rows", 1, 384),+ "columns": _integer(obj["columns"], f"{where}.columns", 1, 384),+ "well_capacity_uL": capacity,+ "dead_volume_uL": dead,+ "well_depth_mm": _number(+ obj["well_depth_mm"],+ f"{where}.well_depth_mm",+ maximum=MAX_DIMENSION_MM,+ minimum_inclusive=False,+ ),+ }+++def validate_manifest(data: dict[str, Any]) -> dict[str, Any]:+ """Validate and normalize protocol manifest schema v1.0."""+ top = _exact_keys(+ data,+ ("schema_version", "protocol_id", "mode", "units", "deck", "resources", "constraints"),+ (),+ "manifest",+ )+ if top["schema_version"] != SCHEMA_VERSION:+ raise ValidationError(f"schema_version must be {SCHEMA_VERSION!r}")+ protocol_id = _name(top["protocol_id"], "protocol_id")+ if top["mode"] != "offline":+ raise ValidationError("mode must be 'offline'; live execution is not supported")++ units = _exact_keys(top["units"], ("volume", "length", "rate", "time"), (), "units")+ expected_units = {"volume": "uL", "length": "mm", "rate": "uL/s", "time": "s"}+ if units != expected_units:+ raise ValidationError(f"units must exactly equal {expected_units}")++ deck_obj = _exact_keys(top["deck"], ("name", "size_mm"), (), "deck")+ deck = {+ "name": _name(deck_obj["name"], "deck.name"),+ "size_mm": _xyz(deck_obj["size_mm"], "deck.size_mm", positive=True),+ }++ resources_value = top["resources"]+ if (+ not isinstance(resources_value, list)+ or not resources_value+ or len(resources_value) > MAX_RESOURCES+ ):+ raise ValidationError(f"resources must contain 1 to {MAX_RESOURCES} objects")++ resources: list[dict[str, Any]] = []+ resource_names: set[str] = set()+ for index, raw_resource in enumerate(resources_value):+ where = f"resources[{index}]"+ base = _exact_keys(+ raw_resource,+ ("name", "kind", "location_mm", "size_mm"),+ ("grid", "initial_volumes_uL", "tip_type", "tips_available"),+ where,+ )+ name = _name(base["name"], f"{where}.name")+ if name in resource_names:+ raise ValidationError(f"duplicate resource name: {name}")+ resource_names.add(name)+ kind = base["kind"]+ if kind not in RESOURCE_KINDS:+ raise ValidationError(f"{where}.kind must be one of {sorted(RESOURCE_KINDS)}")+ normalized: dict[str, Any] = {+ "name": name,+ "kind": kind,+ "location_mm": _xyz(base["location_mm"], f"{where}.location_mm", positive=False),+ "size_mm": _xyz(base["size_mm"], f"{where}.size_mm", positive=True),+ }++ if kind == "waste":+ forbidden = {"grid", "initial_volumes_uL", "tip_type", "tips_available"} & set(base)+ if forbidden:+ raise ValidationError(f"{where} waste has forbidden keys: {', '.join(sorted(forbidden))}")+ elif kind == "tip_rack":+ if "grid" not in base or "tip_type" not in base or "tips_available" not in base:+ raise ValidationError(f"{where} tip_rack requires grid, tip_type, and tips_available")+ if "initial_volumes_uL" in base:+ raise ValidationError(f"{where} tip_rack cannot define initial volumes")+ grid = _validate_grid(base["grid"], kind, f"{where}.grid")+ tips = _string_list(base["tips_available"], f"{where}.tips_available", 384 * 384)+ for tip_index, tip in enumerate(tips):+ validate_well(tip, grid["rows"], grid["columns"], f"{where}.tips_available[{tip_index}]")+ normalized.update(+ grid=grid,+ tip_type=_name(base["tip_type"], f"{where}.tip_type"),+ tips_available=tips,+ )+ else:+ if "grid" not in base or "initial_volumes_uL" not in base:+ raise ValidationError(f"{where} {kind} requires grid and initial_volumes_uL")+ if "tip_type" in base or "tips_available" in base:+ raise ValidationError(f"{where} {kind} cannot define tip fields")+ grid = _validate_grid(base["grid"], kind, f"{where}.grid")+ volumes = base["initial_volumes_uL"]+ if not isinstance(volumes, dict):+ raise ValidationError(f"{where}.initial_volumes_uL must be an object")+ normalized_volumes: dict[str, float] = {}+ for well, volume in volumes.items():+ validate_well(well, grid["rows"], grid["columns"], f"{where}.initial_volumes_uL key")+ normalized_volumes[well] = _number(+ volume,+ f"{where}.initial_volumes_uL.{well}",+ maximum=grid["well_capacity_uL"],+ )+ normalized.update(grid=grid, initial_volumes_uL=normalized_volumes)+ resources.append(normalized)++ if not any(resource["kind"] == "waste" for resource in resources):+ raise ValidationError("manifest must declare at least one waste resource")++ constraints_obj = _exact_keys(+ top["constraints"],+ (+ "allowed_liquid_classes",+ "allowed_tip_types",+ "channels",+ "requires_human_confirmation",+ "max_transfer_uL",+ "max_rate_uL_s",+ ),+ (),+ "constraints",+ )+ if constraints_obj["requires_human_confirmation"] is not True:+ raise ValidationError("constraints.requires_human_confirmation must be true")+ constraints = {+ "allowed_liquid_classes": _string_list(+ constraints_obj["allowed_liquid_classes"], "constraints.allowed_liquid_classes"+ ),+ "allowed_tip_types": _string_list(+ constraints_obj["allowed_tip_types"], "constraints.allowed_tip_types"+ ),+ "channels": _integer(+ constraints_obj["channels"], "constraints.channels", 1, MAX_CHANNELS+ ),+ "requires_human_confirmation": True,+ "max_transfer_uL": _number(+ constraints_obj["max_transfer_uL"],+ "constraints.max_transfer_uL",+ maximum=MAX_VOLUME_UL,+ minimum_inclusive=False,+ ),+ "max_rate_uL_s": _number(+ constraints_obj["max_rate_uL_s"],+ "constraints.max_rate_uL_s",+ maximum=MAX_RATE_UL_S,+ minimum_inclusive=False,+ ),+ }++ for resource in resources:+ if resource["kind"] == "tip_rack" and resource["tip_type"] not in constraints["allowed_tip_types"]:+ raise ValidationError(+ f"tip rack {resource['name']} uses a tip_type outside constraints.allowed_tip_types"+ )++ return {+ "schema_version": SCHEMA_VERSION,+ "protocol_id": protocol_id,+ "mode": "offline",+ "units": expected_units,+ "deck": deck,+ "resources": resources,+ "constraints": constraints,+ }+++def _parse_float_text(+ value: str,+ where: str,+ *,+ maximum: float,+ minimum: float = 0.0,+ minimum_inclusive: bool = True,+) -> float:+ try:+ parsed = float(value)+ except ValueError as exc:+ raise ValidationError(f"{where} must be a decimal number") from exc+ return _number(+ parsed,+ where,+ minimum=minimum,+ maximum=maximum,+ minimum_inclusive=minimum_inclusive,+ )+++def _parse_int_text(value: str, where: str, minimum: int, maximum: int) -> int:+ if INT_TEXT_RE.fullmatch(value) is None:+ raise ValidationError(f"{where} must be an unsigned base-10 integer")+ parsed = int(value)+ if parsed < minimum or parsed > maximum:+ raise ValidationError(f"{where} must be in [{minimum}, {maximum}]")+ return parsed+++def _endpoint(value: str, where: str) -> tuple[str, str]:+ if value.count(":") != 1:+ raise ValidationError(f"{where} must use resource:WELL syntax")+ resource, well = value.split(":")+ _name(resource, f"{where} resource")+ if WELL_RE.fullmatch(well) is None:+ raise ValidationError(f"{where} well must be uppercase, for example A1")+ return resource, well+++def validate_transfers(rows: list[dict[str, str]]) -> list[dict[str, Any]]:+ normalized: list[dict[str, Any]] = []+ identifiers: set[str] = set()+ for index, row in enumerate(rows):+ where = f"transfers[{index}]"+ transfer_id = _name(row["transfer_id"], f"{where}.transfer_id")+ if transfer_id in identifiers:+ raise ValidationError(f"duplicate transfer_id: {transfer_id}")+ identifiers.add(transfer_id)+ if row["tip_policy"] != "new":+ raise ValidationError(f"{where}.tip_policy must be 'new' for contamination safety")+ normalized.append(+ {+ "transfer_id": transfer_id,+ "source": _endpoint(row["source"], f"{where}.source"),+ "destination": _endpoint(row["destination"], f"{where}.destination"),+ "volume_uL": _parse_float_text(+ row["volume_uL"],+ f"{where}.volume_uL",+ maximum=MAX_VOLUME_UL,+ minimum_inclusive=False,+ ),+ "tip_policy": "new",+ "tip_type": _name(row["tip_type"], f"{where}.tip_type"),+ "liquid_class": _name(row["liquid_class"], f"{where}.liquid_class"),+ "aspiration_height_mm": _parse_float_text(+ row["aspiration_height_mm"],+ f"{where}.aspiration_height_mm",+ maximum=MAX_DIMENSION_MM,+ ),+ "dispense_height_mm": _parse_float_text(+ row["dispense_height_mm"],+ f"{where}.dispense_height_mm",+ maximum=MAX_DIMENSION_MM,+ ),+ "aspiration_rate_uL_s": _parse_float_text(+ row["aspiration_rate_uL_s"],+ f"{where}.aspiration_rate_uL_s",+ maximum=MAX_RATE_UL_S,+ minimum_inclusive=False,+ ),+ "dispense_rate_uL_s": _parse_float_text(+ row["dispense_rate_uL_s"],+ f"{where}.dispense_rate_uL_s",+ maximum=MAX_RATE_UL_S,+ minimum_inclusive=False,+ ),+ "channel": _parse_int_text(+ row["channel"], f"{where}.channel", 0, MAX_CHANNELS - 1+ ),+ }+ )+ return normalized+++def geometry_report(manifest: dict[str, Any]) -> dict[str, Any]:+ deck_size = manifest["deck"]["size_mm"]+ resources = manifest["resources"]+ out_of_bounds: list[dict[str, Any]] = []+ for resource in resources:+ axes: list[str] = []+ for axis in ("x", "y", "z"):+ start = resource["location_mm"][axis]+ end = start + resource["size_mm"][axis]+ if start < 0 or end > deck_size[axis]:+ axes.append(axis)+ if axes:+ out_of_bounds.append({"resource": resource["name"], "axes": axes})++ collisions: list[dict[str, str]] = []+ for left_index, left in enumerate(resources):+ for right in resources[left_index + 1 :]:+ overlaps = all(+ min(+ left["location_mm"][axis] + left["size_mm"][axis],+ right["location_mm"][axis] + right["size_mm"][axis],+ )+ > max(left["location_mm"][axis], right["location_mm"][axis])+ for axis in ("x", "y", "z")+ )+ if overlaps:+ collisions.append({"resource_a": left["name"], "resource_b": right["name"]})++ return {+ "ok": not out_of_bounds and not collisions,+ "out_of_bounds": out_of_bounds,+ "collisions": collisions,+ "model": "axis-aligned static bounding boxes in millimetres",+ "limitations": [+ "does not model rotations, gripper/channel motion envelopes, lids, tubing, cables, or tolerances",+ "passing this check is not evidence that a physical run is collision-free",+ ],+ }+++def plan_transfers(+ manifest: dict[str, Any],+ transfers: list[dict[str, Any]],+) -> dict[str, Any]:+ resources = {resource["name"]: resource for resource in manifest["resources"]}+ constraints = manifest["constraints"]+ liquid_classes = set(constraints["allowed_liquid_classes"])+ tip_types = set(constraints["allowed_tip_types"])+ waste = next(resource["name"] for resource in manifest["resources"] if resource["kind"] == "waste")++ available_tips: dict[str, list[tuple[str, str, float]]] = {tip_type: [] for tip_type in tip_types}+ for resource in manifest["resources"]:+ if resource["kind"] == "tip_rack":+ for well in resource["tips_available"]:+ available_tips[resource["tip_type"]].append(+ (resource["name"], well, resource["grid"]["tip_capacity_uL"])+ )++ ledger: dict[tuple[str, str], float] = {}+ known_liquid_state: set[tuple[str, str]] = set()+ for resource in manifest["resources"]:+ if resource["kind"] in LIQUID_KINDS:+ for well, volume in resource["initial_volumes_uL"].items():+ ledger[(resource["name"], well)] = volume+ known_liquid_state.add((resource["name"], well))++ operations: list[dict[str, Any]] = []+ tip_cursor: dict[str, int] = {tip_type: 0 for tip_type in tip_types}+ for index, transfer in enumerate(transfers):+ where = f"transfers[{index}]"+ source_name, source_well = transfer["source"]+ destination_name, destination_well = transfer["destination"]+ if source_name not in resources or destination_name not in resources:+ raise ValidationError(f"{where} references an unknown resource")+ source_resource = resources[source_name]+ destination_resource = resources[destination_name]+ if source_resource["kind"] not in LIQUID_KINDS:+ raise ValidationError(f"{where}.source must reference liquid-holding labware")+ if destination_resource["kind"] not in LIQUID_KINDS:+ raise ValidationError(f"{where}.destination must reference liquid-holding labware")+ validate_well(+ source_well,+ source_resource["grid"]["rows"],+ source_resource["grid"]["columns"],+ f"{where}.source",+ )+ validate_well(+ destination_well,+ destination_resource["grid"]["rows"],+ destination_resource["grid"]["columns"],+ f"{where}.destination",+ )+ source_key = (source_name, source_well)+ destination_key = (destination_name, destination_well)+ if source_key == destination_key:+ raise ValidationError(f"{where} source and destination must differ")+ if source_key not in known_liquid_state:+ raise ValidationError(f"{where}.source requires declared or previously transferred volume")++ volume = transfer["volume_uL"]+ if volume > constraints["max_transfer_uL"]:+ raise ValidationError(f"{where}.volume_uL exceeds constraints.max_transfer_uL")+ if transfer["liquid_class"] not in liquid_classes:+ raise ValidationError(f"{where}.liquid_class is not allowlisted")+ if transfer["tip_type"] not in tip_types:+ raise ValidationError(f"{where}.tip_type is not allowlisted")+ if transfer["channel"] >= constraints["channels"]:+ raise ValidationError(f"{where}.channel exceeds the declared channel count")+ if (+ transfer["aspiration_rate_uL_s"] > constraints["max_rate_uL_s"]+ or transfer["dispense_rate_uL_s"] > constraints["max_rate_uL_s"]+ ):+ raise ValidationError(f"{where} rate exceeds constraints.max_rate_uL_s")+ if transfer["aspiration_height_mm"] > source_resource["grid"]["well_depth_mm"]:+ raise ValidationError(f"{where}.aspiration_height_mm exceeds source well depth")+ if transfer["dispense_height_mm"] > destination_resource["grid"]["well_depth_mm"]:+ raise ValidationError(f"{where}.dispense_height_mm exceeds destination well depth")++ remaining = ledger[source_key] - volume+ if remaining < source_resource["grid"]["dead_volume_uL"]:+ raise ValidationError(f"{where} would aspirate below source dead volume")+ destination_volume = ledger.get(destination_key, 0.0) + volume+ if destination_volume > destination_resource["grid"]["well_capacity_uL"]:+ raise ValidationError(f"{where} would exceed destination well capacity")++ tips = available_tips.get(transfer["tip_type"], [])+ cursor = tip_cursor[transfer["tip_type"]]+ if cursor >= len(tips):+ raise ValidationError(f"{where} has no unused compatible tip")+ tip_rack, tip_well, tip_capacity = tips[cursor]+ if volume > tip_capacity:+ raise ValidationError(f"{where}.volume_uL exceeds selected tip capacity")+ tip_cursor[transfer["tip_type"]] += 1++ ledger[source_key] = remaining+ ledger[destination_key] = destination_volume+ known_liquid_state.add(destination_key)+ operations.append(+ {+ **transfer,+ "source": f"{source_name}:{source_well}",+ "destination": f"{destination_name}:{destination_well}",+ "assigned_tip": f"{tip_rack}:{tip_well}",+ "drop_tip_at": waste,+ }+ )++ final_ledger = [+ {"location": f"{resource}:{well}", "volume_uL": round(volume, 9)}+ for (resource, well), volume in sorted(ledger.items())+ ]+ used_tips = sum(tip_cursor.values())+ return {+ "ok": True,+ "protocol_id": manifest["protocol_id"],+ "operations": operations,+ "final_volume_ledger": final_ledger,+ "tip_summary": {+ "policy": "one new tip per transfer",+ "used": used_tips,+ "remaining": sum(len(available_tips[key]) - tip_cursor[key] for key in tip_cursor),+ },+ "bookkeeping_warning": (+ "Volumes and tips are planned state only; they do not detect physical liquid or tip presence."+ ),+ }+++def emit_json(payload: Any, *, stream: Any = None) -> None:+ if stream is None:+ stream = sys.stdout+ print(json.dumps(payload, indent=2, sort_keys=True, allow_nan=False), file=stream)+++def emit_error(error: Exception) -> int:+ emit_json(+ {"ok": False, "error": type(error).__name__, "message": str(error)},+ stream=sys.stderr,+ )+ return 2diff --git a/skills/pylabrobot/scripts/check_deck_geometry.py b/skills/pylabrobot/scripts/check_deck_geometry.pynew file mode 100644index 00000000..7fc9758d--- /dev/null+++ b/skills/pylabrobot/scripts/check_deck_geometry.py@@ -0,0 +1,52 @@+#!/usr/bin/env python3+"""Check bounded static deck geometry without importing PyLabRobot."""++from __future__ import annotations++import argparse+from typing import Sequence++if __package__:+ from ._common import (+ ValidationError,+ emit_error,+ emit_json,+ geometry_report,+ load_json,+ validate_manifest,+ )+else:+ from _common import (+ ValidationError,+ emit_error,+ emit_json,+ geometry_report,+ load_json,+ validate_manifest,+ )+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Check resource bounds and static axis-aligned collisions in an offline "+ "manifest. No hardware, serial, USB, or network access occurs."+ )+ )+ parser.add_argument("--input", required=True, help="Local UTF-8 .json manifest")+ return parser+++def main(argv: Sequence[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ manifest = validate_manifest(load_json(args.input))+ report = geometry_report(manifest)+ except (OSError, ValidationError) as error:+ return emit_error(error)+ emit_json({"protocol_id": manifest["protocol_id"], **report})+ return 0 if report["ok"] else 3+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pylabrobot/scripts/generate_simulation_plan.py b/skills/pylabrobot/scripts/generate_simulation_plan.pynew file mode 100644index 00000000..9af0aca5--- /dev/null+++ b/skills/pylabrobot/scripts/generate_simulation_plan.py@@ -0,0 +1,140 @@+#!/usr/bin/env python3+"""Generate a non-executable, hardware-blocked simulation plan as JSON."""++from __future__ import annotations++import argparse+from typing import Any, Sequence++if __package__:+ from ._common import (+ PYLABROBOT_VERSION,+ ValidationError,+ emit_error,+ emit_json,+ geometry_report,+ load_csv,+ load_json,+ plan_transfers,+ validate_manifest,+ validate_transfers,+ )+else:+ from _common import (+ PYLABROBOT_VERSION,+ ValidationError,+ emit_error,+ emit_json,+ geometry_report,+ load_csv,+ load_json,+ plan_transfers,+ validate_manifest,+ validate_transfers,+ )+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Generate a deterministic JSON plan for offline review. The output is data, "+ "not executable Python; this command cannot select or connect to live hardware."+ )+ )+ parser.add_argument("--manifest", required=True, help="Local UTF-8 .json manifest")+ parser.add_argument("--transfers", required=True, help="Local UTF-8 .csv transfer table")+ return parser+++def _steps(operations: list[dict[str, Any]]) -> list[dict[str, Any]]:+ steps: list[dict[str, Any]] = []+ for operation in operations:+ common = {+ "transfer_id": operation["transfer_id"],+ "channel": operation["channel"],+ }+ steps.extend(+ [+ {+ **common,+ "action": "pick_up_tip",+ "tip": operation["assigned_tip"],+ "tip_type": operation["tip_type"],+ },+ {+ **common,+ "action": "aspirate",+ "resource": operation["source"],+ "volume_uL": operation["volume_uL"],+ "height_mm": operation["aspiration_height_mm"],+ "rate_uL_s": operation["aspiration_rate_uL_s"],+ "liquid_class_review_label": operation["liquid_class"],+ },+ {+ **common,+ "action": "dispense",+ "resource": operation["destination"],+ "volume_uL": operation["volume_uL"],+ "height_mm": operation["dispense_height_mm"],+ "rate_uL_s": operation["dispense_rate_uL_s"],+ "liquid_class_review_label": operation["liquid_class"],+ },+ {+ **common,+ "action": "drop_tip",+ "resource": operation["drop_tip_at"],+ },+ ]+ )+ return steps+++def main(argv: Sequence[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ manifest = validate_manifest(load_json(args.manifest))+ geometry = geometry_report(manifest)+ if not geometry["ok"]:+ raise ValidationError("deck geometry must pass before a simulation plan is generated")+ transfers = validate_transfers(load_csv(args.transfers))+ transfer_plan = plan_transfers(manifest, transfers)+ except (OSError, ValidationError) as error:+ return emit_error(error)++ emit_json(+ {+ "ok": True,+ "plan_kind": "offline_review_only",+ "protocol_id": manifest["protocol_id"],+ "pylabrobot_target": PYLABROBOT_VERSION,+ "backend": (+ "pylabrobot.liquid_handling.backends.chatterbox."+ "LiquidHandlerChatterboxBackend"+ ),+ "backend_setup_permitted": True,+ "live_backend_permitted": False,+ "connection_attempted": False,+ "serial_usb_network_access": False,+ "geometry": geometry,+ "steps": _steps(transfer_plan["operations"]),+ "final_volume_ledger": transfer_plan["final_volume_ledger"],+ "tip_summary": transfer_plan["tip_summary"],+ "mandatory_human_review": [+ "physically reconcile deck and labware identities with this manifest",+ "verify calibration, collision envelopes, coordinates, channels, and units",+ "verify source volumes, dead volumes, destination capacity, and physical liquid",+ "verify tips, contamination controls, heights, rates, and vendor liquid classes",+ "confirm guards and emergency stop are ready before any separately authorized live run",+ ],+ "limitations": [+ "the chatterbox backend reports planned commands but does not model robot physics",+ "the visualizer renders tracker state but does not perform simulation logic",+ "bookkeeping cannot detect physical liquid, tips, seals, lids, tubing, or obstacles",+ ],+ }+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pylabrobot/scripts/inspect_backends.py b/skills/pylabrobot/scripts/inspect_backends.pynew file mode 100644index 00000000..7ac1d03a--- /dev/null+++ b/skills/pylabrobot/scripts/inspect_backends.py@@ -0,0 +1,216 @@+#!/usr/bin/env python3+"""Inspect a pinned PyLabRobot API surface without constructing a backend."""++from __future__ import annotations++import argparse+import inspect+import re+from importlib.metadata import PackageNotFoundError, metadata, version+from typing import Any, Sequence++if __package__:+ from ._common import PYLABROBOT_VERSION, ValidationError, emit_error, emit_json+else:+ from _common import PYLABROBOT_VERSION, ValidationError, emit_error, emit_json++VERSION_RE = re.compile(r"^[0-9]+(?:\.[0-9]+){2}$")+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Inspect installed PyLabRobot version, known backend symbols, frontend "+ "methods, and stable support labels. Imports are lazy; no class is "+ "instantiated and no setup, serial, USB, or network operation is performed."+ )+ )+ parser.add_argument(+ "--expected-version",+ default=PYLABROBOT_VERSION,+ help=f"Expected exact stable version (default: {PYLABROBOT_VERSION})",+ )+ parser.add_argument(+ "--strict",+ action="store_true",+ help="Exit nonzero when PyLabRobot is absent, mismatched, or symbols fail to import",+ )+ return parser+++def _class_record(+ class_object: type[Any],+ *,+ support: str,+ transport: str,+ methods: Sequence[str],+) -> dict[str, Any]:+ return {+ "class": class_object.__name__,+ "import_path": f"{class_object.__module__}.{class_object.__name__}",+ "signature": str(inspect.signature(class_object)),+ "stable_support": support,+ "transport": transport,+ "declared_methods": {+ method: hasattr(class_object, method)+ for method in methods+ },+ }+++def inspect_installation(expected_version: str) -> dict[str, Any]:+ if VERSION_RE.fullmatch(expected_version) is None:+ raise ValidationError("--expected-version must use X.Y.Z numeric form")+ try:+ installed_version = version("PyLabRobot")+ package_metadata = metadata("PyLabRobot")+ except PackageNotFoundError:+ return {+ "ok": True,+ "installed": False,+ "expected_version": expected_version,+ "connection_attempted": False,+ "serial_usb_network_access": False,+ "message": "PyLabRobot is not installed; help and local planning CLIs remain available.",+ }++ import_errors: list[str] = []+ backends: list[dict[str, Any]] = []+ frontends: dict[str, dict[str, bool]] = {}+ try:+ from pylabrobot.liquid_handling import LiquidHandler+ from pylabrobot.liquid_handling.backends import (+ EVOBackend,+ LiquidHandlerChatterboxBackend,+ OpentronsOT2Backend,+ STARBackend,+ VantageBackend,+ )++ operation_methods = (+ "setup",+ "stop",+ "pick_up_tips",+ "drop_tips",+ "aspirate",+ "dispense",+ )+ backends = [+ _class_record(+ LiquidHandlerChatterboxBackend,+ support="testing/offline",+ transport="console only",+ methods=operation_methods,+ ),+ _class_record(+ STARBackend,+ support="Full",+ transport="vendor firmware over USB",+ methods=operation_methods,+ ),+ _class_record(+ VantageBackend,+ support="Mostly",+ transport="vendor firmware over USB",+ methods=operation_methods,+ ),+ _class_record(+ EVOBackend,+ support="Basic",+ transport="vendor firmware interface",+ methods=operation_methods,+ ),+ _class_record(+ OpentronsOT2Backend,+ support="Mostly",+ transport="HTTP to explicitly configured host",+ methods=operation_methods,+ ),+ ]+ frontends["LiquidHandler"] = {+ method: hasattr(LiquidHandler, method)+ for method in (+ "setup",+ "stop",+ "pick_up_tips",+ "drop_tips",+ "return_tips",+ "aspirate",+ "dispense",+ "transfer",+ )+ }+ except (ImportError, AttributeError) as error:+ import_errors.append(f"liquid_handling: {type(error).__name__}: {error}")++ try:+ from pylabrobot.centrifuge import Centrifuge+ from pylabrobot.heating_shaking import HeaterShaker+ from pylabrobot.plate_reading import PlateReader+ from pylabrobot.pumps import Pump+ from pylabrobot.scales import Scale+ from pylabrobot.shaking import Shaker+ from pylabrobot.temperature_controlling import TemperatureController+ from pylabrobot.visualizer import Visualizer++ method_map: dict[str, tuple[type[Any], tuple[str, ...]]] = {+ "PlateReader": (+ PlateReader,+ ("setup", "stop", "open", "close", "read_absorbance", "read_fluorescence"),+ ),+ "Pump": (Pump, ("setup", "stop", "run_for_duration", "run_continuously", "halt")),+ "Scale": (Scale, ("setup", "stop", "get_weight", "tare", "zero")),+ "HeaterShaker": (+ HeaterShaker,+ ("setup", "stop", "set_temperature", "shake", "stop_shaking"),+ ),+ "Shaker": (Shaker, ("setup", "stop", "shake", "stop_shaking")),+ "TemperatureController": (+ TemperatureController,+ ("setup", "stop", "set_temperature", "get_temperature", "deactivate"),+ ),+ "Centrifuge": (+ Centrifuge,+ ("setup", "stop", "open_door", "close_door", "lock_door", "spin"),+ ),+ "Visualizer": (Visualizer, ("setup", "stop")),+ }+ for name, (class_object, methods) in method_map.items():+ frontends[name] = {method: hasattr(class_object, method) for method in methods}+ except (ImportError, AttributeError) as error:+ import_errors.append(f"equipment: {type(error).__name__}: {error}")++ return {+ "ok": not import_errors and installed_version == expected_version,+ "installed": True,+ "installed_version": installed_version,+ "expected_version": expected_version,+ "version_match": installed_version == expected_version,+ "requires_python": package_metadata.get("Requires-Python"),+ "connection_attempted": False,+ "serial_usb_network_access": False,+ "backend_instances_created": 0,+ "backends": backends,+ "frontends": frontends,+ "import_errors": import_errors,+ "stable_status_note": (+ "Support labels are the PyLabRobot 0.2.1 stable supported-machines labels; "+ "availability and capabilities remain model/firmware/configuration specific."+ ),+ }+++def main(argv: Sequence[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ report = inspect_installation(args.expected_version)+ except ValidationError as error:+ return emit_error(error)+ emit_json(report)+ if args.strict and not report.get("ok", False):+ return 4+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pylabrobot/scripts/plan_transfers.py b/skills/pylabrobot/scripts/plan_transfers.pynew file mode 100644index 00000000..3d0dc262--- /dev/null+++ b/skills/pylabrobot/scripts/plan_transfers.py@@ -0,0 +1,59 @@+#!/usr/bin/env python3+"""Plan a deterministic volume ledger and one-use tip allocation."""++from __future__ import annotations++import argparse+from typing import Sequence++if __package__:+ from ._common import (+ ValidationError,+ emit_error,+ emit_json,+ load_csv,+ load_json,+ plan_transfers,+ validate_manifest,+ validate_transfers,+ )+else:+ from _common import (+ ValidationError,+ emit_error,+ emit_json,+ load_csv,+ load_json,+ plan_transfers,+ validate_manifest,+ validate_transfers,+ )+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Validate transfer CSV rows, source/dead/destination volumes, tip capacity, "+ "rates, heights, wells, channels, and one-use tip assignments. Planning "+ "state is not physical liquid or tip detection."+ )+ )+ parser.add_argument("--manifest", required=True, help="Local UTF-8 .json manifest")+ parser.add_argument("--transfers", required=True, help="Local UTF-8 .csv transfer table")+ return parser+++def main(argv: Sequence[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ manifest = validate_manifest(load_json(args.manifest))+ transfers = validate_transfers(load_csv(args.transfers))+ report = plan_transfers(manifest, transfers)+ except (OSError, ValidationError) as error:+ return emit_error(error)+ emit_json(report)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pylabrobot/scripts/validate_manifest.py b/skills/pylabrobot/scripts/validate_manifest.pynew file mode 100644index 00000000..9e4f5ac2--- /dev/null+++ b/skills/pylabrobot/scripts/validate_manifest.py@@ -0,0 +1,47 @@+#!/usr/bin/env python3+"""Validate a strict offline PyLabRobot protocol manifest."""++from __future__ import annotations++import argparse+from typing import Sequence++if __package__:+ from ._common import ValidationError, emit_error, emit_json, load_json, validate_manifest+else:+ from _common import ValidationError, emit_error, emit_json, load_json, validate_manifest+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Validate protocol-manifest schema v1.0. This command is dependency-free "+ "and never imports PyLabRobot or accesses hardware/network interfaces."+ )+ )+ parser.add_argument("--input", required=True, help="Local UTF-8 .json manifest")+ return parser+++def main(argv: Sequence[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ manifest = validate_manifest(load_json(args.input))+ except (OSError, ValidationError) as error:+ return emit_error(error)+ emit_json(+ {+ "ok": True,+ "protocol_id": manifest["protocol_id"],+ "schema_version": manifest["schema_version"],+ "mode": manifest["mode"],+ "resource_count": len(manifest["resources"]),+ "requires_human_confirmation": True,+ "hardware_access": False,+ }+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pylabrobot/tests/__init__.py b/skills/pylabrobot/tests/__init__.pynew file mode 100644index 00000000..f5d93555--- /dev/null+++ b/skills/pylabrobot/tests/__init__.py@@ -0,0 +1 @@+"""Tests for the PyLabRobot skill's offline utilities."""diff --git a/skills/pylabrobot/tests/fixtures/collision_manifest.json b/skills/pylabrobot/tests/fixtures/collision_manifest.jsonnew file mode 100644index 00000000..a23072f9--- /dev/null+++ b/skills/pylabrobot/tests/fixtures/collision_manifest.json@@ -0,0 +1,116 @@+{+ "schema_version": "1.0",+ "protocol_id": "synthetic_collision",+ "mode": "offline",+ "units": {+ "volume": "uL",+ "length": "mm",+ "rate": "uL/s",+ "time": "s"+ },+ "deck": {+ "name": "synthetic_deck",+ "size_mm": {+ "x": 600.0,+ "y": 400.0,+ "z": 200.0+ }+ },+ "resources": [+ {+ "name": "source_plate",+ "kind": "plate",+ "location_mm": {+ "x": 10.0,+ "y": 10.0,+ "z": 0.0+ },+ "size_mm": {+ "x": 127.76,+ "y": 85.48,+ "z": 15.0+ },+ "grid": {+ "rows": 8,+ "columns": 12,+ "well_capacity_uL": 360.0,+ "dead_volume_uL": 20.0,+ "well_depth_mm": 11.0+ },+ "initial_volumes_uL": {+ "A1": 200.0+ }+ },+ {+ "name": "destination_plate",+ "kind": "plate",+ "location_mm": {+ "x": 100.0,+ "y": 50.0,+ "z": 0.0+ },+ "size_mm": {+ "x": 127.76,+ "y": 85.48,+ "z": 15.0+ },+ "grid": {+ "rows": 8,+ "columns": 12,+ "well_capacity_uL": 360.0,+ "dead_volume_uL": 0.0,+ "well_depth_mm": 11.0+ },+ "initial_volumes_uL": {}+ },+ {+ "name": "tips",+ "kind": "tip_rack",+ "location_mm": {+ "x": 10.0,+ "y": 180.0,+ "z": 0.0+ },+ "size_mm": {+ "x": 127.76,+ "y": 85.48,+ "z": 60.0+ },+ "grid": {+ "rows": 8,+ "columns": 12,+ "tip_capacity_uL": 300.0+ },+ "tip_type": "generic_300uL",+ "tips_available": [+ "A1"+ ]+ },+ {+ "name": "waste",+ "kind": "waste",+ "location_mm": {+ "x": 320.0,+ "y": 120.0,+ "z": 0.0+ },+ "size_mm": {+ "x": 100.0,+ "y": 100.0,+ "z": 100.0+ }+ }+ ],+ "constraints": {+ "allowed_liquid_classes": [+ "water_validated"+ ],+ "allowed_tip_types": [+ "generic_300uL"+ ],+ "channels": 8,+ "requires_human_confirmation": true,+ "max_transfer_uL": 250.0,+ "max_rate_uL_s": 500.0+ }+}diff --git a/skills/pylabrobot/tests/fixtures/protocol_manifest.json b/skills/pylabrobot/tests/fixtures/protocol_manifest.jsonnew file mode 100644index 00000000..ed568981--- /dev/null+++ b/skills/pylabrobot/tests/fixtures/protocol_manifest.json@@ -0,0 +1,119 @@+{+ "schema_version": "1.0",+ "protocol_id": "synthetic_transfer",+ "mode": "offline",+ "units": {+ "volume": "uL",+ "length": "mm",+ "rate": "uL/s",+ "time": "s"+ },+ "deck": {+ "name": "synthetic_deck",+ "size_mm": {+ "x": 600.0,+ "y": 400.0,+ "z": 200.0+ }+ },+ "resources": [+ {+ "name": "source_plate",+ "kind": "plate",+ "location_mm": {+ "x": 10.0,+ "y": 10.0,+ "z": 0.0+ },+ "size_mm": {+ "x": 127.76,+ "y": 85.48,+ "z": 15.0+ },+ "grid": {+ "rows": 8,+ "columns": 12,+ "well_capacity_uL": 360.0,+ "dead_volume_uL": 20.0,+ "well_depth_mm": 11.0+ },+ "initial_volumes_uL": {+ "A1": 200.0,+ "B1": 150.0+ }+ },+ {+ "name": "destination_plate",+ "kind": "plate",+ "location_mm": {+ "x": 160.0,+ "y": 10.0,+ "z": 0.0+ },+ "size_mm": {+ "x": 127.76,+ "y": 85.48,+ "z": 15.0+ },+ "grid": {+ "rows": 8,+ "columns": 12,+ "well_capacity_uL": 360.0,+ "dead_volume_uL": 0.0,+ "well_depth_mm": 11.0+ },+ "initial_volumes_uL": {}+ },+ {+ "name": "tips",+ "kind": "tip_rack",+ "location_mm": {+ "x": 10.0,+ "y": 120.0,+ "z": 0.0+ },+ "size_mm": {+ "x": 127.76,+ "y": 85.48,+ "z": 60.0+ },+ "grid": {+ "rows": 8,+ "columns": 12,+ "tip_capacity_uL": 300.0+ },+ "tip_type": "generic_300uL",+ "tips_available": [+ "A1",+ "B1",+ "C1"+ ]+ },+ {+ "name": "waste",+ "kind": "waste",+ "location_mm": {+ "x": 320.0,+ "y": 120.0,+ "z": 0.0+ },+ "size_mm": {+ "x": 100.0,+ "y": 100.0,+ "z": 100.0+ }+ }+ ],+ "constraints": {+ "allowed_liquid_classes": [+ "water_validated"+ ],+ "allowed_tip_types": [+ "generic_300uL"+ ],+ "channels": 8,+ "requires_human_confirmation": true,+ "max_transfer_uL": 250.0,+ "max_rate_uL_s": 500.0+ }+}diff --git a/skills/pylabrobot/tests/fixtures/transfers.csv b/skills/pylabrobot/tests/fixtures/transfers.csvnew file mode 100644index 00000000..d93f1e48--- /dev/null+++ b/skills/pylabrobot/tests/fixtures/transfers.csv@@ -0,0 +1,3 @@+transfer_id,source,destination,volume_uL,tip_policy,tip_type,liquid_class,aspiration_height_mm,dispense_height_mm,aspiration_rate_uL_s,dispense_rate_uL_s,channel+transfer_1,source_plate:A1,destination_plate:A1,50,new,generic_300uL,water_validated,1.0,2.0,50,75,0+transfer_2,source_plate:B1,destination_plate:B1,25,new,generic_300uL,water_validated,1.0,2.0,40,60,1diff --git a/skills/pylabrobot/tests/test_clis.py b/skills/pylabrobot/tests/test_clis.pynew file mode 100644index 00000000..ba591396--- /dev/null+++ b/skills/pylabrobot/tests/test_clis.py@@ -0,0 +1,161 @@+"""Deterministic tests for the PyLabRobot offline planning CLIs."""++from __future__ import annotations++import io+import json+import os+import sys+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path++SKILL_ROOT = Path(__file__).resolve().parents[1]+if str(SKILL_ROOT) not in sys.path:+ sys.path.insert(0, str(SKILL_ROOT))++from scripts import ( # noqa: E402+ check_deck_geometry,+ generate_simulation_plan,+ inspect_backends,+ plan_transfers,+ validate_manifest,+)+++class CliTests(unittest.TestCase):+ def setUp(self) -> None:+ self.previous_cwd = Path.cwd()+ os.chdir(SKILL_ROOT)++ def tearDown(self) -> None:+ os.chdir(self.previous_cwd)++ @staticmethod+ def run_main(function, arguments: list[str]) -> tuple[int, str, str]:+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ code = function(arguments)+ return code, stdout.getvalue(), stderr.getvalue()++ def test_all_help_paths_are_dependency_free(self) -> None:+ modules = (+ validate_manifest,+ check_deck_geometry,+ plan_transfers,+ generate_simulation_plan,+ inspect_backends,+ )+ for module in modules:+ output = io.StringIO()+ with self.subTest(module=module.__name__), redirect_stdout(output):+ with self.assertRaises(SystemExit) as raised:+ module.main(["--help"])+ self.assertEqual(raised.exception.code, 0)+ self.assertIn("usage:", output.getvalue())++ def test_manifest_and_geometry_pass(self) -> None:+ code, stdout, stderr = self.run_main(+ validate_manifest.main,+ ["--input", "tests/fixtures/protocol_manifest.json"],+ )+ self.assertEqual((code, stderr), (0, ""))+ self.assertTrue(json.loads(stdout)["ok"])++ code, stdout, stderr = self.run_main(+ check_deck_geometry.main,+ ["--input", "tests/fixtures/protocol_manifest.json"],+ )+ self.assertEqual((code, stderr), (0, ""))+ self.assertTrue(json.loads(stdout)["ok"])++ def test_collision_fixture_is_rejected(self) -> None:+ code, stdout, stderr = self.run_main(+ check_deck_geometry.main,+ ["--input", "tests/fixtures/collision_manifest.json"],+ )+ self.assertEqual(stderr, "")+ self.assertEqual(code, 3)+ report = json.loads(stdout)+ self.assertFalse(report["ok"])+ self.assertEqual(+ report["collisions"],+ [{"resource_a": "source_plate", "resource_b": "destination_plate"}],+ )++ def test_transfer_ledger_and_tip_plan(self) -> None:+ code, stdout, stderr = self.run_main(+ plan_transfers.main,+ [+ "--manifest",+ "tests/fixtures/protocol_manifest.json",+ "--transfers",+ "tests/fixtures/transfers.csv",+ ],+ )+ self.assertEqual((code, stderr), (0, ""))+ report = json.loads(stdout)+ self.assertEqual(report["tip_summary"]["used"], 2)+ self.assertEqual(+ [operation["assigned_tip"] for operation in report["operations"]],+ ["tips:A1", "tips:B1"],+ )+ ledger = {+ row["location"]: row["volume_uL"]+ for row in report["final_volume_ledger"]+ }+ self.assertEqual(ledger["source_plate:A1"], 150.0)+ self.assertEqual(ledger["source_plate:B1"], 125.0)+ self.assertEqual(ledger["destination_plate:A1"], 50.0)+ self.assertEqual(ledger["destination_plate:B1"], 25.0)++ def test_generated_plan_cannot_enable_live_hardware(self) -> None:+ code, stdout, stderr = self.run_main(+ generate_simulation_plan.main,+ [+ "--manifest",+ "tests/fixtures/protocol_manifest.json",+ "--transfers",+ "tests/fixtures/transfers.csv",+ ],+ )+ self.assertEqual((code, stderr), (0, ""))+ report = json.loads(stdout)+ self.assertEqual(report["plan_kind"], "offline_review_only")+ self.assertFalse(report["live_backend_permitted"])+ self.assertFalse(report["connection_attempted"])+ self.assertFalse(report["serial_usb_network_access"])+ self.assertEqual(len(report["steps"]), 8)++ def test_duplicate_json_key_is_rejected(self) -> None:+ with tempfile.TemporaryDirectory(dir=SKILL_ROOT / "tests") as directory:+ path = Path(directory) / "duplicate.json"+ path.write_text('{"schema_version":"1.0","schema_version":"1.0"}', encoding="utf-8")+ relative_path = path.relative_to(SKILL_ROOT)+ code, stdout, stderr = self.run_main(+ validate_manifest.main,+ ["--input", str(relative_path)],+ )+ self.assertEqual((code, stdout), (2, ""))+ self.assertIn("duplicate JSON key", json.loads(stderr)["message"])++ def test_parent_directory_traversal_is_rejected(self) -> None:+ code, stdout, stderr = self.run_main(+ validate_manifest.main,+ ["--input", "tests/fixtures/../fixtures/protocol_manifest.json"],+ )+ self.assertEqual((code, stdout), (2, ""))+ self.assertIn("traversal", json.loads(stderr)["message"])++ def test_backend_inspector_never_connects(self) -> None:+ code, stdout, stderr = self.run_main(inspect_backends.main, [])+ self.assertEqual((code, stderr), (0, ""))+ report = json.loads(stdout)+ self.assertFalse(report["connection_attempted"])+ self.assertFalse(report["serial_usb_network_access"])+++if __name__ == "__main__":+ unittest.main()