<!-- Sema documentation — biological-computer
     Sema is a new AI-native, neurosymbolic programming language most models
     have not been trained on. Full corpus: https://sema.cortex.a2olabs.com/llms-full.txt
     Install language support: https://sema.cortex.a2olabs.com/install-skill/ -->

# biological-computer

> The biological-computer worked example.

> The biological-computer worked example.

Run it from `sema/`:

```bash
sema check examples/biological-computer
SEMA_STRICT=1 sema run examples/biological-computer
sema assure examples/biological-computer --grade silver
```

## Source

### `src/main.sema`

```sema
"""Sema-owned biological workflow with evidence-gated foreign kernels and non-authoritative projections."""
from std.crypto import file_sha256

from biological_computer.openmm import openmm_adapter, openmm_backend
from biological_computer.coarse import coarse_backend
from biological_computer.ensemble import ensemble_backend
from biological_computer.reference import molecular_reference
from biological_computer.rare_event import rare_event_backend
from biological_computer.mace import mace_backend
from biological_computer.mace_off import mace_off_backend
from biological_computer.insulin import insulin_backend
from biological_computer.insulin_structure import insulin_structure_backend
from biological_computer.insulin_pmf import insulin_pmf_backend
from biological_computer.qmmm import qmmm_backend
from biological_computer.qmmm_multicode import run_profile as run_qmmm_multicode
from biological_computer.mesoscopic import mesoscopic_backend
from biological_computer.readdy_calibration import readdy_calibration_backend
from biological_computer.physicell import physicell_backend
from biological_computer.dynamics import ControlIntent, Phase8AdmissionEvidence, admit_association_model, preview_unadmitted_multiscale_dynamics
from biological_computer.live import serve_live
from biological_computer.volume import run_volume_profile
from biological_computer.portable import portable_backend
from biological_computer.rerun import rerun_projection
from biological_computer.viewer import prepare_viewer
from biological_computer.phase10 import Phase10QualificationResult, qualify_phase10

assure silver


args BiologicalComputerCli:
    live: bool = flag("--live")
    prepare_viewer_only: bool = flag("--prepare-viewer")
    qualify_phase10_only: bool = flag("--qualify-phase10")
    port: int = option("--port", default=8790)



def phase10_summary(result: Phase10QualificationResult):
    return (
        "phase=10 state=confined_local_preview_untrusted profile=" + result.profile_id
        + " scales=" + str(result.scale_count)
        + " minimum_fps=" + str(result.minimum_average_fps)
        + " input_hz=" + str(result.interaction_hz)
        + " canonical_update_hz=" + str(result.canonical_update_hz)
        + " pick_p95_ms=" + str(result.pick_p95_ms)
        + " gpu_allocated_bytes=" + str(result.gpu_allocated_bytes)
        + " scene_sha256=" + result.scene_sha256
        + " bundle_sha256=" + result.bundle_sha256
        + " external_reference_sha256=" + result.external_reference_sha256
        + " pixel_equality_observed=" + str(result.pixel_equality_observed)
        + " capture_provenance=" + result.capture_provenance_status
        + " admission=false"
        + " visual_regression_replay=" + str(result.visual_regression_replay_pass)
        + " scientific_admission=" + str(result.scientific_validated)
    )


def main() !{ffi.call, fs.read, fs.write, net.listen}:
    if BiologicalComputerCli.qualify_phase10_only:
        print(phase10_summary(qualify_phase10()))
        return
    if BiologicalComputerCli.prepare_viewer_only:
        viewer_scene = prepare_viewer()
        print("viewer_scene=" + viewer_scene.path + " sha256=" + viewer_scene.file_sha256)
        return
    if BiologicalComputerCli.live:
        serve_live(BiologicalComputerCli.port)
        return
    ensure file_sha256("src/live.sema") == "2a447254090468057239653441109e02940e94e084f73b494a003c452e2f25e0"
    ensure file_sha256("viewer/public/data/scene.json") == "644bf09172c4d4ea4c221287af2f7f74350bd5ec29efd918dcbaa185fa345c1f"
    probe = openmm_adapter.backend_probe()
    if probe.available:
        result = openmm_backend.run_openmm_cpu()
        coarse_result = coarse_backend.analyze_coarse_state(
            "coarse.toml",
            result.frames_path,
            "runs/cpu/" + result.benchmark_id + "-coarse.json",
            result.frames_sha256,
        )
        ensure coarse_result.source_frames_sha256 == result.frames_sha256
        ensure coarse_result.source_model_sha256 == result.system_sha256
        ensure coarse_result.source_parameter_sha256 == result.config_sha256
        ensemble_result = ensemble_backend.run_ensemble(
            "ensemble.toml",
            "coarse.toml",
            "runs/ensemble/" + result.benchmark_id + "-ensemble.json",
        )
        ensure ensemble_result.benchmark_config_sha256 == result.config_sha256
        ensure ensemble_result.coarse_config_sha256 == coarse_result.config_sha256
        ensure ensemble_result.source_model_sha256 == result.system_sha256
        reference_result = molecular_reference.run_reference(
            "reference.toml",
            "runs/reference/ala2-mdshare.json",
        )
        ensure reference_result.target_config_sha256 == result.config_sha256
        ensure reference_result.reproduced
        ensure reference_result.ensemble_converged
        ensure reference_result.condition_matched == false
        ensure reference_result.evidence_class == "published_related_reference"
        rare_event_result = rare_event_backend.run_metadynamics(
            "rare_event.toml",
            "runs/rare-event/symmetric-double-well.json",
        )
        ensure rare_event_result.converged
        mace_result = mace_backend.run_profile(
            "mace.toml",
            "runs/mace/direct.json",
            "runs/mace/mace_mp_0a_small_si_v1.json",
        )
        ensure mace_result.direct_parity_pass
        ensure mace_result.technical_pass
        ensure mace_result.uncertainty_available == false
        ensure mace_result.molecular_validated == false
        mace_off_result = mace_off_backend.run_profile(
            "mace_off.toml",
            "runs/mace-off/direct.json",
            "runs/mace-off/mace_off23_spice_holdout.json",
        )
        ensure mace_off_result.direct_parity_pass
        ensure mace_off_result.accuracy_pass
        ensure mace_off_result.uncertainty_pass
        ensure mace_off_result.ood_pass
        ensure mace_off_result.ablation_pass
        ensure mace_off_result.molecular_validated
        insulin_result = insulin_backend.run_profile(
            "insulin.toml",
            "runs/insulin/direct.json",
            "runs/insulin/human_itc.json",
        )
        ensure insulin_result.direct_parity_pass
        ensure insulin_result.condition_pass
        ensure insulin_result.thermodynamic_pass
        ensure insulin_result.validated
        insulin_structure_result = insulin_structure_backend.run_profile(
            "insulin_structure.toml",
            "runs/insulin/structure-direct.json",
            "runs/insulin/structure-sema.json",
        )
        ensure insulin_structure_result.direct_parity_pass
        ensure insulin_structure_result.structural_pass
        ensure insulin_structure_result.technical_pass
        ensure insulin_structure_result.association_validated == false
        insulin_pmf_result = insulin_pmf_backend.run_profile(
            "insulin_pmf.toml",
            "runs/insulin-pmf/direct.json",
            "runs/insulin-pmf/sema.json",
        )
        ensure insulin_pmf_result.direct_parity_pass
        ensure insulin_pmf_result.technical_pass
        ensure insulin_pmf_result.standard_state_delta_g_available == false
        ensure len(insulin_pmf_result.standard_state_delta_g_kj_mol) == 0
        ensure insulin_pmf_result.scientific_validated == false
        ensure insulin_pmf_result.failure_type == "InsulinPmfNonConverged"
        qmmm_result = qmmm_backend.run_profile(
            "qmmm.toml",
            "runs/qmmm/direct.json",
            "runs/qmmm/fixed_partition.json",
        )
        ensure qmmm_result.direct_parity_pass
        ensure qmmm_result.technical_pass
        ensure qmmm_result.multicode_validated == false
        qmmm_multicode_result = run_qmmm_multicode(
            "qmmm_multicode.toml",
            "runs/qmmm/phase7-direct.json",
            "runs/qmmm/phase7-sema.json",
        )
        ensure qmmm_multicode_result.direct_parity_pass
        ensure qmmm_multicode_result.primary_converged
        ensure qmmm_multicode_result.primary_technical_pass
        ensure qmmm_multicode_result.insulin_partition_validated
        ensure qmmm_multicode_result.secondary_status == "unavailable"
        ensure qmmm_multicode_result.secondary_executed == false
        ensure qmmm_multicode_result.multicode_energy_parity_pass == false
        ensure qmmm_multicode_result.multicode_force_parity_pass == false
        ensure qmmm_multicode_result.multicode_charge_parity_pass == false
        ensure qmmm_multicode_result.multicode_reaction_coordinate_parity_pass == false
        ensure qmmm_multicode_result.multicode_technical_pass == false
        ensure qmmm_multicode_result.multicode_residuals_available == false
        ensure qmmm_multicode_result.maximum_energy_residual_hartree == -1.0
        ensure qmmm_multicode_result.maximum_force_residual_hartree_per_angstrom == -1.0
        ensure qmmm_multicode_result.maximum_atomic_charge_residual_e == -1.0
        ensure qmmm_multicode_result.phase7_validated == false
        ensure qmmm_multicode_result.scientific_validated == false
        mesoscopic_result = mesoscopic_backend.run_profile(
            "mesoscopic.toml",
            "runs/mesoscopic/phase8-direct.json",
            "runs/mesoscopic/phase8-sema.json",
        )
        ensure mesoscopic_result.direct_parity_pass
        ensure mesoscopic_result.transfer_pass
        ensure mesoscopic_result.readdy_executed
        ensure mesoscopic_result.readdy_status == "failed"
        ensure mesoscopic_result.readdy_spatial_evidence
        ensure mesoscopic_result.readdy_target_rate_evidence == false
        ensure mesoscopic_result.readdy_concentration_evidence == false
        ensure mesoscopic_result.readdy_uncertainty_evidence
        ensure mesoscopic_result.readdy_validated == false
        ensure mesoscopic_result.physicell_status == "unavailable"
        ensure mesoscopic_result.physicell_executed == false
        ensure mesoscopic_result.physicell_validated == false
        ensure mesoscopic_result.phase8_technical_pass == false
        ensure mesoscopic_result.scientific_validated == false
        readdy_calibration_result = readdy_calibration_backend.run_profile(
            "readdy_calibration.toml",
            "runs/readdy-calibration/direct.json",
            "runs/readdy-calibration/sema.json",
        )
        readdy_direct_file_sha256 = file_sha256("runs/readdy-calibration/direct.json")
        readdy_sema_file_sha256 = file_sha256("runs/readdy-calibration/sema.json")
        ensure readdy_direct_file_sha256 == readdy_sema_file_sha256
        ensure readdy_calibration_result.config_sha256 == file_sha256("readdy_calibration.toml")
        ensure readdy_calibration_result.profile_id == "insulin_dimer_readdy_2_0_14_preregistered_v1"
        ensure readdy_calibration_result.calibration_lock["heldout_inspected_before_lock"] == false
        ensure readdy_calibration_result.heldout_design["disjoint_from_training"] == true
        ensure readdy_calibration_result.heldout_design["parameters_locked_before_execution"] == false
        ensure readdy_calibration_result.heldout_evidence_admission["chronology_proven"] == false
        ensure readdy_calibration_result.heldout_evidence_admission["metrics_classification"] == "exploratory_unadmitted"
        ensure readdy_calibration_result.calibration_evidence_status == "chronology_unproven"
        ensure readdy_calibration_result.gates["rate_pass"]
        ensure readdy_calibration_result.gates["kd_pass"]
        ensure readdy_calibration_result.gates["uncertainty_ci_pass"]
        ensure readdy_calibration_result.gates["concentration_pass"]
        ensure readdy_calibration_result.gates["event_count_pass"]
        ensure readdy_calibration_result.gates["spatial_pass"] == false
        ensure readdy_calibration_result.gates["convergence_pass"] == false
        ensure readdy_calibration_result.statistics["maximum_spatial_axis_ks"] > 0.15
        ensure readdy_calibration_result.statistics["total_effective_samples"] < 100.0
        ensure readdy_calibration_result.qualification_pass == false
        ensure readdy_calibration_result.failure_type == "ReaddyCalibrationChronologyUnproven"
        ensure len(readdy_calibration_result.blockers) == 3
        ensure readdy_calibration_result.blockers[0] == "heldout_chronology_unproven"
        ensure readdy_calibration_result.blockers[1] == "convergence_pass"
        ensure readdy_calibration_result.blockers[2] == "spatial_pass"
        ensure readdy_calibration_result.phase8_scientific_validation == false
        ensure readdy_calibration_result.scientific_validated == false
        physicell_result = physicell_backend.run_profile(
            "physicell.toml",
            "sema",
            "runs/physicell/direct.json",
            "runs/physicell/sema.json",
        )
        ensure physicell_result.release_version == "1.14.2"
        ensure physicell_result.config_sha256 == file_sha256("physicell.toml")
        ensure physicell_result.phase8_result_sha256 == mesoscopic_result.result_sha256
        ensure physicell_result.phase8_artifact_sha256 == file_sha256("runs/mesoscopic/phase8-sema.json")
        ensure physicell_result.profile_id == "physicell_1_14_2_arm64_phase8_field_coupling_v1"
        ensure physicell_result.release_asset_bytes == 2371922
        ensure physicell_result.binary_bytes == 7656072
        ensure physicell_result.host_architecture == "arm64"
        ensure len(physicell_result.arm64_dependencies) == 1
        ensure physicell_result.arm64_dependencies[0] == "/usr/lib/libSystem.B.dylib"
        ensure physicell_result.fetch_manifest_schema == "sema.physicell-fetch/v1"
        ensure physicell_result.fetch_manifest_sha256 == file_sha256(physicell_result.fetch_manifest_path)
        ensure physicell_result.fetch_manifest_path == ".physicell-cache/manifest.json"
        ensure physicell_result.fetch_remote_verified
        ensure physicell_result.tag_commit == "dbd3499250141b27600e91e501c54c46f68f2763"
        ensure physicell_result.tag_ref_sha == physicell_result.tag_commit
        ensure physicell_result.tag_commit_verified
        ensure physicell_result.fetch_manifest_pass
        ensure physicell_result.executable_pass
        ensure physicell_result.platform_pass
        ensure physicell_result.config_xml_field_coupling_pass
        ensure physicell_result.field_output_pass
        ensure physicell_result.concentration_transfer_pass
        ensure physicell_result.spatial_transfer_pass
        ensure physicell_result.mass_transfer_pass
        ensure physicell_result.uncertainty_bound_transfer_pass
        ensure physicell_result.cell_secretion_uptake_coupling_pass
        ensure physicell_result.failure_contract_pass
        ensure physicell_result.missing_failure_typed
        ensure physicell_result.corrupt_failure_typed
        ensure physicell_result.wrong_arch_failure_typed
        ensure physicell_result.timeout_failure_typed
        ensure physicell_result.oversized_output_failure_typed
        ensure physicell_result.manifest_missing_failure_typed
        ensure physicell_result.manifest_unverified_failure_typed
        ensure physicell_result.manifest_tampered_failure_typed
        ensure physicell_result.corrupt_asset_failure_typed
        ensure physicell_result.corrupt_binary_failure_typed
        ensure physicell_result.timeout_descendants_reaped
        ensure physicell_result.oversized_output_descendants_reaped
        ensure physicell_result.technical_qualified
        ensure physicell_result.direct_parity_pass
        ensure physicell_result.direct_residual == 0.0
        ensure physicell_result.direct_artifact_sha256 == file_sha256("runs/physicell/direct.json")
        ensure physicell_result.result_sha256 == physicell_result.direct_result_sha256
        ensure physicell_result.target_rate_evidence == false
        ensure physicell_result.insulin_reaction_supported == false
        ensure physicell_result.scientific_uncertainty_evidence == false
        ensure physicell_result.scientific_validated == false
        phase8_admission_evidence = Phase8AdmissionEvidence(
            phase8_technical_pass=mesoscopic_result.phase8_technical_pass,
            readdy_chronology_proven=readdy_calibration_result.heldout_evidence_admission["chronology_proven"],
            readdy_qualification_pass=readdy_calibration_result.qualification_pass,
            readdy_convergence_pass=readdy_calibration_result.gates["convergence_pass"],
            readdy_spatial_pass=readdy_calibration_result.gates["spatial_pass"],
            readdy_admission_pass=readdy_calibration_result.phase8_scientific_validation,
            physicell_custom_insulin_pass=physicell_result.insulin_reaction_supported,
            physicell_target_rate_pass=physicell_result.target_rate_evidence,
            physicell_uncertainty_pass=physicell_result.scientific_uncertainty_evidence,
            physicell_scientific_pass=physicell_result.scientific_validated,
        )
        dynamics_adaptation = admit_association_model(
            mesoscopic_result.profile_id,
            mesoscopic_result.association_rate_per_micromolar_s,
            mesoscopic_result.dissociation_rate_per_s,
            mesoscopic_result.source_kd_sem_micromolar / mesoscopic_result.source_kd_micromolar,
            mesoscopic_result.kd_relative_residual,
            mesoscopic_result.result_sha256,
            mesoscopic_result.simulated_time_s,
            phase8_admission_evidence,
        )
        ensure dynamics_adaptation.admission_status == "exploratory_unadmitted"
        ensure dynamics_adaptation.candidate_model_id == mesoscopic_result.profile_id
        ensure dynamics_adaptation.selected_model_id == dynamics_adaptation.active_model_id
        ensure dynamics_adaptation.activated == false
        ensure dynamics_adaptation.admitted == false
        ensure dynamics_adaptation.exploratory
        ensure dynamics_adaptation.evidence_reliability == 0.0
        ensure dynamics_adaptation.parameter_apply_authorized == false
        dynamics_result = preview_unadmitted_multiscale_dynamics(
            mesoscopic_result.profile_id,
            mesoscopic_result.observed_monomer_micromolar,
            mesoscopic_result.observed_dimer_micromolar,
            mesoscopic_result.association_rate_per_micromolar_s,
            mesoscopic_result.dissociation_rate_per_s,
            ControlIntent(
                id="inspect-bounded-tissue-response-preview-v1",
                natural_language="Inspect a bounded tissue-response preview without applying unadmitted Phase8 parameters",
                target_tissue_response=0.08,
                maximum_cellular_gain=1.0,
                effort_penalty=0.0001,
                horizon_s=mesoscopic_result.simulated_time_s,
                evidence_ids=[mesoscopic_result.result_sha256, mesoscopic_result.direct_oracle_result_sha256],
            ),
            dynamics_adaptation,
        )
        ensure dynamics_result.admission_status == "exploratory_unadmitted"
        ensure dynamics_result.admitted == false
        ensure dynamics_result.exploratory
        ensure dynamics_result.parameter_apply_authorized == false
        ensure dynamics_result.technical_pass == false
        ensure dynamics_result.scientific_validated == false
        volume_result = run_volume_profile(
            "volume.toml",
            "runs/volumes/cellular-tissue.json",
        )
        ensure volume_result.source_result_sha256 == mesoscopic_result.result_sha256
        ensure volume_result.deterministic_pass
        ensure volume_result.source_binding_pass
        ensure volume_result.phase10_technical_pass
        ensure volume_result.scientific_validated == false
        portable_result = portable_backend.run_profile(
            "portable.toml",
            "runs/portable/direct-phase9.json",
            "runs/portable/sema-phase9.json",
        )
        ensure portable_result.source_result_sha256 == mesoscopic_result.result_sha256
        ensure portable_result.source_artifact_sha256 == file_sha256("runs/mesoscopic/phase8-sema.json")
        ensure portable_result.direct_oracle_artifact_sha256 == file_sha256("runs/portable/direct-phase9.json")
        ensure portable_result.direct_oracle_path == "runs/portable/direct-phase9.json"
        ensure portable_result.direct_parity_pass
        ensure portable_result.bulk_abi_pass
        ensure portable_result.scientific_parity_pass
        ensure portable_result.single_node_portability_pass
        ensure portable_result.worker_loss_failure_validated
        ensure portable_result.same_node_distributed_process_pass
        ensure portable_result.distributed_validated == false
        ensure portable_result.checkpoint_pass
        ensure portable_result.device_loss_failure_validated
        ensure portable_result.device_loss_injection_observed
        ensure portable_result.device_loss_recovery_pass
        ensure portable_result.local_technical_pass
        ensure portable_result.portable_core_validated == false
        ensure portable_result.phase9_admitted == false
        ensure portable_result.phase9_validated == false
        ensure portable_result.cross_node_distributed_validated == false
        ensure portable_result.physical_device_loss_validated == false
        ensure portable_result.sema_bridge_zero_copy_validated == false
        ensure portable_result.evidence_class == "local_technical_evidence"
        ensure portable_result.scientific_validated == false
        ensure portable_result.source_result_sha256 == "3164645981cd04fae5811856b166156769b39b35a85bf441748a468a24fa19f7"
        recording = rerun_projection.record_run(
            result.frames_path,
            coarse_result.result_path,
            ensemble_result.result_path,
            rare_event_result.result_path,
            mace_result.result_path,
            ".sema/cache/inputs/" + result.input_sha256 + ".pdb",
            "runs/cpu/" + result.benchmark_id + ".rrd",
            result.result_sha256,
        )
        ensure recording.source_frames_sha256 == result.frames_sha256
        ensure recording.source_result_sha256 == result.result_sha256
        ensure recording.coarse_result_sha256 == coarse_result.result_sha256
        ensure recording.ensemble_result_sha256 == ensemble_result.result_sha256
        ensure recording.ensemble_sampling_converged == ensemble_result.converged
        ensure recording.rare_event_result_sha256 == rare_event_result.result_sha256
        ensure recording.rare_event_technical_converged == rare_event_result.converged
        ensure recording.mace_result_sha256 == mace_result.result_sha256
        ensure recording.mace_technical_pass == mace_result.technical_pass
        ensure recording.mace_uncertainty_available == mace_result.uncertainty_available
        ensure recording.mace_molecular_validated == mace_result.molecular_validated
        ensure recording.model_sha256 == result.system_sha256
        ensure recording.parameter_sha256 == result.config_sha256
        viewer_scene = prepare_viewer()
        ensure viewer_scene.source_result_sha256 == result.result_sha256
        ensure viewer_scene.source_frames_sha256 == result.frames_sha256
        phase10_result = qualify_phase10()
        ensure phase10_result.scene_sha256 == viewer_scene.file_sha256
        ensure phase10_result.evidence_sha256 == "82b00f0bf08250a6e40e7d1b437ee4e4a8527607b61765782ff1668323989110"
        ensure phase10_result.scene_sha256 == "644bf09172c4d4ea4c221287af2f7f74350bd5ec29efd918dcbaa185fa345c1f"
        ensure phase10_result.bundle_sha256 == "7336af8d81101b20705005f9eff8cb957552f57945542527d781c76b2e243b92"
        ensure phase10_result.scientific_result_sha256 == result.result_sha256
        ensure phase10_result.pixel_equality_observed
        ensure phase10_result.capture_provenance_status == "technical_untrusted"
        ensure phase10_result.visual_regression_replay_pass == false
        ensure phase10_result.scientific_validated == false
        print("backend=" + probe.engine + " version=" + probe.version)
        print("benchmark=" + result.benchmark_id + " platform=" + result.platform)
        print("frames=" + str(result.frames) + " result_sha256=" + result.result_sha256)
        print("recording_sha256=" + recording.sha256)
        print("viewer_scene=" + viewer_scene.path + " sha256=" + viewer_scene.file_sha256)
        print("equation_terms=" + str(recording.equation_terms))
        print(
            "coarse_samples=" + str(coarse_result.samples)
            + " transitions=" + str(coarse_result.transitions)
            + " effective_samples=" + str(coarse_result.effective_samples)
            + " converged=" + str(coarse_result.sampling_converged)
        )
        print(
            "exploratory_ensemble_replicas=" + str(ensemble_result.replicas)
            + " transitions=" + str(ensemble_result.transitions)
            + " effective_samples=" + str(ensemble_result.effective_samples)
            + " rhat=" + str(ensemble_result.rhat_max)
            + " converged=" + str(ensemble_result.converged)
        )
        print(
            "reference=" + reference_result.reference_id
            + " replicas=" + str(reference_result.replicas)
            + " slow_ps=" + str(reference_result.slow_timescale_ps)
            + " fast_ps=" + str(reference_result.fast_timescale_ps)
            + " effective_samples=" + str(reference_result.effective_samples)
            + " reproduced=" + str(reference_result.reproduced)
            + " ensemble_transitions=" + str(reference_result.ensemble_transitions)
            + " ensemble_rhat=" + str(reference_result.ensemble_rhat)
            + " ensemble_converged=" + str(reference_result.ensemble_converged)
            + " condition_matched=" + str(reference_result.condition_matched)
        )
        print(
            "rare_event=" + rare_event_result.benchmark_id
            + " replicas=" + str(rare_event_result.replicas)
            + " min_transitions=" + str(rare_event_result.min_transitions)
            + " left_population=" + str(rare_event_result.left_population_mean)
            + " delta_f_kj_mol="
            + str(rare_event_result.free_energy_difference_mean_kj_mol)
            + " converged=" + str(rare_event_result.converged)
        )
        print(
            "mace_profile=" + mace_result.profile_id
            + " checkpoint_sha256=" + mace_result.checkpoint_sha256
            + " direct_parity=" + str(mace_result.direct_parity_pass)
            + " technical_pass=" + str(mace_result.technical_pass)
            + " molecular_admission=" + str(mace_result.molecular_validated)
        )
        print(
            "mace_off_profile=" + mace_off_result.profile_id
            + " energy_rmse_mev_atom="
            + str(mace_off_result.heldout_energy_rmse_mev_per_atom)
            + " force_rmse_mev_a="
            + str(mace_off_result.heldout_force_rmse_mev_per_angstrom)
            + " coverage=" + str(mace_off_result.conformal_coverage)
            + " ood_blocked=" + str(mace_off_result.ood_blocked)
            + " holdout_evidence_pass=" + str(mace_off_result.molecular_validated)
        )
        print(
            "phase=5 state=technical_evidence_unadmitted reference_ensemble_converged="
            + str(reference_result.ensemble_converged)
            + " exact_condition=" + str(reference_result.condition_matched)
            + " reference_profile=" + reference_result.reference_id
            + " learned_profile=" + mace_off_result.profile_id
        )
        print(
            "phase=6 state=technical_evidence_unadmitted reference_model_evidence=published_related thermodynamic_profile="
            + insulin_result.profile_id
            + " atomistic_profile=" + insulin_structure_result.profile_id
            + " atoms=" + str(insulin_structure_result.atoms)
            + " binding_free_energy_kj_mol="
            + str(insulin_result.modeled_binding_free_energy_kj_mol)
            + " experiments=" + str(insulin_result.independent_experiments)
            + " association_admission=" + str(insulin_structure_result.association_validated)
        )
        print(
            "insulin_pmf_profile=" + insulin_pmf_result.profile_id
            + " evidence_sha256=" + insulin_pmf_result.evidence_sha256
            + " failure_type=" + insulin_pmf_result.failure_type
            + " technical_pass=" + str(insulin_pmf_result.technical_pass)
            + " standard_state_delta_g_available=" + str(insulin_pmf_result.standard_state_delta_g_available)
            + " scientific_admission=" + str(insulin_pmf_result.scientific_validated)
        )
        print(
            "phase=7 state=technical_evidence_unadmitted zundel_technical="
            + str(qmmm_result.technical_pass)
            + " insulin_partition_evidence=" + str(qmmm_multicode_result.insulin_partition_validated)
            + " primary_backend=" + qmmm_multicode_result.primary_backend
            + " primary_technical=" + str(qmmm_multicode_result.primary_technical_pass)
            + " secondary_backend=" + qmmm_multicode_result.secondary_backend
            + " secondary_status=" + qmmm_multicode_result.secondary_status
            + " multicode_technical=" + str(qmmm_multicode_result.multicode_technical_pass)
            + " scientific_admission=" + str(qmmm_multicode_result.scientific_validated)
        )
        print(
            "phase=8 state=exploratory_unadmitted transfer_pass="
            + str(mesoscopic_result.transfer_pass)
            + " readdy_status=" + mesoscopic_result.readdy_status
            + " readdy_spatial_evidence=" + str(mesoscopic_result.readdy_spatial_evidence)
            + " readdy_admission=" + str(mesoscopic_result.readdy_validated)
            + " active_mesoscopic_physicell_status=" + mesoscopic_result.physicell_status
            + " scientific_admission=" + str(mesoscopic_result.scientific_validated)
            + " result_sha256=" + mesoscopic_result.result_sha256
            + " artifact_sha256=" + file_sha256("runs/mesoscopic/phase8-sema.json")
        )
        print(
            "readdy_calibration_profile=" + readdy_calibration_result.profile_id
            + " config_sha256=" + readdy_calibration_result.config_sha256
            + " evidence_sha256=" + readdy_calibration_result.evidence_sha256
            + " direct_sema_byte_sha256=" + readdy_direct_file_sha256
            + " result_sha256=" + readdy_calibration_result.result_sha256
            + " qualification_pass=" + str(readdy_calibration_result.qualification_pass)
            + " calibration_evidence_status=" + readdy_calibration_result.calibration_evidence_status
            + " parameters_locked_before_execution=" + str(readdy_calibration_result.heldout_design["parameters_locked_before_execution"])
            + " metrics_classification=" + readdy_calibration_result.heldout_evidence_admission["metrics_classification"]
            + " blockers=heldout_chronology_unproven,convergence_pass,spatial_pass"
            + " spatial_ks=" + str(readdy_calibration_result.statistics["maximum_spatial_axis_ks"])
            + " ess=" + str(readdy_calibration_result.statistics["total_effective_samples"])
        )
        print(
            "physicell_profile=" + physicell_result.profile_id
            + " source=official_prebuilt"
            + " release_asset_sha256=" + physicell_result.release_asset_sha256
            + " binary_sha256=" + physicell_result.binary_sha256
            + " fetch_manifest_sha256=" + physicell_result.fetch_manifest_sha256
            + " fetch_evidence_sha256=" + physicell_result.fetch_evidence_sha256
            + " fetch_remote_verified=" + str(physicell_result.fetch_remote_verified)
            + " tag_commit=" + physicell_result.tag_commit
            + " tag_commit_verified=" + str(physicell_result.tag_commit_verified)
            + " timeout_descendants_reaped=" + str(physicell_result.timeout_descendants_reaped)
            + " oversized_output_descendants_reaped=" + str(physicell_result.oversized_output_descendants_reaped)
            + " fetch_manifest_pass=" + str(physicell_result.fetch_manifest_pass)
            + " canonical_result_sha256=" + physicell_result.result_sha256
            + " direct_parity=" + str(physicell_result.direct_parity_pass)
            + " technical_evidence_pass=" + str(physicell_result.technical_qualified)
            + " target_rate_evidence=" + str(physicell_result.target_rate_evidence)
            + " insulin_reaction_supported=" + str(physicell_result.insulin_reaction_supported)
            + " manifest_missing_typed=" + str(physicell_result.manifest_missing_failure_typed)
            + " manifest_unverified_typed=" + str(physicell_result.manifest_unverified_failure_typed)
            + " manifest_tampered_typed=" + str(physicell_result.manifest_tampered_failure_typed)
            + " corrupt_asset_typed=" + str(physicell_result.corrupt_asset_failure_typed)
            + " corrupt_binary_typed=" + str(physicell_result.corrupt_binary_failure_typed)
            + " scientific_admission=" + str(physicell_result.scientific_validated)
            + " blocker=custom_insulin_2M_to_D_reaction_and_uncertainty"
        )
        print(
            "dynamics_contract=" + dynamics_result.contract_id
            + " adaptation=" + dynamics_result.adaptation.selected_model_id
            + " admission_status=" + dynamics_result.admission_status
            + " activated=" + str(dynamics_result.adaptation.activated)
            + " admitted=" + str(dynamics_result.admitted)
            + " exploratory=" + str(dynamics_result.exploratory)
            + " evidence_reliability=" + str(dynamics_result.adaptation.evidence_reliability)
            + " parameter_apply_authorized=" + str(dynamics_result.parameter_apply_authorized)
            + " optimizer_scope=" + dynamics_result.optimizer_scope
            + " cellular_gain=" + str(dynamics_result.cellular_gain)
            + " tissue_response=" + str(dynamics_result.final_state[3])
            + " mass_residual=" + str(dynamics_result.molecular_mass_relative_residual)
            + " technical_evidence_pass=" + str(dynamics_result.technical_pass)
            + " scientific_admission=" + str(dynamics_result.scientific_validated)
        )
        print(
            "phase=9 state=local_technical_evidence_unadmitted profile=" + portable_result.profile_id
            + " bulk_abi=" + str(portable_result.bulk_abi_pass)
            + " single_node=" + str(portable_result.single_node_portability_pass)
            + " local_technical_pass=" + str(portable_result.local_technical_pass)
            + " same_node_distributed_process=" + str(portable_result.same_node_distributed_process_pass)
            + " distributed_admission=" + str(portable_result.distributed_validated)
            + " cross_node=" + str(portable_result.cross_node_distributed_validated)
            + " device_loss_injected=" + str(portable_result.device_loss_injection_observed)
            + " physical_device_loss=" + str(portable_result.physical_device_loss_validated)
            + " sema_bridge_zero_copy=" + str(portable_result.sema_bridge_zero_copy_validated)
            + " phase9_admission=" + str(portable_result.phase9_admitted)
            + " external_gate_admission=" + str(portable_result.phase9_validated)
            + " evidence_class=" + portable_result.evidence_class
            + " scientific_admission=" + str(portable_result.scientific_validated)
            + " phase8_result_sha256=" + portable_result.source_result_sha256
            + " phase8_artifact_sha256=" + portable_result.source_artifact_sha256
            + " direct_oracle_path=" + portable_result.direct_oracle_path
            + " result_sha256=" + portable_result.result_sha256
            + " artifact_sha256=" + file_sha256("runs/portable/sema-phase9.json")
        )
        print(phase10_summary(phase10_result))
    else:
        print("phase=2 state=blocked reason=" + probe.detail)
```

### `src/agent.sema`

```sema
"""Proposal-only agent contract for bounded biological programming."""

from std.crypto import sha256_json
from biological_computer.programming import compile_biological_command

assure silver


pub def propose_agent_program(payload: dict[str, any]) -> dict[str, any] !{}:
    required = ["agent_id", "request_id", "objective", "commands", "max_compute_units", "evidence_ids"]
    if not all(payload.has(field) for field in required):
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "agent proposal is missing a required field"}
    if len(payload["agent_id"]) == 0 or len(payload["agent_id"]) > 128:
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "agent_id must contain 1..128 characters"}
    if len(payload["request_id"]) == 0 or len(payload["request_id"]) > 128:
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "request_id must contain 1..128 characters"}
    if len(payload["objective"]) == 0 or len(payload["objective"]) > 512:
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "objective must contain 1..512 characters"}
    commands = payload["commands"]
    if len(commands) == 0 or len(commands) > 4:
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "commands must contain 1..4 bounded programs"}
    if payload["max_compute_units"] <= 0 or payload["max_compute_units"] > 32:
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "max_compute_units must be within 1..32"}
    if len(payload["evidence_ids"]) == 0 or len(payload["evidence_ids"]) > 16:
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "evidence_ids must contain 1..16 digests"}
    if not all(len(evidence_id) == 64 for evidence_id in payload["evidence_ids"]):
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "every evidence id must be a 64-character digest"}
    mut operations: list[dict[str, any]] = []
    for command in commands:
        compiled = compile_biological_command(command)
        if not compiled["ok"]:
            return {"ok": false, "error": compiled["error"], "detail": compiled["detail"]}
        for operation in compiled["operations"]:
            operations.append(operation)
    if len(operations) == 0 or len(operations) > 8 or len(operations) > payload["max_compute_units"]:
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "compiled operations exceed the declared compute or instruction bound"}
    if len(operations) > 1 and any(operation["kind"] == "reset_program" for operation in operations):
        return {"ok": false, "error": "AgentProposalInvalid", "detail": "reset_program must be proposed alone"}
    proposal = {
        "agent_id": payload["agent_id"],
        "request_id": payload["request_id"],
        "objective": payload["objective"],
        "commands": commands,
        "operations": operations,
        "evidence_ids": payload["evidence_ids"],
    }
    return {
        "ok": true,
        "schema": "sema.biological-agent-proposal/v1",
        "backend": "Sema",
        "proposal_id": sha256_json(proposal),
        "status": "proposed",
        "operations": operations,
        "compute_units": len(operations),
        "evidence_ids": payload["evidence_ids"],
        "requires_explicit_commit": true,
        "safety_class": "simulation_only",
        "scientific_validated": false,
    }


pub def agent_capabilities() -> dict[str, any] !{}:
    return {
        "schema": "sema.biological-agent-capabilities/v1",
        "mode": "proposal_only",
        "max_commands": 4,
        "max_operations": 8,
        "max_compute_units": 32,
        "commit_endpoint": "/api/sema/program",
        "proposal_endpoint": "/api/sema/agent/propose",
        "training_contract": "versioned_state_and_evidence_bound",
    }


test "agent proposals are bounded evidence-bound and never self-commit":
    evidence_id = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
    proposal = propose_agent_program({
        "agent_id": "training-agent-01",
        "request_id": "episode-0001",
        "objective": "Adjust bounded simulator signals",
        "commands": ["set glucose to 8", "inhibit cytokine release"],
        "max_compute_units": 4,
        "evidence_ids": [evidence_id],
    })
    ensure proposal["ok"]
    ensure proposal["compute_units"] == 2
    ensure proposal["requires_explicit_commit"]
    ensure proposal["scientific_validated"] == false
    rejected = propose_agent_program({
        "agent_id": "training-agent-01",
        "request_id": "episode-0002",
        "objective": "Attempt an invalid mixed reset",
        "commands": ["reset", "stiffen bonds"],
        "max_compute_units": 4,
        "evidence_ids": [evidence_id],
    })
    ensure not rejected["ok"]
    ensure rejected["error"] == "AgentProposalInvalid"
```

### `src/api.sema`

```sema
"""Canonical HTTP contract emitted with every biological-computer scene."""

assure silver


pub def biological_api_contract() -> dict[str, any] !{}:
    return {
        "schema": "sema.biological-api/v1",
        "backend": "Sema",
        "base_path": "/api/sema",
        "state_ownership": "sema",
        "scientific_validated": false,
        "endpoints": [
            {"method": "GET", "path": "/status", "response_schema": "sema.biological-live-status/v1", "mutates": false, "max_request_bytes": 0},
            {"method": "GET", "path": "/capabilities", "response_schema": "sema.biological-programming-capabilities/v1", "mutates": false, "max_request_bytes": 0},
            {"method": "POST", "path": "/step", "response_schema": "sema.multiscale-dynamics-step/v1", "mutates": true, "max_request_bytes": 4096},
            {"method": "POST", "path": "/intervene", "response_schema": "sema.biological-live-status/v1", "mutates": true, "max_request_bytes": 4096},
            {"method": "POST", "path": "/molecule", "response_schema": "sema.molecular-session/v1", "mutates": true, "max_request_bytes": 4096},
            {"method": "POST", "path": "/molecule/step", "response_schema": "sema.molecular-session/v1", "mutates": true, "max_request_bytes": 4096},
            {"method": "POST", "path": "/program", "response_schema": "sema.biological-program-result/v1", "mutates": true, "max_request_bytes": 8192},
            {"method": "POST", "path": "/design", "response_schema": "sema.molecular-design-result/v1", "mutates": true, "max_request_bytes": 8192},
            {"method": "POST", "path": "/dock", "response_schema": "sema.molecular-binding-result/v1", "mutates": true, "max_request_bytes": 4096},
            {"method": "POST", "path": "/introduce", "response_schema": "sema.biological-live-status/v1", "mutates": true, "max_request_bytes": 4096},
            {"method": "POST", "path": "/agent/propose", "response_schema": "sema.biological-agent-proposal/v1", "mutates": false, "max_request_bytes": 8192},
            {"method": "POST", "path": "/cortex/propose", "response_schema": "sema.biological-llm-proposal/v1", "mutates": false, "max_request_bytes": 8192},
        ],
        "conflict_status": 409,
        "validation_status": 422,
        "not_found_status": 404,
        "over_cap_status": 413,
        "max_request_bytes": 8192,
    }
```

### `src/assurance.sema`

```sema
"""Behavioral assurance gates for the multiscale biological-computer contracts."""

from biological_computer.discovery import CandidateClaim, CandidateEvidence, CandidateHypothesis, CandidateKind, CandidateStatus, DiscoveryBatch, SearchBoundary, admit_candidate, may_report_claim, validate_discovery_batch
from biological_computer.domain import Atom, Bond, EvidenceKind, EvidenceRecord, InteractionTerm, MolecularTopology, PeriodicBox, PhaseEvidence, PhaseState, Vector3, interaction_ownership_valid, phase_validated, topology_valid
from biological_computer.models import ApplicabilityDecision, EquationTermDescriptor, HybridPrediction, LearnedModelManifest, LearnedRole, PredictionStatus, PredictionUncertainty, TermImplementation, assess_hybrid_prediction, prediction_admissible
from biological_computer.profiles import AcceleratorKind, KernelDemand, NativeAccelerationProfile, NativeKernelKind, ParameterizationEdge, PlatformBenchmark, QmMmPartition, benchmark_comparable, parameterization_valid, qmmm_partition_valid, select_native_acceleration
from biological_computer.resolution import ApproximationContract, EdgeKind, ResolutionEdge, TransitionState, commit_transition, prepare_transition, validate_transition
from biological_computer.statistics import BasinPopulations, PmfCorrections, basin_populations, compare_populations, corrected_pmf, diagnose_ensemble
from biological_computer.visualization import ComplexityScenario, EntityFocusPath, EquationStateSample, EquationTermSample, EquationUpdateKind, FieldOfViewBudget, FidelityClass, GeometryOrigin, SemanticScaleSource, SemanticZoomDecision, ViewportQuery, VisualObservationEnvelope, VisualPrimitiveBinding, VisualRepresentation, VisualScale, decide_multiscale_compute, decide_semantic_zoom, focus_path_valid, validate_visual_observation

assure silver


def digest():
    return "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"


def evidence(id: str, accepted: bool):
    return EvidenceRecord(
        id=id,
        kind=EvidenceKind.computational,
        source="bounded assurance fixture",
        summary="condition-matched deterministic evidence",
        artifact_sha256=digest(),
        observed_at_s=1.0,
        accepted=accepted,
    )


def alanine_topology():
    atoms = [
        Atom(id="atom:N", index=0, element="N", residue="ALA", mass_da=14.0, charge_e=-0.3, position_nm=Vector3(x=0.0, y=0.0, z=0.0)),
        Atom(id="atom:CA", index=1, element="C", residue="ALA", mass_da=12.0, charge_e=0.1, position_nm=Vector3(x=0.1, y=0.0, z=0.0)),
        Atom(id="atom:C", index=2, element="C", residue="ALA", mass_da=12.0, charge_e=0.2, position_nm=Vector3(x=0.2, y=0.0, z=0.0)),
    ]
    bonds = [Bond(left_index=0, right_index=1, order=1), Bond(left_index=1, right_index=2, order=1)]
    return MolecularTopology(
        id="ala-fragment",
        atoms=atoms,
        bonds=bonds,
        box=PeriodicBox(x_nm=1.0, y_nm=1.0, z_nm=1.0),
        source_sha256=digest(),
    )


def approximation(valid: bool, maximum_error: f64):
    return ApproximationContract(
        id="ala2-aa-to-phi-psi-v1",
        source_model_id="ala2-aa-v1",
        target_model_id="ala2-phi-psi-v1",
        transform="periodic phi/psi restriction",
        preserved_observables=["phi", "psi", "basin_population"],
        marginalized_degrees=["solvent", "bond_vibration"],
        calibration_domain="aqueous alanine dipeptide at 300 K",
        maximum_error=maximum_error,
        refine_threshold=0.1,
        evidence_ids=["held-out-aa-ensemble"],
        valid=valid,
    )


def coarse_edge(contract: ApproximationContract):
    return ResolutionEdge(
        id="edge:ala2-aa-to-phi-psi-v1",
        kind=EdgeKind.coarsen,
        source_node_id="ala2-aa-v1",
        target_node_id="ala2-phi-psi-v1",
        approximation=contract,
        restriction="extract periodic phi and psi",
        prolongation="sample conditional atomistic microstate ensemble",
        checkpoint_only=true,
    )


def learned_manifest(output_unit: str):
    return LearnedModelManifest(
        id="ala2-hybrid-residual-v1",
        family="periodic residual potential",
        version="1.0.0",
        role=LearnedRole.energy,
        architecture_sha256=digest(),
        weights_sha256=digest(),
        training_data_sha256=digest(),
        validation_data_sha256=digest(),
        license_id="MIT",
        preprocessing="wrapped phi/psi radians",
        input_units=["rad", "rad"],
        output_unit=output_unit,
        chemical_domain="aqueous alanine dipeptide",
        thermodynamic_domain="300 K NVT",
        symmetry_contract="2pi periodic in both coordinates",
        calibration_method="held-out conformal interval",
        uncertainty_method="deep ensemble",
        ood_method="training-support distance",
        backend_profile_id="cpu-f64-v1",
        evidence_ids=["held-out-model-report"],
        validated=true,
    )


def hybrid_term():
    return EquationTermDescriptor(
        id="term:ala2-free-energy",
        owner_model_id="ala2-phi-psi-v1",
        implementation=TermImplementation.hybrid,
        role=LearnedRole.energy,
        input_units=["rad", "rad"],
        output_unit="kJ/mol",
        symbolic_expression="fourier(phi, psi)",
        learned_model_id="ala2-hybrid-residual-v1",
        combination_rule="symbolic_plus_gated_residual",
        authoritative_outputs=["free_energy"],
    )


def calibrated_uncertainty():
    return PredictionUncertainty(
        aleatoric=0.02,
        epistemic=0.03,
        lower=-0.1,
        upper=0.1,
        coverage=0.95,
        calibrated=true,
    )


def assess(
    manifest: LearnedModelManifest,
    applicability: ApplicabilityDecision,
    gate: f64,
    uncertainty: PredictionUncertainty,
):
    return assess_hybrid_prediction(
        hybrid_term(),
        manifest,
        2.0,
        -0.25,
        gate,
        uncertainty,
        applicability,
        0.01,
        0.02,
        0.2,
        0.1,
        ["prediction-observation-1"],
    )


def search_boundary():
    return SearchBoundary(
        id="search:interaction-v1",
        description="bounded interaction proposals for alanine fixtures",
        allowed_kinds=[CandidateKind.interaction],
        max_candidates=4,
        max_rounds=2,
        max_compute_units=100,
        prior_art_sources=["Crossref", "PDB"],
        safety_policy_id="research-only-v1",
    )


def interaction_candidate(compute_units: int):
    return CandidateHypothesis(
        id="candidate:interaction-1",
        parent_ids=[],
        kind=CandidateKind.interaction,
        representation_digest=digest(),
        rationale="rank a bounded model-proposed interaction",
        provenance_ids=["model-run-1"],
        prior_art_scope_id="search:interaction-v1",
        model_id="ala2-hybrid-residual-v1",
        model_version=1,
        equation_graph_id="ala2-phi-psi-v1",
        equation_version=1,
        uncertainty=0.05,
        requested_compute_units=compute_units,
        status=CandidateStatus.proposed,
        rejection_reasons=[],
    )


test "canonical topology and interaction ownership reject inconsistent state":
    topology = alanine_topology()
    ensure topology_valid(topology)
    invalid_topology = MolecularTopology(
        id=topology.id,
        atoms=topology.atoms,
        bonds=[Bond(left_index=0, right_index=4, order=1)],
        box=topology.box,
        source_sha256=topology.source_sha256,
    )
    ensure not topology_valid(invalid_topology)
    term = InteractionTerm(id="bond:0-1", family="bond", owner_model_id="ff-v1", active=true, target_observable="energy", evidence_ids=["ff-source"])
    duplicate = InteractionTerm(id="bond:0-1", family="bond", owner_model_id="other-v1", active=true, target_observable="energy", evidence_ids=["other-source"])
    ensure not interaction_ownership_valid([term, duplicate])


test "phase validation needs positive and negative evidence":
    complete = PhaseEvidence(phase=1, state=PhaseState.validated, profile_id="domain-v1", positive_evidence=["valid-topology"], negative_evidence=["invalid-topology-rejected"], blockers=[])
    incomplete = PhaseEvidence(phase=1, state=PhaseState.validated, profile_id="domain-v1", positive_evidence=["valid-topology"], negative_evidence=[], blockers=[])
    ensure phase_validated(complete)
    ensure not phase_validated(incomplete)


test "resolution transition is prepare validate commit and preserves active state on failure":
    prepared = prepare_transition(0, coarse_edge(approximation(true, 0.05)), 7, 1.0)
    ensure prepared.state == TransitionState.prepared
    ensure prepared.from_state_version == 7
    ensure prepared.to_state_version == 8
    rejected = validate_transition(prepared, [evidence("rejected", false)], 0.2, 0.1)
    ensure rejected.state == TransitionState.blocked
    ensure rejected.to_state_version == rejected.from_state_version
    validated = validate_transition(prepared, [evidence("accepted", true)], 0.05, 0.1)
    committed = commit_transition(validated)
    ensure committed.state == TransitionState.committed
    ensure committed.to_state_version == 8
    blocked = prepare_transition(1, coarse_edge(approximation(false, 0.05)), 8, 2.0)
    ensure blocked.state == TransitionState.blocked
    ensure commit_transition(blocked).to_state_version == 8


test "hybrid prediction is admitted only inside manifest units calibration and domain":
    accepted = assess(learned_manifest("kJ/mol"), ApplicabilityDecision.applicable, 0.5, calibrated_uncertainty())
    ensure prediction_admissible(accepted)
    ensure accepted.combined_value == 1.875
    wrong_units = assess(learned_manifest("eV"), ApplicabilityDecision.applicable, 0.5, calibrated_uncertainty())
    ensure wrong_units.status == PredictionStatus.blocked
    ensure not prediction_admissible(wrong_units)
    ood = assess(learned_manifest("kJ/mol"), ApplicabilityDecision.out_of_domain, 0.5, calibrated_uncertainty())
    ensure ood.status == PredictionStatus.blocked
    invalid_gate = assess(learned_manifest("kJ/mol"), ApplicabilityDecision.applicable, 1.5, calibrated_uncertainty())
    ensure invalid_gate.status == PredictionStatus.blocked
    ensure not prediction_admissible(invalid_gate)


test "uncalibrated learned uncertainty fails closed":
    uncalibrated = PredictionUncertainty(
        aleatoric=0.01,
        epistemic=0.01,
        lower=-0.1,
        upper=0.1,
        coverage=0.95,
        calibrated=false,
    )
    prediction = assess(learned_manifest("kJ/mol"), ApplicabilityDecision.applicable, 0.5, uncalibrated)
    ensure prediction.status == PredictionStatus.blocked


test "ensemble and coarse observables remain statistical":
    fine = basin_populations([-1.0, -2.0, -1.5, -2.8], [-0.5, 2.0, 1.5, -2.8])
    coarse = BasinPopulations(alpha=0.25, beta=0.5, other=0.25, samples=400)
    comparison = compare_populations(fine, coarse, 0.26)
    ensure comparison.passed
    diagnostics = diagnose_ensemble([1.0, 1.2, 0.8, 1.1, 0.9, 1.0], 3, 3.0)
    ensure diagnostics.replicas == 3
    pmf = corrected_pmf(-7.0, PmfCorrections(restraint_kj_mol=0.5, jacobian_kj_mol=0.2, finite_box_kj_mol=0.1, standard_state_kj_mol=1.0), 0.05, 200.0, 4, true)
    ensure pmf.corrected_delta_g_kj_mol == -5.2
    ensure pmf.validated


test "bounded discovery rejects excess compute and keeps predictions provisional":
    boundary = search_boundary()
    candidate = interaction_candidate(40)
    batch = DiscoveryBatch(boundary_id=boundary.id, round_index=1, candidate_ids=[candidate.id], requested_compute_units=40)
    ensure validate_discovery_batch(batch, [candidate], boundary)
    admitted = admit_candidate(candidate, boundary, true, true, true, true, true)
    ensure admitted.status == CandidateStatus.admitted
    excessive = admit_candidate(interaction_candidate(101), boundary, true, true, true, true, true)
    ensure excessive.status == CandidateStatus.rejected
    proposed_evidence = CandidateEvidence(candidate_id=candidate.id, observation_ids=[], oracle_evidence_ids=[], prior_art_evidence_ids=[], objective_names=["affinity"], objective_values=[0.5], uncertainty=0.1, information_gain=0.2, claim=CandidateClaim.predicted_interaction, status=CandidateStatus.ranked)
    ensure not may_report_claim(proposed_evidence)
    ranked_evidence = CandidateEvidence(candidate_id=candidate.id, observation_ids=["prediction-observation-1"], oracle_evidence_ids=[], prior_art_evidence_ids=[], objective_names=["affinity"], objective_values=[0.5], uncertainty=0.1, information_gain=0.2, claim=CandidateClaim.predicted_interaction, status=CandidateStatus.ranked)
    ensure may_report_claim(ranked_evidence)


test "canonical visual geometry is synchronized with its equation state":
    term = EquationTermSample(term_id="bond-energy", symbol="E_bond", value=1.2, unit_symbol="kJ/mol", owner_model_id="ff-v1")
    equation = EquationStateSample(entity_id="atom:CA", model_id="ff-v1", model_version=1, equation_id="bonded-v1", equation_version=1, parameter_version=1, update_kind=EquationUpdateKind.state_step, terms=[term], residuals=[], active_constraints=["bond-length"], transition_id="step:1", cause="backend state step")
    binding = VisualPrimitiveBinding(primitive_id="sphere:CA", entity_id="atom:CA", observation_id="observation:1", source_state_version=1, scale=VisualScale.atomic, fidelity=FidelityClass.canonical, origin=GeometryOrigin.simulated, source_algorithm="OpenMM position", source_parameters=[])
    frame = VisualObservationEnvelope(schema="sema.biological-visual-observation/v1", scenario_id="ala2", run_id="run:1", observation_id="observation:1", physical_time_s=0.001, scheduler_tick=1, state_version=1, resolution_version=1, model_version=1, equation_version=1, parameter_version=1, source_frame_age_ms=10.0, bindings=[binding], equation_states=[equation], dropped_frames=0, interpolation_ratio=0.0)
    ensure validate_visual_observation(frame)
    stale = VisualPrimitiveBinding(primitive_id="sphere:CA", entity_id="atom:CA", observation_id="observation:1", source_state_version=2, scale=VisualScale.atomic, fidelity=FidelityClass.canonical, origin=GeometryOrigin.simulated, source_algorithm="stale position", source_parameters=[])
    stale_frame = VisualObservationEnvelope(schema=frame.schema, scenario_id=frame.scenario_id, run_id=frame.run_id, observation_id=frame.observation_id, physical_time_s=frame.physical_time_s, scheduler_tick=frame.scheduler_tick, state_version=frame.state_version, resolution_version=frame.resolution_version, model_version=frame.model_version, equation_version=frame.equation_version, parameter_version=frame.parameter_version, source_frame_age_ms=frame.source_frame_age_ms, bindings=[stale], equation_states=[equation], dropped_frames=0, interpolation_ratio=0.0)
    ensure not validate_visual_observation(stale_frame)


test "semantic zoom renders only evidence-bound scale sources":
    query = ViewportQuery(query_id="viewport:1", requested_scale=VisualScale.atomic, field_of_view_m=0.0000000005, observation_id="observation:1", state_version=1, resolution_version=1)
    atomic = SemanticScaleSource(source_id="ala2-atoms", scale=VisualScale.atomic, minimum_length_m=0.0000000001, maximum_length_m=0.000000001, available=true, fidelity=FidelityClass.canonical, origin=GeometryOrigin.simulated, observation_id="observation:1", representation_ids=[VisualRepresentation.particles, VisualRepresentation.topology_bonds], source_algorithm="OpenMM recorded positions and topology",)
    decision = decide_semantic_zoom(query, [atomic])
    ensure decision.renderable
    ensure decision.fidelity == FidelityClass.canonical
    ensure decision.source_observation_id == query.observation_id
    unavailable = SemanticScaleSource(source_id="cell-volume", scale=VisualScale.cellular, minimum_length_m=0.000001, maximum_length_m=0.0001, available=false, fidelity=FidelityClass.unknown, origin=GeometryOrigin.unknown, observation_id="", representation_ids=[], source_algorithm="registered scalar or segmented volume required")
    cellular_query = ViewportQuery(query_id="viewport:2", requested_scale=VisualScale.cellular, field_of_view_m=0.00005, observation_id="observation:1", state_version=1, resolution_version=1)
    blocked = decide_semantic_zoom(cellular_query, [atomic, unavailable])
    ensure not blocked.renderable
    ensure blocked.fidelity == FidelityClass.unknown
    outside_atomic_range = ViewportQuery(query_id="viewport:3", requested_scale=VisualScale.atomic, field_of_view_m=0.00000001, observation_id="observation:1", state_version=1, resolution_version=1)
    range_blocked = decide_semantic_zoom(outside_atomic_range, [atomic])
    ensure not range_blocked.renderable


test "field of view bounds multiscale GPU work and preserves focus":
    focus = EntityFocusPath(path_id="focus:1", entity_ids=["TISSUE:PANCREAS", "ISLET:01", "CELL:BETA:0001", "PROTEIN:INSULIN"], selected_depth=2)
    ensure focus_path_valid(focus)
    scenario = ComplexityScenario(id="healthy-fed", glucose_millimolar=8.0, oxygen_fraction=0.96, cytokine_fraction=0.05, insulin_demand_fraction=0.55, illustrative=true)
    ensure scenario.illustrative
    bounded = decide_multiscale_compute(FieldOfViewBudget(field_of_view_m=0.00000005, candidate_instances=30000, required_upload_bytes=65536, desired_update_hz=60, max_visible_instances=16384, max_upload_bytes=262144, max_update_hz=60))
    ensure bounded.scale == VisualScale.molecular
    ensure bounded.admissible
    ensure bounded.visible_instances == 16384
    blocked = decide_multiscale_compute(FieldOfViewBudget(field_of_view_m=0.0005, candidate_instances=2000, required_upload_bytes=300000, desired_update_hz=30, max_visible_instances=16384, max_upload_bytes=262144, max_update_hz=60))
    ensure blocked.scale == VisualScale.tissue
    ensure not blocked.admissible


test "native acceleration selects measured evidence rather than backend labels":
    demand = KernelDemand(operation="surface-projection", precision="f32", tolerance_profile="visual-proxy-v1", minimum_throughput_per_s=30.0, maximum_p95_ms=8.0, maximum_observable_error=0.1, maximum_resident_memory_bytes=100000000)
    cpu = NativeAccelerationProfile(profile_id="fixture-cpu", kernel_id="surface-v1", native_kind=NativeKernelKind.sema_aot, accelerator=AcceleratorKind.cpu, device_name="fixture CPU", precision="f32", tolerance_profile="visual-proxy-v1", available=true, qualified=true, zero_copy=true, unified_memory=true, supported_operations=["surface-projection"], measured_throughput_per_s=60.0, measured_p95_ms=2.5, observable_error=0.01, resident_memory_bytes=1000000, host_device_transfer_bytes=0, artifact_sha256=digest(), model_sha256=digest(), oracle_evidence_ids=["fixture-oracle"], benchmark_evidence_ids=["fixture-benchmark"])
    cuda = NativeAccelerationProfile(profile_id="fixture-cuda", kernel_id="surface-v1", native_kind=NativeKernelKind.cpp_abi, accelerator=AcceleratorKind.cuda, device_name="fixture CUDA", precision="f32", tolerance_profile="visual-proxy-v1", available=true, qualified=true, zero_copy=false, unified_memory=false, supported_operations=["surface-projection"], measured_throughput_per_s=90.0, measured_p95_ms=1.5, observable_error=0.01, resident_memory_bytes=2000000, host_device_transfer_bytes=4000000, artifact_sha256=digest(), model_sha256=digest(), oracle_evidence_ids=["fixture-oracle"], benchmark_evidence_ids=["fixture-benchmark"])
    mlx = NativeAccelerationProfile(profile_id="fixture-mlx", kernel_id="surface-v1", native_kind=NativeKernelKind.cpp_abi, accelerator=AcceleratorKind.mlx, device_name="fixture unified GPU", precision="f32", tolerance_profile="visual-proxy-v1", available=true, qualified=true, zero_copy=true, unified_memory=true, supported_operations=["surface-projection"], measured_throughput_per_s=80.0, measured_p95_ms=0.9, observable_error=0.01, resident_memory_bytes=1500000, host_device_transfer_bytes=0, artifact_sha256=digest(), model_sha256=digest(), oracle_evidence_ids=["fixture-oracle"], benchmark_evidence_ids=["fixture-benchmark"])
    declared_only = NativeAccelerationProfile(profile_id="fixture-unqualified", kernel_id="surface-v1", native_kind=NativeKernelKind.cpp_abi, accelerator=AcceleratorKind.cuda, device_name="fixture unavailable evidence", precision="f32", tolerance_profile="visual-proxy-v1", available=true, qualified=false, zero_copy=true, unified_memory=false, supported_operations=["surface-projection"], measured_throughput_per_s=1000.0, measured_p95_ms=0.1, observable_error=0.0, resident_memory_bytes=1000, host_device_transfer_bytes=0, artifact_sha256=digest(), model_sha256=digest(), oracle_evidence_ids=[], benchmark_evidence_ids=[])
    selected = select_native_acceleration(demand, [cpu, cuda, mlx, declared_only])
    ensure selected.selected
    ensure selected.profile_id == "fixture-mlx"
    ensure selected.zero_copy


test "advanced phase profiles fail closed without complete evidence":
    partition = QmMmPartition(id="qmmm:1", qm_atom_indices=[0], mm_atom_indices=[1, 2], boundary_atom_indices=[1], total_charge_e=0, spin_multiplicity=1, embedding="electrostatic", backend_profile_id="qmmm-backend-v1")
    ensure qmmm_partition_valid(partition, 3)
    invalid_partition = QmMmPartition(id="qmmm:bad", qm_atom_indices=[0, 1], mm_atom_indices=[1, 2], boundary_atom_indices=[1], total_charge_e=0, spin_multiplicity=1, embedding="electrostatic", backend_profile_id="qmmm-backend-v1")
    ensure not qmmm_partition_valid(invalid_partition, 3)
    parameters = ParameterizationEdge(id="edge:qmmm-to-mm", source_model_id="qmmm-v1", target_model_id="ff-v2", parameter_names=["charge"], values=[-0.2], uncertainties=[0.01], units=["e"], evidence_ids=["fit-report"])
    ensure parameterization_valid(parameters)
    reference = PlatformBenchmark(profile_id="cpu-ref", hardware="Apple Silicon", operating_system="Darwin", backend="OpenMM", precision="mixed", model_digest=digest(), tolerance_profile="ala2-v1", simulated_ns_per_day=1.0, p50_step_ms=1.0, p95_step_ms=2.0, resident_memory_bytes=1000, transfer_bytes=0, observable_error=0.01, evidence_ids=["benchmark-ref"])
    candidate = PlatformBenchmark(profile_id="cpu-candidate", hardware="Apple Silicon", operating_system="Darwin", backend="OpenMM", precision="mixed", model_digest=digest(), tolerance_profile="ala2-v1", simulated_ns_per_day=1.1, p50_step_ms=0.9, p95_step_ms=1.8, resident_memory_bytes=1000, transfer_bytes=0, observable_error=0.01, evidence_ids=["benchmark-candidate"])
    ensure benchmark_comparable(reference, candidate)
```

### `src/binding.sema`

```sema
"""Bounded, deterministic ligand/target docking and designed-species physiology coupling.

Every number produced here is an empirical rank, never a measurement. The scoring function and
its calibration constants are published on each result so a reader can see exactly how a score
becomes a free energy, and every payload carries `scientific_validated: false`.
"""

import math
from biological_computer.physiology import initial_physiology_parameters, physiology_parameter_bounds

assure silver


BINDING_SCHEMA = "sema.molecular-binding-result/v1"
SPECIES_SCHEMA = "sema.designed-species-state/v1"
SCORING_FUNCTION = "lj12-6 + dd-dielectric coulomb + gaussian hydrophobic contact"
CALIBRATION_NAME = "linear_score_to_free_energy_v1"
CALIBRATION_SLOPE = 0.35
CALIBRATION_INTERCEPT = -4.0
CALIBRATION_NOTE = "empirical rank-to-energy map: delta_g = 0.35 * score - 4.0 kJ/mol, chosen so bounded fragment scores land in a plausible micromolar window. It is not regressed against measured affinities and must never be read as one."
GAS_CONSTANT_KJ_PER_MOL_K = 0.0083145
BODY_TEMPERATURE_K = 310.15
INTERACTION_CUTOFF_ANGSTROM = 8.0
CLOSE_CONTACT_ANGSTROM = 0.8
CLASH_DISTANCE_ANGSTROM = 2.2
CLASH_STIFFNESS_KJ_PER_MOL_ANGSTROM2 = 400.0
LJ_PAIR_CEILING_KJ_PER_MOL = 200.0
COULOMB_CONSTANT_KJ_ANGSTROM_PER_MOL = 1389.35
DIELECTRIC_SLOPE = 4.0
HYDROPHOBIC_DEPTH_KJ_PER_MOL = 0.35
HYDROPHOBIC_CENTER_ANGSTROM = 4.0
HYDROPHOBIC_WIDTH_ANGSTROM = 1.2
CONTACT_DISTANCE_ANGSTROM = 4.5
BURIAL_DISTANCE_ANGSTROM = 5.0
MAX_CONTACTS = 64
MAX_TARGET_ATOMS = 4096
MAX_LIGAND_ATOMS = 512
MAX_SPECIES = 16
MIN_POSE_BUDGET = 64
DEFAULT_POSE_BUDGET = 512
MAX_POSE_BUDGET = 4096
ANGLE_LADDER_STEPS = 6
TRANSLATION_HALF_EXTENT_ANGSTROM = 2.0
POSE_TRANSLATION_LIMIT_ANGSTROM = 3.6
GRID_CELL_ANGSTROM = 4.0
POCKET_PROBE_LIMIT = 512
POCKET_COARSE_SPACING_ANGSTROM = 3.0
POCKET_FINE_STEPS = 2
POCKET_MIN_CLEARANCE_ANGSTROM = 2.6
POCKET_MAX_CLEARANCE_ANGSTROM = 8.0
POCKET_CLUSTER_FRACTION = 0.9
REFINEMENT_MAX_STEPS = 24
REFINEMENT_TRANSLATION_STEP_ANGSTROM = 0.8
REFINEMENT_ROTATION_STEP_RADIAN = 0.14
REFINEMENT_TOLERANCE_ANGSTROM = 0.1
MIN_CONCENTRATION_MICROMOLAR = 0.000001
MAX_CONCENTRATION_MICROMOLAR = 1000000.0
MIN_KD_MICROMOLAR = 0.000001
MAX_KD_MICROMOLAR = 1000000.0
IMMUNE_SHIELDING_CEILING = 1.0
EXOGENOUS_INSULIN_CEILING = 5000.0


def lj_parameters(atomic_number: int):
    """OPLS-AA style [sigma in Angstrom, epsilon in kJ/mol]; unmapped elements fall back to carbon."""
    if atomic_number == 1:
        return [2.42, 0.0657]
    if atomic_number == 6:
        return [3.40, 0.3598]
    if atomic_number == 7:
        return [3.25, 0.7113]
    if atomic_number == 8:
        return [2.96, 0.8786]
    if atomic_number == 9:
        return [3.12, 0.2552]
    if atomic_number == 11:
        return [2.35, 0.5443]
    if atomic_number == 12:
        return [1.64, 3.6610]
    if atomic_number == 15:
        return [3.74, 0.8368]
    if atomic_number == 16:
        return [3.55, 1.0460]
    if atomic_number == 17:
        return [3.47, 1.1087]
    if atomic_number == 20:
        return [2.41, 2.1502]
    if atomic_number == 26:
        return [2.19, 0.0134]
    if atomic_number == 30:
        return [1.96, 0.0523]
    return [3.40, 0.3598]


def partial_charge(atomic_number: int, degree: int, polar_neighbours: int):
    """Bounded element-plus-bond-context charge in elementary charge units; no QM, no force-field fit."""
    if atomic_number == 1:
        return 0.30 if polar_neighbours > 0 else 0.06
    if atomic_number == 6:
        return min(0.40, 0.14 * polar_neighbours)
    if atomic_number == 7:
        return -0.45
    if atomic_number == 8:
        return -0.50 if degree <= 1 else -0.40
    if atomic_number == 15:
        return 0.60
    if atomic_number == 16:
        return -0.20
    if atomic_number == 9 or atomic_number == 17:
        return -0.20
    if atomic_number == 11:
        return 1.00
    if atomic_number == 12 or atomic_number == 20 or atomic_number == 26 or atomic_number == 30:
        return 2.00
    return 0.0


def partial_charges(atomic_numbers: list[int], bond_pairs: list[int]):
    mut degree = [0 for atomic_number in atomic_numbers]
    mut polar = [0 for atomic_number in atomic_numbers]
    for bond_index in range(len(bond_pairs) // 2):
        left = bond_pairs[bond_index * 2]
        right = bond_pairs[bond_index * 2 + 1]
        degree[left] = degree[left] + 1
        degree[right] = degree[right] + 1
        if atomic_numbers[right] == 7 or atomic_numbers[right] == 8:
            polar[left] = polar[left] + 1
        if atomic_numbers[left] == 7 or atomic_numbers[left] == 8:
            polar[right] = polar[right] + 1
    return [partial_charge(atomic_numbers[index], degree[index], polar[index]) for index in range(len(atomic_numbers))]


def bounding_box(x: list[f64], y: list[f64], z: list[f64]):
    mut minimum = [x[0], y[0], z[0]]
    mut maximum = [x[0], y[0], z[0]]
    for index in range(len(x)):
        minimum = [min(minimum[0], x[index]), min(minimum[1], y[index]), min(minimum[2], z[index])]
        maximum = [max(maximum[0], x[index]), max(maximum[1], y[index]), max(maximum[2], z[index])]
    return [minimum, maximum]


def neighbour_grid(x: list[f64], y: list[f64], z: list[f64], cell_size: f64, minimum: list[f64], maximum: list[f64]):
    """Uniform bucket grid in compressed-row form: `starts[cell]..starts[cell + 1]` indexes `entries`."""
    counts = [max(1, math.floor((maximum[axis] - minimum[axis]) / cell_size) + 1) for axis in range(3)]
    cell_count = counts[0] * counts[1] * counts[2]
    mut cell_of = [0 for index in range(len(x))]
    mut starts = [0 for cell in range(cell_count + 1)]
    for index in range(len(x)):
        cell_x = min(counts[0] - 1, max(0, math.floor((x[index] - minimum[0]) / cell_size)))
        cell_y = min(counts[1] - 1, max(0, math.floor((y[index] - minimum[1]) / cell_size)))
        cell_z = min(counts[2] - 1, max(0, math.floor((z[index] - minimum[2]) / cell_size)))
        cell = (cell_x * counts[1] + cell_y) * counts[2] + cell_z
        cell_of[index] = cell
        starts[cell + 1] = starts[cell + 1] + 1
    for cell in range(cell_count):
        starts[cell + 1] = starts[cell + 1] + starts[cell]
    mut cursor = [starts[cell] for cell in range(cell_count)]
    mut entries = [0 for index in range(len(x))]
    for index in range(len(x)):
        cell = cell_of[index]
        entries[cursor[cell]] = index
        cursor[cell] = cursor[cell] + 1
    return {"origin": minimum, "counts": counts, "cell_size": cell_size, "starts": starts, "entries": entries}


def probe_metrics(grid: dict[str, any], x: list[f64], y: list[f64], z: list[f64], point: list[f64]):
    """One grid walk yielding [atoms within 8 A, atoms within 3 A, distance to the closest atom]."""
    origin = grid["origin"]
    counts = grid["counts"]
    cell_size = grid["cell_size"]
    starts = grid["starts"]
    entries = grid["entries"]
    far_squared = INTERACTION_CUTOFF_ANGSTROM * INTERACTION_CUTOFF_ANGSTROM
    near_squared = 9.0
    low_x = max(0, math.floor((point[0] - INTERACTION_CUTOFF_ANGSTROM - origin[0]) / cell_size))
    high_x = min(counts[0] - 1, math.floor((point[0] + INTERACTION_CUTOFF_ANGSTROM - origin[0]) / cell_size))
    low_y = max(0, math.floor((point[1] - INTERACTION_CUTOFF_ANGSTROM - origin[1]) / cell_size))
    high_y = min(counts[1] - 1, math.floor((point[1] + INTERACTION_CUTOFF_ANGSTROM - origin[1]) / cell_size))
    low_z = max(0, math.floor((point[2] - INTERACTION_CUTOFF_ANGSTROM - origin[2]) / cell_size))
    high_z = min(counts[2] - 1, math.floor((point[2] + INTERACTION_CUTOFF_ANGSTROM - origin[2]) / cell_size))
    mut far = 0
    mut near = 0
    mut closest = far_squared
    for cell_x in range(low_x, high_x + 1):
        for cell_y in range(low_y, high_y + 1):
            row = (cell_x * counts[1] + cell_y) * counts[2]
            for cell_z in range(low_z, high_z + 1):
                cell = row + cell_z
                for slot in range(starts[cell], starts[cell + 1]):
                    index = entries[slot]
                    dx = point[0] - x[index]
                    dy = point[1] - y[index]
                    dz = point[2] - z[index]
                    separation = dx * dx + dy * dy + dz * dz
                    if separation >= far_squared:
                        continue
                    far = far + 1
                    if separation < near_squared:
                        near = near + 1
                    if separation < closest:
                        closest = separation
    return [far - near, math.sqrt(closest)]


def pocket_site(grid: dict[str, any], x: list[f64], y: list[f64], z: list[f64]) -> dict[str, any]:
    """Highest-buriedness placeable grid point, refined on a local sub-lattice and averaged over its cluster.

    A probe is placeable when its closest target atom sits in
    [POCKET_MIN_CLEARANCE_ANGSTROM, POCKET_MAX_CLEARANCE_ANGSTROM]: close enough to be a surface
    cavity rather than bulk solvent, open enough for a ligand heavy atom to occupy. Without that
    filter the verbatim argmax lands in the protein core (measured on 6S34: clearance 0.67 Angstrom),
    where every pose clashes.
    """
    box = bounding_box(x, y, z)
    minimum = box[0]
    maximum = box[1]
    mut spacing = POCKET_COARSE_SPACING_ANGSTROM
    mut steps = [1, 1, 1]
    for attempt in range(8):
        steps = [max(1, math.floor((maximum[axis] - minimum[axis] + 2.0 * POCKET_MIN_CLEARANCE_ANGSTROM) / spacing) + 1) for axis in range(3)]
        if steps[0] * steps[1] * steps[2] <= POCKET_PROBE_LIMIT:
            break
        spacing = spacing * 1.25
    origin = [minimum[axis] - POCKET_MIN_CLEARANCE_ANGSTROM for axis in range(3)]
    mut center = [(minimum[axis] + maximum[axis]) * 0.5 for axis in range(3)]
    mut best = -1.0
    mut probes = 0
    for step_x in range(steps[0]):
        for step_y in range(steps[1]):
            for step_z in range(steps[2]):
                point = [origin[0] + step_x * spacing, origin[1] + step_y * spacing, origin[2] + step_z * spacing]
                metrics = probe_metrics(grid, x, y, z, point)
                probes = probes + 1
                if metrics[1] < POCKET_MIN_CLEARANCE_ANGSTROM or metrics[1] >= POCKET_MAX_CLEARANCE_ANGSTROM:
                    continue
                if metrics[0] > best:
                    best = metrics[0]
                    center = point
    fine_spacing = spacing / (2.0 * POCKET_FINE_STEPS)
    mut cluster = [0.0, 0.0, 0.0]
    mut cluster_size = 0
    for step_x in range(-POCKET_FINE_STEPS, POCKET_FINE_STEPS + 1):
        for step_y in range(-POCKET_FINE_STEPS, POCKET_FINE_STEPS + 1):
            for step_z in range(-POCKET_FINE_STEPS, POCKET_FINE_STEPS + 1):
                point = [center[0] + step_x * fine_spacing, center[1] + step_y * fine_spacing, center[2] + step_z * fine_spacing]
                metrics = probe_metrics(grid, x, y, z, point)
                probes = probes + 1
                if metrics[1] < POCKET_MIN_CLEARANCE_ANGSTROM or metrics[1] >= POCKET_MAX_CLEARANCE_ANGSTROM:
                    continue
                if metrics[0] > best:
                    best = metrics[0]
                if metrics[0] >= POCKET_CLUSTER_FRACTION * best:
                    cluster = [cluster[axis] + point[axis] for axis in range(3)]
                    cluster_size = cluster_size + 1
    if cluster_size > 0:
        center = [cluster[axis] / cluster_size for axis in range(3)]
    return {"center": center, "buriedness": best, "probes": probes, "spacing": spacing}


def quaternion_from_axis_angle(axis: list[f64], angle: f64):
    half = math.sin(angle * 0.5)
    return [math.cos(angle * 0.5), axis[0] * half, axis[1] * half, axis[2] * half]


def quaternion_multiply(left: list[f64], right: list[f64]):
    return [
        left[0] * right[0] - left[1] * right[1] - left[2] * right[2] - left[3] * right[3],
        left[0] * right[1] + left[1] * right[0] + left[2] * right[3] - left[3] * right[2],
        left[0] * right[2] - left[1] * right[3] + left[2] * right[0] + left[3] * right[1],
        left[0] * right[3] + left[1] * right[2] - left[2] * right[1] + left[3] * right[0],
    ]


def rotation_from_quaternion(q: list[f64]):
    """Row-major 3x3 rotation matrix from a unit quaternion [w, x, y, z]."""
    w = q[0]
    x = q[1]
    y = q[2]
    z = q[3]
    return [
        1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - z * w), 2.0 * (x * z + y * w),
        2.0 * (x * y + z * w), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - x * w),
        2.0 * (x * z - y * w), 2.0 * (y * z + x * w), 1.0 - 2.0 * (x * x + y * y),
    ]


def golden_spiral_axis(index: int, count: int):
    """Deterministic quasi-uniform unit axis; the spiral increment is the golden angle pi (3 - sqrt 5)."""
    height = 1.0 - 2.0 * (index + 0.5) / count
    radius = math.sqrt(max(0.0, 1.0 - height * height))
    azimuth = math.pi * (3.0 - math.sqrt(5.0)) * index
    return [radius * math.cos(azimuth), radius * math.sin(azimuth), height]


def translation_lattice(half_extent: f64):
    """Nine deterministic offsets: the pocket point plus the eight corners of a cube around it."""
    mut lattice = [[0.0, 0.0, 0.0]]
    for corner in range(8):
        lattice.append([
            half_extent if corner % 2 == 0 else -half_extent,
            half_extent if (corner // 2) % 2 == 0 else -half_extent,
            half_extent if (corner // 4) % 2 == 0 else -half_extent,
        ])
    return lattice


def posed_coordinates(probe: dict[str, any], rotation: list[f64], center: list[f64], translation: list[f64]):
    local_x = probe["x"]
    local_y = probe["y"]
    local_z = probe["z"]
    shift_x = center[0] + translation[0]
    shift_y = center[1] + translation[1]
    shift_z = center[2] + translation[2]
    mut pose_x = [0.0 for value in local_x]
    mut pose_y = [0.0 for value in local_y]
    mut pose_z = [0.0 for value in local_z]
    for index in range(len(local_x)):
        px = local_x[index]
        py = local_y[index]
        pz = local_z[index]
        pose_x[index] = rotation[0] * px + rotation[1] * py + rotation[2] * pz + shift_x
        pose_y[index] = rotation[3] * px + rotation[4] * py + rotation[5] * pz + shift_y
        pose_z[index] = rotation[6] * px + rotation[7] * py + rotation[8] * pz + shift_z
    return [pose_x, pose_y, pose_z]


def score_pose(field: dict[str, any], probe: dict[str, any], pose: list[list[f64]]):
    """Interaction terms [lennard_jones, coulomb, hydrophobic, clash] in kJ/mol for one rigid pose.

    Cost is O(n_ligand * k) where k is the number of shell atoms in the grid cells overlapping an
    8 Angstrom sphere. The grid holds the pocket shell only, so k tracks local packing density and
    never the target atom count: a 3948-atom target costs the same as a 796-atom one.
    """
    pose_x = pose[0]
    pose_y = pose[1]
    pose_z = pose[2]
    probe_sigma = probe["sigma"]
    probe_root_epsilon = probe["root_epsilon"]
    probe_coulomb = probe["coulomb"]
    probe_carbon = probe["carbon"]
    shell_x = field["x"]
    shell_y = field["y"]
    shell_z = field["z"]
    shell_sigma = field["sigma"]
    shell_root_epsilon = field["root_epsilon"]
    shell_charge = field["charge"]
    shell_carbon = field["carbon"]
    grid = field["grid"]
    origin = grid["origin"]
    counts = grid["counts"]
    cell_size = grid["cell_size"]
    starts = grid["starts"]
    entries = grid["entries"]
    last_x = counts[0] - 1
    last_y = counts[1] - 1
    last_z = counts[2] - 1
    stride_y = counts[2]
    stride_x = counts[1] * counts[2]
    cutoff_squared = INTERACTION_CUTOFF_ANGSTROM * INTERACTION_CUTOFF_ANGSTROM
    mut lennard_jones = 0.0
    mut coulomb = 0.0
    mut hydrophobic = 0.0
    mut clash = 0.0
    for index in range(len(pose_x)):
        px = pose_x[index]
        py = pose_y[index]
        pz = pose_z[index]
        sigma_i = probe_sigma[index]
        root_epsilon_i = probe_root_epsilon[index]
        coulomb_i = probe_coulomb[index]
        carbon_i = probe_carbon[index]
        low_x = max(0, math.floor((px - INTERACTION_CUTOFF_ANGSTROM - origin[0]) / cell_size))
        high_x = min(last_x, math.floor((px + INTERACTION_CUTOFF_ANGSTROM - origin[0]) / cell_size))
        low_y = max(0, math.floor((py - INTERACTION_CUTOFF_ANGSTROM - origin[1]) / cell_size))
        high_y = min(last_y, math.floor((py + INTERACTION_CUTOFF_ANGSTROM - origin[1]) / cell_size))
        low_z = max(0, math.floor((pz - INTERACTION_CUTOFF_ANGSTROM - origin[2]) / cell_size))
        high_z = min(last_z, math.floor((pz + INTERACTION_CUTOFF_ANGSTROM - origin[2]) / cell_size))
        for cell_x in range(low_x, high_x + 1):
            for cell_y in range(low_y, high_y + 1):
                row = cell_x * stride_x + cell_y * stride_y
                for cell_z in range(low_z, high_z + 1):
                    cell = row + cell_z
                    for slot in range(starts[cell], starts[cell + 1]):
                        target_index = entries[slot]
                        dx = px - shell_x[target_index]
                        dy = py - shell_y[target_index]
                        dz = pz - shell_z[target_index]
                        separation = dx * dx + dy * dy + dz * dz
                        if separation >= cutoff_squared:
                            continue
                        distance = math.sqrt(separation)
                        guarded = max(distance, CLOSE_CONTACT_ANGSTROM)
                        ratio = (sigma_i + shell_sigma[target_index]) * 0.5 / guarded
                        ratio_six = ratio * ratio * ratio
                        ratio_six = ratio_six * ratio_six
                        lennard_jones = lennard_jones + min(LJ_PAIR_CEILING_KJ_PER_MOL, 4.0 * root_epsilon_i * shell_root_epsilon[target_index] * ratio_six * (ratio_six - 1.0))
                        coulomb = coulomb + coulomb_i * shell_charge[target_index] / (guarded * guarded)
                        if carbon_i and shell_carbon[target_index]:
                            spread = (distance - HYDROPHOBIC_CENTER_ANGSTROM) / HYDROPHOBIC_WIDTH_ANGSTROM
                            hydrophobic = hydrophobic - HYDROPHOBIC_DEPTH_KJ_PER_MOL * math.exp(-spread * spread)
                        if distance < CLASH_DISTANCE_ANGSTROM:
                            gap = CLASH_DISTANCE_ANGSTROM - distance
                            clash = clash + CLASH_STIFFNESS_KJ_PER_MOL_ANGSTROM2 * gap * gap
    return [lennard_jones, coulomb, hydrophobic, clash]


def pose_energy(field: dict[str, any], probe: dict[str, any], pose: list[list[f64]]):
    terms = score_pose(field, probe, pose)
    return terms[0] + terms[1] + terms[2] + terms[3]


def refined_state(field: dict[str, any], probe: dict[str, any], center: list[f64], base: list[f64], start: list[f64]):
    """Bounded local coordinate descent over three translations and three body-frame rotations."""
    mut state = [value for value in start]
    mut best = pose_energy(field, probe, posed_coordinates(probe, rotation_from_quaternion(descent_quaternion(base, state)), center, state))
    mut translation_step = REFINEMENT_TRANSLATION_STEP_ANGSTROM
    mut rotation_step = REFINEMENT_ROTATION_STEP_RADIAN
    mut steps = 0
    mut converged = false
    while steps < REFINEMENT_MAX_STEPS:
        steps = steps + 1
        mut improved = false
        for axis in range(6):
            for direction in range(2):
                delta = translation_step if axis < 3 else rotation_step
                mut candidate = [value for value in state]
                candidate[axis] = candidate[axis] + (delta if direction == 0 else -delta)
                if candidate[0] * candidate[0] + candidate[1] * candidate[1] + candidate[2] * candidate[2] > POSE_TRANSLATION_LIMIT_ANGSTROM * POSE_TRANSLATION_LIMIT_ANGSTROM:
                    continue
                trial = pose_energy(field, probe, posed_coordinates(probe, rotation_from_quaternion(descent_quaternion(base, candidate)), center, candidate))
                if trial < best - 0.000001:
                    best = trial
                    state = candidate
                    improved = true
        if not improved:
            translation_step = translation_step * 0.5
            rotation_step = rotation_step * 0.5
            if translation_step < REFINEMENT_TOLERANCE_ANGSTROM:
                converged = true
                break
    return {"state": state, "score": best, "steps": steps, "converged": converged}


def descent_quaternion(base: list[f64], state: list[f64]):
    """Enumerated orientation composed with the descent's body-frame x, y, then z rotations."""
    rotated = quaternion_multiply(quaternion_from_axis_angle([1.0, 0.0, 0.0], state[3]), base)
    rotated = quaternion_multiply(quaternion_from_axis_angle([0.0, 1.0, 0.0], state[4]), rotated)
    return quaternion_multiply(quaternion_from_axis_angle([0.0, 0.0, 1.0], state[5]), rotated)


def structure_positions(structure: dict[str, any]):
    return structure["positions"]


def structure_bonds(structure: dict[str, any]):
    return structure["bonds"] if structure.has("bonds") else structure["bond_pairs"]


pub def docking_rejection(target: dict[str, any], ligand: dict[str, any], budget: int) -> str !{}:
    """Empty string when the pair is dockable, otherwise the reason a caller should report as 422."""
    if not target.has("positions") or not target.has("atomic_numbers"):
        return "target is not a loaded molecular session"
    if not ligand.has("positions") or not ligand.has("atomic_numbers"):
        return "ligand structure carries no positions or atomic numbers"
    if not ligand.has("bonds") and not ligand.has("bond_pairs"):
        return "ligand structure carries no bond list"
    target_atoms = len(target["atomic_numbers"])
    ligand_atoms = len(ligand["atomic_numbers"])
    if target_atoms < 1 or target_atoms > MAX_TARGET_ATOMS:
        return "target must carry 1.." + str(MAX_TARGET_ATOMS) + " atoms"
    if ligand_atoms < 1 or ligand_atoms > MAX_LIGAND_ATOMS:
        return "ligand must carry 1.." + str(MAX_LIGAND_ATOMS) + " atoms"
    if len(target["positions"]) != target_atoms * 3:
        return "target positions must hold three Angstrom coordinates per atom"
    if len(structure_positions(ligand)) != ligand_atoms * 3:
        return "ligand positions must hold three Angstrom coordinates per atom"
    ligand_bonds = structure_bonds(ligand)
    if len(ligand_bonds) % 2 != 0:
        return "ligand bond list must hold index pairs"
    for atom_index in ligand_bonds:
        if atom_index < 0 or atom_index >= ligand_atoms:
            return "ligand bond list references an atom outside the structure"
    if budget != 0 and (budget < MIN_POSE_BUDGET or budget > MAX_POSE_BUDGET):
        return "pose budget must be 0 for the default or " + str(MIN_POSE_BUDGET) + ".." + str(MAX_POSE_BUDGET)
    return ""


def clamped_budget(budget: int):
    if budget <= 0:
        return DEFAULT_POSE_BUDGET
    return min(MAX_POSE_BUDGET, max(MIN_POSE_BUDGET, budget))


def target_field(target: dict[str, any], center: list[f64], pose_reach: f64):
    """Pocket shell: every target atom a posed ligand atom could reach, with its grid and Verlet lists."""
    positions = target["positions"]
    atomic_numbers = target["atomic_numbers"]
    charges = partial_charges(atomic_numbers, target["bond_pairs"])
    mut x: list[f64] = []
    mut y: list[f64] = []
    mut z: list[f64] = []
    mut sigma: list[f64] = []
    mut root_epsilon: list[f64] = []
    mut charge: list[f64] = []
    mut carbon: list[bool] = []
    mut source: list[int] = []
    reach_squared = (INTERACTION_CUTOFF_ANGSTROM + pose_reach) * (INTERACTION_CUTOFF_ANGSTROM + pose_reach)
    for atom_index in range(len(atomic_numbers)):
        offset = atom_index * 3
        dx = positions[offset] - center[0]
        dy = positions[offset + 1] - center[1]
        dz = positions[offset + 2] - center[2]
        if dx * dx + dy * dy + dz * dz > reach_squared:
            continue
        parameters = lj_parameters(atomic_numbers[atom_index])
        x.append(positions[offset])
        y.append(positions[offset + 1])
        z.append(positions[offset + 2])
        sigma.append(parameters[0])
        root_epsilon.append(math.sqrt(parameters[1]))
        charge.append(charges[atom_index])
        carbon.append(atomic_numbers[atom_index] == 6)
        source.append(atom_index)
    box = bounding_box(x, y, z)
    minimum = [min(box[0][axis], center[axis] - pose_reach) for axis in range(3)]
    maximum = [max(box[1][axis], center[axis] + pose_reach) for axis in range(3)]
    grid = neighbour_grid(x, y, z, GRID_CELL_ANGSTROM, minimum, maximum)
    return {
        "x": x,
        "y": y,
        "z": z,
        "sigma": sigma,
        "root_epsilon": root_epsilon,
        "charge": charge,
        "carbon": carbon,
        "source": source,
        "grid": grid,
    }


def ligand_probe(ligand: dict[str, any]) -> dict[str, any]:
    """Ligand recentred on its centroid; the internal geometry is never re-optimised (rigid ligand)."""
    positions = structure_positions(ligand)
    atomic_numbers = ligand["atomic_numbers"]
    charges = partial_charges(atomic_numbers, structure_bonds(ligand))
    count = len(atomic_numbers)
    mut centroid = [0.0, 0.0, 0.0]
    for atom_index in range(count):
        offset = atom_index * 3
        centroid = [centroid[0] + positions[offset], centroid[1] + positions[offset + 1], centroid[2] + positions[offset + 2]]
    centroid = [centroid[axis] / count for axis in range(3)]
    mut x = [0.0 for atom_index in range(count)]
    mut y = [0.0 for atom_index in range(count)]
    mut z = [0.0 for atom_index in range(count)]
    mut sigma = [0.0 for atom_index in range(count)]
    mut root_epsilon = [0.0 for atom_index in range(count)]
    mut coulomb = [0.0 for atom_index in range(count)]
    mut carbon = [false for atom_index in range(count)]
    mut radius = 0.0
    for atom_index in range(count):
        offset = atom_index * 3
        x[atom_index] = positions[offset] - centroid[0]
        y[atom_index] = positions[offset + 1] - centroid[1]
        z[atom_index] = positions[offset + 2] - centroid[2]
        radius = max(radius, math.sqrt(x[atom_index] * x[atom_index] + y[atom_index] * y[atom_index] + z[atom_index] * z[atom_index]))
        parameters = lj_parameters(atomic_numbers[atom_index])
        sigma[atom_index] = parameters[0]
        root_epsilon[atom_index] = math.sqrt(parameters[1])
        coulomb[atom_index] = COULOMB_CONSTANT_KJ_ANGSTROM_PER_MOL * charges[atom_index] / DIELECTRIC_SLOPE
        carbon[atom_index] = atomic_numbers[atom_index] == 6
    return {"x": x, "y": y, "z": z, "sigma": sigma, "root_epsilon": root_epsilon, "coulomb": coulomb, "carbon": carbon, "radius": radius, "centroid": centroid}


def pose_contacts(field: dict[str, any], pose: list[list[f64]]):
    """The MAX_CONTACTS shortest ligand/target contacts under CONTACT_DISTANCE_ANGSTROM, nearest first."""
    pose_x = pose[0]
    pose_y = pose[1]
    pose_z = pose[2]
    shell_x = field["x"]
    shell_y = field["y"]
    shell_z = field["z"]
    source = field["source"]
    limit_squared = CONTACT_DISTANCE_ANGSTROM * CONTACT_DISTANCE_ANGSTROM
    mut distances: list[f64] = []
    mut probe_indices: list[int] = []
    mut target_indices: list[int] = []
    for index in range(len(pose_x)):
        for shell_index in range(len(shell_x)):
            dx = pose_x[index] - shell_x[shell_index]
            dy = pose_y[index] - shell_y[shell_index]
            dz = pose_z[index] - shell_z[shell_index]
            separation = dx * dx + dy * dy + dz * dz
            if separation >= limit_squared:
                continue
            distance = math.sqrt(separation)
            filled = len(distances)
            if filled == MAX_CONTACTS and distance >= distances[filled - 1]:
                continue
            if filled < MAX_CONTACTS:
                distances.append(distance)
                probe_indices.append(index)
                target_indices.append(source[shell_index])
            else:
                distances[filled - 1] = distance
                probe_indices[filled - 1] = index
                target_indices[filled - 1] = source[shell_index]
            mut slot = len(distances) - 1
            while slot > 0 and distances[slot] < distances[slot - 1]:
                held_distance = distances[slot - 1]
                held_probe = probe_indices[slot - 1]
                held_target = target_indices[slot - 1]
                distances[slot - 1] = distances[slot]
                probe_indices[slot - 1] = probe_indices[slot]
                target_indices[slot - 1] = target_indices[slot]
                distances[slot] = held_distance
                probe_indices[slot] = held_probe
                target_indices[slot] = held_target
                slot = slot - 1
    return [[probe_indices[slot], target_indices[slot], distances[slot]] for slot in range(len(distances))]


def buried_ligand_fraction(field: dict[str, any], pose: list[list[f64]]):
    pose_x = pose[0]
    pose_y = pose[1]
    pose_z = pose[2]
    shell_x = field["x"]
    shell_y = field["y"]
    shell_z = field["z"]
    limit_squared = BURIAL_DISTANCE_ANGSTROM * BURIAL_DISTANCE_ANGSTROM
    mut buried = 0
    for index in range(len(pose_x)):
        for shell_index in range(len(shell_x)):
            dx = pose_x[index] - shell_x[shell_index]
            dy = pose_y[index] - shell_y[shell_index]
            dz = pose_z[index] - shell_z[shell_index]
            if dx * dx + dy * dy + dz * dz < limit_squared:
                buried = buried + 1
                break
    return buried / len(pose_x)


pub def free_energy_kj_mol(score: f64) -> f64 !{}:
    return CALIBRATION_SLOPE * score + CALIBRATION_INTERCEPT


pub def dissociation_constant_micromolar(delta_g_kj_mol: f64) -> f64 !{}:
    """Kd = exp(dG / RT) * 1e6 uM at 310.15 K, clamped to the published reporting window."""
    exponent = max(-40.0, min(40.0, delta_g_kj_mol / (GAS_CONSTANT_KJ_PER_MOL_K * BODY_TEMPERATURE_K)))
    return max(MIN_KD_MICROMOLAR, min(MAX_KD_MICROMOLAR, math.exp(exponent) * 1000000.0))


pub def dock_ligand(target: dict[str, any], ligand: dict[str, any], budget: int) -> dict[str, any] !{}:
    sem "Rank a rigid ligand pose against a target pocket with a published empirical scoring function"
    require docking_rejection(target, ligand, budget) == ""
    ensure result["schema"] == BINDING_SCHEMA
    ensure result["kd_micromolar"] >= MIN_KD_MICROMOLAR and result["kd_micromolar"] <= MAX_KD_MICROMOLAR
    poses = clamped_budget(budget)
    positions = target["positions"]
    atom_count = len(target["atomic_numbers"])
    target_x = [positions[atom_index * 3] for atom_index in range(atom_count)]
    target_y = [positions[atom_index * 3 + 1] for atom_index in range(atom_count)]
    target_z = [positions[atom_index * 3 + 2] for atom_index in range(atom_count)]
    target_box = bounding_box(target_x, target_y, target_z)
    site = pocket_site(neighbour_grid(target_x, target_y, target_z, GRID_CELL_ANGSTROM, target_box[0], target_box[1]), target_x, target_y, target_z)
    center = site["center"]
    probe = ligand_probe(ligand)
    field = target_field(target, center, POSE_TRANSLATION_LIMIT_ANGSTROM + probe["radius"])
    lattice = translation_lattice(TRANSLATION_HALF_EXTENT_ANGSTROM)
    angle_steps = ANGLE_LADDER_STEPS
    axis_count = max(1, (poses + len(lattice) * angle_steps - 1) // (len(lattice) * angle_steps))
    mut best_score = math.inf
    mut best_quaternion = [1.0, 0.0, 0.0, 0.0]
    mut best_translation = [0.0, 0.0, 0.0]
    for pose_index in range(poses):
        translation = lattice[pose_index % len(lattice)]
        orientation = pose_index // len(lattice)
        quaternion = quaternion_from_axis_angle(golden_spiral_axis(orientation // angle_steps, axis_count), 2.0 * math.pi * (orientation % angle_steps) / angle_steps)
        score = pose_energy(field, probe, posed_coordinates(probe, rotation_from_quaternion(quaternion), center, translation))
        if score < best_score:
            best_score = score
            best_quaternion = quaternion
            best_translation = translation
    refinement = refined_state(field, probe, center, best_quaternion, [best_translation[0], best_translation[1], best_translation[2], 0.0, 0.0, 0.0])
    state = refinement["state"]
    quaternion = descent_quaternion(best_quaternion, state)
    translation = [state[0], state[1], state[2]]
    pose = posed_coordinates(probe, rotation_from_quaternion(quaternion), center, translation)
    terms = score_pose(field, probe, pose)
    score = terms[0] + terms[1] + terms[2] + terms[3]
    delta_g = free_energy_kj_mol(score)
    mut flat: list[f64] = []
    for index in range(len(pose[0])):
        flat.append(pose[0][index])
        flat.append(pose[1][index])
        flat.append(pose[2][index])
    return {
        "schema": BINDING_SCHEMA,
        "backend": "Sema",
        "evidence_class": "derived_illustrative",
        "scientific_validated": false,
        "target_key": target["key"],
        "target_source_sha256": target["source_sha256"],
        "ligand_name": ligand["key"],
        "ligand_source_sha256": ligand["source_sha256"],
        "scoring_function": SCORING_FUNCTION,
        "calibration": {
            "name": CALIBRATION_NAME,
            "slope": CALIBRATION_SLOPE,
            "intercept": CALIBRATION_INTERCEPT,
            "note": CALIBRATION_NOTE,
        },
        "pocket_center_angstrom": center,
        "pocket_buriedness": site["buriedness"],
        "pocket_probes": site["probes"],
        "pose_translation_angstrom": translation,
        "pose_quaternion": quaternion,
        "score": score,
        "lennard_jones": terms[0],
        "coulomb": terms[1],
        "hydrophobic": terms[2],
        "clash_penalty": terms[3],
        "delta_g_kj_mol": delta_g,
        "kd_micromolar": dissociation_constant_micromolar(delta_g),
        "contacts": pose_contacts(field, pose),
        "buried_fraction": buried_ligand_fraction(field, pose),
        "poses_evaluated": poses,
        "refinement_steps": refinement["steps"],
        "converged": refinement["converged"],
        "shell_atoms": len(field["x"]),
        "ligand_rigid": true,
        "notes": [
            "rigid ligand: internal strain is not re-optimised during docking",
            "score is an empirical rank, not a measured or computed binding free energy",
            "pocket is the highest-buriedness placeable grid point, refined on a local sub-lattice",
        ],
        "ligand_positions_angstrom": flat,
    }


pub def occupancy_fraction(kd_micromolar: f64, concentration_micromolar: f64) -> f64 !{}:
    sem "Mass-action receptor occupancy c / (Kd + c) for a single independent site"
    ensure result >= 0.0 and result <= 1.0
    kd = max(MIN_KD_MICROMOLAR, kd_micromolar)
    concentration = max(0.0, concentration_micromolar)
    return concentration / (kd + concentration)


pub def binding_mechanisms() -> list[str] !{}:
    return ["secretion_agonist", "secretion_antagonist", "cytokine_inhibitor", "immune_shield", "insulin_analog", "inert"]


def bounded_multiplier(name: str, multiplier: f64):
    """Cap a multiplier so the published baseline parameter stays inside its physiology bound."""
    baseline = initial_physiology_parameters()[name]
    bound = physiology_parameter_bounds()[name]
    return max(bound[0] / baseline, min(bound[1] / baseline, multiplier))


pub def species_effect(mechanism: str, occupancy: f64) -> dict[str, f64] !{}:
    """Physiology couplings keyed by effect kind.

    `parameter:<name>` multiplies that physiology parameter, `signal_max:<name>` raises the signal
    to at least the value, `signal_add:<name>` adds to it. Occupancy is clamped to [0, 1] and every
    value here is already bounded against the published baseline, so applying it to the source
    parameters can never leave `physiology_parameter_bounds()`; `apply_species_effects` clamps again
    against whatever the live parameters happen to be.
    """
    fraction = max(0.0, min(1.0, occupancy))
    if mechanism == "secretion_agonist":
        return {"parameter:insulin_secretion_micro_u_ml_day_mg": bounded_multiplier("insulin_secretion_micro_u_ml_day_mg", 1.0 + 1.4 * fraction)}
    if mechanism == "secretion_antagonist":
        return {"parameter:insulin_secretion_micro_u_ml_day_mg": bounded_multiplier("insulin_secretion_micro_u_ml_day_mg", 1.0 - 0.7 * fraction)}
    if mechanism == "cytokine_inhibitor":
        return {"parameter:cytokine_release_per_day": bounded_multiplier("cytokine_release_per_day", 1.0 - 0.8 * fraction)}
    if mechanism == "immune_shield":
        return {"signal_max:immune_shielding": min(IMMUNE_SHIELDING_CEILING, 0.95 * fraction)}
    if mechanism == "insulin_analog":
        return {"signal_add:exogenous_insulin_micro_u_ml_day": min(EXOGENOUS_INSULIN_CEILING, 900.0 * fraction)}
    return {}


def signal_ceiling(name: str):
    """Upper bounds mirror the signal table in programming.sema; species may never exceed them."""
    if name == "immune_shielding":
        return IMMUNE_SHIELDING_CEILING
    if name == "exogenous_insulin_micro_u_ml_day":
        return EXOGENOUS_INSULIN_CEILING
    return 0.0


pub def apply_species_effects(parameters: dict[str, f64], signals: dict[str, f64], registry: dict[str, any]) -> dict[str, any] !{}:
    sem "Combine every registered species onto a copy of the physiology parameters and signals"
    ensure result["species_applied"] >= 0
    bounds = physiology_parameter_bounds()
    mut next_parameters = {name: value for name, value in parameters.items()}
    mut next_signals = {name: value for name, value in signals.items()}
    mut applied = 0
    for name in sorted(registry.keys()):
        effect = registry[name]["effect"]
        applied = applied + 1
        for key in sorted(effect.keys()):
            value = effect[key]
            if key.startswith("parameter:"):
                parameter = key.slice(10, len(key))
                if next_parameters.has(parameter) and bounds.has(parameter):
                    next_parameters[parameter] = max(bounds[parameter][0], min(bounds[parameter][1], next_parameters[parameter] * value))
            elif key.startswith("signal_max:"):
                signal = key.slice(11, len(key))
                if next_signals.has(signal):
                    next_signals[signal] = max(0.0, min(signal_ceiling(signal), max(next_signals[signal], value)))
            elif key.startswith("signal_add:"):
                signal = key.slice(11, len(key))
                if next_signals.has(signal):
                    next_signals[signal] = max(0.0, min(signal_ceiling(signal), next_signals[signal] + value))
    return {"parameters": next_parameters, "signals": next_signals, "species_applied": applied}


pub def initial_species_registry() -> dict[str, any] !{}:
    return {}


pub def species_registration_error(registry: dict[str, any], spec: dict[str, any], docking: dict[str, any], concentration_micromolar: f64, mechanism: str) -> dict[str, str] !{}:
    """`{"error": "", "detail": ""}` when the species may be introduced, otherwise the typed refusal."""
    if not spec.has("name") or not spec.has("label") or not spec.has("class"):
        return {"error": "SpeciesRejected", "detail": "design spec must carry name, label, and class"}
    chosen = mechanism if len(mechanism) > 0 else spec["mechanism"]
    if not binding_mechanisms().contains(chosen):
        return {"error": "SpeciesRejected", "detail": "mechanism must be one of " + str(binding_mechanisms())}
    if concentration_micromolar <= 0.0 or concentration_micromolar > MAX_CONCENTRATION_MICROMOLAR:
        return {"error": "SpeciesRejected", "detail": "concentration must be within (0, 1e6] micromolar"}
    if len(docking) > 0 and docking["schema"] != BINDING_SCHEMA:
        return {"error": "SpeciesRejected", "detail": "docking record must be a " + BINDING_SCHEMA}
    if not registry.has(spec["name"]) and len(registry) >= MAX_SPECIES:
        return {"error": "SpeciesRegistryFull", "detail": "at most " + str(MAX_SPECIES) + " designed species may coexist"}
    return {"error": "", "detail": ""}


pub def register_species(registry: dict[str, any], spec: dict[str, any], structure: dict[str, any], docking: dict[str, any], concentration_micromolar: f64, mechanism: str, introduced_at_days: f64) -> dict[str, any] !{}:
    sem "Introduce or replace one designed species in a bounded registry, leaving the input untouched"
    require species_registration_error(registry, spec, docking, concentration_micromolar, mechanism)["error"] == ""
    ensure len(result) <= MAX_SPECIES
    docked = len(docking) > 0
    chosen = mechanism if len(mechanism) > 0 else spec["mechanism"]
    kd = docking["kd_micromolar"] if docked else MAX_KD_MICROMOLAR
    occupancy = occupancy_fraction(kd, concentration_micromolar)
    mut next_registry = {name: record for name, record in registry.items()}
    next_registry[spec["name"]] = {
        "schema": SPECIES_SCHEMA,
        "name": spec["name"],
        "label": spec["label"],
        "class": spec["class"],
        "mechanism": chosen,
        "target_key": docking["target_key"] if docked else spec["target_key"],
        "concentration_micromolar": concentration_micromolar,
        "kd_micromolar": kd,
        "occupancy_fraction": occupancy,
        "structure_sha256": structure["asset_sha256"],
        "atoms": len(structure["atomic_numbers"]),
        "bonds": len(structure_bonds(structure)) // 2,
        "introduced_at_days": introduced_at_days,
        "docked": docked,
        "effect": species_effect(chosen, occupancy),
        "scientific_validated": false,
    }
    return next_registry


pub def species_public_state(registry: dict[str, any]) -> list[dict[str, any]] !{}:
    sem "Every designed species as a sema.designed-species-state/v1 record, ordered by name"
    ensure len(result) <= MAX_SPECIES
    return [registry[name] for name in sorted(registry.keys())]


pub def binding_capabilities() -> dict[str, any] !{}:
    return {
        "schema": "sema.molecular-binding-capabilities/v1",
        "backend": "Sema",
        "evidence_class": "derived_illustrative",
        "scientific_validated": false,
        "pose_budget": [MIN_POSE_BUDGET, MAX_POSE_BUDGET],
        "default_pose_budget": DEFAULT_POSE_BUDGET,
        "max_target_atoms": MAX_TARGET_ATOMS,
        "max_ligand_atoms": MAX_LIGAND_ATOMS,
        "max_species": MAX_SPECIES,
        "max_contacts": MAX_CONTACTS,
        "scoring_function": SCORING_FUNCTION,
        "search": "golden-spiral rotation axes x a " + str(ANGLE_LADDER_STEPS) + "-step angle ladder x a 9-point translation lattice, then bounded local coordinate descent",
        "pocket_rule": "highest buriedness (atoms within 8 A minus atoms within 3 A) over placeable probes whose closest target atom lies in [2.6, 8.0] A, refined on a local sub-lattice and averaged over its cluster",
        "rigid_ligand": true,
        "calibration": {
            "name": CALIBRATION_NAME,
            "slope": CALIBRATION_SLOPE,
            "intercept": CALIBRATION_INTERCEPT,
            "note": CALIBRATION_NOTE,
        },
        "constants": {
            "interaction_cutoff_angstrom": INTERACTION_CUTOFF_ANGSTROM,
            "clash_distance_angstrom": CLASH_DISTANCE_ANGSTROM,
            "clash_stiffness_kj_per_mol_angstrom2": CLASH_STIFFNESS_KJ_PER_MOL_ANGSTROM2,
            "lj_pair_ceiling_kj_per_mol": LJ_PAIR_CEILING_KJ_PER_MOL,
            "coulomb_constant_kj_angstrom_per_mol": COULOMB_CONSTANT_KJ_ANGSTROM_PER_MOL,
            "dielectric_model": "distance dependent, epsilon(r) = 4r",
            "hydrophobic_depth_kj_per_mol": HYDROPHOBIC_DEPTH_KJ_PER_MOL,
            "hydrophobic_center_angstrom": HYDROPHOBIC_CENTER_ANGSTROM,
            "hydrophobic_width_angstrom": HYDROPHOBIC_WIDTH_ANGSTROM,
            "gas_constant_kj_per_mol_k": GAS_CONSTANT_KJ_PER_MOL_K,
            "temperature_k": BODY_TEMPERATURE_K,
            "kd_window_micromolar": [MIN_KD_MICROMOLAR, MAX_KD_MICROMOLAR],
        },
        "mechanisms": {
            "secretion_agonist": "insulin_secretion_micro_u_ml_day_mg x (1 + 1.4 occupancy)",
            "secretion_antagonist": "insulin_secretion_micro_u_ml_day_mg x (1 - 0.7 occupancy)",
            "cytokine_inhibitor": "cytokine_release_per_day x (1 - 0.8 occupancy)",
            "immune_shield": "immune_shielding raised to at least 0.95 occupancy",
            "insulin_analog": "exogenous_insulin_micro_u_ml_day increased by 900 occupancy",
            "inert": "no physiology coupling",
        },
        "occupancy_model": "mass action, occupancy = c / (Kd + c)",
        "parameter_bounds": physiology_parameter_bounds(),
    }
```

### `src/coarse.sema`

```sema
"""Periodic phi/psi coarse-state mapping with explicit sampling diagnostics."""

assure silver


pub struct CoarseStateResult:
    schema: str
    analysis_id: str
    config_sha256: str
    source_frames_sha256: str
    source_model_sha256: str
    source_parameter_sha256: str
    result_sha256: str
    result_path: str
    samples: int
    basin_ids: list[str]
    counts: list[int]
    transition_counts: list[int]
    transitions: int
    observed_basins: int
    lag_frames: int
    pseudocount: f64
    free_energy_kj_mol: list[f64]
    effective_samples: f64
    mapping_validated: bool
    sampling_converged: bool
    evidence_class: str
    invariant schema == "sema.coarse-state-result/v1"
    invariant len(analysis_id) > 0
    invariant len(config_sha256) == 64
    invariant len(source_frames_sha256) == 64
    invariant len(source_model_sha256) == 64
    invariant len(source_parameter_sha256) == 64
    invariant len(result_sha256) == 64
    invariant len(result_path) > 0
    invariant samples > 1 and samples <= 101
    invariant len(basin_ids) >= 2 and len(basin_ids) <= 16
    invariant len(counts) == len(basin_ids)
    invariant len(transition_counts) == len(basin_ids) * len(basin_ids)
    invariant transitions >= 0 and transitions < samples
    invariant observed_basins > 0 and observed_basins <= len(basin_ids)
    invariant lag_frames > 0 and lag_frames < samples
    invariant pseudocount > 0.0
    invariant len(free_energy_kj_mol) == len(basin_ids)
    invariant effective_samples >= 0.0 and effective_samples <= f64(samples)
    invariant mapping_validated
    invariant evidence_class == "exploratory"


pub bridge python.inline coarse_backend from "foreign/python/coarse_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def analyze_coarse_state(
            config_path: str,
            frames_path: str,
            output_path: str,
            expected_frames_sha256: str,
        ) -> CoarseStateResult !{ffi.call}:
            sem "Map canonical atomistic phi/psi frames onto preregistered periodic coarse basins"
```

### `src/cortex.sema`

```sema
"""Governed proposal-only Cortex bridge with native Sema contract revalidation."""

from biological_computer.programming import programming_capabilities

assure silver


bridge python.inline cortex_sdk_backend from "foreign/python/cortex_sdk_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def propose_cortex_backend(payload: any) -> dict[str, any] !{ffi.call}:
            sem "Request one bounded proposal from a warm Cortex session without mutating live state"


def cortex_units():
    return {
        "glucose": "mmol/L",
        "oxygen": "kPa",
        "cytokine": "fraction",
        "morphology": "relative",
        "amplitude": "relative",
        "attraction": "relative",
        "molecular_temperature": "relative",
        "bond_stiffness": "relative",
        "meal_intensity": "relative",
        "exercise_intensity": "relative",
        "exogenous_insulin_micro_u_ml_day": "microU/mL/day",
        "immune_shielding": "fraction",
        "graft_target_mg": "mg",
        "physiology_seconds_per_real_second": "model-s/real-s",
        "glucose_inflow_mg_dl_day": "mg/dL/day",
        "insulin_sensitivity_ml_micro_u_day": "mL/microU/day",
        "glucose_effectiveness_per_day": "1/day",
        "insulin_secretion_micro_u_ml_day_mg": "microU/mL/day/mg",
        "insulin_clearance_per_day": "1/day",
        "secretion_half_saturation_mg2_dl2": "mg2/dL2",
        "beta_death_per_day": "1/day",
        "beta_growth_dl_mg_day": "dL/mg/day",
        "beta_glucotoxicity_dl2_mg2_day": "dL2/mg2/day",
        "immune_activation_per_day": "1/day",
        "immune_clearance_per_day": "1/day",
        "immune_kill_per_day": "1/day",
        "cytokine_release_per_day": "1/day",
        "cytokine_clearance_per_day": "1/day",
        "regulatory_recovery_per_day": "1/day",
        "graft_engraftment_per_day": "1/day",
        "graft_rejection_per_day": "1/day",
    }


def cortex_operation_error(operation: any) !{}:
    if not (operation is dict):
        return "Cortex operation must be an object"
    if not all(operation.has(field) for field in ["kind", "name", "value", "unit"]):
        return "Cortex operation is missing a required field"
    if not (operation["kind"] is str) or not (operation["name"] is str) or not (operation["unit"] is str):
        return "Cortex operation kind, name, and unit must be strings"
    kind = operation["kind"]
    name = operation["name"]
    capabilities = programming_capabilities()
    mut bounds: any = None
    if kind == "set_signal" and capabilities["signals"].has(name):
        bounds = capabilities["signals"][name]
    elif kind == "set_parameter" and capabilities["parameters"].has(name):
        bounds = capabilities["parameters"][name]
    else:
        return "Cortex operation kind or name is unsupported"
    units = cortex_units()
    if not units.has(name) or operation["unit"] != units[name]:
        return "Cortex operation unit does not match its Sema contract"
    if operation["value"] < bounds[0] or operation["value"] > bounds[1]:
        return "Cortex operation value is outside its Sema bounds"
    return ""


def cortex_proposal_error(proposal: any) !{}:
    if not (proposal is dict):
        return "Cortex proposal must be an object"
    required = ["schema", "provider", "harness", "model", "summary", "rationale", "assumptions", "warnings", "operations", "requires_explicit_apply", "scientific_validated"]
    if not all(proposal.has(field) for field in required):
        return "Cortex proposal is missing a required field"
    if not (proposal["summary"] is str) or not (proposal["rationale"] is str):
        return "Cortex proposal summary and rationale must be strings"
    if not (proposal["assumptions"] is list) or not (proposal["warnings"] is list) or not (proposal["operations"] is list):
        return "Cortex proposal list fields are malformed"
    if proposal["schema"] != "sema.biological-llm-proposal/v1" or proposal["provider"] != "Cortex":
        return "Cortex proposal schema or provider identity is invalid"
    if proposal["harness"] != "omp" or proposal["model"] != "openai-codex/gpt-5.6-sol":
        return "Cortex proposal harness or model identity is invalid"
    if proposal["requires_explicit_apply"] != true or proposal["scientific_validated"] != false:
        return "Cortex proposal safety identity is invalid"
    if len(proposal["summary"]) == 0 or len(proposal["summary"]) > 240 or len(proposal["rationale"]) == 0 or len(proposal["rationale"]) > 900:
        return "Cortex proposal summary or rationale is outside its text bound"
    if len(proposal["assumptions"]) > 4 or len(proposal["warnings"]) > 4:
        return "Cortex proposal assumptions or warnings exceed their list bound"
    if any(not (entry is str) or len(entry) == 0 or len(entry) > 180 for entry in proposal["assumptions"]):
        return "Cortex proposal assumption text is invalid"
    if any(not (entry is str) or len(entry) == 0 or len(entry) > 180 for entry in proposal["warnings"]):
        return "Cortex proposal warning text is invalid"
    operations = proposal["operations"]
    if len(operations) < 1 or len(operations) > 6:
        return "Cortex proposal must contain 1..6 operations"
    for operation in operations:
        operation_error = cortex_operation_error(operation)
        if len(operation_error) > 0:
            return operation_error
    return ""


pub def propose_cortex(payload: any) -> dict[str, any] !{ffi.call}:
    if not (payload is dict):
        return {"ok": false, "error": "CortexProposalInvalid", "detail": "Cortex proposal request must be an object"}
    required = ["prompt", "scenario_id", "program", "physiology"]
    if not all(payload.has(field) for field in required):
        return {"ok": false, "error": "CortexProposalInvalid", "detail": "Cortex proposal request is missing a required field"}
    if not (payload["prompt"] is str) or not (payload["scenario_id"] is str):
        return {"ok": false, "error": "CortexProposalInvalid", "detail": "prompt and scenario_id must be strings"}
    if not (payload["program"] is dict) or not (payload["physiology"] is dict):
        return {"ok": false, "error": "CortexProposalInvalid", "detail": "program and physiology must be objects"}
    if len(payload["prompt"]) == 0 or len(payload["prompt"]) > 1200:
        return {"ok": false, "error": "CortexProposalInvalid", "detail": "prompt must contain 1..1200 characters"}
    if len(payload["scenario_id"]) == 0 or len(payload["scenario_id"]) > 80:
        return {"ok": false, "error": "CortexProposalInvalid", "detail": "scenario_id must contain 1..80 characters"}
    if not payload["program"].has("schema") or payload["program"]["schema"] != "sema.biological-program-state/v2":
        return {"ok": false, "error": "CortexProposalInvalid", "detail": "program must use sema.biological-program-state/v2"}
    if not payload["physiology"].has("schema") or payload["physiology"]["schema"] != "sema.metabolic-immune-observation/v1":
        return {"ok": false, "error": "CortexProposalInvalid", "detail": "physiology must use sema.metabolic-immune-observation/v1"}
    result = cortex_sdk_backend.propose_cortex_backend(payload)
    if not result.has("ok") or result["ok"] != true:
        if result.has("error") and result.has("detail"):
            return {"ok": false, "error": result["error"], "detail": result["detail"]}
        return {"ok": false, "error": "CortexProposalUnavailable", "detail": "Cortex proposal adapter failed closed"}
    if not result.has("proposal"):
        return {"ok": false, "error": "CortexProposalInvalid", "detail": "Cortex proposal adapter returned no proposal"}
    proposal_error = cortex_proposal_error(result["proposal"])
    if len(proposal_error) > 0:
        return {"ok": false, "error": "CortexProposalInvalid", "detail": proposal_error}
    return {"ok": true, "proposal": result["proposal"]}


pub def cortex_capabilities() -> dict[str, any] !{}:
    return {
        "schema": "sema.biological-cortex-capabilities/v1",
        "provider": "Cortex",
        "harness": "omp",
        "model": "openai-codex/gpt-5.6-sol",
        "proposal_endpoint": "/api/sema/cortex/propose",
        "request_schema": "prompt + scenario_id + sema.biological-program-state/v2 + sema.metabolic-immune-observation/v1",
        "response_schema": "sema.biological-llm-proposal/v1",
        "operation_kinds": ["set_signal", "set_parameter"],
        "max_operations": 6,
        "requires_explicit_apply": true,
        "scientific_validated": false,
    }
```

### `src/design.sema`

```sema
"""Bounded de-novo molecular design: natural-language specs turned into computed geometry.

Everything here is exploratory engineering, never a measurement. Structures are built from
published internal coordinates by natural-extension-reference-frame placement and a bounded
steepest-descent relaxation, so every coordinate is computed rather than copied from a table of
positions. Designed structures therefore carry `fidelity: "engineered_unvalidated"`,
`biological_match: "designed_de_novo"` and `scientific_validated: false` downstream: no claim is
made that any of these molecules exists, folds, or binds.
"""

import math
from std.crypto import sha256_json

assure silver


SPEC_SCHEMA = "sema.molecular-design-spec/v1"
MAX_COMMAND_CHARS = 320
MAX_DESIGNS = 16
MAX_DESIGN_ATOMS = 512
MAX_DESIGN_BONDS = 1024
MAX_RESIDUES = 24
MAX_FRAGMENTS = 6
RESIDUE_ALPHABET = "ACDEFGHIKLMNPQRSTVWY"
SIDECHAIN_MODEL = "backbone_plus_truncated_sidechain"
SIDECHAIN_HEAVY_ATOM_LIMIT = 4

BOND_N_CA_ANGSTROM = 1.458
BOND_CA_C_ANGSTROM = 1.525
BOND_C_N_ANGSTROM = 1.329
BOND_C_O_ANGSTROM = 1.231
BOND_CA_CB_ANGSTROM = 1.530
BOND_C_OXT_ANGSTROM = 1.249
ANGLE_N_CA_C_DEGREE = 111.2
ANGLE_CA_C_N_DEGREE = 116.2
ANGLE_C_N_CA_DEGREE = 121.7
ANGLE_CA_C_O_DEGREE = 120.8
ANGLE_C_CA_CB_DEGREE = 110.5
ANGLE_CA_C_OXT_DEGREE = 118.0
DIHEDRAL_N_C_CA_CB_DEGREE = 122.6
OMEGA_DEGREE = 180.0
EXTENDED_PHI_DEGREE = -135.0
EXTENDED_PSI_DEGREE = 135.0
HELIX_PHI_DEGREE = -57.0
HELIX_PSI_DEGREE = -47.0

FRAGMENT_LINK_ANGSTROM = 1.50
SEED_DIHEDRAL_POINT = [0.0, 1.0, 0.0]
SEED_AXIS_POINT = [-1.5, 0.0, 0.0]
GROWTH_LATERAL = 0.55
GROWTH_VERTICAL = 0.35

BOND_STIFFNESS_KJ_PER_MOL_ANGSTROM2 = 4000.0
ANGLE_STIFFNESS_KJ_PER_MOL_ANGSTROM2 = 1200.0
CLASH_CORE_ANGSTROM = 2.70
CLASH_FLOOR_ANGSTROM = 2.60
CORE_EPSILON_KJ_PER_MOL = 8.0
CORE_EPSILON_ESCALATED_KJ_PER_MOL = 48.0
MIN_SEPARATION_ANGSTROM = 0.5
NEIGHBOUR_SKIN_ANGSTROM = 2.0
NEIGHBOUR_REBUILD_STEPS = 24
PEPTIDE_RELAXATION_STEPS = 200
MOLECULE_RELAXATION_STEPS = 320
INITIAL_STEP = 0.0005
STEP_GROWTH = 1.3
STEP_SHRINK = 0.4
MAX_DISPLACEMENT_ANGSTROM = 0.05
FORCE_TOLERANCE_KJ_PER_MOL_ANGSTROM = 1.0
UNIT_SCALE = 0.1


def design_target_keys():
    return [
        "insulin",
        "glucagon",
        "somatostatin",
        "pancreatic_polypeptide",
        "amylase",
        "adiponectin",
        "interleukin_1_beta",
        "von_willebrand_a1",
        "b_dna",
        "hemoglobin",
    ]


def design_mechanisms():
    return [
        "secretion_agonist",
        "secretion_antagonist",
        "cytokine_inhibitor",
        "immune_shield",
        "insulin_analog",
        "inert",
    ]


def design_fragment_names():
    return [
        "benzene",
        "cyclohexane",
        "phenol",
        "carboxyl",
        "amine",
        "amide",
        "sulfonyl",
        "sulfonylurea",
        "hydroxyl",
        "methyl",
        "ethyl",
        "guanidine",
        "imidazole",
        "glucosyl",
    ]


def listed(values: list[str], value: str):
    return any(candidate == value for candidate in values)


def element_name(atomic_number: int):
    if atomic_number == 6:
        return "Carbon"
    if atomic_number == 7:
        return "Nitrogen"
    if atomic_number == 8:
        return "Oxygen"
    if atomic_number == 16:
        return "Sulfur"
    return "Unmapped element"


def atomic_radius(atomic_number: int, radius_kind: str):
    if atomic_number == 6:
        return 1.70 if radius_kind == "vdw" else 0.76
    if atomic_number == 7:
        return 1.55 if radius_kind == "vdw" else 0.71
    if atomic_number == 8:
        return 1.52 if radius_kind == "vdw" else 0.66
    if atomic_number == 16:
        return 1.80 if radius_kind == "vdw" else 1.05
    return 1.80 if radius_kind == "vdw" else 0.80


def unit_vector(vector: list[f64]):
    length = max(0.000001, math.sqrt(vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2]))
    return [vector[0] / length, vector[1] / length, vector[2] / length]


def cross(left: list[f64], right: list[f64]):
    return [
        left[1] * right[2] - left[2] * right[1],
        left[2] * right[0] - left[0] * right[2],
        left[0] * right[1] - left[1] * right[0],
    ]


def difference(from_point: list[f64], to_point: list[f64]):
    return [to_point[0] - from_point[0], to_point[1] - from_point[1], to_point[2] - from_point[2]]


def point_at(positions: list[f64], atom_index: int):
    offset = atom_index * 3
    return [positions[offset], positions[offset + 1], positions[offset + 2]]


def place_atom(first: list[f64], second: list[f64], third: list[f64], bond_angstrom: f64, angle_degree: f64, dihedral_degree: f64):
    sem "Natural extension reference frame: place one atom bonded to `third` from a bond length, the valence angle second-third-new, and the IUPAC torsion first-second-third-new"
    require bond_angstrom > 0.0
    theta = angle_degree * math.pi / 180.0
    phi = dihedral_degree * math.pi / 180.0
    axis = unit_vector(difference(second, third))
    normal = unit_vector(cross(difference(first, second), axis))
    side = cross(normal, axis)
    along = -bond_angstrom * math.cos(theta)
    lateral = bond_angstrom * math.sin(theta) * math.cos(phi)
    outward = bond_angstrom * math.sin(theta) * math.sin(phi)
    return [third[a] + along * axis[a] + lateral * side[a] + outward * normal[a] for a in range(3)]


def rotation_between(source: list[f64], target: list[f64]):
    """Rodrigues rotation matrix (row-major, flat 9) carrying unit `source` onto unit `target`."""
    u = unit_vector(source)
    v = unit_vector(target)
    axis = cross(u, v)
    sine = math.sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2])
    cosine = u[0] * v[0] + u[1] * v[1] + u[2] * v[2]
    if sine < 0.000001 and cosine >= 0.0:
        return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
    if sine < 0.000001:
        p = unit_vector(cross(u, [0.0, 1.0, 0.0] if abs(u[0]) > 0.9 else [1.0, 0.0, 0.0]))
        return [
            2.0 * p[0] * p[0] - 1.0, 2.0 * p[0] * p[1], 2.0 * p[0] * p[2],
            2.0 * p[1] * p[0], 2.0 * p[1] * p[1] - 1.0, 2.0 * p[1] * p[2],
            2.0 * p[2] * p[0], 2.0 * p[2] * p[1], 2.0 * p[2] * p[2] - 1.0,
        ]
    k = [axis[0] / sine, axis[1] / sine, axis[2] / sine]
    rest = 1.0 - cosine
    return [
        cosine + rest * k[0] * k[0], rest * k[0] * k[1] - sine * k[2], rest * k[0] * k[2] + sine * k[1],
        rest * k[1] * k[0] + sine * k[2], cosine + rest * k[1] * k[1], rest * k[1] * k[2] - sine * k[0],
        rest * k[2] * k[0] - sine * k[1], rest * k[2] * k[1] + sine * k[0], cosine + rest * k[2] * k[2],
    ]


def rotated(matrix: list[f64], vector: list[f64]):
    return [
        matrix[0] * vector[0] + matrix[1] * vector[1] + matrix[2] * vector[2],
        matrix[3] * vector[0] + matrix[4] * vector[1] + matrix[5] * vector[2],
        matrix[6] * vector[0] + matrix[7] * vector[1] + matrix[8] * vector[2],
    ]


def residue_three_letter(code: str):
    names = {
        "A": "ALA", "C": "CYS", "D": "ASP", "E": "GLU", "F": "PHE",
        "G": "GLY", "H": "HIS", "I": "ILE", "K": "LYS", "L": "LEU",
        "M": "MET", "N": "ASN", "P": "PRO", "Q": "GLN", "R": "ARG",
        "S": "SER", "T": "THR", "V": "VAL", "W": "TRP", "Y": "TYR",
    }
    return names[code]


def residue_charge(code: str):
    """Side-chain formal charge at pH 7.4; the free N- and C-termini cancel and are omitted."""
    if code == "D" or code == "E":
        return -1.0
    if code == "K" or code == "R":
        return 1.0
    return 0.0


def residue_sidechains():
    """Truncated side chains beyond C-beta as internal coordinates.

    Every row is `[atom name, atomic number, torsion reference, angle reference, bonded parent,
    bond length in angstrom, valence angle in degrees, torsion in degrees]`; references -3, -2 and
    -1 are backbone N, CA and CB and a non-negative reference is an earlier row of the same
    residue. At most four heavy atoms are emitted per side chain, so anything past the delta shell
    is truncated - the structure declares this through `sidechain_model`.
    """
    return {
        "G": [],
        "A": [],
        "S": [["OG", 8, -3, -2, -1, 1.417, 110.8, -60.0]],
        "C": [["SG", 16, -3, -2, -1, 1.808, 114.0, -60.0]],
        "T": [["OG1", 8, -3, -2, -1, 1.433, 109.6, -60.0], ["CG2", 6, -3, -2, -1, 1.521, 110.5, 60.0]],
        "V": [["CG1", 6, -3, -2, -1, 1.521, 110.5, -60.0], ["CG2", 6, -3, -2, -1, 1.521, 110.5, 60.0]],
        "P": [["CG", 6, -3, -2, -1, 1.492, 106.1, 16.5], ["CD", 6, -2, -1, 0, 1.503, 104.5, -8.0]],
        "L": [["CG", 6, -3, -2, -1, 1.530, 116.3, -60.0], ["CD1", 6, -2, -1, 0, 1.521, 110.7, 175.0], ["CD2", 6, -2, -1, 0, 1.521, 110.7, -60.0]],
        "I": [["CG1", 6, -3, -2, -1, 1.530, 110.4, -60.0], ["CG2", 6, -3, -2, -1, 1.521, 110.5, 60.0], ["CD1", 6, -2, -1, 0, 1.521, 113.8, 170.0]],
        "M": [["CG", 6, -3, -2, -1, 1.520, 114.1, -60.0], ["SD", 16, -2, -1, 0, 1.803, 112.7, 180.0], ["CE", 6, -1, 0, 1, 1.791, 100.9, 75.0]],
        "F": [["CG", 6, -3, -2, -1, 1.502, 113.8, -60.0], ["CD1", 6, -2, -1, 0, 1.384, 120.8, 90.0], ["CD2", 6, -2, -1, 0, 1.384, 120.8, -90.0], ["CE1", 6, -1, 0, 1, 1.382, 120.8, 180.0]],
        "Y": [["CG", 6, -3, -2, -1, 1.512, 113.8, -60.0], ["CD1", 6, -2, -1, 0, 1.389, 120.8, 90.0], ["CD2", 6, -2, -1, 0, 1.389, 120.8, -90.0], ["CE1", 6, -1, 0, 1, 1.382, 121.1, 180.0]],
        "W": [["CG", 6, -3, -2, -1, 1.498, 113.6, -60.0], ["CD1", 6, -2, -1, 0, 1.365, 127.0, 90.0], ["CD2", 6, -2, -1, 0, 1.433, 126.6, -90.0], ["NE1", 7, -1, 0, 1, 1.375, 110.2, 180.0]],
        "H": [["CG", 6, -3, -2, -1, 1.497, 113.8, -60.0], ["ND1", 7, -2, -1, 0, 1.378, 122.7, 90.0], ["CD2", 6, -2, -1, 0, 1.354, 131.0, -90.0], ["CE1", 6, -1, 0, 1, 1.321, 109.3, 180.0]],
        "N": [["CG", 6, -3, -2, -1, 1.516, 112.6, -60.0], ["OD1", 8, -2, -1, 0, 1.231, 120.8, -30.0], ["ND2", 7, -2, -1, 0, 1.328, 116.4, 150.0]],
        "D": [["CG", 6, -3, -2, -1, 1.516, 112.6, -60.0], ["OD1", 8, -2, -1, 0, 1.249, 118.4, -30.0], ["OD2", 8, -2, -1, 0, 1.249, 118.4, 150.0]],
        "Q": [["CG", 6, -3, -2, -1, 1.520, 114.1, -60.0], ["CD", 6, -2, -1, 0, 1.516, 112.6, 180.0], ["OE1", 8, -1, 0, 1, 1.231, 120.8, -30.0], ["NE2", 7, -1, 0, 1, 1.328, 116.4, 150.0]],
        "E": [["CG", 6, -3, -2, -1, 1.520, 114.1, -60.0], ["CD", 6, -2, -1, 0, 1.516, 112.6, 180.0], ["OE1", 8, -1, 0, 1, 1.249, 118.4, -30.0], ["OE2", 8, -1, 0, 1, 1.249, 118.4, 150.0]],
        "K": [["CG", 6, -3, -2, -1, 1.520, 114.1, -60.0], ["CD", 6, -2, -1, 0, 1.520, 111.3, 180.0], ["CE", 6, -1, 0, 1, 1.520, 111.3, 180.0], ["NZ", 7, 0, 1, 2, 1.489, 111.9, 180.0]],
        "R": [["CG", 6, -3, -2, -1, 1.520, 114.1, -60.0], ["CD", 6, -2, -1, 0, 1.520, 111.3, 180.0], ["NE", 7, -1, 0, 1, 1.461, 111.8, 180.0], ["CZ", 6, 0, 1, 2, 1.329, 124.2, 180.0]],
    }


def fragment_template(name: str) -> dict[str, any]:
    """Literature internal coordinates for one attachable fragment.

    Rings are generated from their bond length and ring size; every other atom is an
    `[name, atomic number, torsion reference, angle reference, bonded parent, bond, angle,
    torsion]` row placed by the same reference-frame routine as the peptide backbone. References
    -2 and -1 are the two virtual seed points that define the incoming bond direction, a
    non-negative reference indexes an atom already placed in this fragment, and a zero bond length
    means the atom is the fragment head sitting at the local origin. `head` bonds to the previous
    fragment and `tail` carries the growing chain onward.
    """
    if name == "benzene":
        return {"tag": "BEN", "charge_e": 0.0, "ring": 6, "ring_bond": 1.390, "ring_pucker": 0.0, "ring_elements": [6, 6, 6, 6, 6, 6], "extras": [], "extra_bonds": [], "head": 0, "tail": 3}
    if name == "cyclohexane":
        return {"tag": "CHX", "charge_e": 0.0, "ring": 6, "ring_bond": 1.530, "ring_pucker": 0.25, "ring_elements": [6, 6, 6, 6, 6, 6], "extras": [], "extra_bonds": [], "head": 0, "tail": 3}
    if name == "phenol":
        return {"tag": "PHO", "charge_e": 0.0, "ring": 6, "ring_bond": 1.390, "ring_pucker": 0.0, "ring_elements": [6, 6, 6, 6, 6, 6], "extras": [["O1", 8, 0, 1, 2, 1.362, 120.0, 180.0]], "extra_bonds": [[2, 6]], "head": 0, "tail": 3}
    if name == "imidazole":
        return {"tag": "IMD", "charge_e": 0.0, "ring": 5, "ring_bond": 1.360, "ring_pucker": 0.0, "ring_elements": [7, 6, 7, 6, 6], "extras": [], "extra_bonds": [], "head": 0, "tail": 3}
    if name == "glucosyl":
        return {"tag": "GLC", "charge_e": 0.0, "ring": 6, "ring_bond": 1.492, "ring_pucker": 0.25, "ring_elements": [6, 6, 6, 6, 6, 8], "extras": [["O2", 8, 5, 0, 1, 1.430, 109.5, 180.0], ["O3", 8, 0, 1, 2, 1.430, 109.5, 180.0], ["C6", 6, 2, 3, 4, 1.520, 111.0, 180.0], ["O6", 8, 3, 4, 8, 1.430, 111.0, 180.0]], "extra_bonds": [[1, 6], [2, 7], [4, 8], [8, 9]], "head": 0, "tail": 3}
    if name == "methyl":
        return {"tag": "MET", "charge_e": 0.0, "ring": 0, "ring_bond": 0.0, "ring_pucker": 0.0, "ring_elements": [], "extras": [["C1", 6, 0, 0, 0, 0.0, 0.0, 0.0]], "extra_bonds": [], "head": 0, "tail": 0}
    if name == "hydroxyl":
        return {"tag": "OHX", "charge_e": 0.0, "ring": 0, "ring_bond": 0.0, "ring_pucker": 0.0, "ring_elements": [], "extras": [["O1", 8, 0, 0, 0, 0.0, 0.0, 0.0]], "extra_bonds": [], "head": 0, "tail": 0}
    if name == "amine":
        return {"tag": "NH2", "charge_e": 1.0, "ring": 0, "ring_bond": 0.0, "ring_pucker": 0.0, "ring_elements": [], "extras": [["N1", 7, 0, 0, 0, 0.0, 0.0, 0.0]], "extra_bonds": [], "head": 0, "tail": 0}
    if name == "ethyl":
        return {"tag": "ETY", "charge_e": 0.0, "ring": 0, "ring_bond": 0.0, "ring_pucker": 0.0, "ring_elements": [], "extras": [["C1", 6, 0, 0, 0, 0.0, 0.0, 0.0], ["C2", 6, -2, -1, 0, 1.530, 111.0, 180.0]], "extra_bonds": [[0, 1]], "head": 0, "tail": 1}
    if name == "carboxyl":
        return {"tag": "COO", "charge_e": -1.0, "ring": 0, "ring_bond": 0.0, "ring_pucker": 0.0, "ring_elements": [], "extras": [["C1", 6, 0, 0, 0, 0.0, 0.0, 0.0], ["O1", 8, -2, -1, 0, 1.230, 120.0, 0.0], ["O2", 8, -2, -1, 0, 1.312, 117.0, 180.0]], "extra_bonds": [[0, 1], [0, 2]], "head": 0, "tail": 2}
    if name == "amide":
        return {"tag": "AMD", "charge_e": 0.0, "ring": 0, "ring_bond": 0.0, "ring_pucker": 0.0, "ring_elements": [], "extras": [["C1", 6, 0, 0, 0, 0.0, 0.0, 0.0], ["O1", 8, -2, -1, 0, 1.230, 120.5, 0.0], ["N1", 7, -2, -1, 0, 1.335, 116.5, 180.0]], "extra_bonds": [[0, 1], [0, 2]], "head": 0, "tail": 2}
    if name == "sulfonyl":
        return {"tag": "SO2", "charge_e": 0.0, "ring": 0, "ring_bond": 0.0, "ring_pucker": 0.0, "ring_elements": [], "extras": [["S1", 16, 0, 0, 0, 0.0, 0.0, 0.0], ["O1", 8, -2, -1, 0, 1.440, 108.0, 60.0], ["O2", 8, -2, -1, 0, 1.440, 108.0, -60.0]], "extra_bonds": [[0, 1], [0, 2]], "head": 0, "tail": 0}
    if name == "sulfonylurea":
        return {"tag": "SUR", "charge_e": 0.0, "ring": 0, "ring_bond": 0.0, "ring_pucker": 0.0, "ring_elements": [], "extras": [["S1", 16, 0, 0, 0, 0.0, 0.0, 0.0], ["O1", 8, -2, -1, 0, 1.440, 108.0, 60.0], ["O2", 8, -2, -1, 0, 1.440, 108.0, -60.0], ["N1", 7, -2, -1, 0, 1.633, 106.0, 180.0], ["C1", 6, -1, 0, 3, 1.380, 122.0, 180.0], ["O3", 8, 0, 3, 4, 1.226, 121.5, 0.0], ["N2", 7, 0, 3, 4, 1.340, 115.0, 180.0]], "extra_bonds": [[0, 1], [0, 2], [0, 3], [3, 4], [4, 5], [4, 6]], "head": 0, "tail": 6}
    return {"tag": "GUA", "charge_e": 1.0, "ring": 0, "ring_bond": 0.0, "ring_pucker": 0.0, "ring_elements": [], "extras": [["N1", 7, 0, 0, 0, 0.0, 0.0, 0.0], ["C1", 6, -2, -1, 0, 1.329, 124.0, 180.0], ["N2", 7, -1, 0, 1, 1.329, 120.0, 0.0], ["N3", 7, -1, 0, 1, 1.329, 120.0, 180.0]], "extra_bonds": [[0, 1], [1, 2], [1, 3]], "head": 0, "tail": 3}


def build_fragment(name: str):
    """Instantiate one fragment in a local frame with its head at the origin and its head-to-tail
    axis on +x, so the chain builder can drop it onto a growth direction with one rotation."""
    template = fragment_template(name)
    ring_size = template["ring"]
    pucker = template["ring_pucker"]
    mut points: list[list[f64]] = []
    mut atomic_numbers: list[int] = []
    mut atom_names: list[str] = []
    mut bonds: list[int] = []
    if ring_size > 0:
        # A regular ring: the in-plane radius follows from the bond length once the alternating
        # chair displacement is removed, so the emitted bonds are exactly `ring_bond` long.
        radius = math.sqrt(max(0.000001, template["ring_bond"] * template["ring_bond"] - 4.0 * pucker * pucker)) / (2.0 * math.sin(math.pi / ring_size))
        for vertex in range(ring_size):
            angle = math.pi - 2.0 * math.pi * vertex / ring_size
            element = template["ring_elements"][vertex]
            points.append([radius * math.cos(angle), radius * math.sin(angle), pucker if vertex % 2 == 0 else -pucker])
            atomic_numbers.append(element)
            atom_names.append(("C" if element == 6 else ("N" if element == 7 else "O")) + str(vertex + 1))
            bonds.append(vertex)
            bonds.append((vertex + 1) % ring_size)
    for row in template["extras"]:
        if row[5] == 0.0:
            points.append([0.0, 0.0, 0.0])
        else:
            first = SEED_DIHEDRAL_POINT if row[2] == -2 else (SEED_AXIS_POINT if row[2] == -1 else points[row[2]])
            second = SEED_DIHEDRAL_POINT if row[3] == -2 else (SEED_AXIS_POINT if row[3] == -1 else points[row[3]])
            third = SEED_DIHEDRAL_POINT if row[4] == -2 else (SEED_AXIS_POINT if row[4] == -1 else points[row[4]])
            points.append(place_atom(first, second, third, row[5], row[6], row[7]))
        atomic_numbers.append(row[1])
        atom_names.append(row[0])
    for pair in template["extra_bonds"]:
        bonds.append(pair[0])
        bonds.append(pair[1])
    head = points[template["head"]]
    mut local = [[point[a] - head[a] for a in range(3)] for point in points]
    if template["tail"] != template["head"]:
        alignment = rotation_between(local[template["tail"]], [1.0, 0.0, 0.0])
        local = [rotated(alignment, point) for point in local]
    return {
        "points": local,
        "atomic_numbers": atomic_numbers,
        "atom_names": atom_names,
        "bonds": bonds,
        "head": template["head"],
        "tail": template["tail"],
        "tag": template["tag"],
    }


def new_build():
    return {
        "positions": [],
        "atomic_numbers": [],
        "labels": [],
        "mobile": [],
        "bonds": [],
        "fragment_of": [],
        "trace": [],
    }


def add_atom(built: dict[str, any], position: list[f64], atomic_number: int, label: str, mobile: bool, group: int) !{}:
    for axis in range(3):
        built["positions"].append(position[axis])
    built["atomic_numbers"].append(atomic_number)
    built["labels"].append(label)
    built["mobile"].append(mobile)
    built["fragment_of"].append(group)
    return len(built["atomic_numbers"]) - 1


def add_bond(built: dict[str, any], left: int, right: int) !{}:
    built["bonds"].append(left)
    built["bonds"].append(right)


def build_peptide(spec: dict[str, any]) !{}:
    """Grow the backbone and truncated side chains residue by residue from standard internal
    coordinates; only the side-chain atoms are later relaxed so the backbone torsions stay exact."""
    sequence = spec["sequence"]
    helix = spec["conformation"] == "helix"
    phi = HELIX_PHI_DEGREE if helix else EXTENDED_PHI_DEGREE
    psi = HELIX_PSI_DEGREE if helix else EXTENDED_PSI_DEGREE
    table = residue_sidechains()
    mut built = new_build()
    mut previous = [-1, -1, -1]
    for residue_index in range(len(sequence)):
        code = sequence.slice(residue_index, residue_index + 1)
        prefix = "A:" + str(residue_index + 1) + ":" + residue_three_letter(code) + ":"
        if previous[0] < 0:
            nitrogen = [0.0, 0.0, 0.0]
            alpha = [BOND_N_CA_ANGSTROM, 0.0, 0.0]
            carbon = place_atom(SEED_DIHEDRAL_POINT, nitrogen, alpha, BOND_CA_C_ANGSTROM, ANGLE_N_CA_C_DEGREE, phi)
        else:
            nitrogen = place_atom(point_at(built["positions"], previous[0]), point_at(built["positions"], previous[1]), point_at(built["positions"], previous[2]), BOND_C_N_ANGSTROM, ANGLE_CA_C_N_DEGREE, psi)
            alpha = place_atom(point_at(built["positions"], previous[1]), point_at(built["positions"], previous[2]), nitrogen, BOND_N_CA_ANGSTROM, ANGLE_C_N_CA_DEGREE, OMEGA_DEGREE)
            carbon = place_atom(point_at(built["positions"], previous[2]), nitrogen, alpha, BOND_CA_C_ANGSTROM, ANGLE_N_CA_C_DEGREE, phi)
        oxygen = place_atom(nitrogen, alpha, carbon, BOND_C_O_ANGSTROM, ANGLE_CA_C_O_DEGREE, psi + 180.0)
        nitrogen_index = add_atom(built, nitrogen, 7, prefix + "N", false, residue_index)
        alpha_index = add_atom(built, alpha, 6, prefix + "CA", false, residue_index)
        carbon_index = add_atom(built, carbon, 6, prefix + "C", false, residue_index)
        oxygen_index = add_atom(built, oxygen, 8, prefix + "O", false, residue_index)
        add_bond(built, nitrogen_index, alpha_index)
        add_bond(built, alpha_index, carbon_index)
        add_bond(built, carbon_index, oxygen_index)
        if previous[0] >= 0:
            add_bond(built, previous[2], nitrogen_index)
        for axis in range(3):
            built["trace"].append(alpha[axis])
        previous = [nitrogen_index, alpha_index, carbon_index]
        if code == "G":
            continue
        beta = place_atom(nitrogen, carbon, alpha, BOND_CA_CB_ANGSTROM, ANGLE_C_CA_CB_DEGREE, DIHEDRAL_N_C_CA_CB_DEGREE)
        mut slots = [nitrogen_index, alpha_index, add_atom(built, beta, 6, prefix + "CB", true, residue_index)]
        add_bond(built, alpha_index, slots[2])
        for row in table[code]:
            placed = place_atom(point_at(built["positions"], slots[row[2] + 3]), point_at(built["positions"], slots[row[3] + 3]), point_at(built["positions"], slots[row[4] + 3]), row[5], row[6], row[7])
            index = add_atom(built, placed, row[1], prefix + row[0], true, residue_index)
            add_bond(built, slots[row[4] + 3], index)
            slots.append(index)
        if code == "P":
            # Proline's pyrrolidine ring closes back onto the backbone nitrogen through CD.
            add_bond(built, slots[4], nitrogen_index)
    last = len(sequence) - 1
    terminal = place_atom(point_at(built["positions"], previous[0]), point_at(built["positions"], previous[1]), point_at(built["positions"], previous[2]), BOND_C_OXT_ANGSTROM, ANGLE_CA_C_OXT_DEGREE, psi)
    add_bond(built, previous[2], add_atom(built, terminal, 8, "A:" + str(last + 1) + ":" + residue_three_letter(sequence.slice(last, last + 1)) + ":OXT", false, last))
    built["max_steps"] = PEPTIDE_RELAXATION_STEPS
    return built


def build_molecule(spec: dict[str, any]) !{}:
    """Attach fragment templates head to tail along a zig-zagging growth axis so the initial guess
    is an extended chain rather than a stack; the relaxation then resolves the linkage geometry."""
    mut built = new_build()
    mut cursor = [0.0, 0.0, 0.0]
    mut previous_tail = -1
    for fragment_index in range(len(spec["fragments"])):
        fragment = build_fragment(spec["fragments"][fragment_index])
        direction = unit_vector([
            1.0,
            GROWTH_LATERAL if fragment_index % 2 == 0 else -GROWTH_LATERAL,
            GROWTH_VERTICAL if (fragment_index // 2) % 2 == 0 else -GROWTH_VERTICAL,
        ])
        placement = rotation_between([1.0, 0.0, 0.0], direction)
        base = len(built["atomic_numbers"])
        prefix = "L:" + str(fragment_index + 1) + ":" + fragment["tag"] + ":"
        for atom in range(len(fragment["atomic_numbers"])):
            turned = rotated(placement, fragment["points"][atom])
            add_atom(built, [turned[a] + cursor[a] for a in range(3)], fragment["atomic_numbers"][atom], prefix + fragment["atom_names"][atom], true, fragment_index)
        for entry in range(len(fragment["bonds"]) // 2):
            add_bond(built, base + fragment["bonds"][entry * 2], base + fragment["bonds"][entry * 2 + 1])
        if previous_tail >= 0:
            add_bond(built, previous_tail, base + fragment["head"])
        previous_tail = base + fragment["tail"]
        advance = fragment["points"][fragment["tail"]][0] + FRAGMENT_LINK_ANGSTROM
        cursor = [cursor[a] + direction[a] * advance for a in range(3)]
    built["max_steps"] = MOLECULE_RELAXATION_STEPS
    return built


def restraint_field(built: dict[str, any]):
    """Harmonic 1-2 bonds at their as-built length plus 1-3 Urey-Bradley terms.

    Inside a fragment or a residue the 1-3 rest length is the template distance, so the published
    fragment geometry is preserved exactly. Across a head-to-tail link there is no template angle,
    so the rest length comes from the law of cosines on the two bond lengths and the ideal valence
    angle for the central atom's coordination number.
    """
    positions = built["positions"]
    count = len(built["atomic_numbers"])
    bonds = built["bonds"]
    mut excluded = [false for slot in range(count * count)]
    mut left: list[int] = []
    mut right: list[int] = []
    mut length: list[f64] = []
    mut stiffness: list[f64] = []
    mut neighbours = [[] for atom in range(count)]
    mut neighbour_length = [[] for atom in range(count)]
    for entry in range(len(bonds) // 2):
        a = bonds[entry * 2]
        b = bonds[entry * 2 + 1]
        separation = math.sqrt(sum((positions[b * 3 + axis] - positions[a * 3 + axis]) ** 2 for axis in range(3)))
        left.append(a)
        right.append(b)
        length.append(separation)
        stiffness.append(BOND_STIFFNESS_KJ_PER_MOL_ANGSTROM2)
        excluded[a * count + b] = true
        excluded[b * count + a] = true
        neighbours[a].append(b)
        neighbours[b].append(a)
        neighbour_length[a].append(separation)
        neighbour_length[b].append(separation)
    for centre in range(count):
        ideal = math.cos(109.5 * math.pi / 180.0) if len(neighbours[centre]) >= 4 else math.cos(120.0 * math.pi / 180.0)
        for first in range(len(neighbours[centre])):
            for second in range(first + 1, len(neighbours[centre])):
                a = neighbours[centre][first]
                b = neighbours[centre][second]
                if excluded[a * count + b]:
                    continue
                same_group = built["fragment_of"][a] == built["fragment_of"][centre] and built["fragment_of"][b] == built["fragment_of"][centre]
                first_bond = neighbour_length[centre][first]
                second_bond = neighbour_length[centre][second]
                template = math.sqrt(sum((positions[b * 3 + axis] - positions[a * 3 + axis]) ** 2 for axis in range(3)))
                left.append(a)
                right.append(b)
                length.append(template if same_group else math.sqrt(first_bond * first_bond + second_bond * second_bond - 2.0 * first_bond * second_bond * ideal))
                stiffness.append(ANGLE_STIFFNESS_KJ_PER_MOL_ANGSTROM2)
                excluded[a * count + b] = true
                excluded[b * count + a] = true
    return {
        "count": count,
        "mobile": built["mobile"],
        "excluded": excluded,
        "restraint_left": left,
        "restraint_right": right,
        "restraint_length": length,
        "restraint_stiffness": stiffness,
        "neighbour_left": [],
        "neighbour_right": [],
    }


def rebuild_neighbours(field: dict[str, any], positions: list[f64]):
    """Verlet candidate list: only pairs inside the repulsive core plus a skin can ever clash, and
    a pair of frozen atoms contributes a constant energy so it never changes the line search."""
    count = field["count"]
    limit = (CLASH_CORE_ANGSTROM + NEIGHBOUR_SKIN_ANGSTROM) ** 2
    mut left: list[int] = []
    mut right: list[int] = []
    for a in range(count):
        for b in range(a + 1, count):
            if field["excluded"][a * count + b] or (not field["mobile"][a] and not field["mobile"][b]):
                continue
            if sum((positions[b * 3 + axis] - positions[a * 3 + axis]) ** 2 for axis in range(3)) < limit:
                left.append(a)
                right.append(b)
    field["neighbour_left"] = left
    field["neighbour_right"] = right


def relaxation_energy(field: dict[str, any], positions: list[f64], forces: list[f64]):
    """Harmonic restraints plus a purely repulsive r^-12 core truncated and shifted to zero at
    `CLASH_CORE_ANGSTROM`. Fills `forces` with -dE/dx and returns the energy in kJ/mol."""
    for slot in range(len(forces)):
        forces[slot] = 0.0
    mut energy = 0.0
    for entry in range(len(field["restraint_length"])):
        a = field["restraint_left"][entry] * 3
        b = field["restraint_right"][entry] * 3
        dx = positions[b] - positions[a]
        dy = positions[b + 1] - positions[a + 1]
        dz = positions[b + 2] - positions[a + 2]
        separation = max(MIN_SEPARATION_ANGSTROM, math.sqrt(dx * dx + dy * dy + dz * dz))
        stretch = separation - field["restraint_length"][entry]
        gradient = 2.0 * field["restraint_stiffness"][entry] * stretch / separation
        energy = energy + field["restraint_stiffness"][entry] * stretch * stretch
        forces[a] = forces[a] + gradient * dx
        forces[a + 1] = forces[a + 1] + gradient * dy
        forces[a + 2] = forces[a + 2] + gradient * dz
        forces[b] = forces[b] - gradient * dx
        forces[b + 1] = forces[b + 1] - gradient * dy
        forces[b + 2] = forces[b + 2] - gradient * dz
    for pair in range(len(field["neighbour_left"])):
        a = field["neighbour_left"][pair] * 3
        b = field["neighbour_right"][pair] * 3
        dx = positions[b] - positions[a]
        dy = positions[b + 1] - positions[a + 1]
        dz = positions[b + 2] - positions[a + 2]
        separation = max(MIN_SEPARATION_ANGSTROM, math.sqrt(dx * dx + dy * dy + dz * dz))
        if separation >= CLASH_CORE_ANGSTROM:
            continue
        cube = (CLASH_CORE_ANGSTROM / separation) ** 3
        power = cube * cube * cube * cube
        gradient = 12.0 * field["epsilon"] * power / (separation * separation)
        energy = energy + field["epsilon"] * (power - 1.0)
        forces[a] = forces[a] - gradient * dx
        forces[a + 1] = forces[a + 1] - gradient * dy
        forces[a + 2] = forces[a + 2] - gradient * dz
        forces[b] = forces[b] + gradient * dx
        forces[b + 1] = forces[b + 1] + gradient * dy
        forces[b + 2] = forces[b + 2] + gradient * dz
    for atom in range(field["count"]):
        if not field["mobile"][atom]:
            for axis in range(3):
                forces[atom * 3 + axis] = 0.0
    return energy


def minimise(field: dict[str, any], positions: list[f64], max_steps: int, epsilon: f64):
    """Bounded steepest descent with a backtracking step: accept a trial move only when it lowers
    the energy, otherwise shrink the step. Deterministic and capped at `max_steps` evaluations."""
    field["epsilon"] = epsilon
    mut current = [coordinate for coordinate in positions]
    mut trial = [coordinate for coordinate in positions]
    mut forces = [0.0 for coordinate in positions]
    mut trial_forces = [0.0 for coordinate in positions]
    rebuild_neighbours(field, current)
    mut energy = relaxation_energy(field, current, forces)
    mut step = INITIAL_STEP
    mut used = 0
    mut max_force = 0.0
    for iteration in range(max_steps):
        if iteration > 0 and iteration % NEIGHBOUR_REBUILD_STEPS == 0:
            rebuild_neighbours(field, current)
            energy = relaxation_energy(field, current, forces)
        max_force = 0.0
        for atom in range(field["count"]):
            offset = atom * 3
            max_force = max(max_force, math.sqrt(forces[offset] ** 2 + forces[offset + 1] ** 2 + forces[offset + 2] ** 2))
        used = iteration + 1
        if max_force < FORCE_TOLERANCE_KJ_PER_MOL_ANGSTROM:
            break
        scale = min(step, MAX_DISPLACEMENT_ANGSTROM / max_force)
        for slot in range(len(current)):
            trial[slot] = current[slot] + scale * forces[slot]
        candidate = relaxation_energy(field, trial, trial_forces)
        if candidate < energy:
            for slot in range(len(current)):
                current[slot] = trial[slot]
                forces[slot] = trial_forces[slot]
            energy = candidate
            step = step * STEP_GROWTH
        else:
            step = step * STEP_SHRINK
    return {"positions": current, "steps": used, "max_force": max_force}


def minimum_free_separation(field: dict[str, any], positions: list[f64]):
    """Closest approach over heavy-atom pairs that are more than two bonds apart; 1-2 and 1-3 pairs
    are covalent geometry (a ring's meta carbons sit at 2.4 angstrom by construction) and excluded."""
    count = field["count"]
    mut closest = 1000.0
    for a in range(count):
        for b in range(a + 1, count):
            if field["excluded"][a * count + b]:
                continue
            closest = min(closest, math.sqrt(sum((positions[b * 3 + axis] - positions[a * 3 + axis]) ** 2 for axis in range(3))))
    return closest


def relax_build(built: dict[str, any]):
    field = restraint_field(built)
    relaxed = minimise(field, built["positions"], built["max_steps"], CORE_EPSILON_KJ_PER_MOL)
    if minimum_free_separation(field, relaxed["positions"]) >= CLASH_FLOOR_ANGSTROM:
        return relaxed
    escalated = minimise(field, relaxed["positions"], built["max_steps"], CORE_EPSILON_ESCALATED_KJ_PER_MOL)
    return {"positions": escalated["positions"], "steps": relaxed["steps"] + escalated["steps"], "max_force": escalated["max_force"]}


def design_compile_error(detail: str):
    return {"ok": false, "error": "DesignCompileError", "detail": detail}


def spec_core(name: str, label: str, design_class: str, conformation: str, sequence: str, fragments: list[str], target_key: str, mechanism: str, charge_e: f64):
    return {
        "schema": SPEC_SCHEMA,
        "name": name,
        "label": label,
        "class": design_class,
        "conformation": conformation,
        "sequence": sequence,
        "fragments": fragments,
        "target_key": target_key,
        "mechanism": mechanism,
        "charge_e": charge_e,
    }


def sealed_spec(core: dict[str, any]) !{}:
    mut sealed = {key: value for key, value in core.items()}
    sealed["spec_sha256"] = sha256_json(core)
    return sealed


def targeting_suffix(target_key: str):
    return "" if len(target_key) == 0 else " targeting " + target_key


def peptide_spec(form: str, raw_sequence: str, name: str, target_key: str) !{}:
    if len(target_key) > 0 and not listed(design_target_keys(), target_key):
        return design_compile_error("targeting key is not a bounded molecular library key")
    sequence = raw_sequence.upper()
    conformation = "helix" if form == "helix" else "extended"
    charge = sum(residue_charge(sequence.slice(index, index + 1)) for index in range(len(sequence)))
    label = name + " - designed " + conformation + " peptide " + sequence + ", backbone N/CA/C/O plus CB with side chains truncated to at most " + str(SIDECHAIN_HEAVY_ATOM_LIMIT) + " heavy atoms beyond CB" + targeting_suffix(target_key)
    return {"ok": true, "kind": "design", "name": name, "spec": sealed_spec(spec_core(name, label, "peptide", conformation, sequence, [], target_key, "inert", charge))}


def molecule_spec(raw_fragments: str, name: str, target_key: str) !{}:
    if len(target_key) > 0 and not listed(design_target_keys(), target_key):
        return design_compile_error("targeting key is not a bounded molecular library key")
    fragments = raw_fragments.split("+")
    if len(fragments) > MAX_FRAGMENTS:
        return design_compile_error("a designed molecule may chain at most " + str(MAX_FRAGMENTS) + " fragments")
    known = design_fragment_names()
    for fragment in fragments:
        if not listed(known, fragment):
            return design_compile_error("unknown fragment '" + fragment + "'; the library is " + ", ".join(known))
    charge = sum(fragment_template(fragment)["charge_e"] for fragment in fragments)
    label = name + " - designed small molecule " + "+".join(fragments) + ", fragment templates linked head to tail and relaxed" + targeting_suffix(target_key)
    return {"ok": true, "kind": "design", "name": name, "spec": sealed_spec(spec_core(name, label, "small_molecule", "extended", "", fragments, target_key, "inert", charge))}


pub def compile_design_command(command: str) -> dict[str, any] !{}:
    sem "Compile one bounded natural-language molecular design instruction into a sealed design spec"
    if len(command) == 0 or len(command) > MAX_COMMAND_CHARS:
        return design_compile_error("command must contain 1..320 characters")
    text = command.lower().strip()
    match text:
        # Match "design peptide <one-letter sequence> as <handle>" with no targeting clause.
        case re"^design peptide (?P<sequence>[acdefghiklmnpqrstvwy]{1,24}) as (?P<name>[a-z][a-z0-9-]{0,23})$":
            return peptide_spec("peptide", sequence, name, "")
        # Match the same extended-peptide command followed by a "targeting <library key>" clause.
        case re"^design peptide (?P<sequence>[acdefghiklmnpqrstvwy]{1,24}) as (?P<name>[a-z][a-z0-9-]{0,23}) targeting (?P<target>[a-z0-9_]{1,32})$":
            return peptide_spec("peptide", sequence, name, target)
        # Match "design helix <one-letter sequence> as <handle>" with no targeting clause.
        case re"^design helix (?P<sequence>[acdefghiklmnpqrstvwy]{1,24}) as (?P<name>[a-z][a-z0-9-]{0,23})$":
            return peptide_spec("helix", sequence, name, "")
        # Match the same alpha-helix command followed by a "targeting <library key>" clause.
        case re"^design helix (?P<sequence>[acdefghiklmnpqrstvwy]{1,24}) as (?P<name>[a-z][a-z0-9-]{0,23}) targeting (?P<target>[a-z0-9_]{1,32})$":
            return peptide_spec("helix", sequence, name, target)
        # Match "design molecule <fragment>[+<fragment>]... as <handle>" with no targeting clause.
        case re"^design molecule (?P<fragments>[a-z]+(\+[a-z]+)*) as (?P<name>[a-z][a-z0-9-]{0,23})$":
            return molecule_spec(fragments, name, "")
        # Match the same molecule command followed by a "targeting <library key>" clause.
        case re"^design molecule (?P<fragments>[a-z]+(\+[a-z]+)*) as (?P<name>[a-z][a-z0-9-]{0,23}) targeting (?P<target>[a-z0-9_]{1,32})$":
            return molecule_spec(fragments, name, target)
        # Match "set mechanism of <handle> to <mechanism>" for an already designed species.
        case re"^set mechanism of (?P<name>[a-z][a-z0-9-]{0,23}) to (?P<mechanism>[a-z_]{1,32})$":
            if not listed(design_mechanisms(), mechanism):
                return design_compile_error("unknown mechanism '" + mechanism + "'; supported mechanisms are " + ", ".join(design_mechanisms()))
            return {"ok": true, "kind": "set_mechanism", "name": name, "mechanism": mechanism}
        case _:
            return design_compile_error("command does not match the bounded molecular design grammar")


def design_name_valid(name: str):
    match name:
        # Match a design handle: one lowercase letter then up to 23 letters, digits or hyphens.
        case re"^[a-z][a-z0-9-]{0,23}$":
            return true
        case _:
            return false


pub def design_spec_valid(spec: dict[str, any]) -> bool !{}:
    sem "Accept only a sealed design spec whose fields are inside every declared bound and whose digest still matches"
    fields = ["schema", "name", "label", "class", "conformation", "sequence", "fragments", "target_key", "mechanism", "charge_e", "spec_sha256"]
    if not all(spec.has(field) for field in fields):
        return false
    if spec["schema"] != SPEC_SCHEMA or not design_name_valid(spec["name"]) or len(spec["label"]) == 0:
        return false
    if not listed(["extended", "helix"], spec["conformation"]) or not listed(design_mechanisms(), spec["mechanism"]):
        return false
    if len(spec["target_key"]) > 0 and not listed(design_target_keys(), spec["target_key"]):
        return false
    if spec["class"] == "peptide":
        sequence = spec["sequence"]
        if len(sequence) == 0 or len(sequence) > MAX_RESIDUES or len(spec["fragments"]) > 0:
            return false
        if not all(RESIDUE_ALPHABET.contains(sequence.slice(index, index + 1)) for index in range(len(sequence))):
            return false
    elif spec["class"] == "small_molecule":
        fragments = spec["fragments"]
        if len(fragments) == 0 or len(fragments) > MAX_FRAGMENTS or len(spec["sequence"]) > 0:
            return false
        if not all(listed(design_fragment_names(), fragment) for fragment in fragments):
            return false
    else:
        return false
    return spec["spec_sha256"] == sha256_json(spec_core(spec["name"], spec["label"], spec["class"], spec["conformation"], spec["sequence"], spec["fragments"], spec["target_key"], spec["mechanism"], spec["charge_e"]))


pub def design_capabilities() -> dict[str, any] !{}:
    return {
        "max_designs": MAX_DESIGNS,
        "max_atoms": MAX_DESIGN_ATOMS,
        "max_bonds": MAX_DESIGN_BONDS,
        "classes": ["peptide", "small_molecule"],
        "mechanisms": design_mechanisms(),
        "fragments": design_fragment_names(),
        "residues": RESIDUE_ALPHABET,
        "examples": [
            "design peptide ACDEFG as probe-1 targeting insulin",
            "design helix eaalkkleaalkk as shield-1 targeting interleukin_1_beta",
            "design molecule benzene+sulfonylurea as sulfa-1",
            "design molecule phenol+carboxyl+glucosyl as sugar-acid-1 targeting amylase",
            "set mechanism of sulfa-1 to secretion_agonist",
        ],
        "commands": [
            "design peptide <sequence 1..24 of ACDEFGHIKLMNPQRSTVWY> as <name>",
            "design peptide <sequence> as <name> targeting <target-key>",
            "design helix <sequence> as <name>[ targeting <target-key>]",
            "design molecule <fragment>[+<fragment>]... (1..6 fragments) as <name>[ targeting <target-key>]",
            "set mechanism of <name> to <mechanism>",
        ],
    }


pub def build_designed_structure(spec: dict[str, any]) -> dict[str, any] !{}:
    sem "Build computed engineered geometry for a sealed design spec in the shape the molecular viewer already renders"
    require design_spec_valid(spec)
    built = build_peptide(spec) if spec["class"] == "peptide" else build_molecule(spec)
    count = len(built["atomic_numbers"])
    ensure count > 0 and count <= MAX_DESIGN_ATOMS
    ensure len(built["bonds"]) // 2 <= MAX_DESIGN_BONDS
    relaxed = relax_build(built)
    coordinates = relaxed["positions"]
    mut centre = [0.0, 0.0, 0.0]
    for atom in range(count):
        for axis in range(3):
            centre[axis] = centre[axis] + coordinates[atom * 3 + axis] / count
    positions = [coordinates[slot] - centre[slot % 3] for slot in range(len(coordinates))]
    mut minimum = [positions[0], positions[1], positions[2]]
    mut maximum = [positions[0], positions[1], positions[2]]
    mut radius_angstrom = 0.0
    for atom in range(count):
        offset = atom * 3
        # The framing radius is the van der Waals envelope, so a one-atom design is still non-zero.
        radius_angstrom = max(radius_angstrom, math.sqrt(positions[offset] ** 2 + positions[offset + 1] ** 2 + positions[offset + 2] ** 2) + atomic_radius(built["atomic_numbers"][atom], "vdw"))
        for axis in range(3):
            minimum[axis] = min(minimum[axis], positions[offset + axis])
            maximum[axis] = max(maximum[axis], positions[offset + axis])
    ensure radius_angstrom > 0.0
    traces = [] if spec["class"] == "small_molecule" else [{
        "chain_id": "A",
        "polymer_type": "protein",
        "secondary": "helix" if spec["conformation"] == "helix" else "coil",
        "positions": [built["trace"][slot] - centre[slot % 3] for slot in range(len(built["trace"]))],
    }]
    structure = {
        "key": spec["name"],
        "label": spec["label"],
        "pdb_id": "",
        "source_sha256": spec["spec_sha256"],
        "topology_sha256": sha256_json({"source_sha256": spec["spec_sha256"], "bonds": built["bonds"]}),
        "fidelity": "engineered_unvalidated",
        "biological_match": "designed_de_novo",
        "source_page": "sema://design/" + spec["name"],
        "atomic_numbers": built["atomic_numbers"],
        "element_names": [element_name(atomic_number) for atomic_number in built["atomic_numbers"]],
        "positions": positions,
        "labels": built["labels"],
        "bonds": built["bonds"],
        "traces": traces,
        "covalent_radii_angstrom": [atomic_radius(atomic_number, "covalent") for atomic_number in built["atomic_numbers"]],
        "vdw_radii_angstrom": [atomic_radius(atomic_number, "vdw") for atomic_number in built["atomic_numbers"]],
        "radius_angstrom": radius_angstrom,
        "unit_scale": UNIT_SCALE,
        "radius_nm": radius_angstrom * UNIT_SCALE,
        "extent_nm": [(maximum[axis] - minimum[axis]) * UNIT_SCALE for axis in range(3)],
        "center_offset_angstrom": [0.0, 0.0, 0.0],
        "base_bond_count": len(built["bonds"]) // 2,
        "bond_capacity": len(built["bonds"]) // 2 + 16,
        "structural_edits": 0,
        "coordinate_edits": 0,
        "sidechain_model": SIDECHAIN_MODEL if spec["class"] == "peptide" else "fragment_template_chain",
        "relaxation_steps": relaxed["steps"],
        "max_force_kj_mol_angstrom": relaxed["max_force"],
    }
    mut sealed = {key: value for key, value in structure.items()}
    sealed["asset_sha256"] = sha256_json(structure)
    return sealed


test "the design grammar seals specs, rejects everything outside its bounds, and builds computed geometry":
    peptide = compile_design_command("design peptide ACDEFG as probe-1 targeting insulin")
    ensure peptide["ok"] and peptide["kind"] == "design" and peptide["name"] == "probe-1"
    spec = peptide["spec"]
    ensure spec["class"] == "peptide" and spec["conformation"] == "extended" and spec["sequence"] == "ACDEFG"
    ensure spec["target_key"] == "insulin" and spec["mechanism"] == "inert" and spec["charge_e"] == -2.0
    ensure len(spec["spec_sha256"]) == 64 and design_spec_valid(spec)
    structure = build_designed_structure(spec)
    atoms = len(structure["atomic_numbers"])
    ensure atoms >= 40 and atoms <= 512
    ensure len(structure["positions"]) == atoms * 3 and len(structure["labels"]) == atoms
    ensure len(structure["element_names"]) == atoms and len(structure["covalent_radii_angstrom"]) == atoms
    ensure len(structure["vdw_radii_angstrom"]) == atoms and len(structure["bonds"]) % 2 == 0
    ensure structure["radius_angstrom"] > 0.0 and len(structure["extent_nm"]) == 3
    ensure len(structure["source_sha256"]) == 64 and len(structure["asset_sha256"]) == 64
    ensure structure["fidelity"] == "engineered_unvalidated" and structure["biological_match"] == "designed_de_novo"
    ensure structure["sidechain_model"] == "backbone_plus_truncated_sidechain"
    ensure len(structure["traces"]) == 1 and len(structure["traces"][0]["positions"]) == 18
    ensure build_designed_structure(spec)["asset_sha256"] == structure["asset_sha256"]
    other = compile_design_command("design peptide ACDEFH as probe-1 targeting insulin")["spec"]
    ensure build_designed_structure(other)["asset_sha256"] != structure["asset_sha256"]
    molecule = compile_design_command("design molecule benzene+sulfonylurea as sulfa-1")
    ensure molecule["ok"] and molecule["spec"]["class"] == "small_molecule"
    ensure molecule["spec"]["fragments"] == ["benzene", "sulfonylurea"]
    built = build_designed_structure(molecule["spec"])
    ensure len(built["atomic_numbers"]) == 13 and built["traces"] == []
    ensure built["relaxation_steps"] > 0 and built["max_force_kj_mol_angstrom"] >= 0.0
    mechanism = compile_design_command("set mechanism of sulfa-1 to secretion_agonist")
    ensure mechanism["ok"] and mechanism["kind"] == "set_mechanism" and mechanism["mechanism"] == "secretion_agonist"
    ensure not compile_design_command("set mechanism of sulfa-1 to teleport")["ok"]
    ensure not compile_design_command("design peptide ACBX as bad-1")["ok"]
    ensure not compile_design_command("design molecule unobtainium as bad-2")["ok"]
    ensure not compile_design_command("design molecule benzene+benzene+benzene+benzene+benzene+benzene+benzene as bad-3")["ok"]
    ensure not compile_design_command("design peptide ACDEFG as probe-1 targeting unicorn")["ok"]
    ensure compile_design_command("")["error"] == "DesignCompileError"
    ensure not design_spec_valid({"schema": SPEC_SCHEMA, "name": "x"})
```

### `src/discovery.sema`

```sema
"""Bounded computational-discovery lineage, gates, and honest result classes."""

assure silver


pub enum CandidateKind:
    molecule | bond | interaction | circuit | equation_change | experiment


pub enum CandidateStatus:
    proposed | rejected | admitted | simulated | ranked | blocked


pub enum CandidateClaim:
    unseen_in_bounded_search | predicted_interaction | simulated_association | experimentally_supported | clinical


pub struct SearchBoundary:
    id: str
    description: str
    allowed_kinds: list[CandidateKind]
    max_candidates: int
    max_rounds: int
    max_compute_units: int
    prior_art_sources: list[str]
    safety_policy_id: str
    invariant len(id) > 0
    invariant len(description) > 0
    invariant max_candidates > 0
    invariant max_rounds > 0
    invariant max_compute_units > 0
    invariant len(prior_art_sources) > 0
    invariant len(safety_policy_id) > 0


pub struct DiscoveryBatch:
    boundary_id: str
    round_index: int
    candidate_ids: list[str]
    requested_compute_units: int
    invariant len(boundary_id) > 0
    invariant round_index > 0
    invariant len(candidate_ids) > 0
    invariant requested_compute_units > 0


pub struct CandidateHypothesis:
    id: str
    parent_ids: list[str]
    kind: CandidateKind
    representation_digest: str
    rationale: str
    provenance_ids: list[str]
    prior_art_scope_id: str
    model_id: str
    model_version: int
    equation_graph_id: str
    equation_version: int
    uncertainty: f64
    requested_compute_units: int
    status: CandidateStatus
    rejection_reasons: list[str]
    invariant len(id) > 0
    invariant len(representation_digest) == 64
    invariant len(rationale) > 0
    invariant len(provenance_ids) > 0
    invariant len(prior_art_scope_id) > 0
    invariant len(model_id) > 0
    invariant model_version > 0
    invariant len(equation_graph_id) > 0
    invariant equation_version > 0
    invariant uncertainty >= 0.0
    invariant requested_compute_units > 0


pub struct CandidateEvidence:
    candidate_id: str
    observation_ids: list[str]
    oracle_evidence_ids: list[str]
    prior_art_evidence_ids: list[str]
    objective_names: list[str]
    objective_values: list[f64]
    uncertainty: f64
    information_gain: f64
    claim: CandidateClaim
    status: CandidateStatus
    invariant len(candidate_id) > 0
    invariant len(objective_names) == len(objective_values)
    invariant uncertainty >= 0.0
    invariant information_gain >= 0.0


def within_boundary(candidate: CandidateHypothesis, boundary: SearchBoundary):
    if candidate.requested_compute_units > boundary.max_compute_units:
        return false
    if candidate.prior_art_scope_id != boundary.id:
        return false
    return candidate.kind in boundary.allowed_kinds


pub def validate_discovery_batch(
    batch: DiscoveryBatch,
    candidates: list[CandidateHypothesis],
    boundary: SearchBoundary,
) -> bool !{}:
    if batch.boundary_id != boundary.id:
        return false
    if batch.round_index > boundary.max_rounds:
        return false
    if len(candidates) == 0 or len(candidates) > boundary.max_candidates:
        return false
    if len(batch.candidate_ids) != len(candidates):
        return false
    mut compute_units = 0
    mut seen_ids: list[str] = []
    for candidate in candidates:
        if not within_boundary(candidate, boundary):
            return false
        if candidate.id not in batch.candidate_ids or candidate.id in seen_ids:
            return false
        seen_ids.append(candidate.id)
        compute_units = compute_units + candidate.requested_compute_units
        if compute_units > boundary.max_compute_units:
            return false
    return compute_units == batch.requested_compute_units


def reject_candidate(candidate: CandidateHypothesis, reason: str):
    require len(reason) > 0
    mut reasons = candidate.rejection_reasons
    reasons.append(reason)
    return CandidateHypothesis(
        id=candidate.id,
        parent_ids=candidate.parent_ids,
        kind=candidate.kind,
        representation_digest=candidate.representation_digest,
        rationale=candidate.rationale,
        provenance_ids=candidate.provenance_ids,
        prior_art_scope_id=candidate.prior_art_scope_id,
        model_id=candidate.model_id,
        model_version=candidate.model_version,
        equation_graph_id=candidate.equation_graph_id,
        equation_version=candidate.equation_version,
        uncertainty=candidate.uncertainty,
        requested_compute_units=candidate.requested_compute_units,
        status=CandidateStatus.rejected,
        rejection_reasons=reasons,
    )


pub def admit_candidate(
    candidate: CandidateHypothesis,
    boundary: SearchBoundary,
    chemistry_valid: bool,
    topology_valid: bool,
    applicability_valid: bool,
    evidence_valid: bool,
    safety_valid: bool,
) -> CandidateHypothesis !{}:
    if not within_boundary(candidate, boundary):
        return reject_candidate(candidate, "outside declared search or resource boundary")
    if not chemistry_valid:
        return reject_candidate(candidate, "chemistry validation failed")
    if not topology_valid:
        return reject_candidate(candidate, "topology validation failed")
    if not applicability_valid:
        return reject_candidate(candidate, "model applicability validation failed")
    if not evidence_valid:
        return reject_candidate(candidate, "evidence preflight failed")
    if not safety_valid:
        return reject_candidate(candidate, "safety policy denied candidate")
    return CandidateHypothesis(
        id=candidate.id,
        parent_ids=candidate.parent_ids,
        kind=candidate.kind,
        representation_digest=candidate.representation_digest,
        rationale=candidate.rationale,
        provenance_ids=candidate.provenance_ids,
        prior_art_scope_id=candidate.prior_art_scope_id,
        model_id=candidate.model_id,
        model_version=candidate.model_version,
        equation_graph_id=candidate.equation_graph_id,
        equation_version=candidate.equation_version,
        uncertainty=candidate.uncertainty,
        requested_compute_units=candidate.requested_compute_units,
        status=CandidateStatus.admitted,
        rejection_reasons=[],
    )


pub def may_report_claim(evidence: CandidateEvidence) -> bool !{}:
    if evidence.claim == CandidateClaim.clinical:
        return false
    if evidence.claim == CandidateClaim.unseen_in_bounded_search:
        return len(evidence.prior_art_evidence_ids) > 0 and evidence.status == CandidateStatus.ranked
    if evidence.claim == CandidateClaim.experimentally_supported:
        return len(evidence.oracle_evidence_ids) > 0
    if evidence.claim == CandidateClaim.simulated_association:
        return len(evidence.observation_ids) > 0 and len(evidence.oracle_evidence_ids) > 0
    if evidence.claim == CandidateClaim.predicted_interaction:
        return len(evidence.observation_ids) > 0 and evidence.status == CandidateStatus.ranked
    return evidence.status == CandidateStatus.ranked
```

### `src/domain.sema`

```sema
"""Typed physical identities, topology, backend profiles, observations, and phase evidence."""

assure silver


pub enum PhaseState:
    not_started | implemented_unvalidated | validated | blocked


enum EntityKind:
    particle | atom | residue | molecule | ensemble | coarse_state | field | membrane | organelle | cell | tissue


pub enum ModelScale:
    quantum | atomistic | coarse | mesoscopic | network | cellular | tissue


enum ResultClass:
    validated | calibrated | exploratory | unknown | invalid | failed


enum ReplayClass:
    exact | deterministic_tolerance | statistical | unavailable


pub enum EvidenceKind:
    computational | structural | ensemble | experimental | performance | negative

enum InteractionMethod:
    classical_fixed_topology | reactive_force_field | learned_potential | quantum | qmmm | particle_reaction_diffusion

enum PropertyValueKind:
    scalar | vector | tensor | per_atom | categorical | distribution


enum ReactionState:
    proposed | parameterized | computed | validated | blocked


pub struct Vector3:
    x: f64
    y: f64
    z: f64


pub struct Atom:
    id: str
    index: int
    element: str
    residue: str
    mass_da: f64
    charge_e: f64
    position_nm: Vector3
    invariant len(id) > 0
    invariant index >= 0
    invariant len(element) > 0
    invariant len(residue) > 0
    invariant mass_da > 0.0


pub struct Bond:
    left_index: int
    right_index: int
    order: int
    invariant left_index >= 0
    invariant right_index >= 0
    invariant order >= 1 and order <= 3


pub struct PeriodicBox:
    x_nm: f64
    y_nm: f64
    z_nm: f64
    invariant x_nm > 0.0
    invariant y_nm > 0.0
    invariant z_nm > 0.0


pub struct MolecularTopology:
    id: str
    atoms: list[Atom]
    bonds: list[Bond]
    box: PeriodicBox
    source_sha256: str
    invariant len(id) > 0
    invariant len(atoms) > 0 and len(atoms) <= 10000
    invariant len(bonds) <= 30000
    invariant len(source_sha256) == 64


struct BackendProfile:
    id: str
    engine: str
    version: str
    platform: str
    precision: str
    properties: list[str]
    artifact_sha256: str
    replay: ReplayClass
    invariant len(id) > 0
    invariant len(engine) > 0
    invariant len(version) > 0
    invariant len(platform) > 0
    invariant len(precision) > 0
    invariant len(properties) <= 64
    invariant len(artifact_sha256) == 64


pub struct EvidenceRecord:
    id: str
    kind: EvidenceKind
    source: str
    summary: str
    artifact_sha256: str
    observed_at_s: f64
    accepted: bool
    invariant len(id) > 0
    invariant len(source) > 0
    invariant len(summary) > 0
    invariant len(artifact_sha256) == 64
    invariant observed_at_s >= 0.0


pub struct InteractionTerm:
    id: str
    family: str
    owner_model_id: str
    active: bool
    target_observable: str
    evidence_ids: list[str]
    invariant len(id) > 0
    invariant len(family) > 0
    invariant len(owner_model_id) > 0
    invariant len(target_observable) > 0
    invariant len(evidence_ids) <= 128

struct MolecularProperty:
    id: str
    entity_id: str
    property_name: str
    scope_id: str
    value_kind: PropertyValueKind
    values: list[f64]
    labels: list[str]
    shape: list[int]
    unit_symbol: str
    uncertainty: f64
    conditions: list[str]
    method_profile_id: str
    evidence_ids: list[str]
    valid: bool
    invariant len(id) > 0
    invariant len(entity_id) > 0
    invariant len(property_name) > 0
    invariant len(scope_id) > 0
    invariant len(values) > 0 or len(labels) > 0
    invariant len(values) <= 1000000
    invariant len(labels) <= 1000000
    invariant len(shape) <= 8
    invariant len(unit_symbol) > 0
    invariant uncertainty >= 0.0
    invariant len(conditions) <= 128
    invariant len(method_profile_id) > 0
    invariant len(evidence_ids) <= 128


struct InteractionProfile:
    id: str
    method: InteractionMethod
    engine: str
    version: str
    parameter_sha256: str
    scope_id: str
    supported_elements: list[str]
    properties: list[str]
    minimum_atoms: int
    maximum_atoms: int
    conditions: list[str]
    supports_topology_change: bool
    qualified: bool
    uncertainty_policy: str
    evidence_ids: list[str]
    invariant len(id) > 0
    invariant len(engine) > 0
    invariant len(version) > 0
    invariant len(parameter_sha256) == 64
    invariant len(scope_id) > 0
    invariant len(supported_elements) > 0 and len(supported_elements) <= 118
    invariant len(properties) > 0 and len(properties) <= 128
    invariant minimum_atoms > 0 and maximum_atoms >= minimum_atoms
    invariant maximum_atoms <= 1000000
    invariant len(conditions) > 0 and len(conditions) <= 128
    invariant len(uncertainty_policy) > 0
    invariant len(evidence_ids) <= 128


struct ReactionProposal:
    id: str
    reactant_topology_sha256: str
    product_topology_sha256: str
    elements: list[str]
    atom_map: list[int]
    total_charge: int
    spin_multiplicity: int
    profile_id: str
    scope_id: str
    conditions: list[str]
    evidence_ids: list[str]
    invariant len(id) > 0
    invariant len(reactant_topology_sha256) == 64
    invariant len(product_topology_sha256) == 64
    invariant len(elements) > 0 and len(elements) <= 256
    invariant len(atom_map) == len(elements)
    invariant spin_multiplicity > 0
    invariant len(profile_id) > 0
    invariant len(scope_id) > 0
    invariant len(conditions) > 0 and len(conditions) <= 128
    invariant len(evidence_ids) <= 128


struct ReactionDecision:
    proposal_id: str
    state: ReactionState
    admissible: bool
    profile_id: str
    reason: str
    invariant len(proposal_id) > 0
    invariant len(profile_id) > 0
    invariant len(reason) > 0


struct ObservationFrame:
    schema: str
    run_id: str
    state_version: int
    step: int
    physical_time_ps: f64
    potential_energy_kj_mol: f64
    kinetic_energy_kj_mol: f64
    max_force_kj_mol_nm: f64
    phi_rad: f64
    psi_rad: f64
    backend_profile_id: str
    evidence_ids: list[str]
    invariant schema == "sema.molecular-observation/v1"
    invariant len(run_id) > 0
    invariant state_version >= 0
    invariant step >= 0
    invariant physical_time_ps >= 0.0
    invariant max_force_kj_mol_nm >= 0.0
    invariant len(backend_profile_id) > 0
    invariant len(evidence_ids) <= 128


pub struct PhaseEvidence:
    phase: int
    state: PhaseState
    profile_id: str
    positive_evidence: list[str]
    negative_evidence: list[str]
    blockers: list[str]
    invariant phase >= 0 and phase <= 10
    invariant len(profile_id) > 0
    invariant len(positive_evidence) <= 128
    invariant len(negative_evidence) <= 128
    invariant len(blockers) <= 128


def distinct_atom_ids(atoms: list[Atom]):
    mut expected_index = 0
    mut seen_ids: list[str] = []
    for atom in atoms:
        if atom.index != expected_index or atom.id in seen_ids:
            return false
        seen_ids.append(atom.id)
        expected_index = expected_index + 1
    return true


def bonds_reference_atoms(topology: MolecularTopology):
    for bond in topology.bonds:
        if bond.left_index >= len(topology.atoms) or bond.right_index >= len(topology.atoms):
            return false
        if bond.left_index == bond.right_index:
            return false
    return true


pub def topology_valid(topology: MolecularTopology) -> bool !{}:
    return distinct_atom_ids(topology.atoms) and bonds_reference_atoms(topology)


pub def interaction_ownership_valid(terms: list[InteractionTerm]) -> bool !{}:
    mut left = 0
    for term in terms:
        mut right = 0
        for other in terms:
            if left != right and term.active and other.active and term.id == other.id:
                return false
            right = right + 1
        left = left + 1
    return true


def profile_supports_elements(profile: InteractionProfile, elements: list[str]):
    for element in elements:
        if element not in profile.supported_elements:
            return false
    return true


def reaction_atom_map_valid(proposal: ReactionProposal):
    mut seen: list[int] = []
    for atom_index in proposal.atom_map:
        if atom_index < 0 or atom_index >= len(proposal.atom_map) or atom_index in seen:
            return false
        seen.append(atom_index)
    return true


def molecular_property_admissible(property: MolecularProperty, profile: InteractionProfile):
    return property.valid and property.method_profile_id == profile.id and property.scope_id == profile.scope_id and property.conditions == profile.conditions and property.property_name in profile.properties and len(property.evidence_ids) > 0


def admit_reaction(proposal: ReactionProposal, profile: InteractionProfile):
    if proposal.profile_id != profile.id:
        return ReactionDecision(proposal_id=proposal.id, state=ReactionState.blocked, admissible=false, profile_id=profile.id, reason="proposal and interaction profile identities differ")
    if proposal.scope_id != profile.scope_id or proposal.conditions != profile.conditions:
        return ReactionDecision(proposal_id=proposal.id, state=ReactionState.blocked, admissible=false, profile_id=profile.id, reason="proposal scope or conditions differ from the interaction profile")
    if len(proposal.elements) < profile.minimum_atoms or len(proposal.elements) > profile.maximum_atoms:
        return ReactionDecision(proposal_id=proposal.id, state=ReactionState.blocked, admissible=false, profile_id=profile.id, reason="proposal atom count lies outside the interaction profile")
    if not profile.supports_topology_change:
        return ReactionDecision(proposal_id=proposal.id, state=ReactionState.blocked, admissible=false, profile_id=profile.id, reason="selected interaction profile cannot change topology")
    if not profile.qualified:
        return ReactionDecision(proposal_id=proposal.id, state=ReactionState.blocked, admissible=false, profile_id=profile.id, reason="selected interaction profile is not qualified")
    if not profile_supports_elements(profile, proposal.elements):
        return ReactionDecision(proposal_id=proposal.id, state=ReactionState.blocked, admissible=false, profile_id=profile.id, reason="proposal contains elements outside the interaction profile")
    if not reaction_atom_map_valid(proposal):
        return ReactionDecision(proposal_id=proposal.id, state=ReactionState.blocked, admissible=false, profile_id=profile.id, reason="proposal atom mapping is not bijective")
    if len(proposal.evidence_ids) == 0 or len(profile.evidence_ids) == 0:
        return ReactionDecision(proposal_id=proposal.id, state=ReactionState.blocked, admissible=false, profile_id=profile.id, reason="reaction proposal or interaction profile lacks evidence")
    return ReactionDecision(proposal_id=proposal.id, state=ReactionState.parameterized, admissible=true, profile_id=profile.id, reason="proposal lies inside the qualified interaction profile")


pub def phase_validated(phase: PhaseEvidence) -> bool !{}:
    return phase.state == PhaseState.validated and len(phase.positive_evidence) > 0 and len(phase.negative_evidence) > 0 and len(phase.blockers) == 0


def blocked_phase(phase: int, profile_id: str, reason: str):
    require len(reason) > 0
    return PhaseEvidence(phase=phase, state=PhaseState.blocked, profile_id=profile_id, positive_evidence=[], negative_evidence=[], blockers=[reason])
```

### `src/dynamics.sema`

```sema
"""Sema-owned multiscale dynamics, model admission, control, and solver evidence."""

from std.adaptive_dynamics import ActivationDecision, ModelDescriptor, ModelLifecycle, SelectionPolicy, activate_validated, validate_candidate
from std.epistemic import Assumption, Evidence, ValidityRegion

assure silver


pub struct ControlIntent:
    id: str
    natural_language: str
    target_tissue_response: f64
    maximum_cellular_gain: f64
    effort_penalty: f64
    horizon_s: f64
    evidence_ids: list[str]
    invariant len(id) > 0
    invariant len(natural_language) > 0
    invariant target_tissue_response >= 0.0 and target_tissue_response <= 1.0
    invariant maximum_cellular_gain > 0.0 and maximum_cellular_gain <= 1.0
    invariant effort_penalty > 0.0
    invariant horizon_s > 0.0 and horizon_s <= 1000.0
    invariant len(evidence_ids) > 0 and len(evidence_ids) <= 128



pub struct Phase8AdmissionEvidence:
    phase8_technical_pass: bool
    readdy_chronology_proven: bool
    readdy_qualification_pass: bool
    readdy_convergence_pass: bool
    readdy_spatial_pass: bool
    readdy_admission_pass: bool
    physicell_custom_insulin_pass: bool
    physicell_target_rate_pass: bool
    physicell_uncertainty_pass: bool
    physicell_scientific_pass: bool


pub def phase8_admission_evidence_complete(evidence: Phase8AdmissionEvidence) -> bool !{}:
    sem "Require every technical and scientific Phase8 gate before association-model admission"
    return evidence.phase8_technical_pass and evidence.readdy_chronology_proven and evidence.readdy_qualification_pass and evidence.readdy_convergence_pass and evidence.readdy_spatial_pass and evidence.readdy_admission_pass and evidence.physicell_custom_insulin_pass and evidence.physicell_target_rate_pass and evidence.physicell_uncertainty_pass and evidence.physicell_scientific_pass

pub struct AdaptationSummary:
    active_model_id: str
    candidate_model_id: str
    selected_model_id: str
    activated: bool
    admission_status: str
    admitted: bool
    exploratory: bool
    evidence_reliability: f64
    parameter_apply_authorized: bool
    reason: str
    evidence_ids: list[str]
    invariant len(active_model_id) > 0
    invariant len(candidate_model_id) > 0
    invariant len(selected_model_id) > 0
    invariant len(reason) > 0
    invariant len(evidence_ids) > 0 and len(evidence_ids) <= 128
    invariant admission_status == "admitted" or admission_status == "exploratory_unadmitted"
    invariant admitted == activated and exploratory != admitted
    invariant evidence_reliability == (1.0 if admitted else 0.0)
    invariant parameter_apply_authorized == admitted


pub struct DynamicsResult:
    schema: str
    contract_id: str
    semantics: str
    formal_equations: list[str]
    state_names: list[str]
    state_units: list[str]
    final_state: list[f64]
    cellular_gain: f64
    target_tissue_response: f64
    tissue_target_error: f64
    initial_molecular_mass_micromolar: f64
    final_molecular_mass_micromolar: f64
    molecular_mass_relative_residual: f64
    integration_error_bound: f64
    integration_steps_accepted: int
    integration_steps_rejected: int
    integration_method: str
    optimizer_status: str
    optimizer_scope: str
    optimizer_objective: f64
    optimizer_iterations: int
    adaptation: AdaptationSummary
    evidence_ids: list[str]
    admission_status: str
    admitted: bool
    exploratory: bool
    parameter_apply_authorized: bool
    technical_pass: bool
    scientific_validated: bool
    invariant schema == "sema.multiscale-dynamics-result/v1"
    invariant len(contract_id) > 0
    invariant len(semantics) > 0
    invariant len(formal_equations) == 4
    invariant len(state_names) == 4 and len(state_units) == 4 and len(final_state) == 4
    invariant cellular_gain >= 0.0 and cellular_gain <= 1.0
    invariant tissue_target_error >= 0.0
    invariant initial_molecular_mass_micromolar > 0.0
    invariant final_molecular_mass_micromolar > 0.0
    invariant molecular_mass_relative_residual >= 0.0
    invariant integration_error_bound >= 0.0
    invariant integration_steps_accepted > 0 and integration_steps_rejected >= 0
    invariant len(integration_method) > 0
    invariant len(optimizer_status) > 0 and len(optimizer_scope) > 0
    invariant optimizer_iterations >= 0
    invariant len(evidence_ids) > 0 and len(evidence_ids) <= 128
    invariant admission_status == adaptation.admission_status
    invariant admitted == adaptation.admitted and exploratory == adaptation.exploratory
    invariant parameter_apply_authorized == adaptation.parameter_apply_authorized
    invariant admitted or technical_pass == false
    invariant scientific_validated == false


pub struct PopulationState:
    schema: str
    total_cells: int
    viable_cells: int
    dead_cells: int
    mutated_cells: int
    adapted_cells: int
    injected_micromolar: f64
    applied_force_pn: f64
    stress_fraction: f64
    injected_molecule: str
    mutation_label: str
    last_intervention: str
    affected_index: int
    affected_kind: str
    event_count: int
    scientific_validated: bool
    invariant schema == "sema.biological-population-state/v2"
    invariant total_cells > 0 and viable_cells >= 0 and viable_cells + dead_cells == total_cells
    invariant mutated_cells >= 0 and mutated_cells <= viable_cells
    invariant adapted_cells >= 0 and adapted_cells <= viable_cells
    invariant injected_micromolar >= 0.0 and injected_micromolar <= 1000.0
    invariant abs(applied_force_pn) <= 80.0
    invariant stress_fraction >= 0.0 and stress_fraction <= 1.0
    invariant len(injected_molecule) > 0 and len(mutation_label) > 0 and len(last_intervention) > 0
    invariant affected_index >= -1 and affected_index < 16384
    invariant affected_kind == "none" or affected_kind == "population" or affected_kind == "tissue-cell" or affected_kind == "vessel" or affected_kind == "granule" or affected_kind == "mitochondrion" or affected_kind == "receptor" or affected_kind == "protein" or affected_kind == "protein-atom" or affected_kind == "source-atom" or affected_kind == "membrane" or affected_kind == "nucleus" or affected_kind == "cytoskeleton" or affected_kind == "endoplasmic-reticulum" or affected_kind == "lipid-droplet" or affected_kind == "vessel-wall" or affected_kind == "vessel-lumen" or affected_kind == "erythrocyte"
    invariant event_count >= 0
    invariant scientific_validated == false


pub struct DynamicsStep:
    schema: str
    sequence: int
    state_version: int
    equation_id: str
    equation_version: int
    model_id: str
    semantics: str
    state: list[f64]
    target_tissue_response: f64
    cellular_gain: f64
    molecular_integrity: f64
    dt_s: f64
    molecular_mass_relative_residual: f64
    integration_error_bound: f64
    integration_steps_accepted: int
    integration_steps_rejected: int
    optimizer_status: str
    optimizer_scope: str
    evidence_ids: list[str]
    physiology: dict[str, any]
    population: PopulationState
    admission_status: str
    admitted: bool
    exploratory: bool
    parameter_apply_authorized: bool
    technical_pass: bool
    scientific_validated: bool
    invariant schema == "sema.multiscale-dynamics-step/v1"
    invariant sequence >= 0 and state_version >= 1
    invariant equation_id == "insulin-association-cell-tissue-control"
    invariant equation_version == 1
    invariant len(model_id) > 0 and len(semantics) > 0
    invariant len(state) == 4
    invariant target_tissue_response >= 0.0 and target_tissue_response <= 1.0
    invariant cellular_gain >= 0.0 and cellular_gain <= 1.0
    invariant molecular_integrity >= 0.0 and molecular_integrity <= 1.0
    invariant dt_s >= 0.01 and dt_s <= 0.25
    invariant molecular_mass_relative_residual >= 0.0
    invariant integration_error_bound >= 0.0
    invariant integration_steps_accepted > 0 and integration_steps_rejected >= 0
    invariant optimizer_status == "Optimal" and optimizer_scope == "global-convex"
    invariant len(evidence_ids) > 0 and len(evidence_ids) <= 128
    invariant physiology["schema"] == "sema.metabolic-immune-observation/v1" and physiology["technical_pass"]
    invariant admission_status == "admitted" or admission_status == "exploratory_unadmitted"
    invariant admitted == (admission_status == "admitted") and exploratory != admitted
    invariant parameter_apply_authorized == admitted
    invariant admitted or technical_pass == false
    invariant scientific_validated == false


pub def initial_population_state(total_cells: int) -> PopulationState !{}:
    require total_cells > 0 and total_cells <= 16384
    return PopulationState(schema="sema.biological-population-state/v2", total_cells=total_cells, viable_cells=total_cells, dead_cells=0, mutated_cells=0, adapted_cells=0, injected_micromolar=0.0, applied_force_pn=0.0, stress_fraction=0.0, injected_molecule="none", mutation_label="none", last_intervention="baseline", affected_index=-1, affected_kind="none", event_count=0, scientific_validated=false)


pub def apply_biological_intervention(state: PopulationState, kind: str, target_index: int, target_kind: str, magnitude: f64, amount: f64, molecule: str, mutation: str, seed_cells: int) -> PopulationState !{}:
    sem "Apply a bounded force, molecule injection, mutation seed, or ablation to Sema-owned population state"
    require kind == "force" or kind == "inject" or kind == "mutate" or kind == "ablate"
    require target_index >= -1 and target_index < 16384
    require target_kind == "population" or target_kind == "tissue-cell" or target_kind == "vessel" or target_kind == "granule" or target_kind == "mitochondrion" or target_kind == "receptor" or target_kind == "protein" or target_kind == "protein-atom" or target_kind == "source-atom" or target_kind == "membrane" or target_kind == "nucleus" or target_kind == "cytoskeleton" or target_kind == "endoplasmic-reticulum" or target_kind == "lipid-droplet" or target_kind == "vessel-wall" or target_kind == "vessel-lumen" or target_kind == "erythrocyte"
    require magnitude >= -80.0 and magnitude <= 80.0
    require amount >= 0.0 and amount <= 100.0
    require seed_cells >= 0 and seed_cells <= 32
    viable = state.viable_cells
    dead = state.dead_cells
    mutated = state.mutated_cells
    adapted = state.adapted_cells
    injected = state.injected_micromolar
    force = state.applied_force_pn
    stress = state.stress_fraction
    injected_molecule = state.injected_molecule
    mutation_label = state.mutation_label
    if kind == "force":
        ensure target_index >= 0 and abs(magnitude) > 0.0
        ensure target_kind != "population"
        force = magnitude
        stress = min(1.0, stress + abs(magnitude) / 800.0)
        if abs(magnitude) >= 20.0:
            adapted = min(viable, adapted + 1)
    elif kind == "inject":
        ensure molecule == "insulin" or molecule == "glucose" or molecule == "cytokine" or molecule == "oxygen"
        ensure amount > 0.0
        injected = min(1000.0, injected + amount)
        injected_molecule = molecule
        if molecule == "cytokine":
            stress = min(1.0, stress + amount / 200.0)
        elif molecule == "oxygen":
            stress = max(0.0, stress - amount / 300.0)
    elif kind == "mutate":
        ensure len(mutation) > 0 and seed_cells > 0
        ensure target_kind == "population" or target_kind == "tissue-cell"
        mutated = min(viable, mutated + seed_cells)
        mutation_label = mutation
        stress = min(1.0, stress + f64(seed_cells) / f64(state.total_cells))
    else:
        ensure target_index >= 0 and viable > 0
        ensure target_kind == "tissue-cell"
        dead = min(state.total_cells, dead + 1)
        viable = state.total_cells - dead
        mutated = min(mutated, viable)
        adapted = min(adapted, viable)
        stress = min(1.0, stress + 0.04)
    return PopulationState(schema=state.schema, total_cells=state.total_cells, viable_cells=viable, dead_cells=dead, mutated_cells=mutated, adapted_cells=adapted, injected_micromolar=injected, applied_force_pn=force, stress_fraction=stress, injected_molecule=injected_molecule, mutation_label=mutation_label, last_intervention=kind, affected_index=target_index, affected_kind=target_kind, event_count=state.event_count + 1, scientific_validated=false)


def advance_population_dynamics(state: PopulationState, dt_s: f64, cellular_signal: f64, tissue_response: f64, beta_function_fraction: f64, immune_effector_fraction: f64):
    sem "Advance bounded mutation propagation, stress, adaptation, molecule clearance, and physiology-coupled cell viability"
    require dt_s >= 0.01 and dt_s <= 0.25
    require cellular_signal >= 0.0 and cellular_signal <= 1.0 and tissue_response >= 0.0 and tissue_response <= 1.0
    require beta_function_fraction >= 0.0 and beta_function_fraction <= 1.5
    require immune_effector_fraction >= 0.0 and immune_effector_fraction <= 1.0
    events = state.event_count + 1
    immune_stress = immune_effector_fraction * 0.35
    stress = max(0.0, min(1.0, state.stress_fraction + dt_s * immune_stress - dt_s * (0.01 + tissue_response * 0.02)))
    injected = max(0.0, state.injected_micromolar * (1.0 - dt_s * 0.025))
    force = state.applied_force_pn
    if force > 0.0:
        force = max(0.0, force - dt_s * 2.0)
    elif force < 0.0:
        force = min(0.0, force + dt_s * 2.0)
    viable = state.viable_cells
    dead = state.dead_cells
    mutated = state.mutated_cells
    adapted = state.adapted_cells
    if mutated > 0 and mutated < viable and stress > 0.03 and events % 20 == 0:
        mutated = mutated + 1
    if stress > 0.05 and adapted < viable and events % 25 == 0:
        adapted = adapted + 1
    target_beta_deaths = int(f64(state.total_cells) * 0.24 * (1.0 - min(1.0, beta_function_fraction)))
    if (dead < target_beta_deaths or immune_effector_fraction > 0.6) and viable > 0 and events % 10 == 0:
        dead = dead + 1
        viable = state.total_cells - dead
        mutated = min(mutated, viable)
        adapted = min(adapted, viable)
    return PopulationState(schema=state.schema, total_cells=state.total_cells, viable_cells=viable, dead_cells=dead, mutated_cells=mutated, adapted_cells=adapted, injected_micromolar=injected, applied_force_pn=force, stress_fraction=stress, injected_molecule=state.injected_molecule, mutation_label=state.mutation_label, last_intervention="advance", affected_index=state.affected_index, affected_kind=state.affected_kind, event_count=events, scientific_validated=false)


pub def dynamics_equations() -> list[str] !{}:
    return ["d[M]/dt = -2 k_on [M]^2 + 2 k_off [D]", "d[D]/dt = k_on [M]^2 - k_off [D]", "d[C]/dt = u I [D]/([M]+2[D]) - k_C C", "d[T]/dt = g_T C - k_T T"]


equation insulin_signal_rhs(t, state, association_rate, dissociation_rate, cellular_gain, molecular_integrity, cellular_decay, tissue_gain, tissue_decay) -> any:
    association_flux := association_rate * state[0]^2
    dissociation_flux := dissociation_rate * state[1]
    molecular_mass := state[0] + 2.0 * state[1]
    dimer_fraction := state[1] / molecular_mass
    return [
        0.0 - 2.0 * association_flux + 2.0 * dissociation_flux,
        association_flux - dissociation_flux,
        cellular_gain * molecular_integrity * dimer_fraction - cellular_decay * state[2],
        tissue_gain * state[2] - tissue_decay * state[3],
    ]


equation optimize_cellular_gain(dimer_fraction, target, maximum_gain, effort_penalty, cellular_decay, tissue_gain, tissue_decay) -> any:
    response_gain := tissue_gain * dimer_fraction / (cellular_decay * tissue_decay)
    quadratic := 2.0 * (response_gain^2 + effort_penalty)
    linear := 0.0 - 2.0 * response_gain * target
    return quadratic_program([[quadratic]], [linear], [[1.0], [-1.0]], [maximum_gain, 0.0])


equation integrate_insulin_signal(monomer, dimer, horizon, association_rate, dissociation_rate, cellular_gain, cellular_decay, tissue_gain, tissue_decay) -> any:
    return ode(insulin_signal_rhs, 0.0, [monomer, dimer, 0.0, 0.0], horizon, 0.000000001, 0.000000000001, 100000, [association_rate, dissociation_rate, cellular_gain, 1.0, cellular_decay, tissue_gain, tissue_decay], "rk45")


equation integrate_insulin_live_state(state, horizon, association_rate, dissociation_rate, cellular_gain, molecular_integrity, cellular_decay, tissue_gain, tissue_decay) -> any:
    return ode(insulin_signal_rhs, 0.0, state, horizon, 0.000000001, 0.000000000001, 10000, [association_rate, dissociation_rate, cellular_gain, molecular_integrity, cellular_decay, tissue_gain, tissue_decay], "rk45")


def exploratory_unadmitted_association_preview(profile_id: str, evidence_id: str):
    sem "Expose an unadmitted association candidate for inspection without activating assumptions, evidence reliability, parameters, or decision authority"
    require len(profile_id) > 0 and len(evidence_id) == 64
    return AdaptationSummary(
        active_model_id="preregistered-insulin-association-v0",
        candidate_model_id=profile_id,
        selected_model_id="preregistered-insulin-association-v0",
        activated=false,
        admission_status="exploratory_unadmitted",
        admitted=false,
        exploratory=true,
        evidence_reliability=0.0,
        parameter_apply_authorized=false,
        reason="Phase8 admission gates failed; candidate remains proposed for exploratory inspection only",
        evidence_ids=[evidence_id],
    )


pub def admit_association_model(profile_id: str, association_rate: f64, dissociation_rate: f64, reference_error: f64, candidate_error: f64, evidence_id: str, observed_at: f64, admission_evidence: Phase8AdmissionEvidence) -> AdaptationSummary !{}:
    sem "Activate a reaction model only after the complete typed Phase8 evidence predicate plus held-out error, dwell-time, and hysteresis gates"
    require len(profile_id) > 0 and association_rate > 0.0 and dissociation_rate > 0.0
    require reference_error > 0.0 and candidate_error >= 0.0 and observed_at >= 1.0
    require len(evidence_id) == 64
    if not phase8_admission_evidence_complete(admission_evidence):
        return exploratory_unadmitted_association_preview(profile_id, evidence_id)
    validity = ValidityRegion(label=profile_id, in_scope=true, distance_to_boundary=0.0, checked_at=observed_at)
    assumption = Assumption(id="well-mixed-insulin-association", statement="The admitted Phase8 profile defines a bounded well-mixed association model", active=true, checked_at=observed_at, evidence_ids=[evidence_id])
    active = ModelDescriptor(id="preregistered-insulin-association-v0", family="mass-action-association", version=1, lifecycle=ModelLifecycle.active, parameter_names=["association_rate", "dissociation_rate"], parameters=[association_rate, dissociation_rate], structure_signature="M + M <-> D", assumptions=[assumption], validity=validity, fit_error=reference_error, validation_error=reference_error, created_at=0.0, activated_step=0)
    candidate = ModelDescriptor(id=profile_id, family="mass-action-association", version=2, lifecycle=ModelLifecycle.proposed, parameter_names=["association_rate", "dissociation_rate"], parameters=[association_rate, dissociation_rate], structure_signature="M + M <-> D", assumptions=[assumption], validity=validity, fit_error=candidate_error, validation_error=candidate_error, created_at=observed_at, activated_step=0)
    evidence = Evidence(id=evidence_id, source=profile_id, observed_at=observed_at, reliability=1.0, summary="Admitted Phase8 direct parity, mass conservation, interchange, ReaDDy, and PhysiCell validation", provenance=[evidence_id])
    policy = SelectionPolicy(min_validation_improvement=0.1, max_validation_error=0.000001, max_invariant_violations=0, min_dwell_steps=1, hysteresis_margin=0.000001, required_horizon_steps=1)
    validation = validate_candidate(active, candidate, candidate_error, candidate_error, 0, [evidence], observed_at, policy)
    decision = activate_validated(active, validation.model, 1, 1, [evidence], policy)
    match decision:
        case ActivationDecision.activated(previous, current, transition):
            return AdaptationSummary(active_model_id=previous.id, candidate_model_id=candidate.id, selected_model_id=current.id, activated=true, admission_status="admitted", admitted=true, exploratory=false, evidence_reliability=1.0, parameter_apply_authorized=true, reason=transition.reason, evidence_ids=[evidence_id])
        case ActivationDecision.blocked(reason, transition):
            return AdaptationSummary(active_model_id=active.id, candidate_model_id=candidate.id, selected_model_id=active.id, activated=false, admission_status="exploratory_unadmitted", admitted=false, exploratory=true, evidence_reliability=0.0, parameter_apply_authorized=false, reason=reason, evidence_ids=[evidence_id])


def run_multiscale_dynamics(profile_id: str, monomer_micromolar: f64, dimer_micromolar: f64, association_rate: f64, dissociation_rate: f64, intent: ControlIntent, adaptation: AdaptationSummary) !{}:
    sem "Compile a typed natural-language control intent into a globally solved gain, then integrate the admitted cross-scale equations"
    require len(profile_id) > 0 and monomer_micromolar > 0.0 and dimer_micromolar > 0.0
    require association_rate > 0.0 and dissociation_rate > 0.0
    require adaptation.activated and adaptation.selected_model_id == profile_id
    initial_mass = monomer_micromolar + 2.0 * dimer_micromolar
    dimer_fraction = dimer_micromolar / initial_mass
    cellular_decay = 1.0
    tissue_gain = 0.2
    tissue_decay = 0.5
    optimized = optimize_cellular_gain(dimer_fraction, intent.target_tissue_response, intent.maximum_cellular_gain, intent.effort_penalty, cellular_decay, tissue_gain, tissue_decay)
    ensure optimized.status == "Optimal" and optimized.scope == "global-convex"
    cellular_gain = optimized.solution[0]
    solved = integrate_insulin_signal(monomer_micromolar, dimer_micromolar, intent.horizon_s, association_rate, dissociation_rate, cellular_gain, cellular_decay, tissue_gain, tissue_decay)
    approximation = solved[0]
    final_state = [approximation.value[0], approximation.value[1], approximation.value[2], approximation.value[3]]
    final_mass = final_state[0] + 2.0 * final_state[1]
    mass_residual = abs(final_mass - initial_mass) / initial_mass
    target_error = abs(final_state[3] - intent.target_tissue_response)
    technical_pass = approximation.converged and optimized.status == "Optimal" and optimized.scope == "global-convex" and mass_residual <= 0.00000001 and approximation.residual <= 1.0 and target_error <= 0.005 and final_state[0] > 0.0 and final_state[1] > 0.0 and final_state[2] >= 0.0 and final_state[2] <= 1.0 and final_state[3] >= 0.0 and final_state[3] <= 1.0
    return DynamicsResult(schema="sema.multiscale-dynamics-result/v1", contract_id="insulin-association-cell-tissue-control-v1", semantics=intent.natural_language, formal_equations=["d[M]/dt = -2 k_on [M]^2 + 2 k_off [D]", "d[D]/dt = k_on [M]^2 - k_off [D]", "d[C]/dt = u [D]/([M]+2[D]) - k_C C", "d[T]/dt = g_T C - k_T T"], state_names=["insulin_monomer", "insulin_dimer", "cellular_signal", "tissue_response"], state_units=["micromolar", "micromolar", "fraction", "fraction"], final_state=final_state, cellular_gain=cellular_gain, target_tissue_response=intent.target_tissue_response, tissue_target_error=target_error, initial_molecular_mass_micromolar=initial_mass, final_molecular_mass_micromolar=final_mass, molecular_mass_relative_residual=mass_residual, integration_error_bound=approximation.residual, integration_steps_accepted=solved[1], integration_steps_rejected=solved[2], integration_method=approximation.method, optimizer_status=optimized.status, optimizer_scope=optimized.scope, optimizer_objective=optimized.objective, optimizer_iterations=optimized.iterations, adaptation=adaptation, evidence_ids=intent.evidence_ids, admission_status=adaptation.admission_status, admitted=adaptation.admitted, exploratory=adaptation.exploratory, parameter_apply_authorized=adaptation.parameter_apply_authorized, technical_pass=technical_pass, scientific_validated=false)


pub def preview_unadmitted_multiscale_dynamics(profile_id: str, monomer_micromolar: f64, dimer_micromolar: f64, association_rate: f64, dissociation_rate: f64, intent: ControlIntent, adaptation: AdaptationSummary) -> DynamicsResult !{}:
    sem "Compute an explicitly unadmitted, non-authoritative exploratory preview without applying candidate parameters to an active model"
    require len(profile_id) > 0 and monomer_micromolar > 0.0 and dimer_micromolar > 0.0
    require association_rate > 0.0 and dissociation_rate > 0.0
    require adaptation.candidate_model_id == profile_id and adaptation.exploratory and not adaptation.admitted and not adaptation.activated and not adaptation.parameter_apply_authorized
    initial_mass = monomer_micromolar + 2.0 * dimer_micromolar
    dimer_fraction = dimer_micromolar / initial_mass
    cellular_decay = 1.0
    tissue_gain = 0.2
    tissue_decay = 0.5
    optimized = optimize_cellular_gain(dimer_fraction, intent.target_tissue_response, intent.maximum_cellular_gain, intent.effort_penalty, cellular_decay, tissue_gain, tissue_decay)
    ensure optimized.status == "Optimal" and optimized.scope == "global-convex"
    cellular_gain = optimized.solution[0]
    solved = integrate_insulin_signal(monomer_micromolar, dimer_micromolar, intent.horizon_s, association_rate, dissociation_rate, cellular_gain, cellular_decay, tissue_gain, tissue_decay)
    approximation = solved[0]
    final_state = [approximation.value[0], approximation.value[1], approximation.value[2], approximation.value[3]]
    final_mass = final_state[0] + 2.0 * final_state[1]
    mass_residual = abs(final_mass - initial_mass) / initial_mass
    target_error = abs(final_state[3] - intent.target_tissue_response)
    return DynamicsResult(schema="sema.multiscale-dynamics-result/v1", contract_id="insulin-association-cell-tissue-control-v1", semantics="exploratory_unadmitted preview: " + intent.natural_language, formal_equations=["d[M]/dt = -2 k_on [M]^2 + 2 k_off [D]", "d[D]/dt = k_on [M]^2 - k_off [D]", "d[C]/dt = u [D]/([M]+2[D]) - k_C C", "d[T]/dt = g_T C - k_T T"], state_names=["insulin_monomer", "insulin_dimer", "cellular_signal", "tissue_response"], state_units=["micromolar", "micromolar", "fraction", "fraction"], final_state=final_state, cellular_gain=cellular_gain, target_tissue_response=intent.target_tissue_response, tissue_target_error=target_error, initial_molecular_mass_micromolar=initial_mass, final_molecular_mass_micromolar=final_mass, molecular_mass_relative_residual=mass_residual, integration_error_bound=approximation.residual, integration_steps_accepted=solved[1], integration_steps_rejected=solved[2], integration_method=approximation.method, optimizer_status=optimized.status, optimizer_scope=optimized.scope, optimizer_objective=optimized.objective, optimizer_iterations=optimized.iterations, adaptation=adaptation, evidence_ids=intent.evidence_ids, admission_status="exploratory_unadmitted", admitted=false, exploratory=true, parameter_apply_authorized=false, technical_pass=false, scientific_validated=false)


def compute_multiscale_dynamics_step(sequence: int, state_version: int, model_id: str, adaptation: AdaptationSummary, state: list[f64], population: PopulationState, physiology: dict[str, any], dt_s: f64, target_tissue_response: f64, maximum_cellular_gain: f64, effort_penalty: f64, molecular_integrity: f64, association_rate: f64, dissociation_rate: f64, evidence_ids: list[str], admitted_execution: bool) !{}:
    require sequence >= 0 and state_version >= 0
    require len(model_id) > 0 and len(state) == 4
    require state[0] > 0.0 and state[1] > 0.0 and state[2] >= 0.0 and state[2] <= 1.0 and state[3] >= 0.0 and state[3] <= 1.0
    require physiology["schema"] == "sema.metabolic-immune-observation/v1" and physiology["technical_pass"]
    require dt_s >= 0.01 and dt_s <= 0.25
    require target_tissue_response >= 0.0 and target_tissue_response <= 1.0
    require maximum_cellular_gain > 0.0 and maximum_cellular_gain <= 1.0 and effort_penalty > 0.0
    require molecular_integrity >= 0.0 and molecular_integrity <= 1.0
    require association_rate > 0.0 and dissociation_rate > 0.0
    require len(evidence_ids) > 0 and len(evidence_ids) <= 128
    if admitted_execution:
        ensure adaptation.admitted and adaptation.activated and adaptation.parameter_apply_authorized and adaptation.selected_model_id == model_id
    else:
        ensure adaptation.exploratory and not adaptation.admitted and not adaptation.activated and not adaptation.parameter_apply_authorized and adaptation.candidate_model_id == model_id
    population_next = advance_population_dynamics(population, dt_s, state[2], state[3], physiology["beta_function_fraction"], physiology["immune_effector_fraction"])
    effective_integrity = max(0.0, molecular_integrity - population_next.stress_fraction * 0.08)
    effective_target = target_tissue_response
    initial_mass = state[0] + 2.0 * state[1]
    dimer_fraction = state[1] / initial_mass
    cellular_decay = 1.0
    tissue_gain = 0.2
    tissue_decay = 0.5
    optimized = optimize_cellular_gain(dimer_fraction * effective_integrity, effective_target, maximum_cellular_gain, effort_penalty, cellular_decay, tissue_gain, tissue_decay)
    ensure optimized.status == "Optimal" and optimized.scope == "global-convex"
    cellular_gain = optimized.solution[0]
    solved = integrate_insulin_live_state(state, dt_s, association_rate, dissociation_rate, cellular_gain, effective_integrity, cellular_decay, tissue_gain, tissue_decay)
    approximation = solved[0]
    next_state = [approximation.value[0], approximation.value[1], approximation.value[2], approximation.value[3]]
    final_mass = next_state[0] + 2.0 * next_state[1]
    mass_residual = abs(final_mass - initial_mass) / initial_mass
    numerical_pass = approximation.converged and mass_residual <= 0.00000001 and approximation.residual <= 1.0 and next_state[0] > 0.0 and next_state[1] > 0.0 and next_state[2] >= 0.0 and next_state[2] <= 1.0 and next_state[3] >= 0.0 and next_state[3] <= 1.0
    admission_status = "admitted" if admitted_execution else "exploratory_unadmitted"
    semantics = "Sema RK45 molecular signaling coupled to glucose-insulin-beta and immune-graft physiology" if admitted_execution else "exploratory_unadmitted Sema RK45 preview without parameter-apply or decision authority"
    return DynamicsStep(
        schema="sema.multiscale-dynamics-step/v1",
        sequence=sequence,
        state_version=state_version + 1,
        equation_id="insulin-association-cell-tissue-control",
        equation_version=1,
        model_id=model_id,
        semantics=semantics,
        state=next_state,
        target_tissue_response=effective_target,
        cellular_gain=cellular_gain,
        molecular_integrity=effective_integrity,
        dt_s=dt_s,
        molecular_mass_relative_residual=mass_residual,
        integration_error_bound=max(approximation.residual, physiology["integration_error_bound"]),
        integration_steps_accepted=solved[1] + physiology["integration_steps_accepted"],
        integration_steps_rejected=solved[2] + physiology["integration_steps_rejected"],
        optimizer_status=optimized.status,
        optimizer_scope=optimized.scope,
        evidence_ids=evidence_ids,
        physiology=physiology,
        population=population_next,
        admission_status=admission_status,
        admitted=admitted_execution,
        exploratory=not admitted_execution,
        parameter_apply_authorized=admitted_execution,
        technical_pass=admitted_execution and numerical_pass,
        scientific_validated=false,
    )


pub def step_multiscale_dynamics(sequence: int, state_version: int, model_id: str, adaptation: AdaptationSummary, state: list[f64], population: PopulationState, physiology: dict[str, any], dt_s: f64, target_tissue_response: f64, maximum_cellular_gain: f64, effort_penalty: f64, molecular_integrity: f64, association_rate: f64, dissociation_rate: f64, evidence_ids: list[str]) -> DynamicsStep !{}:
    sem "Advance one viewer frame only through an explicitly admitted Phase8 association model"
    require adaptation.admitted and adaptation.activated and adaptation.parameter_apply_authorized
    return compute_multiscale_dynamics_step(sequence, state_version, model_id, adaptation, state, population, physiology, dt_s, target_tissue_response, maximum_cellular_gain, effort_penalty, molecular_integrity, association_rate, dissociation_rate, evidence_ids, true)


pub def preview_unadmitted_multiscale_dynamics_step(sequence: int, state_version: int, model_id: str, adaptation: AdaptationSummary, state: list[f64], population: PopulationState, physiology: dict[str, any], dt_s: f64, target_tissue_response: f64, maximum_cellular_gain: f64, effort_penalty: f64, molecular_integrity: f64, association_rate: f64, dissociation_rate: f64, evidence_ids: list[str]) -> DynamicsStep !{}:
    sem "Advance an isolated exploratory preview without applying candidate parameters to admitted state"
    require adaptation.exploratory and not adaptation.admitted and not adaptation.activated and not adaptation.parameter_apply_authorized
    return compute_multiscale_dynamics_step(sequence, state_version, model_id, adaptation, state, population, physiology, dt_s, target_tissue_response, maximum_cellular_gain, effort_penalty, molecular_integrity, association_rate, dissociation_rate, evidence_ids, false)
```

### `src/ensemble.sema`

```sema
"""Independent stochastic replica evidence with explicit uncertainty and replay class."""

assure silver


pub struct EnsembleResult:
    schema: str
    ensemble_id: str
    config_sha256: str
    coarse_config_sha256: str
    benchmark_config_sha256: str
    source_model_sha256: str
    result_sha256: str
    result_path: str
    platform: str
    replay_class: str
    evidence_class: str
    replicas: int
    samples_per_replica: int
    seeds: list[int]
    initial_state_sha256: list[str]
    distinct_initial_states: int
    basin_ids: list[str]
    occupancy_mean: list[f64]
    occupancy_sem: list[f64]
    transition_counts: list[int]
    transitions: int
    observed_basins: int
    free_energy_mean_kj_mol: list[f64]
    free_energy_sem_kj_mol: list[f64]
    effective_samples: f64
    rhat_defined: bool
    rhat_max: f64
    converged: bool
    invariant schema == "sema.ensemble-result/v1"
    invariant len(ensemble_id) > 0
    invariant len(config_sha256) == 64
    invariant len(coarse_config_sha256) == 64
    invariant len(benchmark_config_sha256) == 64
    invariant len(source_model_sha256) == 64
    invariant len(result_sha256) == 64
    invariant len(result_path) > 0
    invariant platform == "CPU"
    invariant replay_class == "statistical"
    invariant evidence_class == "independently_simulated"
    invariant replicas >= 2 and replicas <= 8
    invariant samples_per_replica > 1 and samples_per_replica <= 1000
    invariant len(seeds) == replicas
    invariant len(initial_state_sha256) == replicas
    invariant distinct_initial_states >= 2 and distinct_initial_states <= replicas
    invariant len(basin_ids) >= 2 and len(basin_ids) <= 16
    invariant len(occupancy_mean) == len(basin_ids)
    invariant len(occupancy_sem) == len(basin_ids)
    invariant len(transition_counts) == len(basin_ids) * len(basin_ids)
    invariant transitions >= 0 and transitions < replicas * samples_per_replica
    invariant observed_basins > 0 and observed_basins <= len(basin_ids)
    invariant len(free_energy_mean_kj_mol) == len(basin_ids)
    invariant len(free_energy_sem_kj_mol) == len(basin_ids)
    invariant effective_samples >= 0.0 and effective_samples <= f64(replicas * samples_per_replica)
    invariant rhat_max >= 0.0


pub bridge python.inline ensemble_backend from "foreign/python/ensemble_backend.py":
    deps "python>=3.12,<3.13"
    # The pinned four-replica workload measured 153.98 s standalone on the
    # qualified CPU profile; 300 s is a finite ~1.95x wall-time ceiling.
    timeout_ms "300000"
    expose:
        def run_ensemble(
            config_path: str,
            coarse_config_path: str,
            output_path: str,
        ) -> EnsembleResult !{ffi.call}:
            sem "Run seeded independent Langevin replicas and report PMF uncertainty and convergence"
```

### `src/insulin_pmf.sema`

```sema
"""Bounded explicit-solvent insulin-dimer association PMF evidence with strict validation gates."""

assure silver


pub struct InsulinPmfResult:
    schema: str
    profile_id: str
    config_sha256: str
    source_sha256: str
    system_sha256: str
    sample_sha256: list[str]
    evidence_sha256: str
    result_sha256: str
    result_path: str
    pdb_id: str
    backend: str
    backend_version: str
    platform: str
    force_field: str
    water_model: str
    temperature_k: f64
    atoms: int
    protein_atoms: int
    windows: int
    replicas_per_window: int
    samples_per_replica: int
    total_dynamics_steps: int
    window_centers_nm: list[f64]
    force_constants_kj_mol_nm2: list[f64]
    initial_centroid_distance_nm: f64
    minimized_energy_kj_mol: f64
    minimum_adjacent_overlap: f64
    adjacent_overlap: list[f64]
    overlap_matrix: list[f64]
    rhat_by_window: list[f64]
    rhat_max: f64
    integrated_autocorrelation_by_replica: list[f64]
    maximum_integrated_autocorrelation: f64
    ess_by_replica: list[f64]
    total_ess: f64
    mbar_free_energies_reduced: list[f64]
    mbar_iterations: int
    mbar_residual: f64
    estimator_converged: bool
    overlap_pass: bool
    rhat_pass: bool
    autocorrelation_pass: bool
    ess_pass: bool
    sampling_converged: bool
    sampling_uncertainty_available: bool
    parameter_uncertainty_available: bool
    model_form_uncertainty_available: bool
    restraint_correction_available: bool
    finite_size_correction_available: bool
    standard_state_correction_available: bool
    experimental_uncertainty_available: bool
    sampling_uncertainty_kj_mol: list[f64]
    parameter_uncertainty_kj_mol: list[f64]
    model_form_uncertainty_kj_mol: list[f64]
    restraint_correction_kj_mol: list[f64]
    finite_size_correction_kj_mol: list[f64]
    standard_state_correction_kj_mol: list[f64]
    experimental_uncertainty_kj_mol: list[f64]
    standard_state_delta_g_available: bool
    standard_state_delta_g_kj_mol: list[f64]
    independent_reference_pass: bool
    scientific_validated: bool
    technical_pass: bool
    failure_type: str
    blockers: list[str]
    resumed_replicas: int
    runtime_seconds: f64
    direct_oracle_result_sha256: str
    direct_oracle_path: str
    direct_parity_pass: bool
    invariant schema == "sema.insulin-association-pmf-result/v1"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(source_sha256) == 64
    invariant len(system_sha256) == 64
    invariant len(evidence_sha256) == 64
    invariant len(result_sha256) == 64
    invariant len(result_path) > 0
    invariant pdb_id == "6S34"
    invariant backend == "OpenMM"
    invariant backend_version == "8.5"
    invariant platform == "CPU"
    invariant force_field == "amber19-all.xml"
    invariant water_model == "amber19/tip3pfb.xml"
    invariant temperature_k == 298.15
    invariant atoms > protein_atoms and protein_atoms > 0
    invariant windows == len(window_centers_nm)
    invariant windows == len(force_constants_kj_mol_nm2)
    invariant len(sample_sha256) == windows * replicas_per_window
    invariant len(adjacent_overlap) == windows - 1
    invariant len(overlap_matrix) == windows * windows
    invariant len(rhat_by_window) == windows
    invariant len(integrated_autocorrelation_by_replica) == windows * replicas_per_window
    invariant len(ess_by_replica) == windows * replicas_per_window
    invariant len(mbar_free_energies_reduced) == windows
    invariant replicas_per_window >= 2
    invariant samples_per_replica > 0
    invariant total_dynamics_steps > 0
    invariant minimum_adjacent_overlap >= 0.0
    invariant total_ess >= 0.0
    invariant mbar_iterations > 0
    invariant mbar_residual >= 0.0
    invariant runtime_seconds >= 0.0
    invariant not scientific_validated or independent_reference_pass
    invariant not standard_state_delta_g_available or scientific_validated
    invariant standard_state_delta_g_available or len(standard_state_delta_g_kj_mol) == 0
    invariant scientific_validated or len(failure_type) > 0
    invariant len(direct_oracle_result_sha256) == 64
    invariant len(direct_oracle_path) > 0


pub bridge python.inline insulin_pmf_backend from "foreign/python/insulin_pmf_backend.py":
    deps "python>=3.12,<3.13", "numpy==2.4.1", "openmm==8.5.0"
    expose:
        def run_profile(config_path: str, oracle_path: str, output_path: str) -> InsulinPmfResult !{ffi.call}:
            sem "Run or resume pinned explicit-solvent insulin umbrella windows and admit no association free energy unless every gate passes"
```

### `src/insulin_structure.sema`

```sema
"""Pinned zinc-free human-insulin dimer construction and explicit-solvent technical evidence."""

assure silver


pub struct InsulinAtomisticResult:
    schema: str
    profile_id: str
    config_sha256: str
    source_sha256: str
    result_sha256: str
    result_path: str
    pdb_id: str
    assembly: int
    license: str
    doi: str
    backend: str
    backend_version: str
    platform: str
    force_field: str
    water_model: str
    temperature_k: f64
    ph: f64
    ionic_strength_molar: f64
    monomers: int
    protein_residues: int
    protein_atoms: int
    atoms: int
    solvent_atoms: int
    disulfide_bonds: int
    interface_contact_angstrom: f64
    initial_energy_kj_mol: f64
    final_energy_kj_mol: f64
    max_force_kj_mol_nm: f64
    steps: int
    system_sha256: str
    final_positions_sha256: str
    structural_pass: bool
    technical_pass: bool
    association_validated: bool
    evidence_class: str
    direct_oracle_result_sha256: str
    direct_oracle_path: str
    direct_parity_pass: bool
    invariant schema == "sema.insulin-atomistic-result/v1"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(source_sha256) == 64
    invariant len(result_sha256) == 64
    invariant len(result_path) > 0
    invariant pdb_id == "6S34"
    invariant assembly == 1
    invariant license == "CC0-1.0"
    invariant backend == "OpenMM"
    invariant platform == "CPU"
    invariant temperature_k == 298.15
    invariant ph == 2.5
    invariant ionic_strength_molar == 0.1
    invariant monomers == 2
    invariant protein_residues == 102
    invariant protein_atoms > 0
    invariant atoms > protein_atoms
    invariant solvent_atoms == atoms - protein_atoms
    invariant disulfide_bonds >= 6
    invariant interface_contact_angstrom >= 0.0
    invariant max_force_kj_mol_nm >= 0.0
    invariant steps > 0 and steps <= 1000
    invariant len(system_sha256) == 64
    invariant len(final_positions_sha256) == 64
    invariant evidence_class == "validated_atomistic_technical" or evidence_class == "failed_atomistic_technical"
    invariant len(direct_oracle_result_sha256) == 64
    invariant len(direct_oracle_path) > 0


pub bridge python.inline insulin_structure_backend from "foreign/python/insulin_structure_backend.py":
    deps "python>=3.12,<3.13", "numpy==2.4.1", "openmm==8.5.0"
    expose:
        def run_profile(config_path: str, oracle_path: str, output_path: str) -> InsulinAtomisticResult !{ffi.call}:
            sem "Construct a pinned zinc-free human-insulin dimer in explicit solvent and verify direct OpenMM parity"
```

### `src/insulin.sema`

```sema
"""Human insulin solution-thermodynamics model with pinned experimental evidence."""

assure silver


pub struct InsulinThermodynamicsResult:
    schema: str
    profile_id: str
    config_sha256: str
    artifact_sha256: str
    pmid: str
    doi: str
    subject: str
    assay: str
    temperature_k: f64
    buffer: str
    ph: f64
    zinc_added: bool
    ligand_added: bool
    independent_experiments: int
    kd_micromolar: f64
    kd_sem_micromolar: f64
    reported_dissociation_free_energy_kj_mol: f64
    reported_dissociation_free_energy_sem_kj_mol: f64
    modeled_dissociation_free_energy_kj_mol: f64
    modeled_dissociation_free_energy_sem_kj_mol: f64
    modeled_binding_free_energy_kj_mol: f64
    free_energy_residual_kj_mol: f64
    uncertainty_residual_kj_mol: f64
    combined_z_score: f64
    condition_pass: bool
    thermodynamic_pass: bool
    validated: bool
    evidence_class: str
    new_atomistic_simulation: bool
    result_sha256: str
    direct_oracle_result_sha256: str
    direct_oracle_path: str
    direct_parity_pass: bool
    result_path: str
    invariant schema == "sema.insulin-thermodynamics-result/v1"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(artifact_sha256) == 64
    invariant len(pmid) > 0
    invariant len(doi) > 0
    invariant len(subject) > 0
    invariant len(assay) > 0
    invariant temperature_k > 0.0
    invariant len(buffer) > 0
    invariant ph > 0.0 and ph <= 14.0
    invariant independent_experiments > 1
    invariant kd_micromolar > 0.0
    invariant kd_sem_micromolar >= 0.0
    invariant reported_dissociation_free_energy_kj_mol > 0.0
    invariant reported_dissociation_free_energy_sem_kj_mol >= 0.0
    invariant modeled_dissociation_free_energy_kj_mol > 0.0
    invariant modeled_dissociation_free_energy_sem_kj_mol >= 0.0
    invariant modeled_binding_free_energy_kj_mol < 0.0
    invariant free_energy_residual_kj_mol >= 0.0
    invariant uncertainty_residual_kj_mol >= 0.0
    invariant combined_z_score >= 0.0
    invariant len(result_sha256) == 64
    invariant len(direct_oracle_result_sha256) == 64
    invariant len(direct_oracle_path) > 0
    invariant len(result_path) > 0
    invariant evidence_class == "validated_human_solution_thermodynamics" or evidence_class ==    "failed_human_solution_thermodynamics"


pub bridge python.inline insulin_backend from "foreign/python/insulin_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def run_profile(config_path: str, oracle_path: str, output_path: str) -> InsulinThermodynamicsResult !{ffi.call}:
            sem "Validate human insulin monomer-dimer thermodynamics against a pinned eight-experiment ITC reference"
```

### `src/live.sema`

```sema
"""Persistent Sema HTTP service for evidence-bound live viewer dynamics."""

import http
from std.crypto import file_sha256
from std.json import decode as decode_json, encode as encode_json, read as read_json
from biological_computer.agent import agent_capabilities, propose_agent_program
from biological_computer.binding import binding_capabilities, dock_ligand, docking_rejection, initial_species_registry, occupancy_fraction, register_species, species_effect, species_public_state, species_registration_error
from biological_computer.cortex import cortex_capabilities, propose_cortex
from biological_computer.design import build_designed_structure, compile_design_command, design_capabilities, design_spec_valid
from biological_computer.dynamics import AdaptationSummary, Phase8AdmissionEvidence, admit_association_model, apply_biological_intervention, dynamics_equations, initial_population_state, phase8_admission_evidence_complete, preview_unadmitted_multiscale_dynamics_step, step_multiscale_dynamics
from biological_computer.molecular import apply_molecular_program, load_molecular_session, molecular_public_state, molecular_session_integrity, step_molecular_session, structure_key_supported
from biological_computer.physiology import initial_physiology_state, physiology_parameter_bounds, physiology_public_state, step_physiology_state
from biological_computer.programming import apply_biological_program, compile_biological_command, initial_program_state, programming_capabilities, signal_bounds

assure silver


struct LiveProfile:
    model_id: str
    association_rate: f64
    dissociation_rate: f64
    initial_state: list[f64]
    evidence_ids: list[str]
    scene_sha256: str
    population_cells: int
    admission_evidence: Phase8AdmissionEvidence
    adaptation: AdaptationSummary
    invariant len(model_id) > 0
    invariant association_rate > 0.0 and dissociation_rate > 0.0
    invariant len(initial_state) == 4
    invariant initial_state[0] > 0.0 and initial_state[1] > 0.0
    invariant len(evidence_ids) == 2
    invariant all(len(evidence_id) == 64 for evidence_id in evidence_ids)
    invariant len(scene_sha256) == 64
    invariant population_cells > 0 and population_cells <= 16384
    invariant adaptation.candidate_model_id == model_id
    invariant adaptation.admitted == false or phase8_admission_evidence_complete(admission_evidence)


def load_live_profile() !{fs.read}:
    ensure file_sha256("runs/mesoscopic/phase8-sema.json") == "9a38dc0a0057fcd667fa88e85d88d99a2d65755eefdf0813aa1337933ec419cc"
    source = read_json("runs/mesoscopic/phase8-sema.json")
    ensure source["result_sha256"] == "3164645981cd04fae5811856b166156769b39b35a85bf441748a468a24fa19f7"
    ensure source["schema"] == "sema.mesoscopic-result/v1"
    ensure source["direct_parity_pass"] and source["transfer_pass"]
    ensure file_sha256("runs/readdy-calibration/sema.json") == "9000bb00e06c6b00daf03b075f834a46b7cfcaff7be4b61d4e393f3258758679"
    readdy = read_json("runs/readdy-calibration/sema.json")
    ensure readdy["schema"] == "sema.readdy-calibration-result/v1"
    ensure readdy["result_sha256"] == "70ab940f6eecb9aaeb309a068ab20055a58e7df85f686be6fb7669c15cd4995a"
    ensure file_sha256("runs/physicell/sema.json") == "27a819ceca949921ce75afe89632255a88c107b207ab224e28ea0498aa5b2c82"
    physicell = read_json("runs/physicell/sema.json")
    ensure physicell["schema"] == "sema.physicell-result/v1"
    ensure physicell["result_sha256"] == "04c0f4cd8885e0dd88535a2e01e5b06d7609bd4cfdfa58f36ff28407fe463b97"
    ensure physicell["phase8_result_sha256"] == source["result_sha256"]
    ensure physicell["phase8_artifact_sha256"] == file_sha256("runs/mesoscopic/phase8-sema.json")
    admission_evidence = Phase8AdmissionEvidence(
        phase8_technical_pass=source["phase8_technical_pass"],
        readdy_chronology_proven=readdy["heldout_evidence_admission"]["chronology_proven"],
        readdy_qualification_pass=readdy["qualification_pass"],
        readdy_convergence_pass=readdy["gates"]["convergence_pass"],
        readdy_spatial_pass=readdy["gates"]["spatial_pass"],
        readdy_admission_pass=readdy["phase8_scientific_validation"],
        physicell_custom_insulin_pass=physicell["insulin_reaction_supported"],
        physicell_target_rate_pass=physicell["target_rate_evidence"],
        physicell_uncertainty_pass=physicell["scientific_uncertainty_evidence"],
        physicell_scientific_pass=physicell["scientific_validated"],
    )
    adaptation = admit_association_model(
        source["profile_id"],
        source["association_rate_per_micromolar_s"],
        source["dissociation_rate_per_s"],
        source["source_kd_sem_micromolar"] / source["source_kd_micromolar"],
        source["kd_relative_residual"],
        source["result_sha256"],
        source["simulated_time_s"],
        admission_evidence,
    )
    scene = read_json("viewer/public/data/scene.json")
    ensure scene["schema"] == "sema.multiscale-viewer/v4"
    return LiveProfile(
        model_id=source["profile_id"],
        association_rate=source["association_rate_per_micromolar_s"],
        dissociation_rate=source["dissociation_rate_per_s"],
        initial_state=[source["observed_monomer_micromolar"], source["observed_dimer_micromolar"], 0.0, 0.0],
        evidence_ids=[source["result_sha256"], source["direct_oracle_result_sha256"]],
        scene_sha256=file_sha256("viewer/public/data/scene.json"),
        population_cells=scene["scene_model"]["tissue"]["cell_count"],
        admission_evidence=admission_evidence,
        adaptation=adaptation,
    )


def response(status: int, body: any) !{}:
    return {
        "status": status,
        "content_type": "application/json",
        "headers": {"Cache-Control": "no-store"},
        "body": encode_json(body),
    }


def error_response(status: int, code: str, detail: str) !{}:
    return response(status, {"schema": "sema.biological-live-error/v1", "error": code, "detail": detail})


def active_species_registry(profile: LiveProfile, session: dict[str, any]):
    return session["preview_species"] if profile.adaptation.exploratory else session["species"]


def species_adjusted_program(program: dict[str, any], registry: dict[str, any]) !{}:
    sem "Fold every introduced designed species into a bounded copy of the physiology parameters and signals"
    introduced = species_public_state(registry)
    if len(introduced) == 0:
        return {"parameters": program["parameters"], "signals": program["signals"]}
    parameter_bounds = physiology_parameter_bounds()
    bounds = signal_bounds()
    mut parameters = {name: value for name, value in program["parameters"].items()}
    mut signals = {name: value for name, value in program["signals"].items()}
    for species in introduced:
        effect = species_effect(species["mechanism"], occupancy_fraction(species["kd_micromolar"], species["concentration_micromolar"]))
        for key in effect.keys():
            if key.startswith("parameter:"):
                name = key.slice(10, len(key))
                limits = parameter_bounds[name]
                parameters[name] = max(limits[0], min(limits[1], parameters[name] * effect[key]))
            elif key.startswith("signal_max:"):
                name = key.slice(11, len(key))
                limits = bounds[name]
                signals[name] = max(limits[0], min(limits[1], max(signals[name], effect[key])))
            elif key.startswith("signal_add:"):
                name = key.slice(11, len(key))
                limits = bounds[name]
                signals[name] = max(limits[0], min(limits[1], signals[name] + effect[key]))
    return {"parameters": parameters, "signals": signals}


def status_response(profile: LiveProfile, session: dict[str, any]) !{}:
    mut molecular: any = None
    if session["molecular"] != None:
        molecular = molecular_public_state(session["molecular"])
        molecular["generation"] = session["molecular_generation"]
    mut visible_state = session["state"]
    mut visible_sequence = session["sequence"]
    mut visible_state_version = session["state_version"]
    mut visible_generation = session["active_generation"]
    mut visible_population = session["population"]
    mut visible_physiology = session["physiology"]
    mut visible_species = session["species"]
    if profile.adaptation.exploratory:
        visible_state = session["preview_state"]
        visible_sequence = session["preview_sequence"]
        visible_state_version = session["preview_state_version"]
        visible_generation = session["preview_generation"]
        visible_population = session["preview_population"]
        visible_physiology = session["preview_physiology"]
        visible_species = session["preview_species"]
    effective = species_adjusted_program(session["program"], visible_species)
    return response(200, {
        "schema": "sema.biological-live-status/v1",
        "backend": "Sema",
        "model_id": profile.model_id,
        "equation_id": "insulin-association-cell-tissue-control",
        "equation_version": 1,
        "equations": dynamics_equations(),
        "state_names": ["insulin_monomer", "insulin_dimer", "cellular_signal", "tissue_response"],
        "state_units": ["micromolar", "micromolar", "fraction", "fraction"],
        "initial_state": profile.initial_state,
        "state": visible_state,
        "sequence": visible_sequence,
        "state_version": visible_state_version,
        "generation": visible_generation,
        "state_admission_status": profile.adaptation.admission_status,
        "active_state": session["state"],
        "active_state_version": session["state_version"],
        "active_generation": session["active_generation"],
        "preview_generation": session["preview_generation"],
        "molecular_generation": session["molecular_generation"],
        "phase8_technical_pass": profile.admission_evidence.phase8_technical_pass,
        "readdy_validated": profile.admission_evidence.readdy_chronology_proven and profile.admission_evidence.readdy_qualification_pass and profile.admission_evidence.readdy_convergence_pass and profile.admission_evidence.readdy_spatial_pass and profile.admission_evidence.readdy_admission_pass,
        "physicell_validated": profile.admission_evidence.physicell_custom_insulin_pass and profile.admission_evidence.physicell_target_rate_pass and profile.admission_evidence.physicell_uncertainty_pass and profile.admission_evidence.physicell_scientific_pass,
        "phase8_admission_evidence_complete": phase8_admission_evidence_complete(profile.admission_evidence),
        "admitted": profile.adaptation.admitted,
        "activated": profile.adaptation.activated,
        "exploratory": profile.adaptation.exploratory,
        "evidence_reliability": profile.adaptation.evidence_reliability,
        "parameter_apply_authorized": profile.adaptation.parameter_apply_authorized,
        "decision_authority": false,
        "technical_pass": profile.adaptation.admitted,
        "update_hz": 10,
        "scene_sha256": profile.scene_sha256,
        "evidence_ids": profile.evidence_ids,
        "population": visible_population,
        "program": session["program"],
        "physiology": physiology_public_state(visible_physiology, effective["signals"], effective["parameters"]),
        "programming_capabilities": programming_capabilities(),
        "molecular": molecular,
        "species": species_public_state(visible_species),
        "design_generation": session["design_generation"],
        "scientific_validated": false,
    })


def step_input_error(payload: any) !{}:
    if not (payload is dict):
        return "step request must be an object"
    required = ["generation", "molecular_generation", "sequence", "state_version", "dt_s", "target_tissue_response"]
    if not all(payload.has(field) for field in required):
        return "step request is missing a required field"
    if not (payload["generation"] is int) or not (payload["molecular_generation"] is int) or not (payload["sequence"] is int) or not (payload["state_version"] is int):
        return "generation, molecular_generation, sequence, and state_version must be integers"
    if payload["generation"] < 0 or payload["molecular_generation"] < 0 or payload["sequence"] < 0 or payload["state_version"] < 0:
        return "generation, molecular_generation, sequence, and state_version must be nonnegative"
    if not (payload["dt_s"] is float) or payload["dt_s"] != payload["dt_s"] or payload["dt_s"] < 0.01 or payload["dt_s"] > 0.25:
        return "dt_s must be a finite number in [0.01, 0.25]"
    if not (payload["target_tissue_response"] is int or payload["target_tissue_response"] is float) or payload["target_tissue_response"] != payload["target_tissue_response"] or payload["target_tissue_response"] < 0.0 or payload["target_tissue_response"] > 1.0:
        return "target_tissue_response must be a finite number in [0, 1]"
    return ""


def canonical_step_request_identity(payload: dict[str, any], profile: LiveProfile, session: dict[str, any], admission_branch: str, step_state: any, step_population: any, step_physiology: any, step_species: any) !{}:
    molecular_integrity = 1.0 if session["molecular"] is None else molecular_session_integrity(session["molecular"])
    return encode_json({
        "schema": "sema.biological-live-step-request-identity/v1",
        "generation": payload["generation"],
        "molecular_generation": payload["molecular_generation"],
        "sequence": payload["sequence"],
        "state_version": payload["state_version"],
        "dt_s": payload["dt_s"],
        "target_tissue_response": payload["target_tissue_response"],
        "admission_branch": admission_branch,
        "admission_status": profile.adaptation.admission_status,
        "admitted": profile.adaptation.admitted,
        "activated": profile.adaptation.activated,
        "exploratory": profile.adaptation.exploratory,
        "parameter_apply_authorized": profile.adaptation.parameter_apply_authorized,
        "model_id": profile.model_id,
        "association_rate": profile.association_rate,
        "dissociation_rate": profile.dissociation_rate,
        "evidence_ids": profile.evidence_ids,
        "molecular_revision": session["molecular_revision"],
        "molecular_integrity": molecular_integrity,
        "program": session["program"],
        "step_state": step_state,
        "step_population": step_population,
        "step_physiology": step_physiology,
        "step_species": species_public_state(step_species),
    })


def live_step_response_body(step: any, generation: int, molecular_generation: int) !{}:
    body = decode_json(encode_json(step))
    body["generation"] = generation
    body["molecular_generation"] = molecular_generation
    return body


def exploratory_step_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}:
    require profile.adaptation.exploratory and not profile.adaptation.admitted and not profile.adaptation.activated and not profile.adaptation.parameter_apply_authorized
    if payload["generation"] != session["preview_generation"]:
        return error_response(409, "LiveGenerationConflict", "generation does not match isolated exploratory_unadmitted preview state")
    if payload["molecular_generation"] != session["molecular_generation"]:
        return error_response(409, "MolecularGenerationConflict", "molecular generation does not match the state coupled to this live step")
    mut step_state = session["preview_state"]
    mut step_population = session["preview_population"]
    mut step_physiology = session["preview_physiology"]
    mut step_species = session["preview_species"]
    mut retrying_retained_request = false
    retry_context = session["preview_retry_context"]
    retry_identifiers_match = retry_context != None and payload["generation"] == retry_context["generation"] and payload["sequence"] == retry_context["sequence"] and payload["state_version"] == retry_context["state_version"]
    completed_identifiers_match = payload["generation"] == session["preview_generation"] and payload["sequence"] == session["preview_sequence"] and payload["state_version"] + 1 == session["preview_state_version"]
    if retry_identifiers_match:
        step_state = retry_context["state"]
        step_population = retry_context["population"]
        step_physiology = retry_context["physiology"]
        step_species = retry_context["species"]
        request_identity = canonical_step_request_identity(payload, profile, session, "exploratory_unadmitted", step_state, step_population, step_physiology, step_species)
        if request_identity != retry_context["request_identity"]:
            return error_response(409, "LiveRequestConflict", "step identifiers are already bound to a different exploratory request identity")
        if session["preview_last_step"] != None and completed_identifiers_match:
            return response(200, session["preview_last_step"])
        retrying_retained_request = true
    elif completed_identifiers_match:
        return error_response(409, "LiveRequestConflict", "completed exploratory step identifiers have no matching retained request identity")
    if not retrying_retained_request and (payload["sequence"] != session["preview_sequence"] + 1 or payload["state_version"] != session["preview_state_version"]):
        return error_response(409, "LiveStateConflict", "sequence or state version does not match isolated exploratory_unadmitted preview state")
    request_identity = canonical_step_request_identity(payload, profile, session, "exploratory_unadmitted", step_state, step_population, step_physiology, step_species)
    effective = species_adjusted_program(session["program"], step_species)
    physiology_state = step_physiology_state(step_physiology, payload["dt_s"], effective["signals"], effective["parameters"])
    if not physiology_state["technical_pass"]:
        return error_response(422, "PhysiologyPreviewRejected", "exploratory physiology preview solver evidence did not pass")
    physiology = physiology_public_state(physiology_state, effective["signals"], effective["parameters"])
    physiology_target = min(1.0, payload["target_tissue_response"] * min(1.0, physiology["beta_function_fraction"]) * (1.0 - physiology["cytokine_fraction"] * 0.4))
    integrity = 1.0 if session["molecular"] is None else molecular_session_integrity(session["molecular"])
    step = preview_unadmitted_multiscale_dynamics_step(
        payload["sequence"],
        payload["state_version"],
        profile.model_id,
        profile.adaptation,
        step_state,
        step_population,
        physiology,
        payload["dt_s"],
        physiology_target,
        1.0,
        0.0001,
        integrity,
        profile.association_rate,
        profile.dissociation_rate,
        profile.evidence_ids,
    )
    ensure step.admission_status == "exploratory_unadmitted" and step.exploratory
    ensure not step.admitted and not step.parameter_apply_authorized and not step.technical_pass and not step.scientific_validated
    session["preview_retry_context"] = {
        "generation": payload["generation"],
        "sequence": payload["sequence"],
        "state_version": payload["state_version"],
        "request_identity": request_identity,
        "state": step_state,
        "population": step_population,
        "physiology": step_physiology,
        "species": step_species,
    }
    session["preview_state"] = step.state
    session["preview_physiology"] = physiology_state
    session["preview_population"] = step.population
    session["preview_sequence"] = step.sequence
    session["preview_state_version"] = step.state_version
    step_body = live_step_response_body(step, session["preview_generation"], session["molecular_generation"])
    session["preview_last_step"] = step_body
    return response(200, step_body)


def step_response(payload: any, profile: LiveProfile, session: dict[str, any]) !{}:
    input_error = step_input_error(payload)
    if len(input_error) > 0:
        return error_response(422, "LiveInputInvalid", input_error)
    if profile.adaptation.exploratory:
        return exploratory_step_response(payload, profile, session)
    if not phase8_admission_evidence_complete(profile.admission_evidence) or not profile.adaptation.admitted or not profile.adaptation.activated or not profile.adaptation.parameter_apply_authorized:
        return error_response(409, "Phase8ModelUnadmitted", "Phase8 association rates cannot advance admitted live state")
    if payload["generation"] != session["active_generation"]:
        return error_response(409, "LiveGenerationConflict", "generation does not match Sema-owned admitted state")
    if payload["molecular_generation"] != session["molecular_generation"]:
        return error_response(409, "MolecularGenerationConflict", "molecular generation does not match the state coupled to this live step")
    mut step_state = session["state"]
    mut step_population = session["population"]
    mut step_physiology = session["physiology"]
    mut step_species = session["species"]
    mut retrying_retained_request = false
    retry_context = session["retry_context"]
    retry_identifiers_match = retry_context != None and payload["generation"] == retry_context["generation"] and payload["sequence"] == retry_context["sequence"] and payload["state_version"] == retry_context["state_version"]
    completed_identifiers_match = payload["generation"] == session["active_generation"] and payload["sequence"] == session["sequence"] and payload["state_version"] + 1 == session["state_version"]
    if retry_identifiers_match:
        step_state = retry_context["state"]
        step_population = retry_context["population"]
        step_physiology = retry_context["physiology"]
        step_species = retry_context["species"]
        request_identity = canonical_step_request_identity(payload, profile, session, "admitted_active", step_state, step_population, step_physiology, step_species)
        if request_identity != retry_context["request_identity"]:
            return error_response(409, "LiveRequestConflict", "step identifiers are already bound to a different admitted request identity")
        if session["last_step"] != None and completed_identifiers_match:
            return response(200, session["last_step"])
        retrying_retained_request = true
    elif completed_identifiers_match:
        return error_response(409, "LiveRequestConflict", "completed admitted step identifiers have no matching retained request identity")
    if not retrying_retained_request and (payload["sequence"] != session["sequence"] + 1 or payload["state_version"] != session["state_version"]):
        return error_response(409, "LiveStateConflict", "sequence or state version does not match Sema-owned state")
    request_identity = canonical_step_request_identity(payload, profile, session, "admitted_active", step_state, step_population, step_physiology, step_species)
    effective = species_adjusted_program(session["program"], step_species)
    physiology_state = step_physiology_state(step_physiology, payload["dt_s"], effective["signals"], effective["parameters"])
    if not physiology_state["technical_pass"]:
        return error_response(422, "PhysiologyStepRejected", "Sema metabolic-immune solver evidence did not pass")
    physiology = physiology_public_state(physiology_state, effective["signals"], effective["parameters"])
    physiology_target = min(1.0, payload["target_tissue_response"] * min(1.0, physiology["beta_function_fraction"]) * (1.0 - physiology["cytokine_fraction"] * 0.4))
    integrity = 1.0 if session["molecular"] is None else molecular_session_integrity(session["molecular"])
    step = step_multiscale_dynamics(
        payload["sequence"],
        payload["state_version"],
        profile.model_id,
        profile.adaptation,
        step_state,
        step_population,
        physiology,
        payload["dt_s"],
        physiology_target,
        1.0,
        0.0001,
        integrity,
        profile.association_rate,
        profile.dissociation_rate,
        profile.evidence_ids,
    )
    if not step.technical_pass:
        return error_response(422, "LiveStepRejected", "Sema numerical or invariant evidence did not pass")
    session["retry_context"] = {
        "generation": payload["generation"],
        "sequence": payload["sequence"],
        "state_version": payload["state_version"],
        "request_identity": request_identity,
        "state": step_state,
        "population": step_population,
        "physiology": step_physiology,
        "species": step_species,
    }
    session["state"] = step.state
    session["physiology"] = physiology_state
    session["population"] = step.population
    session["sequence"] = step.sequence
    session["state_version"] = step.state_version
    step_body = live_step_response_body(step, session["active_generation"], session["molecular_generation"])
    session["last_step"] = step_body
    return response(200, step_body)


def has_intervention_fields(payload: dict[str, any]):
    return all(payload.has(field) for field in ["generation", "state_version", "kind", "target_index", "target_kind", "magnitude", "amount", "molecule", "mutation", "seed_cells"])


def intervention_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}:
    if not has_intervention_fields(payload):
        return error_response(422, "LiveInterventionInvalid", "intervention request is missing a required field")
    if profile.adaptation.exploratory and payload["generation"] != session["preview_generation"]:
        return error_response(409, "LiveGenerationConflict", "generation does not match isolated exploratory_unadmitted preview state")
    if not profile.adaptation.exploratory and payload["generation"] != session["active_generation"]:
        return error_response(409, "LiveGenerationConflict", "generation does not match Sema-owned admitted state")
    if profile.adaptation.exploratory and payload["state_version"] != session["preview_state_version"]:
        return error_response(409, "LiveStateConflict", "state version does not match isolated exploratory_unadmitted preview state")
    if not profile.adaptation.exploratory and payload["state_version"] != session["state_version"]:
        return error_response(409, "LiveStateConflict", "state version does not match Sema-owned admitted state")
    if not (payload["kind"] == "force" or payload["kind"] == "inject" or payload["kind"] == "mutate" or payload["kind"] == "ablate"):
        return error_response(422, "LiveInterventionInvalid", "unsupported intervention kind")
    if payload["target_index"] < -1 or payload["target_index"] >= 16384:
        return error_response(422, "LiveInterventionInvalid", "target index is outside the bounded biological scene")
    if not (payload["target_kind"] == "population" or payload["target_kind"] == "tissue-cell" or payload["target_kind"] == "vessel" or payload["target_kind"] == "granule" or payload["target_kind"] == "mitochondrion" or payload["target_kind"] == "receptor" or payload["target_kind"] == "protein" or payload["target_kind"] == "protein-atom" or payload["target_kind"] == "source-atom" or payload["target_kind"] == "membrane" or payload["target_kind"] == "nucleus" or payload["target_kind"] == "cytoskeleton" or payload["target_kind"] == "endoplasmic-reticulum" or payload["target_kind"] == "lipid-droplet" or payload["target_kind"] == "vessel-wall" or payload["target_kind"] == "vessel-lumen" or payload["target_kind"] == "erythrocyte"):
        return error_response(422, "LiveInterventionInvalid", "unsupported intervention target kind")
    if payload["magnitude"] < -80.0 or payload["magnitude"] > 80.0 or payload["amount"] < 0.0 or payload["amount"] > 100.0:
        return error_response(422, "LiveInterventionInvalid", "force or amount is outside its declared bounds")
    if payload["kind"] == "force" and (payload["target_index"] < 0 or payload["magnitude"] == 0.0):
        return error_response(422, "LiveInterventionInvalid", "force requires a selected target and nonzero signed magnitude")
    if payload["kind"] == "ablate" and payload["target_index"] < 0:
        return error_response(422, "LiveInterventionInvalid", "ablation requires a selected target")
    if payload["kind"] == "ablate" and payload["target_kind"] != "tissue-cell":
        return error_response(422, "LiveInterventionInvalid", "ablation requires a tissue-cell target")
    if payload["kind"] == "mutate" and not (payload["target_kind"] == "population" or payload["target_kind"] == "tissue-cell"):
        return error_response(422, "LiveInterventionInvalid", "mutation requires a population or tissue-cell target")
    if payload["seed_cells"] < 0 or payload["seed_cells"] > 32:
        return error_response(422, "LiveInterventionInvalid", "mutation seed count is outside its declared bound")
    if profile.adaptation.exploratory:
        preview_population = apply_biological_intervention(session["preview_population"], payload["kind"], payload["target_index"], payload["target_kind"], payload["magnitude"], payload["amount"], payload["molecule"], payload["mutation"], payload["seed_cells"])
        session["preview_population"] = preview_population
        session["preview_state_version"] = session["preview_state_version"] + 1
        session["preview_last_step"] = None
        session["preview_retry_context"] = None
        return status_response(profile, session)
    population = apply_biological_intervention(session["population"], payload["kind"], payload["target_index"], payload["target_kind"], payload["magnitude"], payload["amount"], payload["molecule"], payload["mutation"], payload["seed_cells"])
    session["population"] = population
    session["state_version"] = session["state_version"] + 1
    session["last_step"] = None
    session["retry_context"] = None
    return status_response(profile, session)


def store_species(profile: LiveProfile, session: dict[str, any], registry: dict[str, any]):
    if profile.adaptation.exploratory:
        session["preview_species"] = registry
        session["preview_state_version"] = session["preview_state_version"] + 1
        session["preview_last_step"] = None
        session["preview_retry_context"] = None
    else:
        session["species"] = registry
        session["state_version"] = session["state_version"] + 1
        session["last_step"] = None
        session["retry_context"] = None


def docking_identity(target: dict[str, any], ligand: dict[str, any], budget: int) !{}:
    return encode_json({
        "schema": "sema.molecular-binding-request-identity/v1",
        "ligand_source_sha256": ligand["source_sha256"],
        "target_source_sha256": target["source_sha256"],
        "budget": budget,
    })


def dock_design(session: dict[str, any], name: str, budget: int) !{fs.read}:
    mut designs = session["designs"]
    design = designs[name]
    target_key = design["spec"]["target_key"]
    if len(target_key) == 0:
        return {"error": "DockingRejected", "detail": "the design carries no targeting clause, so there is no target to dock against", "design": design}
    if not structure_key_supported(target_key):
        return {"error": "MolecularStructureUnavailable", "detail": "the design target is not in the digest-bound molecular library", "design": design}
    target = load_molecular_session(target_key)
    identity = docking_identity(target, design["structure"], budget)
    if design["docking_identity"] == identity:
        return {"error": "", "detail": "", "design": design}
    rejection = docking_rejection(target, design["structure"], budget)
    if len(rejection) > 0:
        return {"error": "DockingRejected", "detail": rejection, "design": design}
    design["docking"] = dock_ligand(target, design["structure"], budget)
    design["docking_identity"] = identity
    designs[name] = design
    session["designs"] = designs
    return {"error": "", "detail": "", "design": design}


def design_result_body(design: dict[str, any], species: any, summary: list[str]):
    return {
        "schema": "sema.molecular-design-result/v1",
        "backend": "Sema",
        "spec": design["spec"],
        "structure": design["structure"],
        "species": species,
        "summary": summary,
        "scientific_validated": false,
    }


def registration_error_response(registration: dict[str, str]) !{}:
    status = 413 if registration["error"] == "SpeciesRegistryFull" else 422
    return error_response(status, registration["error"], registration["detail"])


def set_design_mechanism(compiled: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}:
    sem "Re-declare what an existing design does biologically, committing the registry only once the species re-registers"
    name = compiled["name"]
    mut designs = session["designs"]
    if not designs.has(name):
        return error_response(404, "DesignUnknown", "no design with that name exists in this Sema session")
    mechanism = compiled["mechanism"]
    design = designs[name]
    registry = active_species_registry(profile, session)
    mut species: any = None
    if registry.has(name):
        introduced = registry[name]
        registration = species_registration_error(registry, design["spec"], design["docking"], introduced["concentration_micromolar"], mechanism)
        if len(registration["error"]) > 0:
            return registration_error_response(registration)
        next_registry = register_species(registry, design["spec"], design["structure"], design["docking"], introduced["concentration_micromolar"], mechanism, introduced["introduced_at_days"])
        species = next_registry[name]
        store_species(profile, session, next_registry)
    design["mechanism"] = mechanism
    designs[name] = design
    session["designs"] = designs
    session["design_generation"] = session["design_generation"] + 1
    return response(200, design_result_body(design, species, ["design=" + name, "mechanism=" + mechanism]))


def apply_design_command(compiled: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}:
    if compiled["kind"] == "set_mechanism":
        return set_design_mechanism(compiled, profile, session)
    name = compiled["name"]
    spec = compiled["spec"]
    if not design_spec_valid(spec):
        return error_response(422, "DesignRejected", "the compiled design specification is outside its declared bounds")
    if active_species_registry(profile, session).has(name):
        return error_response(409, "SpeciesStateConflict", "a designed species with that name is already introduced into the live tissue")
    mut designs = session["designs"]
    if not designs.has(name) and len(designs) >= design_capabilities()["max_designs"]:
        return error_response(413, "DesignRegistryFull", "this Sema session already holds the maximum number of bounded designs")
    structure = build_designed_structure(spec)
    design = {"spec": spec, "structure": structure, "mechanism": spec["mechanism"], "docking": None, "docking_identity": ""}
    designs[name] = design
    session["designs"] = designs
    session["design_generation"] = session["design_generation"] + 1
    return response(200, design_result_body(design, None, [
        "design=" + name,
        "class=" + spec["class"],
        "conformation=" + spec["conformation"],
        "target=" + spec["target_key"],
        "mechanism=" + spec["mechanism"],
        "atoms=" + str(len(structure["atomic_numbers"])),
        "bonds=" + str(len(structure["bonds"]) // 2),
        "fidelity=" + structure["fidelity"],
        "biological_match=" + structure["biological_match"],
    ]))


def design_mutation_identity(payload: dict[str, any]) !{}:
    return encode_json({
        "schema": "sema.biological-design-request-identity/v1",
        "program_state_version": payload["program_state_version"],
        "command": payload["command"],
    })


def design_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}:
    if not payload.has("program_state_version") or not payload.has("command"):
        return error_response(422, "DesignCompileError", "program_state_version and command are required")
    if payload["program_state_version"] != session["program"]["state_version"]:
        return error_response(409, "DesignStateConflict", "program state version does not match Sema-owned program state")
    request_identity = design_mutation_identity(payload)
    if session["design_last_identity"] == request_identity and session["design_last_generation"] == session["design_generation"]:
        return session["design_last_response"]
    compiled = compile_design_command(payload["command"])
    if not compiled["ok"]:
        return error_response(422, compiled["error"], compiled["detail"])
    applied = apply_design_command(compiled, profile, session)
    if applied["status"] == 200:
        session["design_last_identity"] = request_identity
        session["design_last_response"] = applied
        session["design_last_generation"] = session["design_generation"]
    return applied


def dock_response(payload: dict[str, any], session: dict[str, any]) !{fs.read}:
    if not payload.has("generation") or not payload.has("name"):
        return error_response(422, "DockingRejected", "generation and name are required")
    if payload["generation"] != session["design_generation"]:
        return error_response(409, "DesignStateConflict", "generation does not match the Sema-owned design registry")
    if not session["designs"].has(payload["name"]):
        return error_response(404, "DesignUnknown", "no design with that name exists in this Sema session")
    budget = payload["budget"] if payload.has("budget") else 512
    if budget < 64 or budget > 4096:
        return error_response(422, "DockingRejected", "budget must be a pose count in [64, 4096]")
    docked = dock_design(session, payload["name"], budget)
    if len(docked["error"]) > 0:
        return error_response(404 if docked["error"] == "MolecularStructureUnavailable" else 422, docked["error"], docked["detail"])
    return response(200, docked["design"]["docking"])


def introduce_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{fs.read}:
    if not all(payload.has(field) for field in ["state_version", "generation", "name", "concentration_micromolar"]):
        return error_response(422, "SpeciesRejected", "state_version, generation, name, and concentration_micromolar are required")
    if payload["generation"] != session["design_generation"]:
        return error_response(409, "DesignStateConflict", "generation does not match the Sema-owned design registry")
    visible_state_version = session["preview_state_version"] if profile.adaptation.exploratory else session["state_version"]
    if payload["state_version"] != visible_state_version:
        return error_response(409, "SpeciesStateConflict", "state version does not match the Sema-owned live state")
    name = payload["name"]
    if not session["designs"].has(name):
        return error_response(404, "DesignUnknown", "no design with that name exists in this Sema session")
    docked = dock_design(session, name, 512)
    if len(docked["error"]) > 0:
        return error_response(404 if docked["error"] == "MolecularStructureUnavailable" else 422, docked["error"], docked["detail"])
    design = docked["design"]
    mechanism = payload["mechanism"] if payload.has("mechanism") else design["mechanism"]
    concentration = payload["concentration_micromolar"]
    registry = active_species_registry(profile, session)
    registration = species_registration_error(registry, design["spec"], design["docking"], concentration, mechanism)
    if len(registration["error"]) > 0:
        return registration_error_response(registration)
    physiology = session["preview_physiology"] if profile.adaptation.exploratory else session["physiology"]
    store_species(profile, session, register_species(registry, design["spec"], design["structure"], design["docking"], concentration, mechanism, physiology["model_time_days"]))
    return status_response(profile, session)


def invalidate_molecular_step_caches(session: dict[str, any]):
    session["molecular_revision"] = session["molecular_revision"] + 1
    session["last_step"] = None
    session["preview_last_step"] = None
    session["molecular_last_step_identity"] = None
    session["molecular_last_step_response"] = None
    session["molecular_last_mutation_identity"] = None
    session["molecular_last_mutation_response"] = None
    session["molecular_last_mutation_generation"] = None
    session["molecular_last_mutation_program_state_version"] = None


def advance_molecular_generation(session: dict[str, any]):
    session["molecular_generation"] = session["molecular_generation"] + 1
    invalidate_molecular_step_caches(session)

def molecular_mutation_identity(kind: str, payload: dict[str, any]) !{}:
    return encode_json({
        "schema": "sema.biological-molecular-mutation-request-identity/v1",
        "kind": kind,
        "payload": payload,
    })


def retained_molecular_mutation(identity: str, session: dict[str, any]):
    return session["molecular_last_mutation_identity"] == identity and session["molecular_last_mutation_response"] != None and session["molecular_last_mutation_generation"] == session["molecular_generation"] and session["molecular_last_mutation_program_state_version"] == session["program"]["state_version"]


def retain_molecular_mutation(identity: str, body: dict[str, any], session: dict[str, any]):
    session["molecular_last_mutation_identity"] = identity
    session["molecular_last_mutation_response"] = body
    session["molecular_last_mutation_generation"] = session["molecular_generation"]
    session["molecular_last_mutation_program_state_version"] = session["program"]["state_version"]


def molecule_response(payload: dict[str, any], session: dict[str, any]) !{fs.read}:
    if not payload.has("generation") or not payload.has("key"):
        return error_response(422, "MolecularInputInvalid", "generation and key are required")
    request_identity = molecular_mutation_identity("load", payload)
    if retained_molecular_mutation(request_identity, session):
        return response(200, session["molecular_last_mutation_response"])
    if payload["generation"] != session["molecular_generation"]:
        return error_response(409, "MolecularGenerationConflict", "generation does not match Sema-owned molecular state")
    if not structure_key_supported(payload["key"]):
        return error_response(404, "MolecularStructureUnavailable", "the requested digest-bound molecular structure is unavailable")
    molecular = load_molecular_session(payload["key"])
    molecular["thermal_scale"] = session["program"]["signals"]["molecular_temperature"]
    molecular["bond_stiffness"] = session["program"]["signals"]["bond_stiffness"]
    session["molecular"] = molecular
    advance_molecular_generation(session)
    body = molecular_public_state(molecular)
    body["generation"] = session["molecular_generation"]
    retain_molecular_mutation(request_identity, body, session)
    return response(200, body)


def molecule_step_response(payload: dict[str, any], session: dict[str, any]) !{}:
    if not all(payload.has(field) for field in ["generation", "key", "sequence", "state_version", "dt_s"]):
        return error_response(422, "MolecularStepInvalid", "generation, key, sequence, state_version, and dt_s are required")
    request_identity = molecular_mutation_identity("step", payload)
    if retained_molecular_mutation(request_identity, session):
        return response(200, session["molecular_last_mutation_response"])
    if session["molecular"] == None:
        return error_response(409, "MolecularStateUnavailable", "load a molecular structure before stepping it")
    molecular = session["molecular"]
    if payload["generation"] != session["molecular_generation"]:
        return error_response(409, "MolecularGenerationConflict", "generation does not match Sema-owned molecular state")
    if payload["key"] != molecular["key"]:
        return error_response(409, "MolecularStateConflict", "molecular source does not match Sema-owned state")
    if payload["dt_s"] <= 0.0 or payload["dt_s"] > 0.1:
        return error_response(422, "MolecularStepInvalid", "dt_s must be in (0, 0.1]")
    if payload["sequence"] == molecular["sequence"] and payload["state_version"] == molecular["state_version"]:
        if session["molecular_last_step_identity"] == request_identity and session["molecular_last_step_response"] != None:
            return response(200, session["molecular_last_step_response"])
        return error_response(409, "MolecularRequestConflict", "molecular step identifiers are already bound to a different request identity")
    if payload["sequence"] != molecular["sequence"] + 1 or payload["state_version"] != molecular["state_version"]:
        return error_response(409, "MolecularStateConflict", "molecular sequence or state version does not match")
    session["molecular"] = step_molecular_session(molecular, payload["dt_s"])
    advance_molecular_generation(session)
    molecular_response_body = molecular_public_state(session["molecular"])
    molecular_response_body["generation"] = session["molecular_generation"]
    session["molecular_last_step_identity"] = request_identity
    session["molecular_last_step_response"] = molecular_response_body
    retain_molecular_mutation(request_identity, molecular_response_body, session)
    return response(200, molecular_response_body)


def direct_molecular_operations(operations: list[dict[str, any]]):
    for operation in operations:
        if operation["kind"] == "translate_atom" or operation["kind"] == "add_bond" or operation["kind"] == "remove_bond":
            return true
    return false


def program_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{fs.read}:
    if payload.has("command"):
        compiled = compile_biological_command(payload["command"])
        if not compiled["ok"]:
            return error_response(422, compiled["error"], compiled["detail"])
        payload["operations"] = compiled["operations"]
    request_identity = molecular_mutation_identity("program", payload)
    if retained_molecular_mutation(request_identity, session):
        return response(200, session["molecular_last_mutation_response"])
    program_result = apply_biological_program(session["program"], payload)
    if not program_result["ok"]:
        status = 409 if program_result["error"] == "ProgramStateConflict" else 422
        return error_response(status, program_result["error"], program_result["detail"])
    molecular_operations = program_result["molecular_operations"]
    mut molecular: any = None
    if len(molecular_operations) > 0 and session["molecular"] is not None:
        if not payload.has("molecular_generation"):
            return error_response(422, "MolecularProgramInvalid", "molecular_generation is required for a molecular edit")
        if payload["molecular_generation"] != session["molecular_generation"]:
            return error_response(409, "MolecularGenerationConflict", "generation does not match Sema-owned molecular state")
    mut reset_molecular: any = None
    if program_result["reset_molecular"] and session["molecular"] is not None:
        reset_molecular = load_molecular_session(session["molecular"]["key"])
    if program_result["reset_molecular"]:
        if profile.adaptation.exploratory:
            session["preview_generation"] = session["preview_generation"] + 1
            session["preview_sequence"] = 0
            session["preview_state_version"] = 0
            session["preview_state"] = profile.initial_state
            session["preview_population"] = initial_population_state(profile.population_cells)
            session["preview_physiology"] = initial_physiology_state()
            session["preview_last_step"] = None
            session["preview_retry_context"] = None
        else:
            session["active_generation"] = session["active_generation"] + 1
            session["sequence"] = 0
            session["state_version"] = 0
            session["state"] = profile.initial_state
            session["population"] = initial_population_state(profile.population_cells)
            session["physiology"] = initial_physiology_state()
            session["last_step"] = None
            session["retry_context"] = None
        if reset_molecular is not None:
            session["molecular"] = reset_molecular
        advance_molecular_generation(session)
        if session["molecular"] is not None:
            molecular = molecular_public_state(session["molecular"])
            molecular["generation"] = session["molecular_generation"]
    if len(molecular_operations) > 0:
        if session["molecular"] == None:
            if direct_molecular_operations(molecular_operations):
                return error_response(409, "MolecularStateUnavailable", "load a molecular structure before applying topology or coordinate edits")
        else:
            if not payload.has("molecular_state_version"):
                return error_response(422, "MolecularProgramInvalid", "molecular_state_version is required for a molecular edit")
            molecular_result = apply_molecular_program(session["molecular"], {
                "state_version": payload["molecular_state_version"],
                "operations": molecular_operations,
            })
            if not molecular_result["ok"]:
                status = 409 if molecular_result["error"] == "MolecularStateConflict" else 422
                return error_response(status, molecular_result["error"], molecular_result["detail"])
            session["molecular"] = molecular_result["session"]
            advance_molecular_generation(session)
            molecular = molecular_public_state(session["molecular"])
            molecular["generation"] = session["molecular_generation"]
    for design_operation in program_result["design_operations"]:
        design_result = apply_design_command(design_operation, profile, session)
        if design_result["status"] != 200:
            return design_result
    session["program"] = program_result["state"]
    session["last_step"] = None
    session["preview_last_step"] = None
    body = {
        "schema": "sema.biological-program-result/v1",
        "backend": "Sema",
        "active_generation": session["active_generation"],
        "preview_generation": session["preview_generation"],
        "molecular_generation": session["molecular_generation"],
        "program": session["program"],
        "molecular": molecular,
        "summary": program_result["summary"],
    }
    if program_result["reset_molecular"] or (len(molecular_operations) > 0 and session["molecular"] is not None):
        retain_molecular_mutation(request_identity, body, session)
    return response(200, body)


def capabilities_response() !{}:
    capabilities = programming_capabilities()
    capabilities["agent"] = agent_capabilities()
    capabilities["binding"] = binding_capabilities()
    capabilities["cortex"] = cortex_capabilities()
    capabilities["design"] = design_capabilities()
    return response(200, capabilities)


def live_response(request: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{ffi.call, fs.read}:
    if request["method"] == "GET" and request["path"] == "/api/sema/status":
        return status_response(profile, session)
    if request["method"] == "GET" and request["path"] == "/api/sema/capabilities":
        return capabilities_response()
    if request["method"] == "POST" and request["path"] == "/api/sema/step":
        if len(request["body"]) == 0 or len(request["body"]) > 4096:
            return error_response(413, "LiveInputInvalid", "step payload must contain at most 4096 bytes")
        expect payload = decode_json(request["body"]):
            return step_response(payload, profile, session)
        except JsonError as error:
            return error_response(422, "LiveInputInvalid", "step request must contain finite valid JSON")
    if request["method"] == "POST" and request["path"] == "/api/sema/intervene":
        if len(request["body"]) == 0 or len(request["body"]) > 4096:
            return error_response(413, "LiveInterventionInvalid", "intervention payload must contain at most 4096 bytes")
        return intervention_response(decode_json(request["body"]), profile, session)
    if request["method"] == "POST" and request["path"] == "/api/sema/molecule":
        if len(request["body"]) == 0 or len(request["body"]) > 4096:
            return error_response(413, "MolecularInputInvalid", "molecular payload must contain at most 4096 bytes")
        return molecule_response(decode_json(request["body"]), session)
    if request["method"] == "POST" and request["path"] == "/api/sema/molecule/step":
        if len(request["body"]) == 0 or len(request["body"]) > 4096:
            return error_response(413, "MolecularStepInvalid", "molecular step payload must contain at most 4096 bytes")
        return molecule_step_response(decode_json(request["body"]), session)
    if request["method"] == "POST" and request["path"] == "/api/sema/program":
        if len(request["body"]) == 0 or len(request["body"]) > 8192:
            return error_response(413, "ProgramInvalid", "program payload must contain at most 8192 bytes")
        return program_response(decode_json(request["body"]), profile, session)
    if request["method"] == "POST" and request["path"] == "/api/sema/design":
        if len(request["body"]) == 0 or len(request["body"]) > 8192:
            return error_response(413, "DesignCompileError", "design payload must contain at most 8192 bytes")
        return design_response(decode_json(request["body"]), profile, session)
    if request["method"] == "POST" and request["path"] == "/api/sema/dock":
        if len(request["body"]) == 0 or len(request["body"]) > 4096:
            return error_response(413, "DockingRejected", "docking payload must contain at most 4096 bytes")
        return dock_response(decode_json(request["body"]), session)
    if request["method"] == "POST" and request["path"] == "/api/sema/introduce":
        if len(request["body"]) == 0 or len(request["body"]) > 4096:
            return error_response(413, "SpeciesRejected", "introduction payload must contain at most 4096 bytes")
        return introduce_response(decode_json(request["body"]), profile, session)
    if request["method"] == "POST" and request["path"] == "/api/sema/agent/propose":
        if len(request["body"]) == 0 or len(request["body"]) > 8192:
            return error_response(413, "AgentProposalInvalid", "agent proposal must contain at most 8192 bytes")
        proposal = propose_agent_program(decode_json(request["body"]))
        if not proposal["ok"]:
            return error_response(422, proposal["error"], proposal["detail"])
        return response(200, proposal)
    if request["method"] == "POST" and request["path"] == "/api/sema/cortex/propose":
        if len(request["body"]) == 0 or len(request["body"]) > 8192:
            return error_response(413, "CortexProposalInvalid", "Cortex proposal must contain at most 8192 bytes")
        active_state_version_before = session["state_version"]
        active_sequence_before = session["sequence"]
        preview_state_version_before = session["preview_state_version"]
        preview_sequence_before = session["preview_sequence"]
        cortex = propose_cortex(decode_json(request["body"]))
        if not cortex["ok"]:
            if cortex["error"] == "CortexProposalUnavailable":
                return error_response(503, cortex["error"], cortex["detail"])
            return error_response(422, cortex["error"], cortex["detail"])
        ensure session["state_version"] == active_state_version_before and session["sequence"] == active_sequence_before
        ensure session["preview_state_version"] == preview_state_version_before and session["preview_sequence"] == preview_sequence_before
        return response(200, cortex["proposal"])
    return error_response(404, "NotFound", "unknown Sema live endpoint")


pub def serve_live(port: int) -> None !{ffi.call, fs.read, net.listen}:
    sem "Serve the viewer's live equation steps from the same evidence-bound Sema model"
    require port >= 1024 and port <= 65535
    profile = load_live_profile()
    session = {"sequence": 0, "state_version": 0, "active_generation": 0, "state": profile.initial_state, "last_step": None, "retry_context": None, "population": initial_population_state(profile.population_cells), "preview_sequence": 0, "preview_state_version": 0, "preview_generation": 0, "preview_state": profile.initial_state, "preview_last_step": None, "preview_retry_context": None, "preview_population": initial_population_state(profile.population_cells), "preview_physiology": initial_physiology_state(), "program": initial_program_state(), "physiology": initial_physiology_state(), "molecular": None, "molecular_generation": 0, "molecular_revision": 0, "molecular_last_step_identity": None, "molecular_last_step_response": None, "molecular_last_mutation_identity": None, "molecular_last_mutation_response": None, "molecular_last_mutation_generation": None, "molecular_last_mutation_program_state_version": None, "designs": {}, "design_generation": 0, "species": initial_species_registry(), "preview_species": initial_species_registry(), "design_last_identity": None, "design_last_response": None, "design_last_generation": None}
    print("sema_live=http://127.0.0.1:" + str(port) + " model=" + profile.model_id + " admission_status=" + profile.adaptation.admission_status + " activated=" + str(profile.adaptation.activated) + " technical_pass=" + str(profile.adaptation.admitted) + " scientific_validated=false scene_sha256=" + profile.scene_sha256)
    http.serve(port, request => live_response(request, profile, session))
```

### `src/mace_off.sema`

```sema
"""MACE-OFF23 molecular holdout, calibrated uncertainty, OOD, and ablation evidence."""

assure silver


pub struct MaceOffResult:
    schema: str
    profile_id: str
    config_sha256: str
    dataset_sha256: str
    model_sha256: list[str]
    provenance_sha256: str
    checkpoint_license: str
    dataset_license: str
    level_of_theory: str
    calibration_configurations: int
    heldout_configurations: int
    unique_molecules: int
    heldout_energy_rmse_mev_per_atom: f64
    heldout_force_rmse_mev_per_angstrom: f64
    symbolic_only_force_rmse_mev_per_angstrom: f64
    hybrid_force_rmse_mev_per_angstrom: f64
    conformal_scale: f64
    conformal_coverage: f64
    ood_minimum_distance_angstrom: f64
    ood_uncertainty_ratio: f64
    in_domain_force_disagreement_mev_per_angstrom: f64
    ood_force_disagreement_mev_per_angstrom: f64
    ood_blocked: bool
    translation_energy_residual_ev: f64
    translation_force_residual_ev_per_angstrom: f64
    accuracy_pass: bool
    uncertainty_pass: bool
    symmetry_pass: bool
    ood_pass: bool
    ablation_pass: bool
    molecular_validated: bool
    evidence_class: str
    direct_oracle_result_sha256: str
    direct_energy_residual: f64
    direct_force_residual: f64
    direct_parity_pass: bool
    result_sha256: str
    result_path: str
    invariant schema == "sema.mace-off-profile-result/v1"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(dataset_sha256) == 64
    invariant len(model_sha256) == 3
    invariant all(len(digest) == 64 for digest in model_sha256)
    invariant len(provenance_sha256) == 64
    invariant checkpoint_license == "Academic Software License"
    invariant dataset_license == "MIT"
    invariant calibration_configurations == 12
    invariant heldout_configurations == 12
    invariant unique_molecules == calibration_configurations + heldout_configurations
    invariant heldout_energy_rmse_mev_per_atom >= 0.0
    invariant heldout_force_rmse_mev_per_angstrom >= 0.0
    invariant symbolic_only_force_rmse_mev_per_angstrom >= 0.0
    invariant hybrid_force_rmse_mev_per_angstrom >= 0.0
    invariant conformal_scale >= 0.0
    invariant conformal_coverage >= 0.0 and conformal_coverage <= 1.0
    invariant ood_minimum_distance_angstrom > 0.0
    invariant ood_uncertainty_ratio >= 0.0
    invariant in_domain_force_disagreement_mev_per_angstrom >= 0.0
    invariant ood_force_disagreement_mev_per_angstrom >= 0.0
    invariant translation_energy_residual_ev >= 0.0
    invariant translation_force_residual_ev_per_angstrom >= 0.0
    invariant len(direct_oracle_result_sha256) == 64
    invariant direct_energy_residual >= 0.0
    invariant direct_force_residual >= 0.0
    invariant len(result_sha256) == 64
    invariant len(result_path) > 0
    invariant evidence_class == "validated_molecular_holdout" or evidence_class == "failed_molecular_holdout"


pub bridge python.inline mace_off_backend from "foreign/python/mace_off_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def run_profile(config_path: str, oracle_path: str, output_path: str) -> MaceOffResult !{ffi.call}:
            sem "Validate three pinned molecular models on disjoint quantum holdouts with calibrated OOD evidence"
```

### `src/mace.sema`

```sema
"""Pinned MACE-MP technical adapter with independent direct parity."""

assure silver


pub struct MaceProfileResult:
    schema: str
    profile_id: str
    platform: str
    device: str
    default_dtype: str
    mace_torch_version: str
    torch_version: str
    checkpoint_url: str
    checkpoint_sha256: str
    checkpoint_bytes: int
    checkpoint_license: str
    training_domain: str
    provenance_sha256: str
    config_sha256: str
    system_sha256: str
    result_sha256: str
    result_path: str
    direct_oracle_file_sha256: str
    direct_oracle_result_sha256: str
    atoms: int
    base_energy_ev: f64
    displaced_energy_ev: f64
    ablation_energy_delta_ev: f64
    max_force_ev_per_angstrom: f64
    finite_difference_force_residual_ev_per_angstrom: f64
    translation_energy_residual_ev: f64
    translation_force_residual_ev_per_angstrom: f64
    direct_energy_residual_ev: f64
    direct_force_residual_ev_per_angstrom: f64
    finite_difference_pass: bool
    translation_pass: bool
    ablation_pass: bool
    direct_parity_pass: bool
    technical_pass: bool
    reference_kind: str
    replay_class: str
    domain_status: str
    uncertainty_available: bool
    molecular_validated: bool
    evidence_class: str
    invariant schema == "sema.mace-profile-result/v1"
    invariant profile_id == "mace_mp_0a_small_si_v1"
    invariant platform == "CPU" and device == "cpu"
    invariant default_dtype == "float64"
    invariant mace_torch_version == "0.3.16"
    invariant checkpoint_sha256 == "2ddb079cee0e131eaaf6912ba581b394551ead283e95c99cfe78c605d10b5736"
    invariant checkpoint_bytes > 0 and checkpoint_bytes <= 67108864
    invariant checkpoint_license == "MIT"
    invariant len(provenance_sha256) == 64
    invariant len(config_sha256) == 64
    invariant len(system_sha256) == 64
    invariant len(result_sha256) == 64
    invariant len(result_path) > 0
    invariant len(direct_oracle_file_sha256) == 64
    invariant len(direct_oracle_result_sha256) == 64
    invariant atoms == 8
    invariant max_force_ev_per_angstrom >= 0.0
    invariant finite_difference_force_residual_ev_per_angstrom >= 0.0
    invariant translation_energy_residual_ev >= 0.0
    invariant translation_force_residual_ev_per_angstrom >= 0.0
    invariant direct_energy_residual_ev >= 0.0
    invariant direct_force_residual_ev_per_angstrom >= 0.0
    invariant reference_kind == "internal_consistency_only"
    invariant replay_class == "exact"
    invariant domain_status == "composition_supported_geometry_unqualified"
    invariant uncertainty_available == false
    invariant molecular_validated == false
    invariant evidence_class == "validated_technical" or evidence_class == "exploratory"


pub bridge python.inline mace_backend from "foreign/python/mace_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def run_profile(config_path: str, oracle_path: str, output_path: str) -> MaceProfileResult !{ffi.call}:
            sem "Validate a pinned MACE checkpoint against an independent direct invocation and internal physical residuals"
```

### `src/mesoscopic.sema`

```sema
"""Uncertainty-preserving molecular-to-reaction-diffusion parameter transfer."""

assure silver


pub struct MesoscopicResult:
    schema: str
    profile_id: str
    config_sha256: str
    source_result_sha256: str
    source_artifact_sha256: str
    source_kd_micromolar: f64
    source_kd_sem_micromolar: f64
    association_rate_per_micromolar_s: f64
    dissociation_rate_per_s: f64
    voxels: int
    steps: int
    dt_s: f64
    simulated_time_s: f64
    initial_mass_micromolar: f64
    final_mass_micromolar: f64
    mass_relative_residual: f64
    expected_monomer_micromolar: f64
    expected_dimer_micromolar: f64
    observed_monomer_micromolar: f64
    observed_dimer_micromolar: f64
    observed_kd_micromolar: f64
    kd_relative_residual: f64
    spatial_cv: f64
    dimer_uncertainty_min_micromolar: f64
    dimer_uncertainty_max_micromolar: f64
    rate_roundtrip_relative_residual: f64
    sbml_sha256: str
    bngl_sha256: str
    uncertainty_pass: bool
    interchange_pass: bool
    transfer_pass: bool
    reverse_discrepancy_signaled: bool
    adapter_backend_sha256: str
    readdy_status: str
    readdy_unavailable_reason: str
    readdy_version: str
    readdy_source_commit: str
    readdy_wheel_filename: str
    readdy_wheel_sha256: str
    readdy_module_sha256: str
    readdy_platform: str
    readdy_executed: bool
    readdy_target_rate_evidence: bool
    readdy_concentration_evidence: bool
    readdy_spatial_evidence: bool
    readdy_uncertainty_evidence: bool
    readdy_association_events: int
    readdy_dissociation_events: int
    readdy_lower_uncertainty_dissociation_events: int
    readdy_upper_uncertainty_dissociation_events: int
    readdy_final_monomer_particles: int
    readdy_final_dimer_particles: int
    readdy_mass_relative_residual: f64
    readdy_mean_displacement_micrometers: f64
    readdy_observation_sha256: str
    readdy_observation_json: str
    readdy_validated: bool
    physicell_status: str
    physicell_unavailable_reason: str
    physicell_version: str
    physicell_source_commit: str
    physicell_source_url: str
    physicell_executable: str
    physicell_executed: bool
    physicell_target_rate_evidence: bool
    physicell_concentration_evidence: bool
    physicell_spatial_evidence: bool
    physicell_uncertainty_evidence: bool
    physicell_validated: bool
    scientific_validated: bool
    evidence_class: str
    result_sha256: str
    direct_oracle_result_sha256: str
    direct_oracle_path: str
    direct_residual: f64
    direct_parity_pass: bool
    phase8_technical_pass: bool
    sbml_path: str
    bngl_path: str
    result_path: str
    invariant schema == "sema.mesoscopic-result/v1"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(source_result_sha256) == 64
    invariant len(source_artifact_sha256) == 64
    invariant source_kd_micromolar > 0.0
    invariant source_kd_sem_micromolar >= 0.0
    invariant association_rate_per_micromolar_s > 0.0
    invariant dissociation_rate_per_s > 0.0
    invariant voxels > 2
    invariant steps > 0
    invariant dt_s > 0.0
    invariant simulated_time_s > 0.0
    invariant initial_mass_micromolar > 0.0
    invariant final_mass_micromolar > 0.0
    invariant mass_relative_residual >= 0.0
    invariant expected_monomer_micromolar >= 0.0
    invariant expected_dimer_micromolar >= 0.0
    invariant observed_monomer_micromolar >= 0.0
    invariant observed_dimer_micromolar > 0.0
    invariant observed_kd_micromolar > 0.0
    invariant kd_relative_residual >= 0.0
    invariant spatial_cv >= 0.0
    invariant dimer_uncertainty_min_micromolar >= 0.0
    invariant dimer_uncertainty_max_micromolar >= dimer_uncertainty_min_micromolar
    invariant rate_roundtrip_relative_residual >= 0.0
    invariant len(sbml_sha256) == 64
    invariant len(bngl_sha256) == 64
    invariant len(adapter_backend_sha256) == 64
    invariant readdy_status == "qualified" or readdy_status == "failed" or readdy_status == "unavailable"
    invariant readdy_status == "qualified" or len(readdy_unavailable_reason) > 0
    invariant len(readdy_source_commit) == 40
    invariant len(readdy_wheel_filename) > 0
    invariant len(readdy_wheel_sha256) == 64
    invariant len(readdy_observation_sha256) == 64
    invariant len(readdy_observation_json) > 0
    invariant readdy_association_events >= 0
    invariant readdy_dissociation_events >= 0
    invariant readdy_lower_uncertainty_dissociation_events >= 0
    invariant readdy_upper_uncertainty_dissociation_events >= 0
    invariant readdy_final_monomer_particles >= 0
    invariant readdy_final_dimer_particles >= 0
    invariant readdy_mass_relative_residual >= 0.0
    invariant readdy_mean_displacement_micrometers >= 0.0
    invariant not readdy_validated or readdy_executed
    invariant not readdy_validated or readdy_status == "qualified"
    invariant not readdy_validated or readdy_target_rate_evidence
    invariant not readdy_validated or readdy_concentration_evidence
    invariant not readdy_validated or readdy_spatial_evidence
    invariant not readdy_validated or readdy_uncertainty_evidence
    invariant physicell_status == "qualified" or physicell_status == "failed" or physicell_status == "unavailable"
    invariant physicell_status == "qualified" or len(physicell_unavailable_reason) > 0
    invariant len(physicell_version) > 0
    invariant len(physicell_source_commit) == 40
    invariant len(physicell_source_url) > 0
    invariant not physicell_validated or physicell_executed
    invariant not physicell_validated or physicell_target_rate_evidence
    invariant not physicell_validated or physicell_concentration_evidence
    invariant not physicell_validated or physicell_spatial_evidence
    invariant not physicell_validated or physicell_uncertainty_evidence
    invariant not phase8_technical_pass or transfer_pass
    invariant not phase8_technical_pass or direct_parity_pass
    invariant not phase8_technical_pass or readdy_validated
    invariant not scientific_validated or phase8_technical_pass
    invariant len(result_sha256) == 64
    invariant len(direct_oracle_result_sha256) == 64
    invariant len(direct_oracle_path) > 0
    invariant direct_residual >= 0.0
    invariant len(sbml_path) > 0
    invariant len(bngl_path) > 0
    invariant len(result_path) > 0
    invariant evidence_class == "validated_reaction_diffusion_reference" or evidence_class ==    "failed_reaction_diffusion_reference"


pub bridge python.inline mesoscopic_backend from "foreign/python/mesoscopic_backend.py":
    deps "python>=3.12,<3.13", "numpy==2.4.1"
    expose:
        def run_profile(config_path: str, oracle_path: str, output_path: str) -> MesoscopicResult !{ffi.call}:
            sem "Transfer molecular equilibrium evidence into bounded reaction-diffusion with SBML and BioNetGen round trips"
```

### `src/models.sema`

```sema
"""Typed symbolic, learned, and hybrid equation terms with fail-closed evidence gates."""

assure silver


pub enum TermImplementation:
    symbolic | learned | hybrid


pub enum LearnedRole:
    energy | force | rate | transition_probability | structure_proposal | closure | parameter


pub enum ApplicabilityDecision:
    applicable | out_of_domain | unknown


pub enum PredictionStatus:
    proposed | admissible | blocked


pub struct LearnedModelManifest:
    id: str
    family: str
    version: str
    role: LearnedRole
    architecture_sha256: str
    weights_sha256: str
    training_data_sha256: str
    validation_data_sha256: str
    license_id: str
    preprocessing: str
    input_units: list[str]
    output_unit: str
    chemical_domain: str
    thermodynamic_domain: str
    symmetry_contract: str
    calibration_method: str
    uncertainty_method: str
    ood_method: str
    backend_profile_id: str
    evidence_ids: list[str]
    validated: bool
    invariant len(id) > 0
    invariant len(family) > 0
    invariant len(version) > 0
    invariant len(architecture_sha256) == 64
    invariant len(weights_sha256) == 64
    invariant len(training_data_sha256) == 64
    invariant len(validation_data_sha256) == 64
    invariant len(license_id) > 0
    invariant len(preprocessing) > 0
    invariant len(input_units) > 0 and len(input_units) <= 128
    invariant len(output_unit) > 0
    invariant len(chemical_domain) > 0
    invariant len(thermodynamic_domain) > 0
    invariant len(symmetry_contract) > 0
    invariant len(calibration_method) > 0
    invariant len(uncertainty_method) > 0
    invariant len(ood_method) > 0
    invariant len(backend_profile_id) > 0
    invariant len(evidence_ids) <= 128


pub struct EquationTermDescriptor:
    id: str
    owner_model_id: str
    implementation: TermImplementation
    role: LearnedRole
    input_units: list[str]
    output_unit: str
    symbolic_expression: str
    learned_model_id: str
    combination_rule: str
    authoritative_outputs: list[str]
    invariant len(id) > 0
    invariant len(owner_model_id) > 0
    invariant len(input_units) > 0 and len(input_units) <= 128
    invariant len(output_unit) > 0
    invariant len(combination_rule) > 0
    invariant len(authoritative_outputs) > 0 and len(authoritative_outputs) <= 16


pub struct PredictionUncertainty:
    aleatoric: f64
    epistemic: f64
    lower: f64
    upper: f64
    coverage: f64
    calibrated: bool
    invariant aleatoric >= 0.0
    invariant epistemic >= 0.0
    invariant lower <= upper
    invariant coverage > 0.0 and coverage < 1.0


pub struct HybridPrediction:
    term_id: str
    manifest_id: str
    symbolic_value: f64
    learned_value: f64
    gate: f64
    combined_value: f64
    output_unit: str
    uncertainty: PredictionUncertainty
    applicability: ApplicabilityDecision
    ood_score: f64
    symbolic_residual: f64
    evidence_ids: list[str]
    status: PredictionStatus
    reason: str
    invariant len(term_id) > 0
    invariant len(manifest_id) > 0
    invariant len(output_unit) > 0
    invariant ood_score >= 0.0
    invariant symbolic_residual >= 0.0
    invariant len(evidence_ids) <= 128
    invariant len(reason) > 0


equation raw_additive_hybrid_value(symbolic_value: f64, learned_correction: f64, gate: f64) -> f64:
    return symbolic_value + gate * learned_correction


def additive_hybrid_value(symbolic_value: f64, learned_correction: f64, gate: f64) !{}:
    require gate >= 0.0 and gate <= 1.0
    return raw_additive_hybrid_value(symbolic_value, learned_correction, gate)


def manifest_qualified(manifest: LearnedModelManifest):
    return manifest.validated and len(manifest.evidence_ids) > 0

def term_matches_manifest(term: EquationTermDescriptor, manifest: LearnedModelManifest):
    return (
        term.learned_model_id == manifest.id
        and term.role == manifest.role
        and term.input_units == manifest.input_units
        and term.output_unit == manifest.output_unit
    )


def term_descriptor_valid(term: EquationTermDescriptor):
    if term.implementation == TermImplementation.symbolic:
        return len(term.symbolic_expression) > 0 and len(term.learned_model_id) == 0
    if term.implementation == TermImplementation.learned:
        return len(term.learned_model_id) > 0 and term.combination_rule == "learned_only"
    return len(term.symbolic_expression) > 0 and len(term.learned_model_id) > 0


pub def assess_hybrid_prediction(
    term: EquationTermDescriptor,
    manifest: LearnedModelManifest,
    symbolic_value: f64,
    learned_value: f64,
    gate: f64,
    uncertainty: PredictionUncertainty,
    applicability: ApplicabilityDecision,
    ood_score: f64,
    symbolic_residual: f64,
    maximum_uncertainty: f64,
    maximum_residual: f64,
    evidence_ids: list[str],
) -> HybridPrediction !{}:
    require maximum_uncertainty >= 0.0
    require maximum_residual >= 0.0
    mut combined = symbolic_value
    mut status = PredictionStatus.blocked
    mut reason = "gate is outside the closed unit interval"
    if gate >= 0.0 and gate <= 1.0:
        combined = raw_additive_hybrid_value(symbolic_value, learned_value, gate)
        status = PredictionStatus.admissible
        reason = "manifest, applicability, calibration, uncertainty, and residual gates passed"
    if status == PredictionStatus.admissible and (not term_descriptor_valid(term) or not manifest_qualified(manifest)):
        status = PredictionStatus.blocked
        reason = "term or learned model manifest is not qualified"
    elif status == PredictionStatus.admissible and not term_matches_manifest(term, manifest):
        status = PredictionStatus.blocked
        reason = "term and learned model dimensional or semantic contracts differ"
    elif status == PredictionStatus.admissible and applicability != ApplicabilityDecision.applicable:
        status = PredictionStatus.blocked
        reason = "input is out of domain or applicability is unknown"
    elif status == PredictionStatus.admissible and not uncertainty.calibrated:
        status = PredictionStatus.blocked
        reason = "uncertainty is not calibrated"
    elif status == PredictionStatus.admissible and uncertainty.aleatoric + uncertainty.epistemic > maximum_uncertainty:
        status = PredictionStatus.blocked
        reason = "uncertainty exceeds the declared threshold"
    elif status == PredictionStatus.admissible and symbolic_residual > maximum_residual:
        status = PredictionStatus.blocked
        reason = "symbolic residual exceeds the declared threshold"
    elif status == PredictionStatus.admissible and len(evidence_ids) == 0:
        status = PredictionStatus.blocked
        reason = "prediction has no evidence"
    return HybridPrediction(
        term_id=term.id,
        manifest_id=manifest.id,
        symbolic_value=symbolic_value,
        learned_value=learned_value,
        gate=gate,
        combined_value=combined,
        output_unit=term.output_unit,
        uncertainty=uncertainty,
        applicability=applicability,
        ood_score=ood_score,
        symbolic_residual=symbolic_residual,
        evidence_ids=evidence_ids,
        status=status,
        reason=reason,
    )


pub def prediction_admissible(prediction: HybridPrediction) -> bool !{}:
    return (
        prediction.status == PredictionStatus.admissible
        and prediction.gate >= 0.0
        and prediction.gate <= 1.0
        and prediction.applicability == ApplicabilityDecision.applicable
        and prediction.uncertainty.calibrated
        and len(prediction.evidence_ids) > 0
    )
```

### `src/molecular.sema`

```sema
"""Headless, bounded molecular state, topology, and dynamics owned by Sema."""

import math
from std.binary import decode_bytes, decode_f32_le, decode_u16_le
from std.crypto import file_sha256, sha256_json
from std.json import read as read_json

assure silver


def molecular_manifest() !{fs.read}:
    manifest = read_json("viewer/public/data/structures/manifest.json")
    ensure manifest["schema"] == "sema.molecular-structure-library/v1"
    ensure len(manifest["entries"]) > 0 and len(manifest["entries"]) <= 32
    return manifest


pub def structure_key_supported(key: str) -> bool !{fs.read}:
    if len(key) == 0 or len(key) > 64:
        return false
    for entry in molecular_manifest()["entries"]:
        if entry["key"] == key:
            return true
    return false


def structure_entry(key: str) !{fs.read}:
    for entry in molecular_manifest()["entries"]:
        if entry["key"] == key:
            return entry
    ensure false
    return {}


def validate_record(record: dict[str, any], encoding: str, components: int, maximum_items: int):
    ensure record["encoding"] == encoding
    ensure record["components"] == components
    ensure record["items"] > 0 and record["items"] <= maximum_items
    ensure len(record["sha256"]) == 64
    ensure len(record["base64"]) > 0 and len(record["base64"]) <= 8388608


def atomic_radius(atomic_number: int, radius_kind: str):
    if atomic_number == 1:
        return 1.20 if radius_kind == "vdw" else 0.31
    if atomic_number == 6:
        return 1.70 if radius_kind == "vdw" else 0.76
    if atomic_number == 7:
        return 1.55 if radius_kind == "vdw" else 0.71
    if atomic_number == 8:
        return 1.52 if radius_kind == "vdw" else 0.66
    if atomic_number == 15:
        return 1.80 if radius_kind == "vdw" else 1.07
    if atomic_number == 16:
        return 1.80 if radius_kind == "vdw" else 1.05
    return 1.80 if radius_kind == "vdw" else 0.80

def atomic_name(atomic_number: int):
    if atomic_number == 1:
        return "Hydrogen"
    if atomic_number == 6:
        return "Carbon"
    if atomic_number == 7:
        return "Nitrogen"
    if atomic_number == 8:
        return "Oxygen"
    if atomic_number == 9:
        return "Fluorine"
    if atomic_number == 11:
        return "Sodium"
    if atomic_number == 12:
        return "Magnesium"
    if atomic_number == 15:
        return "Phosphorus"
    if atomic_number == 16:
        return "Sulfur"
    if atomic_number == 17:
        return "Chlorine"
    if atomic_number == 20:
        return "Calcium"
    if atomic_number == 26:
        return "Iron"
    if atomic_number == 30:
        return "Zinc"
    return "Unmapped element"


def decoded_traces(source: list[dict[str, any]]) !{}:
    ensure len(source) > 0 and len(source) <= 64
    mut traces: list[dict[str, any]] = []
    for trace in source:
        record = trace["positions_angstrom"]
        validate_record(record, "base64-<f4", 3, 4096)
        traces.append({
            "chain_id": trace["chain_id"],
            "polymer_type": trace["polymer_type"],
            "secondary": trace["secondary"],
            "positions": decode_f32_le(record["base64"], record["sha256"], record["items"] * 3),
        })
    return traces


def active_bond_pairs(session: dict[str, any]):
    mut pairs: list[int] = []
    for bond_index in range(len(session["active_bonds"])):
        if session["active_bonds"][bond_index]:
            pairs.append(session["bond_pairs"][bond_index * 2])
            pairs.append(session["bond_pairs"][bond_index * 2 + 1])
    return pairs


def topology_digest(session: dict[str, any]) !{}:
    return sha256_json({
        "source_sha256": session["source_sha256"],
        "bonds": active_bond_pairs(session),
    })

pub def molecular_session_integrity(session: dict[str, any]) -> f64 !{}:
    mut broken_bonds = 0
    mut added_bonds = 0
    for bond_index in range(session["base_bond_count"]):
        if not session["active_bonds"][bond_index]:
            broken_bonds = broken_bonds + 1
    for bond_index in range(session["base_bond_count"], len(session["active_bonds"])):
        if session["active_bonds"][bond_index]:
            added_bonds = added_bonds + 1
    mut squared_displacement = 0.0
    for coordinate_index in range(len(session["positions"])):
        displacement = session["positions"][coordinate_index] - session["base_positions"][coordinate_index]
        squared_displacement = squared_displacement + displacement * displacement
    rmsd_angstrom = math.sqrt(squared_displacement / len(session["atomic_numbers"]))
    topology_impact = min(1.0, (broken_bonds + added_bonds) / 16.0)
    displacement_impact = min(1.0, rmsd_angstrom / max(0.1, session["radius_angstrom"]))
    return max(0.0, 1.0 - topology_impact * 0.55 - displacement_impact * 0.25)


pub def molecular_public_state(session: dict[str, any]) -> dict[str, any] !{}:
    return {
        "schema": "sema.molecular-session/v1",
        "backend": "Sema",
        "state_version": session["state_version"],
        "sequence": session["sequence"],
        "time_s": session["time_s"],
        "scientific_validated": false,
        "integrity": molecular_session_integrity(session),
        "structure": {
            "key": session["key"],
            "label": session["label"],
            "pdb_id": session["pdb_id"],
            "source_sha256": session["source_sha256"],
            "asset_sha256": session["asset_sha256"],
            "topology_sha256": session["topology_sha256"],
            "fidelity": session["fidelity"],
            "biological_match": session["biological_match"],
            "source_page": session["source_page"],
            "atomic_numbers": session["atomic_numbers"],
            "element_names": session["element_names"],
            "positions": session["positions"],
            "labels": session["labels"],
            "bonds": active_bond_pairs(session),
            "traces": session["traces"],
            "covalent_radii_angstrom": session["covalent_radii_angstrom"],
            "vdw_radii_angstrom": session["vdw_radii_angstrom"],
            "radius_angstrom": session["radius_angstrom"],
            "unit_scale": session["unit_scale"],
            "radius_nm": session["radius_nm"],
            "extent_nm": session["extent_nm"],
            "center_offset_angstrom": session["center_offset_angstrom"],
            "base_bond_count": session["base_bond_count"],
            "bond_capacity": session["base_bond_count"] + 16,
            "structural_edits": session["structural_edits"],
            "coordinate_edits": session["coordinate_edits"],
        },
        "parameters": {
            "thermal_scale": session["thermal_scale"],
            "bond_stiffness": session["bond_stiffness"],
        },
    }


pub def load_molecular_session(key: str) -> dict[str, any] !{fs.read}:
    entry = structure_entry(key)
    asset_path = "viewer/public" + entry["path"]
    ensure file_sha256(asset_path) == entry["sha256"]
    source = read_json(asset_path)
    ensure source["schema"] == "sema.molecular-structure/v1"
    ensure source["key"] == entry["key"] and source["pdb_id"] == entry["pdb_id"]
    ensure source["source_sha256"] == entry["source"]["sha256"]
    atomic_record = source["atomic_numbers"]
    position_record = source["positions_angstrom"]
    bond_record = source["bonds"]
    validate_record(atomic_record, "base64-u1", 1, 4096)
    validate_record(position_record, "base64-<f4", 3, 4096)
    validate_record(bond_record, "base64-<u2", 2, 8192)
    atomic_numbers = decode_bytes(atomic_record["base64"], atomic_record["sha256"], atomic_record["items"])
    positions = decode_f32_le(position_record["base64"], position_record["sha256"], position_record["items"] * 3)
    bonds = decode_u16_le(bond_record["base64"], bond_record["sha256"], bond_record["items"] * 2)
    ensure len(atomic_numbers) == entry["atoms"] and len(source["labels"]) == len(atomic_numbers)
    ensure len(positions) == len(atomic_numbers) * 3 and len(bonds) == entry["bonds"] * 2
    mut radius_squared = 0.0
    mut minimum = [positions[0], positions[1], positions[2]]
    mut maximum = [positions[0], positions[1], positions[2]]
    for atom_index in range(len(atomic_numbers)):
        offset = atom_index * 3
        candidate = positions[offset] * positions[offset] + positions[offset + 1] * positions[offset + 1] + positions[offset + 2] * positions[offset + 2]
        radius_squared = max(radius_squared, candidate)
        for axis in range(3):
            minimum[axis] = min(minimum[axis], positions[offset + axis])
            maximum[axis] = max(maximum[axis], positions[offset + axis])
    radius_angstrom = math.sqrt(radius_squared)
    ensure radius_angstrom > 0.0
    mut rest_lengths: list[f64] = []
    for bond_index in range(len(bonds) // 2):
        left = bonds[bond_index * 2]
        right = bonds[bond_index * 2 + 1]
        ensure left >= 0 and left < len(atomic_numbers) and right >= 0 and right < len(atomic_numbers) and left != right
        left_offset = left * 3
        right_offset = right * 3
        dx = positions[right_offset] - positions[left_offset]
        dy = positions[right_offset + 1] - positions[left_offset + 1]
        dz = positions[right_offset + 2] - positions[left_offset + 2]
        rest_lengths.append(math.sqrt(dx * dx + dy * dy + dz * dz))
    session = {
        "key": entry["key"],
        "label": entry["label"],
        "pdb_id": entry["pdb_id"],
        "source_sha256": source["source_sha256"],
        "asset_sha256": entry["sha256"],
        "fidelity": entry["fidelity"],
        "biological_match": entry["biological_match"],
        "source_page": entry["source_page"],
        "atomic_numbers": atomic_numbers,
        "positions": positions,
        "base_positions": [coordinate for coordinate in positions],
        "velocities": [0.0 for coordinate in positions],
        "labels": source["labels"],
        "bond_pairs": bonds,
        "active_bonds": [true for bond_index in range(len(bonds) // 2)],
        "rest_lengths": rest_lengths,
        "base_bond_count": len(bonds) // 2,
        "traces": decoded_traces(source["traces"]),
        "covalent_radii_angstrom": [atomic_radius(atomic_number, "covalent") for atomic_number in atomic_numbers],
        "vdw_radii_angstrom": [atomic_radius(atomic_number, "vdw") for atomic_number in atomic_numbers],
        "element_names": [atomic_name(atomic_number) for atomic_number in atomic_numbers],
        "radius_angstrom": radius_angstrom,
        "radius_nm": radius_angstrom * 0.1,
        "extent_nm": [(maximum[axis] - minimum[axis]) * 0.1 for axis in range(3)],
        "center_offset_angstrom": [0.0, 0.0, 0.0],
        "unit_scale": 0.1,
        "thermal_scale": 1.0,
        "bond_stiffness": 1.0,
        "structural_edits": 0,
        "coordinate_edits": 0,
        "state_version": 0,
        "sequence": 0,
        "time_s": 0.0,
        "topology_sha256": "",
    }
    session["topology_sha256"] = topology_digest(session)
    return session


def clone_molecular_session(session: dict[str, any]):
    return {
        "key": session["key"],
        "label": session["label"],
        "pdb_id": session["pdb_id"],
        "source_sha256": session["source_sha256"],
        "asset_sha256": session["asset_sha256"],
        "fidelity": session["fidelity"],
        "biological_match": session["biological_match"],
        "source_page": session["source_page"],
        "atomic_numbers": session["atomic_numbers"],
        "positions": [coordinate for coordinate in session["positions"]],
        "base_positions": session["base_positions"],
        "velocities": [velocity for velocity in session["velocities"]],
        "labels": session["labels"],
        "bond_pairs": [atom_index for atom_index in session["bond_pairs"]],
        "active_bonds": [active for active in session["active_bonds"]],
        "rest_lengths": [length for length in session["rest_lengths"]],
        "base_bond_count": session["base_bond_count"],
        "traces": session["traces"],
        "covalent_radii_angstrom": session["covalent_radii_angstrom"],
        "vdw_radii_angstrom": session["vdw_radii_angstrom"],
        "element_names": session["element_names"],
        "radius_angstrom": session["radius_angstrom"],
        "unit_scale": session["unit_scale"],
        "radius_nm": session["radius_nm"],
        "extent_nm": session["extent_nm"],
        "center_offset_angstrom": session["center_offset_angstrom"],
        "thermal_scale": session["thermal_scale"],
        "bond_stiffness": session["bond_stiffness"],
        "structural_edits": session["structural_edits"],
        "coordinate_edits": session["coordinate_edits"],
        "state_version": session["state_version"],
        "sequence": session["sequence"],
        "time_s": session["time_s"],
        "topology_sha256": session["topology_sha256"],
    }


def find_bond_index(session: dict[str, any], left: int, right: int):
    for index in range(len(session["active_bonds"])):
        first = session["bond_pairs"][index * 2]
        second = session["bond_pairs"][index * 2 + 1]
        if session["active_bonds"][index] and ((first == left and second == right) or (first == right and second == left)):
            return index
    return -1


def operation_valid(session: dict[str, any], operation: dict[str, any]):
    if not operation.has("kind"):
        return false
    kind = operation["kind"]
    if kind == "set_thermal_scale" or kind == "set_bond_stiffness":
        return operation.has("value") and operation["value"] >= 0.0 and operation["value"] <= 4.0
    if kind == "translate_atom":
        if not all(operation.has(field) for field in ["atom_index", "delta_angstrom"]):
            return false
        atom_index = operation["atom_index"]
        delta = operation["delta_angstrom"]
        return atom_index >= 0 and atom_index < len(session["atomic_numbers"]) and len(delta) == 3 and max(abs(delta[0]), abs(delta[1]), abs(delta[2])) <= 10.0
    if kind == "remove_bond" or kind == "add_bond":
        if not operation.has("left") or not operation.has("right"):
            return false
        left = operation["left"]
        right = operation["right"]
        if left < 0 or left >= len(session["atomic_numbers"]) or right < 0 or right >= len(session["atomic_numbers"]) or left == right:
            return false
        existing = find_bond_index(session, left, right)
        return existing >= 0 if kind == "remove_bond" else existing < 0 and session["structural_edits"] < 16
    return false


def apply_operation(session: dict[str, any], operation: dict[str, any]) !{}:
    kind = operation["kind"]
    if kind == "set_thermal_scale":
        session["thermal_scale"] = operation["value"]
        return "thermal_scale=" + str(operation["value"])
    if kind == "set_bond_stiffness":
        session["bond_stiffness"] = operation["value"]
        return "bond_stiffness=" + str(operation["value"])
    if kind == "translate_atom":
        offset = operation["atom_index"] * 3
        for axis in range(3):
            session["positions"][offset + axis] = session["positions"][offset + axis] + operation["delta_angstrom"][axis]
        session["coordinate_edits"] = session["coordinate_edits"] + 1
        return "translated_atom=" + str(operation["atom_index"])
    left = operation["left"]
    right = operation["right"]
    if kind == "remove_bond":
        session["active_bonds"][find_bond_index(session, left, right)] = false
        session["structural_edits"] = session["structural_edits"] + 1
        return "removed_bond=" + str(left) + ":" + str(right)
    left_offset = left * 3
    right_offset = right * 3
    dx = session["positions"][right_offset] - session["positions"][left_offset]
    dy = session["positions"][right_offset + 1] - session["positions"][left_offset + 1]
    dz = session["positions"][right_offset + 2] - session["positions"][left_offset + 2]
    session["bond_pairs"].append(left)
    session["bond_pairs"].append(right)
    session["active_bonds"].append(true)
    session["rest_lengths"].append(math.sqrt(dx * dx + dy * dy + dz * dz))
    session["structural_edits"] = session["structural_edits"] + 1
    return "added_bond=" + str(left) + ":" + str(right)


pub def apply_molecular_program(session: dict[str, any], payload: dict[str, any]) -> dict[str, any] !{}:
    if not payload.has("state_version") or not payload.has("operations"):
        return {"ok": false, "error": "MolecularProgramInvalid", "detail": "state_version and operations are required"}
    if payload["state_version"] != session["state_version"]:
        return {"ok": false, "error": "MolecularStateConflict", "detail": "molecular state version does not match"}
    operations = payload["operations"]
    if len(operations) == 0 or len(operations) > 8:
        return {"ok": false, "error": "MolecularProgramInvalid", "detail": "operations must contain 1..8 bounded edits"}
    next_session = clone_molecular_session(session)
    mut summary: list[str] = []
    for operation in operations:
        if not operation_valid(next_session, operation):
            return {"ok": false, "error": "MolecularProgramInvalid", "detail": "an operation is unsupported, out of bounds, or conflicts with topology"}
        summary.append(apply_operation(next_session, operation))
    next_session["state_version"] = next_session["state_version"] + 1
    next_session["topology_sha256"] = topology_digest(next_session)
    return {"ok": true, "session": next_session, "summary": summary}


pub def step_molecular_session(session: dict[str, any], dt_s: f64) -> dict[str, any] !{}:
    require dt_s > 0.0 and dt_s <= 0.1
    atom_count = len(session["atomic_numbers"])
    mut forces = [0.0 for coordinate in session["positions"]]
    next_time = session["time_s"] + dt_s
    thermal = 0.24 * session["thermal_scale"]
    for atom_index in range(atom_count):
        offset = atom_index * 3
        phase = atom_index * 0.754877666 + next_time * (1.7 + (atom_index % 11) * 0.03)
        forces[offset] = (session["base_positions"][offset] - session["positions"][offset]) * 0.35 + math.sin(phase) * thermal
        forces[offset + 1] = (session["base_positions"][offset + 1] - session["positions"][offset + 1]) * 0.35 + math.cos(phase * 1.17) * thermal
        forces[offset + 2] = (session["base_positions"][offset + 2] - session["positions"][offset + 2]) * 0.35 + math.sin(phase * 0.73) * thermal
    for bond in range(len(session["active_bonds"])):
        if not session["active_bonds"][bond]:
            continue
        left = session["bond_pairs"][bond * 2]
        right = session["bond_pairs"][bond * 2 + 1]
        left_offset = left * 3
        right_offset = right * 3
        dx = session["positions"][right_offset] - session["positions"][left_offset]
        dy = session["positions"][right_offset + 1] - session["positions"][left_offset + 1]
        dz = session["positions"][right_offset + 2] - session["positions"][left_offset + 2]
        distance = math.sqrt(dx * dx + dy * dy + dz * dz)
        if distance > 0.000001:
            spring = (distance - session["rest_lengths"][bond]) * session["bond_stiffness"] * 1.8 / distance
            forces[left_offset] = forces[left_offset] + dx * spring
            forces[left_offset + 1] = forces[left_offset + 1] + dy * spring
            forces[left_offset + 2] = forces[left_offset + 2] + dz * spring
            forces[right_offset] = forces[right_offset] - dx * spring
            forces[right_offset + 1] = forces[right_offset + 1] - dy * spring
            forces[right_offset + 2] = forces[right_offset + 2] - dz * spring
    mut next_positions: list[f64] = []
    mut next_velocities: list[f64] = []
    for coordinate in range(len(session["positions"])):
        velocity = (session["velocities"][coordinate] + forces[coordinate] * dt_s) * 0.975
        displacement = clamp(velocity * dt_s, -0.08, 0.08)
        next_velocities.append(velocity)
        next_positions.append(session["positions"][coordinate] + displacement)
    session["positions"] = next_positions
    session["velocities"] = next_velocities
    session["time_s"] = next_time
    session["sequence"] = session["sequence"] + 1
    return session
```

### `src/openmm.sema`

```sema
"""Pinned OpenMM bridge contracts for the first scientific vertical."""

assure silver


pub struct BackendProbe:
    available: bool
    engine: str
    version: str
    platforms: list[str]
    detail: str
    invariant len(engine) > 0
    invariant len(version) > 0
    invariant len(detail) > 0


pub struct OpenMMRun:
    schema: str
    benchmark_id: str
    profile_id: str
    engine_version: str
    platform: str
    platform_properties: list[str]
    config_sha256: str
    input_sha256: str
    system_sha256: str
    atom_count: int
    bond_count: int
    steps: int
    frames: int
    initial_potential_energy_kj_mol: f64
    initial_max_force_kj_mol_nm: f64
    initial_force_sha256: str
    minimized_potential_energy_kj_mol: f64
    minimized_max_force_kj_mol_nm: f64
    minimized_force_sha256: str
    nve_initial_total_energy_kj_mol: f64
    nve_final_total_energy_kj_mol: f64
    nve_drift_kj_mol: f64
    frames_sha256: str
    state_arrays_sha256: str
    frames_path: str
    initial_forces_path: str
    minimized_forces_path: str
    result_sha256: str
    invariant schema == "sema.openmm-benchmark/v1"
    invariant platform == "CPU" or platform == "Reference"
    invariant atom_count > 0
    invariant bond_count > 0
    invariant steps >= 0
    invariant frames > 0
    invariant len(config_sha256) == 64
    invariant len(input_sha256) == 64
    invariant len(system_sha256) == 64
    invariant len(initial_force_sha256) == 64
    invariant len(minimized_force_sha256) == 64
    invariant len(frames_sha256) == 64
    invariant len(state_arrays_sha256) == 64
    invariant len(result_sha256) == 64


pub bridge python.inline openmm_adapter from "foreign/python/openmm_adapter.py":
    deps "python>=3.12,<3.13"
    expose:
        def backend_probe() -> BackendProbe !{ffi.call}:
            sem "Import pinned OpenMM and enumerate real runtime platforms"
            ensure len(result.detail) > 0
            ensure result.engine == "OpenMM"


pub bridge python.inline openmm_backend from "foreign/python/scientific_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def run_openmm_cpu() -> OpenMMRun !{ffi.call}:
            sem "Run the fixed bounded benchmark on the qualified CPU platform"
            ensure result.platform == "CPU"
            ensure result.frames > 0
            ensure len(result.result_sha256) == 64
```

### `src/phase10.sema`

```sema
"""Fail-closed qualification of measured Phase 10 renderer and interaction evidence."""

from std.crypto import file_sha256, sha256_json
from std.json import decode as decode_json
from std.toml import read as read_toml

assure silver


pub struct Phase10QualificationResult:
    schema: str
    profile_id: str
    config_sha256: str
    evidence_sha256: str
    scene_sha256: str
    bundle_sha256: str
    external_reference_sha256: str
    scientific_result_sha256: str
    screenshot_sha256: list[str]
    scale_count: int
    minimum_average_fps: f64
    interaction_hz: int
    canonical_update_hz: int
    pick_p95_ms: f64
    dropped_frames: int
    gpu_allocated_bytes: int
    gpu_resource_count: int
    context_loss_recovered: bool
    semantic_validation_pass: bool
    viewer_disabled_parity_pass: bool
    pixel_equality_observed: bool
    visual_regression_replay_pass: bool
    capture_provenance_status: str
    profile_validated: bool
    scientific_validated: bool
    invariant schema == "sema.phase10-qualification-result/v2"
    invariant profile_id == "apple_m3_max_chrome_webgl2_v1"
    invariant len(config_sha256) == 64 and len(evidence_sha256) == 64
    invariant len(scene_sha256) == 64 and len(bundle_sha256) == 64
    invariant len(external_reference_sha256) == 64 and len(scientific_result_sha256) == 64
    invariant len(screenshot_sha256) == 4 and all(len(digest) == 64 for digest in screenshot_sha256)
    invariant scale_count == 4 and minimum_average_fps >= 30.0
    invariant interaction_hz == 60 and canonical_update_hz == 10
    invariant pick_p95_ms >= 0.0 and pick_p95_ms <= 16.67
    invariant dropped_frames >= 0 and dropped_frames <= 16
    invariant gpu_allocated_bytes > 0 and gpu_resource_count > 0
    invariant context_loss_recovered and semantic_validation_pass and viewer_disabled_parity_pass
    invariant pixel_equality_observed
    invariant capture_provenance_status == "technical_untrusted"
    invariant visual_regression_replay_pass == false
    invariant profile_validated == false
    invariant scientific_validated == false


def covers_four_scales(records: list[any], key: str):
    mut atomic = 0
    mut molecular = 0
    mut cellular = 0
    mut tissue = 0
    for record in records:
        if record[key] == "atomic":
            atomic = atomic + 1
        elif record[key] == "molecular":
            molecular = molecular + 1
        elif record[key] == "cellular":
            cellular = cellular + 1
        elif record[key] == "tissue":
            tissue = tissue + 1
        else:
            return false
    return atomic >= 1 and molecular >= 1 and cellular >= 1 and tissue >= 1


pub def qualify_phase10(config_path: str = "phase10.toml") -> Phase10QualificationResult !{fs.read}:
    sem "Validate bounded renderer evidence without promoting modeled biology to scientific evidence"
    config = read_toml(config_path)
    ensure len(config) == 14
    ensure config["schema"] == "sema.phase10-qualification-profile/v1"
    ensure config["profile_id"] == "apple_m3_max_chrome_webgl2_v1"
    ensure config["scales"] == ["atomic", "molecular", "cellular", "tissue"]
    ensure config["capture_provenance_trust"] == "technical_untrusted"
    ensure len(config["reference"]) == 6 and len(config["thresholds"]) == 29
    ensure len(config["artifacts"]) == 2 and len(config["screenshots"]) == 4
    ensure config["reference"]["role"] == "external_reference_only"
    ensure config["reference"]["geometry_input"] == false
    ensure path.is_relative_to(config["evidence_path"], "runs/phase10")
    ensure path.is_relative_to(config["visual_regression_replay_path"], "runs/phase10")
    ensure path.is_relative_to(config["reference_refresh_path"], "runs/phase10")
    ensure path.is_relative_to(config["scene_path"], "viewer/public/data")
    ensure path.is_relative_to(config["reference"]["local_preview_path"], "viewer/public/data")

    payload = fs.read_text(config["evidence_path"])?
    ensure len(payload) > 0 and len(payload) <= config["thresholds"]["maximum_evidence_bytes"]
    evidence = decode_json(payload)
    ensure len(evidence) == 19
    ensure evidence["schema"] == "sema.phase10-render-evidence/v4"
    canonical_evidence = {key: value for key, value in evidence.items() if key != "evidence_sha256"}
    ensure sha256_json(canonical_evidence) == evidence["evidence_sha256"]
    ensure evidence["profile_id"] == config["profile_id"]
    ensure evidence["capture_provenance_status"] == config["capture_provenance_trust"]
    ensure evidence["profile_validated"] == false
    ensure evidence["scientific_validated"] == false

    scene_record = evidence["scene"]
    ensure len(scene_record) == 4
    ensure scene_record["path"] == config["scene_path"]
    ensure file_sha256(scene_record["path"]) == scene_record["sha256"]
    ensure scene_record["sha256"] == config["artifacts"]["scene_sha256"]
    scene = decode_json(fs.read_text(scene_record["path"])? )
    ensure scene["schema"] == "sema.multiscale-viewer/v4"
    canonical_scene = {key: value for key, value in scene.items() if key != "scene_sha256"}
    ensure sha256_json(canonical_scene) == scene["scene_sha256"]
    ensure scene_record["canonical_sha256"] == scene["scene_sha256"]
    ensure scene_record["scientific_result_sha256"] == scene["source"]["result_sha256"]

    bundle = evidence["viewer_bundle"]
    ensure len(bundle) == 2
    bundle_manifest = bundle["manifest"]
    ensure len(bundle_manifest) == 2
    ensure bundle_manifest["schema"] == "sema.phase10-viewer-bundle-manifest/v1"
    bundle_entries = bundle_manifest["entries"]
    ensure len(bundle_entries) == 6
    ensure all(
        len(entry) == 4
        and path.is_relative_to(entry["path"], config["bundle_root"])
        and entry["path"] == "viewer/dist" + entry["served_path"]
        and entry["served_path"].startswith("/")
        and len(entry["sha256"]) == 64
        and entry["byte_length"] > 0
        and file_sha256(entry["path"]) == entry["sha256"]
        and len([other for other in bundle_entries if other["path"] == entry["path"] and other["served_path"] == entry["served_path"]]) == 1
        for entry in bundle_entries
    )
    ensure len([entry for entry in bundle_entries if entry["path"] == "viewer/dist/index.html" and entry["served_path"] == "/index.html"]) == 1
    ensure len([entry for entry in bundle_entries if entry["path"].endswith(".css") and entry["served_path"].startswith("/assets/")]) == 1
    ensure len([entry for entry in bundle_entries if entry["path"].endswith(".js") and entry["served_path"].startswith("/assets/")]) == 1
    ensure len([entry for entry in bundle_entries if entry["served_path"] == "/data/scene.json" and entry["sha256"] == scene_record["sha256"]]) == 1
    ensure len([entry for entry in bundle_entries if entry["served_path"] == "/data/scene.json.sha256" and entry["sha256"] == file_sha256("viewer/public/data/scene.json.sha256")]) == 1
    ensure len([entry for entry in bundle_entries if entry["served_path"] == "/data/idr0116-deboer-npod-preview.jpg" and entry["sha256"] == config["reference"]["preview_sha256"]]) == 1
    ensure sha256_json(bundle_manifest) == bundle["sha256"]
    ensure bundle["sha256"] == config["artifacts"]["bundle_sha256"]

    baseline_capture = evidence["capture"]
    ensure len(baseline_capture) == 17
    ensure baseline_capture["schema"] == "sema.phase10-capture-provenance/v2"
    ensure baseline_capture["mode"] == "baseline"
    ensure baseline_capture["completed"] and baseline_capture["fresh_stack"]
    ensure baseline_capture["validator_sha256"] == file_sha256("viewer/validate-phase10.mjs")
    ensure baseline_capture["profile_sha256"] == file_sha256(config_path)

    reference = evidence["external_reference"]
    ensure len(reference) == 5
    ensure reference["role"] == config["reference"]["role"]
    ensure reference["geometry_input"] == false
    reference_metadata = {key: value for key, value in reference["metadata"].items() if key != "preview_sha256"}
    ensure reference_metadata == scene["measurement_sources"][0]
    ensure reference_metadata["id"] == config["reference"]["id"]
    ensure reference_metadata["fidelity"] == "measured"
    ensure reference["metadata"]["preview_sha256"] == config["reference"]["preview_sha256"]
    ensure reference["metadata_sha256"] == sha256_json(reference_metadata)
    ensure reference["metadata_sha256"] == config["reference"]["metadata_sha256"]
    local_preview = reference["local_preview"]
    ensure len(local_preview) == 7
    ensure local_preview["path"] == config["reference"]["local_preview_path"]
    ensure local_preview["served_path"] == reference_metadata["local_preview_url"]
    ensure local_preview["served_path"].startswith("/data/") and not local_preview["served_path"].contains("..")
    ensure file_sha256(local_preview["path"]) == local_preview["sha256"]
    ensure local_preview["sha256"] == config["reference"]["preview_sha256"]
    ensure local_preview["byte_length"] > 1024 and local_preview["byte_length"] <= config["thresholds"]["maximum_evidence_bytes"]
    ensure (
        local_preview["source"] == "pinned_local_after_remote_refresh"
        or local_preview["source"] == "pinned_local_offline"
    )
    served_resource = local_preview["served_resource"]
    ensure len(served_resource) == 7
    ensure served_resource["url"].startswith("http://127.0.0.1:")
    ensure served_resource["url"].endswith(local_preview["served_path"])
    ensure len(served_resource["request_id"]) > 0
    ensure served_resource["status"] == 200 and served_resource["mime_type"].startswith("image/")
    ensure served_resource["encoded_data_length"] > 0
    ensure served_resource["sha256"] == local_preview["sha256"]
    ensure len(served_resource["decoded_images"]) == 2
    ensure all(
        len(image) == 5
        and image["complete"]
        and image["src"] == served_resource["url"]
        and image["natural_width"] > 0
        and image["natural_height"] > 0
        for image in served_resource["decoded_images"]
    )
    mut retained_refresh_sha256 = ""
    if local_preview["source"] == "pinned_local_after_remote_refresh":
        ensure len(local_preview["refresh_evidence_sha256"]) == 64
        refresh_payload = fs.read_text(config["reference_refresh_path"])?
        ensure len(refresh_payload) > 0 and len(refresh_payload) <= config["thresholds"]["maximum_evidence_bytes"]
        refresh = decode_json(refresh_payload)
        ensure len(refresh) == 11 and refresh["schema"] == "sema.phase10-reference-refresh/v1"
        canonical_refresh = {key: value for key, value in refresh.items() if key != "evidence_sha256"}
        ensure sha256_json(canonical_refresh) == refresh["evidence_sha256"]
        ensure refresh["source_url"] == reference_metadata["preview_url"]
        ensure refresh["local_path"] == config["reference"]["local_preview_path"]
        ensure refresh["preview_sha256"] == config["reference"]["preview_sha256"]
        ensure refresh["preview_sha256"] == file_sha256(refresh["local_path"])
        ensure refresh["byte_length"] == local_preview["byte_length"]
        ensure refresh["content_type"].startswith("image/")
        ensure refresh["scientific_validated"] == false
        retained_refresh_sha256 = refresh["evidence_sha256"]

    ensure (
        baseline_capture["network_mode"] == "remote_refresh_verified_then_browser_offline"
        or baseline_capture["network_mode"] == "offline_pinned_local"
    )
    baseline_network_policy = baseline_capture["network_policy"]
    ensure len(baseline_network_policy) == 10
    ensure baseline_network_policy["enforcement"] == "cdp_auto_attach_fetch_fail_exact_origin_method_path_before_resume"
    ensure baseline_network_policy["forbidden_protocols"] == ["ws:", "wss:"]
    baseline_origins = baseline_network_policy["spawned_origins"]
    ensure len(baseline_origins) == 2
    baseline_viewer_origin = baseline_origins["viewer"]
    baseline_live_origin = baseline_origins["live"]
    viewer_origin_parts = baseline_viewer_origin.split(":")
    live_origin_parts = baseline_live_origin.split(":")
    ensure len(viewer_origin_parts) == 3 and viewer_origin_parts[0] == "http" and viewer_origin_parts[1] == "//127.0.0.1"
    ensure len(live_origin_parts) == 3 and live_origin_parts[0] == "http" and live_origin_parts[1] == "//127.0.0.1"
    ensure int(viewer_origin_parts[2]) >= 4177 and int(viewer_origin_parts[2]) <= 4187
    ensure int(live_origin_parts[2]) >= 8791 and int(live_origin_parts[2]) <= 8801
    baseline_contracts = baseline_network_policy["allowed_request_contracts"]
    ensure len(baseline_contracts) == 14
    ensure all(
        len(contract) == 4
        and contract["origin"] == baseline_viewer_origin
        and contract["method"] in ["GET", "POST"]
        and contract["path"].startswith("/")
        and (contract["search"] == "" or contract["search"] == "?phase10-viewer=disabled")
        and len([other for other in baseline_contracts if other == contract]) == 1
        for contract in baseline_contracts
    )
    ensure len([contract for contract in baseline_contracts if contract["method"] == "GET" and contract["path"] == "/" and contract["search"] == ""]) == 1
    ensure len([contract for contract in baseline_contracts if contract["method"] == "GET" and contract["path"] == "/" and contract["search"] == "?phase10-viewer=disabled"]) == 1
    ensure all(
        (
            entry["served_path"] == "/index.html"
            and len([contract for contract in baseline_contracts if contract["method"] == "GET" and contract["path"] == entry["served_path"] and contract["search"] == ""]) == 0
        )
        or (
            entry["served_path"] != "/index.html"
            and len([contract for contract in baseline_contracts if contract["method"] == "GET" and contract["path"] == entry["served_path"] and contract["search"] == ""]) == 1
        )
        for entry in bundle_entries
    )
    ensure len([contract for contract in baseline_contracts if contract["method"] == "GET" and contract["path"] == "/api/sema/status" and contract["search"] == ""]) == 1
    ensure len([contract for contract in baseline_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/step" and contract["search"] == ""]) == 1
    ensure len([contract for contract in baseline_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/intervene" and contract["search"] == ""]) == 1
    ensure len([contract for contract in baseline_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/molecule" and contract["search"] == ""]) == 1
    ensure len([contract for contract in baseline_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/molecule/step" and contract["search"] == ""]) == 1
    ensure len([contract for contract in baseline_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/program" and contract["search"] == ""]) == 1
    ensure len([contract for contract in baseline_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/cortex/propose" and contract["search"] == ""]) == 1
    baseline_qualified_contracts = baseline_network_policy["qualified_control_contracts"]
    ensure len(baseline_qualified_contracts) == 2
    ensure all(len(contract) == 4 and contract["origin"] == baseline_viewer_origin and contract["method"] == "POST" and contract["search"] == "" for contract in baseline_qualified_contracts)
    ensure len([contract for contract in baseline_qualified_contracts if contract["path"] == "/api/sema/program"]) == 1
    ensure len([contract for contract in baseline_qualified_contracts if contract["path"] == "/api/sema/cortex/propose"]) == 1
    ensure all(len([allowed for allowed in baseline_contracts if allowed == contract]) == 1 for contract in baseline_qualified_contracts)
    baseline_control_actions = baseline_network_policy["qualified_control_actions"]
    ensure len(baseline_control_actions) == 5
    ensure all(
        len(action) == 14
        and len(action["contract"]) == 4
        and len([contract for contract in baseline_qualified_contracts if contract == action["contract"]]) == 1
        and action["request_url"] == action["contract"]["origin"] + action["contract"]["path"]
        and action["request_method"] == "POST"
        and len(action["request_id"]) > 0
        and action["request_body_byte_length"] > 0 and action["request_body_byte_length"] <= 8192
        and len(action["request_body_sha256"]) == 64
        and action["status"] >= 200 and action["status"] < 300
        and len(action["response_mime_type"]) > 0
        and action["response_encoded_data_length"] > 0
        and action["completion_observed"]
        and len(action["session_id"]) > 0
        and len(action["target_id"]) > 0
        for action in baseline_control_actions
    )
    ensure len([action for action in baseline_control_actions if action["action_id"] == "scenario_select" and action["control_id"] == "scenario-control" and action["contract"]["path"] == "/api/sema/program"]) == 1
    ensure len([action for action in baseline_control_actions if action["action_id"] == "compile_apply" and action["control_id"] == "edit-apply" and action["contract"]["path"] == "/api/sema/program"]) == 1
    ensure len([action for action in baseline_control_actions if action["action_id"] == "cortex_propose" and action["control_id"] == "edit-propose" and action["contract"]["path"] == "/api/sema/cortex/propose"]) == 1
    ensure len([action for action in baseline_control_actions if action["action_id"] == "assistant_apply" and action["control_id"] == "assistant-apply" and action["contract"]["path"] == "/api/sema/program"]) == 1
    ensure len([action for action in baseline_control_actions if action["action_id"] == "program_reset" and action["control_id"] == "edit-reset" and action["contract"]["path"] == "/api/sema/program"]) == 1
    ensure all(len([action for action in baseline_control_actions if action["contract"] == contract]) >= 1 for contract in baseline_qualified_contracts)
    baseline_completed_contracts = baseline_network_policy["completed_request_contracts"]
    ensure baseline_network_policy["exact_contract_coverage_pass"]
    ensure len(baseline_completed_contracts) == len(baseline_contracts)
    ensure all(
        len(completed) == 15
        and completed["origin"] == baseline_viewer_origin
        and completed["method"] in ["GET", "POST"]
        and completed["path"].startswith("/")
        and (completed["search"] == "" or completed["search"] == "?phase10-viewer=disabled")
        and completed["url"].startswith(completed["origin"] + completed["path"])
        and len(completed["request_id"]) > 0
        and completed["request_body_byte_length"] >= 0 and completed["request_body_byte_length"] <= 8192
        and (
            completed["method"] == "GET"
            or (completed["request_body_byte_length"] > 0 and len(completed["request_body_sha256"]) == 64)
        )
        and completed["status"] >= 200 and completed["status"] < 300
        and completed["encoded_data_length"] > 0
        and len(completed["session_id"]) > 0
        and len(completed["target_id"]) > 0
        and completed["target_type"] == "page"
        and completed["completion_observed"]
        and len([contract for contract in baseline_contracts if contract["origin"] == completed["origin"] and contract["method"] == completed["method"] and contract["path"] == completed["path"] and contract["search"] == completed["search"]]) == 1
        for completed in baseline_completed_contracts
    )
    ensure all(
        len([completed for completed in baseline_completed_contracts if completed["origin"] == contract["origin"] and completed["method"] == contract["method"] and completed["path"] == contract["path"] and completed["search"] == contract["search"]]) == 1
        for contract in baseline_contracts
    )
    baseline_targets = baseline_network_policy["governed_targets"]
    ensure len(baseline_targets) >= 3
    ensure all(
        len(target) == 6
        and len(target["session_id"]) > 0
        and len(target["target_id"]) > 0
        and target["target_type"] in ["page", "iframe", "worker", "shared_worker", "service_worker"]
        and (
            (target["target_type"] in ["worker", "shared_worker", "service_worker"] and target["policy_mechanism"] == "network_block_all_worker_before_resume")
            or (target["target_type"] in ["page", "iframe"] and target["policy_mechanism"] == "fetch_request_pause_exact_contract")
        )
        and target["policy_installed"]
        and target["resumed"]
        for target in baseline_targets
    )
    baseline_blocked_probes = baseline_network_policy["blocked_probes"]
    ensure len(baseline_blocked_probes) == 9
    ensure all(
        len(probe) == 12
        and probe["method"] == "GET"
        and probe["rejection_reason"] in ["outside_exact_contract", "websocket_forbidden"]
        and len(probe["request_id"]) > 0
        and len(probe["session_id"]) > 0
        and len(probe["target_id"]) > 0
        and len(probe["policy_target_id"]) > 0
        and probe["policy_target_type"] in ["page", "worker"]
        for probe in baseline_blocked_probes
    )
    ensure any(probe["probe_id"] == "page_hostname" and probe["context"] == "page" and probe["url"] == "https://phase10-page-probe.invalid/page-hostname" for probe in baseline_blocked_probes)
    ensure any(probe["probe_id"] == "page_direct_ip" and probe["context"] == "page" and probe["url"] == "http://93.184.216.34/page-direct-ip" for probe in baseline_blocked_probes)
    ensure any(probe["probe_id"] == "page_rogue_loopback" and probe["context"] == "page" and probe["url"] == "http://127.0.0.1:65534/phase10-page-rogue" for probe in baseline_blocked_probes)
    ensure any(probe["probe_id"] == "page_localhost_alias" and probe["context"] == "page" and probe["url"].startswith("http://localhost:") and probe["url"].endswith("/") for probe in baseline_blocked_probes)
    ensure any(probe["probe_id"] == "page_websocket" and probe["context"] == "page" and probe["url"].startswith("ws://127.0.0.1:") and probe["url"].endswith("/phase10-websocket-rogue") and probe["rejection_reason"] == "websocket_forbidden" for probe in baseline_blocked_probes)
    ensure any(probe["probe_id"] == "blank_hostname" and probe["context"] == "_blank" and probe["url"] == "https://phase10-popup-probe.invalid/popup-target-blank" for probe in baseline_blocked_probes)
    ensure any(probe["probe_id"] == "blank_rogue_loopback" and probe["context"] == "_blank" and probe["url"] == baseline_viewer_origin + "/phase10-popup-rogue" for probe in baseline_blocked_probes)
    ensure any(probe["probe_id"] == "worker_direct_ip" and probe["context"] == "worker" and probe["url"] == "http://93.184.216.34/worker-direct-ip" for probe in baseline_blocked_probes)
    ensure any(probe["probe_id"] == "worker_rogue_loopback" and probe["context"] == "worker" and probe["url"] == baseline_live_origin + "/phase10-worker-rogue" for probe in baseline_blocked_probes)
    ensure len(baseline_capture["runtime"]) == 3
    ensure baseline_capture["runtime"]["platform"] == "darwin"
    ensure baseline_capture["runtime"]["architecture"] == "arm64"
    ensure baseline_capture["runtime"]["node_version"].startswith("v")
    ensure len(baseline_capture["validator_run_id"]) == 36
    ensure len(baseline_capture["session_id"]) == 36
    ensure len(baseline_capture["capture_id"]) == 36
    ensure len(baseline_capture["stack_id"]) == 36
    ensure baseline_capture["validator_run_id"] != baseline_capture["session_id"]
    ensure baseline_capture["validator_run_id"] != baseline_capture["capture_id"]
    ensure baseline_capture["session_id"] != baseline_capture["capture_id"]
    ensure baseline_capture["stack_id"] != baseline_capture["capture_id"]
    ensure baseline_capture["completed_at"] > baseline_capture["started_at"]
    ensure baseline_capture["reference_preview"] == local_preview
    if baseline_capture["reference_preview"]["source"] == "pinned_local_after_remote_refresh":
        ensure baseline_capture["reference_preview"]["refresh_evidence_sha256"] == retained_refresh_sha256
    baseline_groups = baseline_capture["process_groups"]
    ensure len(baseline_groups) >= 5
    ensure all(len(group) == 3 and group["process_group_id"] > 0 for group in baseline_groups)
    ensure len([group for group in baseline_groups if group["role"] == "typecheck"]) == 1
    ensure len([group for group in baseline_groups if group["role"] == "production-build"]) == 1
    ensure len([group for group in baseline_groups if group["role"] == "sema"]) == 1
    ensure len([group for group in baseline_groups if group["role"] == "vite"]) == 1
    ensure len([group for group in baseline_groups if group["role"] == "chrome"]) == 1

    modeled = evidence["modeled_layers"]
    ensure len(modeled) == 2
    ensure any(layer["layer_id"] == "cellular" and layer["scientific_validated"] == false for layer in modeled)
    ensure any(layer["layer_id"] == "tissue" and layer["scientific_validated"] == false for layer in modeled)
    ensure all(len(layer) == 2 for layer in modeled)

    thresholds = config["thresholds"]
    scales = evidence["scale_profiles"]
    ensure len(scales) == 4 and covers_four_scales(scales, "scale_id")
    mut minimum_fps = 1000000.0
    mut dropped_frames = 0
    mut maximum_gpu_bytes = 0
    mut maximum_gpu_resources = 0
    mut total_visible_instances = 0
    for scale in scales:
        ensure len(scale) == 12
        ensure scale["average_fps"] >= thresholds["minimum_scale_fps"]
        ensure scale["dropped_frames"] >= 0 and scale["dropped_frames"] <= thresholds["maximum_dropped_frames_per_scale"]
        ensure len(scale["frame_samples_ms"]) >= thresholds["minimum_scale_frame_samples"]
        ensure len(scale["frame_samples_ms"]) <= thresholds["maximum_scale_frame_samples"]
        ensure all(sample_ms > 0.0 for sample_ms in scale["frame_samples_ms"])
        observed_fps = 1000.0 * f64(len(scale["frame_samples_ms"])) / sum(scale["frame_samples_ms"])
        ensure observed_fps >= thresholds["minimum_scale_fps"]
        ensure abs(observed_fps - scale["average_fps"]) <= thresholds["maximum_reported_fps_residual"]
        ensure scale["gpu_allocated_bytes"] > 0 and scale["gpu_resource_count"] > 0
        ensure scale["visible_instances"] > 0 and scale["visible_instances"] <= scale["max_visible_instances"]
        ensure len(scale["webgl_renderer"]) > 0
        ensure scale["fov_value"] > 0.0 and scale["fov_value"] <= thresholds["maximum_fov_um"]
        ensure scale["fov_unit"] == "micrometer"
        ensure scale["deterministic_switch_pass"]
        total_visible_instances = total_visible_instances + scale["visible_instances"]
        minimum_fps = min(minimum_fps, observed_fps)
        dropped_frames = dropped_frames + scale["dropped_frames"]
        maximum_gpu_bytes = max(maximum_gpu_bytes, scale["gpu_allocated_bytes"])
        maximum_gpu_resources = max(maximum_gpu_resources, scale["gpu_resource_count"])

    interaction = evidence["interaction_profile"]
    ensure len(interaction) == 2 and interaction["hz"] == thresholds["interaction_hz"]
    ensure len(interaction["samples"]) >= thresholds["minimum_interaction_samples"]
    ensure len(interaction["samples"]) <= thresholds["maximum_interaction_samples"]
    ensure all(sample >= 0.0 for sample in interaction["samples"])
    mut previous_interaction_ms = -1.0
    for timestamp_ms in interaction["samples"]:
        ensure timestamp_ms > previous_interaction_ms
        previous_interaction_ms = timestamp_ms
    interaction_interval_ms = (
        interaction["samples"][len(interaction["samples"]) - 1] - interaction["samples"][0]
    ) / f64(len(interaction["samples"]) - 1)
    ensure abs(interaction_interval_ms - 1000.0 / f64(interaction["hz"])) <= thresholds["maximum_interaction_interval_residual_ms"]

    updates = evidence["canonical_updates"]
    ensure len(updates) == 2 and updates["hz"] == thresholds["canonical_update_hz"]
    ensure len(updates["samples"]) >= thresholds["minimum_canonical_updates"]
    ensure len(updates["samples"]) <= thresholds["maximum_canonical_updates"]
    mut previous_sequence = -1
    mut previous_update_ms = -1.0
    for update in updates["samples"]:
        ensure len(update) == 4
        ensure update["sequence"] > previous_sequence and update["canonical"] == false
        ensure update["timestamp_ms"] > previous_update_ms
        ensure update["simulation_digest"] == scene_record["scientific_result_sha256"]
        previous_sequence = update["sequence"]
        previous_update_ms = update["timestamp_ms"]
    canonical_interval_ms = (
        updates["samples"][len(updates["samples"]) - 1]["timestamp_ms"] - updates["samples"][0]["timestamp_ms"]
    ) / f64(len(updates["samples"]) - 1)
    ensure abs(canonical_interval_ms - 1000.0 / f64(updates["hz"])) <= thresholds["maximum_canonical_update_interval_residual_ms"]

    pick = evidence["pick_latency"]
    ensure len(pick) == 2
    ensure pick["p95_ms"] >= 0.0 and pick["p95_ms"] <= thresholds["maximum_pick_p95_ms"]
    ensure len(pick["samples_ms"]) >= thresholds["minimum_pick_samples"]
    ensure len(pick["samples_ms"]) <= thresholds["maximum_pick_samples"]
    ensure all(sample_ms >= 0.0 for sample_ms in pick["samples_ms"])
    mut picks_within_reported_p95 = 0
    for sample_ms in pick["samples_ms"]:
        if sample_ms <= pick["p95_ms"]:
            picks_within_reported_p95 = picks_within_reported_p95 + 1
    ensure picks_within_reported_p95 * 100 >= len(pick["samples_ms"]) * 95

    telemetry = evidence["gpu_telemetry"]
    ensure len(telemetry) == 2
    renderer = telemetry["renderer"]
    ensure len(renderer) == 6
    ensure len(renderer["version"]) > 0 and len(renderer["shading_language_version"]) > 0
    ensure len(renderer["vendor"]) > 0 and len(renderer["renderer"]) > 0
    ensure renderer["max_texture_size"] > 0 and renderer["max_renderbuffer_size"] > 0
    ensure len(telemetry["samples"]) > 0 and len(telemetry["samples"]) <= thresholds["maximum_gpu_samples"]
    for sample in telemetry["samples"]:
        ensure len(sample) == 3
        ensure sample["timestamp_ms"] >= 0.0
        ensure sample["allocated_bytes"] > 0 and sample["resource_count"] > 0
        maximum_gpu_bytes = max(maximum_gpu_bytes, sample["allocated_bytes"])
        maximum_gpu_resources = max(maximum_gpu_resources, sample["resource_count"])

    context_loss = evidence["context_loss"]
    ensure len(context_loss) == 6 and context_loss["classification"] == "expected_test"
    ensure context_loss["negative_observed"] and context_loss["recovered"] and context_loss["resources_reinitialized"]
    ensure context_loss["digest_before"] == scene_record["scientific_result_sha256"]
    ensure context_loss["digest_after"] == context_loss["digest_before"]

    screenshots = evidence["screenshots"]
    ensure len(screenshots) == 4 and covers_four_scales(screenshots, "scale_id")
    screenshot_digests = []
    for screenshot in screenshots:
        ensure len(screenshot) == 6
        ensure path.is_relative_to(screenshot["path"], config["screenshot_root"])
        ensure screenshot["path"].endswith(".png")
        ensure file_sha256(screenshot["path"]) == screenshot["sha256"]
        ensure screenshot["sha256"] == config["screenshots"][screenshot["scale_id"]]
        ensure screenshot["capture_id"] == baseline_capture["capture_id"]
        ensure len(screenshot["capture_nonce"]) == 36
        ensure screenshot["captured_at"] >= baseline_capture["started_at"]
        ensure screenshot["captured_at"] <= baseline_capture["completed_at"]
        ensure len([other for other in screenshots if other["capture_nonce"] == screenshot["capture_nonce"]]) == 1
        screenshot_digests.append(screenshot["sha256"])

    replay_payload = fs.read_text(config["visual_regression_replay_path"])?
    ensure len(replay_payload) > 0 and len(replay_payload) <= thresholds["maximum_evidence_bytes"]
    regression = decode_json(replay_payload)
    ensure len(regression) == 12
    ensure regression["schema"] == "sema.phase10-visual-regression-replay/v4"
    canonical_regression = {key: value for key, value in regression.items() if key != "evidence_sha256"}
    ensure sha256_json(canonical_regression) == regression["evidence_sha256"]
    ensure regression["profile_id"] == evidence["profile_id"]
    baseline_identity = regression["baseline_evidence"]
    ensure len(baseline_identity) == 6
    ensure baseline_identity["path"] == config["evidence_path"]
    ensure baseline_identity["file_sha256"] == file_sha256(config["evidence_path"])
    ensure baseline_identity["evidence_sha256"] == evidence["evidence_sha256"]
    ensure baseline_identity["capture_id"] == baseline_capture["capture_id"]
    ensure baseline_identity["validator_run_id"] == baseline_capture["validator_run_id"]
    ensure baseline_identity["session_id"] == baseline_capture["session_id"]
    replay_capture = regression["replay_capture"]
    ensure len(replay_capture) == 17
    ensure replay_capture["schema"] == "sema.phase10-capture-provenance/v2"
    ensure replay_capture["mode"] == "replay"
    ensure replay_capture["completed"] and replay_capture["fresh_stack"]
    ensure replay_capture["validator_sha256"] == file_sha256("viewer/validate-phase10.mjs")
    ensure replay_capture["validator_sha256"] == baseline_capture["validator_sha256"]
    ensure replay_capture["profile_sha256"] == file_sha256(config_path)
    ensure replay_capture["profile_sha256"] == baseline_capture["profile_sha256"]
    ensure regression["scene_sha256"] == scene_record["sha256"]
    ensure regression["viewer_bundle"] == bundle
    ensure regression["viewer_bundle"]["sha256"] == sha256_json(regression["viewer_bundle"]["manifest"])
    ensure regression["pixel_equality_observed"]
    ensure regression["capture_provenance_status"] == "technical_untrusted"
    ensure regression["visual_regression_replay_pass"] == false
    ensure regression["scientific_validated"] == false

    ensure replay_capture["network_mode"] == "offline_pinned_local"
    replay_network_policy = replay_capture["network_policy"]
    ensure len(replay_network_policy) == 10
    ensure replay_network_policy["enforcement"] == baseline_network_policy["enforcement"]
    ensure replay_network_policy["forbidden_protocols"] == baseline_network_policy["forbidden_protocols"]
    replay_origins = replay_network_policy["spawned_origins"]
    ensure len(replay_origins) == 2
    replay_viewer_origin = replay_origins["viewer"]
    replay_live_origin = replay_origins["live"]
    replay_viewer_origin_parts = replay_viewer_origin.split(":")
    replay_live_origin_parts = replay_live_origin.split(":")
    ensure len(replay_viewer_origin_parts) == 3 and replay_viewer_origin_parts[0] == "http" and replay_viewer_origin_parts[1] == "//127.0.0.1"
    ensure len(replay_live_origin_parts) == 3 and replay_live_origin_parts[0] == "http" and replay_live_origin_parts[1] == "//127.0.0.1"
    ensure int(replay_viewer_origin_parts[2]) >= 4177 and int(replay_viewer_origin_parts[2]) <= 4187
    ensure int(replay_live_origin_parts[2]) >= 8791 and int(replay_live_origin_parts[2]) <= 8801
    replay_contracts = replay_network_policy["allowed_request_contracts"]
    ensure len(replay_contracts) == 14
    ensure all(
        len(contract) == 4
        and contract["origin"] == replay_viewer_origin
        and contract["method"] in ["GET", "POST"]
        and contract["path"].startswith("/")
        and (contract["search"] == "" or contract["search"] == "?phase10-viewer=disabled")
        and len([other for other in replay_contracts if other == contract]) == 1
        for contract in replay_contracts
    )
    ensure len([contract for contract in replay_contracts if contract["method"] == "GET" and contract["path"] == "/" and contract["search"] == ""]) == 1
    ensure len([contract for contract in replay_contracts if contract["method"] == "GET" and contract["path"] == "/" and contract["search"] == "?phase10-viewer=disabled"]) == 1
    ensure all(
        (
            entry["served_path"] == "/index.html"
            and len([contract for contract in replay_contracts if contract["method"] == "GET" and contract["path"] == entry["served_path"] and contract["search"] == ""]) == 0
        )
        or (
            entry["served_path"] != "/index.html"
            and len([contract for contract in replay_contracts if contract["method"] == "GET" and contract["path"] == entry["served_path"] and contract["search"] == ""]) == 1
        )
        for entry in bundle_entries
    )
    ensure len([contract for contract in replay_contracts if contract["method"] == "GET" and contract["path"] == "/api/sema/status" and contract["search"] == ""]) == 1
    ensure len([contract for contract in replay_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/step" and contract["search"] == ""]) == 1
    ensure len([contract for contract in replay_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/intervene" and contract["search"] == ""]) == 1
    ensure len([contract for contract in replay_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/molecule" and contract["search"] == ""]) == 1
    ensure len([contract for contract in replay_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/molecule/step" and contract["search"] == ""]) == 1
    ensure len([contract for contract in replay_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/program" and contract["search"] == ""]) == 1
    ensure len([contract for contract in replay_contracts if contract["method"] == "POST" and contract["path"] == "/api/sema/cortex/propose" and contract["search"] == ""]) == 1
    replay_qualified_contracts = replay_network_policy["qualified_control_contracts"]
    ensure len(replay_qualified_contracts) == 2
    ensure all(len(contract) == 4 and contract["origin"] == replay_viewer_origin and contract["method"] == "POST" and contract["search"] == "" for contract in replay_qualified_contracts)
    ensure len([contract for contract in replay_qualified_contracts if contract["path"] == "/api/sema/program"]) == 1
    ensure len([contract for contract in replay_qualified_contracts if contract["path"] == "/api/sema/cortex/propose"]) == 1
    ensure all(len([allowed for allowed in replay_contracts if allowed == contract]) == 1 for contract in replay_qualified_contracts)
    replay_control_actions = replay_network_policy["qualified_control_actions"]
    ensure len(replay_control_actions) == 5
    ensure all(
        len(action) == 14
        and len(action["contract"]) == 4
        and len([contract for contract in replay_qualified_contracts if contract == action["contract"]]) == 1
        and action["request_url"] == action["contract"]["origin"] + action["contract"]["path"]
        and action["request_method"] == "POST"
        and len(action["request_id"]) > 0
        and action["request_body_byte_length"] > 0 and action["request_body_byte_length"] <= 8192
        and len(action["request_body_sha256"]) == 64
        and action["status"] >= 200 and action["status"] < 300
        and len(action["response_mime_type"]) > 0
        and action["response_encoded_data_length"] > 0
        and action["completion_observed"]
        and len(action["session_id"]) > 0
        and len(action["target_id"]) > 0
        for action in replay_control_actions
    )
    ensure len([action for action in replay_control_actions if action["action_id"] == "scenario_select" and action["control_id"] == "scenario-control" and action["contract"]["path"] == "/api/sema/program"]) == 1
    ensure len([action for action in replay_control_actions if action["action_id"] == "compile_apply" and action["control_id"] == "edit-apply" and action["contract"]["path"] == "/api/sema/program"]) == 1
    ensure len([action for action in replay_control_actions if action["action_id"] == "cortex_propose" and action["control_id"] == "edit-propose" and action["contract"]["path"] == "/api/sema/cortex/propose"]) == 1
    ensure len([action for action in replay_control_actions if action["action_id"] == "assistant_apply" and action["control_id"] == "assistant-apply" and action["contract"]["path"] == "/api/sema/program"]) == 1
    ensure len([action for action in replay_control_actions if action["action_id"] == "program_reset" and action["control_id"] == "edit-reset" and action["contract"]["path"] == "/api/sema/program"]) == 1
    ensure all(len([action for action in replay_control_actions if action["contract"] == contract]) >= 1 for contract in replay_qualified_contracts)
    replay_completed_contracts = replay_network_policy["completed_request_contracts"]
    ensure replay_network_policy["exact_contract_coverage_pass"]
    ensure len(replay_completed_contracts) == len(replay_contracts)
    ensure all(
        len(completed) == 15
        and completed["origin"] == replay_viewer_origin
        and completed["method"] in ["GET", "POST"]
        and completed["path"].startswith("/")
        and (completed["search"] == "" or completed["search"] == "?phase10-viewer=disabled")
        and completed["url"].startswith(completed["origin"] + completed["path"])
        and len(completed["request_id"]) > 0
        and completed["request_body_byte_length"] >= 0 and completed["request_body_byte_length"] <= 8192
        and (
            completed["method"] == "GET"
            or (completed["request_body_byte_length"] > 0 and len(completed["request_body_sha256"]) == 64)
        )
        and completed["status"] >= 200 and completed["status"] < 300
        and completed["encoded_data_length"] > 0
        and len(completed["session_id"]) > 0
        and len(completed["target_id"]) > 0
        and completed["target_type"] == "page"
        and completed["completion_observed"]
        and len([contract for contract in replay_contracts if contract["origin"] == completed["origin"] and contract["method"] == completed["method"] and contract["path"] == completed["path"] and contract["search"] == completed["search"]]) == 1
        for completed in replay_completed_contracts
    )
    ensure all(
        len([completed for completed in replay_completed_contracts if completed["origin"] == contract["origin"] and completed["method"] == contract["method"] and completed["path"] == contract["path"] and completed["search"] == contract["search"]]) == 1
        for contract in replay_contracts
    )
    replay_targets = replay_network_policy["governed_targets"]
    ensure len(replay_targets) >= 3
    ensure all(
        len(target) == 6
        and len(target["session_id"]) > 0
        and len(target["target_id"]) > 0
        and target["target_type"] in ["page", "iframe", "worker", "shared_worker", "service_worker"]
        and (
            (target["target_type"] in ["worker", "shared_worker", "service_worker"] and target["policy_mechanism"] == "network_block_all_worker_before_resume")
            or (target["target_type"] in ["page", "iframe"] and target["policy_mechanism"] == "fetch_request_pause_exact_contract")
        )
        and target["policy_installed"]
        and target["resumed"]
        for target in replay_targets
    )
    replay_blocked_probes = replay_network_policy["blocked_probes"]
    ensure len(replay_blocked_probes) == 9
    ensure all(
        len(probe) == 12
        and probe["method"] == "GET"
        and probe["rejection_reason"] in ["outside_exact_contract", "websocket_forbidden"]
        and len(probe["request_id"]) > 0
        and len(probe["session_id"]) > 0
        and len(probe["target_id"]) > 0
        and len(probe["policy_target_id"]) > 0
        and probe["policy_target_type"] in ["page", "worker"]
        and len([baseline_probe for baseline_probe in baseline_blocked_probes if baseline_probe["probe_id"] == probe["probe_id"] and baseline_probe["context"] == probe["context"] and baseline_probe["target_type"] == probe["target_type"] and baseline_probe["policy_target_type"] == probe["policy_target_type"] and baseline_probe["rejection_reason"] == probe["rejection_reason"]]) == 1
        for probe in replay_blocked_probes
    )
    ensure any(probe["probe_id"] == "page_hostname" and probe["context"] == "page" and probe["target_type"] == "page" and probe["url"] == "https://phase10-page-probe.invalid/page-hostname" for probe in replay_blocked_probes)
    ensure any(probe["probe_id"] == "page_direct_ip" and probe["context"] == "page" and probe["target_type"] == "page" and probe["url"] == "http://93.184.216.34/page-direct-ip" for probe in replay_blocked_probes)
    ensure any(probe["probe_id"] == "blank_hostname" and probe["context"] == "_blank" and probe["target_type"] == "page" and probe["url"] == "https://phase10-popup-probe.invalid/popup-target-blank" for probe in replay_blocked_probes)
    ensure any(probe["probe_id"] == "worker_direct_ip" and probe["context"] == "worker" and probe["target_type"] == "worker" and probe["url"] == "http://93.184.216.34/worker-direct-ip" for probe in replay_blocked_probes)
    ensure any(probe["probe_id"] == "page_rogue_loopback" and probe["url"] == "http://127.0.0.1:65534/phase10-page-rogue" for probe in replay_blocked_probes)
    ensure any(probe["probe_id"] == "page_localhost_alias" and probe["url"].startswith("http://localhost:") and probe["url"].endswith("/") for probe in replay_blocked_probes)
    ensure any(probe["probe_id"] == "page_websocket" and probe["url"].startswith("ws://127.0.0.1:") and probe["url"].endswith("/phase10-websocket-rogue") and probe["rejection_reason"] == "websocket_forbidden" for probe in replay_blocked_probes)
    ensure any(probe["probe_id"] == "blank_rogue_loopback" and probe["url"] == replay_viewer_origin + "/phase10-popup-rogue" for probe in replay_blocked_probes)
    ensure any(probe["probe_id"] == "worker_rogue_loopback" and probe["url"] == replay_live_origin + "/phase10-worker-rogue" for probe in replay_blocked_probes)
    ensure replay_capture["runtime"] == baseline_capture["runtime"]
    ensure replay_capture["started_at"] > baseline_capture["completed_at"]
    ensure replay_capture["completed_at"] > replay_capture["started_at"]
    ensure len(replay_capture["validator_run_id"]) == 36
    ensure len(replay_capture["session_id"]) == 36
    ensure len(replay_capture["capture_id"]) == 36
    ensure len(replay_capture["stack_id"]) == 36
    ensure replay_capture["validator_run_id"] != baseline_capture["validator_run_id"]
    ensure replay_capture["session_id"] != baseline_capture["session_id"]
    ensure replay_capture["capture_id"] != baseline_capture["capture_id"]
    ensure replay_capture["stack_id"] != baseline_capture["stack_id"]
    replay_preview = replay_capture["reference_preview"]
    ensure len(replay_preview) == 7
    ensure replay_preview["path"] == local_preview["path"]
    ensure replay_preview["sha256"] == local_preview["sha256"]
    ensure replay_preview["source"] == "pinned_local_offline"
    ensure replay_preview["served_path"] == local_preview["served_path"]
    ensure file_sha256(replay_preview["path"]) == replay_preview["sha256"]
    replay_served_resource = replay_preview["served_resource"]
    ensure len(replay_served_resource) == 7
    ensure replay_served_resource["url"].startswith("http://127.0.0.1:")
    ensure replay_served_resource["url"].endswith(replay_preview["served_path"])
    ensure len(replay_served_resource["request_id"]) > 0
    ensure replay_served_resource["status"] == 200
    ensure replay_served_resource["mime_type"].startswith("image/")
    ensure replay_served_resource["encoded_data_length"] > 0
    ensure replay_served_resource["sha256"] == replay_preview["sha256"]
    ensure len(replay_served_resource["decoded_images"]) == 2
    ensure all(
        len(image) == 5
        and image["complete"]
        and image["src"] == replay_served_resource["url"]
        and image["natural_width"] > 0
        and image["natural_height"] > 0
        for image in replay_served_resource["decoded_images"]
    )
    ensure replay_served_resource["decoded_images"] == served_resource["decoded_images"]
    replay_groups = replay_capture["process_groups"]
    ensure len(replay_groups) >= 5
    ensure all(len(group) == 3 and group["process_group_id"] > 0 for group in replay_groups)
    ensure len([group for group in replay_groups if group["role"] == "typecheck"]) == 1
    ensure len([group for group in replay_groups if group["role"] == "production-build"]) == 1
    ensure len([group for group in replay_groups if group["role"] == "sema"]) == 1
    ensure len([group for group in replay_groups if group["role"] == "vite"]) == 1
    ensure len([group for group in replay_groups if group["role"] == "chrome"]) == 1

    captures = regression["captures"]
    ensure len(captures) == 4 and covers_four_scales(captures, "scale_id")
    for capture in captures:
        ensure len(capture) == 10
        baseline = [screenshot for screenshot in screenshots if screenshot["scale_id"] == capture["scale_id"]]
        ensure len(baseline) == 1
        ensure capture["baseline_path"] == baseline[0]["path"]
        ensure capture["baseline_sha256"] == baseline[0]["sha256"]
        ensure capture["baseline_capture_id"] == baseline[0]["capture_id"]
        ensure capture["baseline_capture_nonce"] == baseline[0]["capture_nonce"]
        ensure file_sha256(capture["baseline_path"]) == capture["baseline_sha256"]
        ensure path.is_relative_to(capture["replay_path"], "runs/phase10/visual-regression-replay")
        ensure capture["replay_path"].endswith(".png")
        ensure capture["replay_path"] != capture["baseline_path"]
        ensure file_sha256(capture["replay_path"]) == capture["replay_sha256"]
        ensure capture["replay_capture_id"] == replay_capture["capture_id"]
        ensure len(capture["replay_capture_nonce"]) == 36
        ensure capture["replay_capture_nonce"] != capture["baseline_capture_nonce"]
        ensure len([other for other in captures if other["replay_capture_nonce"] == capture["replay_capture_nonce"]]) == 1
        ensure capture["exact_match"]
        ensure capture["replay_sha256"] == capture["baseline_sha256"]

    validator = evidence["validator"]
    ensure len(validator) == 5
    local_url_policy = validator["local_preview_url_policy"]
    ensure len(local_url_policy) == 2
    ensure local_url_policy["canonical_url"] == local_preview["served_path"]
    ensure len(local_url_policy["probes"]) == 4
    ensure all(len(probe) == 3 and probe["rejected"] for probe in local_url_policy["probes"])
    ensure any(probe["probe_id"] == "encoded_dot" and probe["value"] == "/data/%2e%2e/escape.jpg" for probe in local_url_policy["probes"])
    ensure any(probe["probe_id"] == "foreign_origin" and probe["value"] == "https://phase10-origin-probe.invalid/data/reference.jpg" for probe in local_url_policy["probes"])
    ensure any(probe["probe_id"] == "query" and probe["value"] == "/data/reference.jpg?variant=escape" for probe in local_url_policy["probes"])
    ensure any(probe["probe_id"] == "fragment" and probe["value"] == "/data/reference.jpg#escape" for probe in local_url_policy["probes"])
    roundtrips = validator["pick_roundtrips"]
    ensure len(roundtrips) >= 4 and len(roundtrips) <= thresholds["maximum_pick_roundtrips"]
    ensure len(roundtrips) == total_visible_instances
    ensure covers_four_scales(roundtrips, "layer_id")
    for roundtrip in roundtrips:
        ensure len(roundtrip) == 10
        ensure roundtrip["visible"] and roundtrip["roundtrip_pass"]
        ensure len(roundtrip["primitive_id"]) > 0 and len(roundtrip["semantic_id"]) > 0
        ensure len(roundtrip["canonical_entity_id"]) > 0 and roundtrip["canonical_entity_id"] != "unknown"
        ensure len(roundtrip["equation_id"]) > 0 and roundtrip["equation_id"] != "unknown"
        ensure len(roundtrip["evidence_id"]) == 64
        ensure roundtrip["source_frame"] >= 0
        ensure roundtrip["fidelity"] != "unknown" and len(roundtrip["fidelity"]) > 0

    stability = validator["semantic_stability"]
    ensure len(stability) == thresholds["maximum_semantic_stability_records"]
    ensure covers_four_scales(stability, "scale_id")
    for record in stability:
        ensure len(record) == 8
        visible_counts = [scale["visible_instances"] for scale in scales if scale["scale_id"] == record["scale_id"]]
        ensure len(visible_counts) == 1 and record["stable_count"] == visible_counts[0]
        semantic_ids = [roundtrip["semantic_id"] for roundtrip in roundtrips if roundtrip["layer_id"] == record["scale_id"]]
        ensure len(semantic_ids) == record["stable_count"]
        ensure sha256_json(semantic_ids) == record["semantic_ids_sha256"]
        ensure len(record["semantic_ids_sha256"]) == 64
        ensure record["replay_semantic_ids_sha256"] == record["semantic_ids_sha256"]
        ensure record["interpolation_semantic_ids_sha256"] == record["semantic_ids_sha256"]
        ensure record["lod_semantic_ids_sha256"] == record["semantic_ids_sha256"]
        ensure record["simulation_digest_before"] == scene_record["scientific_result_sha256"]
        ensure record["simulation_digest_after"] == record["simulation_digest_before"]

    unsupported = validator["unsupported_layers"]
    ensure len(unsupported) > 0 and len(unsupported) <= thresholds["maximum_unsupported_layers"]
    for layer in unsupported:
        ensure len(layer) == 4
        ensure len(layer["layer_id"]) > 0
        ensure layer["canonical_entity_id"] == "unknown"
        ensure layer["fidelity"] == "unknown" and layer["result"] == "unknown"

    disabled = validator["viewer_disabled_parity"]
    ensure len(disabled) == 3 and disabled["parity_pass"]
    ensure disabled["viewer_enabled_digest"] == scene_record["scientific_result_sha256"]
    ensure disabled["viewer_disabled_digest"] == disabled["viewer_enabled_digest"]

    return Phase10QualificationResult(
        schema="sema.phase10-qualification-result/v2",
        profile_id=evidence["profile_id"],
        config_sha256=file_sha256(config_path),
        evidence_sha256=file_sha256(config["evidence_path"]),
        scene_sha256=scene_record["sha256"],
        bundle_sha256=bundle["sha256"],
        external_reference_sha256=reference["metadata_sha256"],
        scientific_result_sha256=scene_record["scientific_result_sha256"],
        screenshot_sha256=screenshot_digests,
        scale_count=len(scales),
        minimum_average_fps=minimum_fps,
        interaction_hz=interaction["hz"],
        canonical_update_hz=updates["hz"],
        pick_p95_ms=pick["p95_ms"],
        dropped_frames=dropped_frames,
        gpu_allocated_bytes=maximum_gpu_bytes,
        gpu_resource_count=maximum_gpu_resources,
        context_loss_recovered=context_loss["recovered"],
        semantic_validation_pass=true,
        viewer_disabled_parity_pass=disabled["parity_pass"],
        pixel_equality_observed=regression["pixel_equality_observed"],
        capture_provenance_status=regression["capture_provenance_status"],
        visual_regression_replay_pass=false,
        profile_validated=false,
        scientific_validated=false,
    )
```

### `src/physicell.sema`

```sema
"""Pinned official PhysiCell 1.14.2 Apple-arm64 executable and stock XML field-coupling evidence."""

assure silver


pub struct PhysiCellFieldMetrics:
    mean_micromolar: f64
    minimum_micromolar: f64
    maximum_micromolar: f64
    spatial_cv: f64
    field_mass_micromolar_micrometer3: f64


pub struct PhysiCellSubstrateCellMetrics:
    uptake_rates_per_min: list[list[f64]]
    net_export_rates_micromolar_micrometer3_per_min: list[list[f64]]
    internalized_total_micromolar_micrometer3: list[f64]


pub struct PhysiCellSnapshot:
    voxels: int
    cells: int
    total_volume_micrometer3: f64
    substrates: list[str]
    fields: dict[str, PhysiCellFieldMetrics]
    cell_substrates: PhysiCellSubstrateCellMetrics


pub struct PhysiCellScenario:
    name: str
    coupled: bool
    configured_monomer_micromolar: f64
    configured_dimer_micromolar: f64
    initial: PhysiCellSnapshot
    final: PhysiCellSnapshot


pub struct PhysiCellScenarioExecution:
    name: str
    wall_runtime_s: f64
    captured_output_bytes: int
    output_files: int
    output_bytes: int
    initial_xml_sha256: str
    initial_mat_sha256: str
    initial_cell_mat_sha256: str
    final_xml_sha256: str
    final_mat_sha256: str
    final_cell_mat_sha256: str


pub struct PhysiCellExecution:
    scenario_executions: list[PhysiCellScenarioExecution]
    total_wall_runtime_s: f64
    total_output_bytes: int
    total_output_files: int


pub struct PhysiCellResult:
    schema: str
    profile_id: str
    config_sha256: str
    config_path: str
    phase8_result_sha256: str
    phase8_artifact_sha256: str
    release_version: str
    release_asset_sha256: str
    release_asset_bytes: int
    release_asset_id: int
    tag_commit: str
    tag_ref_sha: str
    tag_commit_verified: bool
    license: str
    workflow_sha256: str
    fetch_manifest_schema: str
    fetch_manifest_path: str
    fetch_manifest_sha256: str
    fetch_evidence_sha256: str
    fetch_remote_verified: bool
    fetch_manifest_pass: bool
    binary_sha256: str
    binary_bytes: int
    binary_architectures: list[str]
    host_architecture: str
    arm64_dependencies: list[str]
    initial_concentration_residual_micromolar: f64
    uniform_spatial_cv: f64
    mass_relative_residual: f64
    coupled_monomer_mean_delta_micromolar: f64
    coupled_dimer_mean_delta_micromolar: f64
    coupled_spatial_cv: f64
    coupled_external_monomer_mass_delta_micromolar_micrometer3: f64
    coupled_internalized_monomer_delta_micromolar_micrometer3: f64
    coupled_external_dimer_mass_delta_micromolar_micrometer3: f64
    coupled_internalized_dimer_delta_micromolar_micrometer3: f64
    coupled_mass_transfer_relative_residual: f64
    executable_pass: bool
    platform_pass: bool
    config_xml_field_coupling_pass: bool
    field_output_pass: bool
    concentration_transfer_pass: bool
    spatial_transfer_pass: bool
    mass_transfer_pass: bool
    uncertainty_bound_transfer_pass: bool
    cell_secretion_uptake_coupling_pass: bool
    failure_contract_pass: bool
    missing_failure_typed: bool
    corrupt_failure_typed: bool
    wrong_arch_failure_typed: bool
    timeout_failure_typed: bool
    oversized_output_failure_typed: bool
    manifest_missing_failure_typed: bool
    manifest_unverified_failure_typed: bool
    manifest_tampered_failure_typed: bool
    corrupt_asset_failure_typed: bool
    corrupt_binary_failure_typed: bool
    timeout_descendants_reaped: bool
    oversized_output_descendants_reaped: bool
    typed_failure_classes: list[str]
    target_rate_evidence: bool
    insulin_reaction_supported: bool
    scientific_uncertainty_evidence: bool
    scientific_validated: bool
    technical_qualified: bool
    evidence_class: str
    unsupported_semantics: list[str]
    integration_guidance: list[str]
    scenarios: list[PhysiCellScenario]
    execution: PhysiCellExecution
    result_sha256: str
    mode: str
    direct_parity_pass: bool
    direct_result_sha256: str
    direct_residual: f64
    direct_artifact_sha256: str
    artifact_directory: str
    result_path: str
    invariant schema == "sema.physicell-result/v1"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(phase8_result_sha256) == 64 and len(phase8_artifact_sha256) == 64
    invariant release_version == "1.14.2"
    invariant release_asset_bytes == 2371922 and release_asset_id == 233689828
    invariant len(release_asset_sha256) == 64 and len(workflow_sha256) == 64
    invariant len(tag_commit) == 40 and license == "BSD-3-Clause"
    invariant len(tag_ref_sha) == 40 and tag_commit_verified
    invariant fetch_manifest_schema == "sema.physicell-fetch/v1"
    invariant len(fetch_manifest_path) > 0
    invariant len(fetch_manifest_sha256) == 64 and len(fetch_evidence_sha256) == 64
    invariant fetch_remote_verified and fetch_manifest_pass
    invariant binary_bytes == 7656072 and len(binary_sha256) == 64
    invariant len(binary_architectures) == 2
    invariant host_architecture == "arm64"
    invariant len(arm64_dependencies) == 1
    invariant arm64_dependencies[0] == "/usr/lib/libSystem.B.dylib"
    invariant initial_concentration_residual_micromolar >= 0.0
    invariant uniform_spatial_cv >= 0.0 and mass_relative_residual >= 0.0
    invariant coupled_monomer_mean_delta_micromolar < 0.0
    invariant coupled_dimer_mean_delta_micromolar > 0.0 and coupled_spatial_cv > 0.0
    invariant coupled_external_monomer_mass_delta_micromolar_micrometer3 < 0.0
    invariant coupled_internalized_monomer_delta_micromolar_micrometer3 > 0.0
    invariant coupled_external_dimer_mass_delta_micromolar_micrometer3 > 0.0
    invariant coupled_internalized_dimer_delta_micromolar_micrometer3 < 0.0
    invariant coupled_mass_transfer_relative_residual >= 0.0
    invariant executable_pass and platform_pass and config_xml_field_coupling_pass
    invariant field_output_pass and concentration_transfer_pass and spatial_transfer_pass
    invariant mass_transfer_pass and uncertainty_bound_transfer_pass
    invariant cell_secretion_uptake_coupling_pass and failure_contract_pass
    invariant missing_failure_typed and corrupt_failure_typed and wrong_arch_failure_typed
    invariant timeout_failure_typed and oversized_output_failure_typed
    invariant manifest_missing_failure_typed and manifest_unverified_failure_typed
    invariant manifest_tampered_failure_typed
    invariant corrupt_asset_failure_typed and corrupt_binary_failure_typed
    invariant timeout_descendants_reaped and oversized_output_descendants_reaped
    invariant len(typed_failure_classes) == 6
    invariant not target_rate_evidence and not insulin_reaction_supported
    invariant not scientific_uncertainty_evidence and not scientific_validated
    invariant technical_qualified
    invariant evidence_class == "validated_stock_prebuilt_field_coupling"
    invariant len(unsupported_semantics) == 4
    invariant len(integration_guidance) == 3
    invariant len(scenarios) == 4
    invariant len(execution.scenario_executions) == 4
    invariant execution.total_wall_runtime_s > 0.0
    invariant execution.total_output_bytes > 0 and execution.total_output_files > 0
    invariant mode == "sema" and direct_parity_pass
    invariant len(direct_result_sha256) == 64 and len(direct_artifact_sha256) == 64
    invariant direct_residual >= 0.0
    invariant len(result_sha256) == 64
    invariant len(artifact_directory) > 0 and len(result_path) > 0


pub bridge python.inline physicell_backend from "foreign/python/physicell_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def run_profile(config_path: str, mode: str, direct_path: str, output_path: str) -> PhysiCellResult !{ffi.call}:
            sem "Run the real pinned universal PhysiCell binary on arm64, parse MultiCellDS/BioFVM outputs, and preserve explicit stock-template semantic limits"
```

### `src/physiology.sema`

```sema
"""Evidence-bound glucose, insulin, beta-cell, immune, and graft physiology."""

assure silver


pub def initial_physiology_parameters() -> dict[str, f64] !{}:
    return {
        "glucose_inflow_mg_dl_day": 846.0,
        "insulin_sensitivity_ml_micro_u_day": 0.72,
        "glucose_effectiveness_per_day": 1.44,
        "insulin_secretion_micro_u_ml_day_mg": 43.2,
        "insulin_clearance_per_day": 432.0,
        "secretion_half_saturation_mg2_dl2": 2000.0,
        "beta_death_per_day": 0.06,
        "beta_growth_dl_mg_day": 0.00084,
        "beta_glucotoxicity_dl2_mg2_day": 0.0000024,
        "immune_activation_per_day": 2.4,
        "immune_clearance_per_day": 1.8,
        "immune_kill_per_day": 0.22,
        "cytokine_release_per_day": 1.6,
        "cytokine_clearance_per_day": 2.2,
        "regulatory_recovery_per_day": 0.8,
        "graft_engraftment_per_day": 1.2,
        "graft_rejection_per_day": 0.28,
    }


pub def physiology_parameter_bounds() -> dict[str, list[f64]] !{}:
    return {
        "glucose_inflow_mg_dl_day": [300.0, 1600.0],
        "insulin_sensitivity_ml_micro_u_day": [0.05, 2.0],
        "glucose_effectiveness_per_day": [0.1, 4.0],
        "insulin_secretion_micro_u_ml_day_mg": [5.0, 100.0],
        "insulin_clearance_per_day": [50.0, 1000.0],
        "secretion_half_saturation_mg2_dl2": [500.0, 10000.0],
        "beta_death_per_day": [0.0, 0.5],
        "beta_growth_dl_mg_day": [0.0, 0.005],
        "beta_glucotoxicity_dl2_mg2_day": [0.0, 0.0001],
        "immune_activation_per_day": [0.0, 10.0],
        "immune_clearance_per_day": [0.0, 10.0],
        "immune_kill_per_day": [0.0, 1.0],
        "cytokine_release_per_day": [0.0, 10.0],
        "cytokine_clearance_per_day": [0.0, 10.0],
        "regulatory_recovery_per_day": [0.0, 10.0],
        "graft_engraftment_per_day": [0.0, 10.0],
        "graft_rejection_per_day": [0.0, 1.0],
    }


pub def physiology_parameter_value_valid(name: str, value: f64) -> bool !{}:
    bounds = physiology_parameter_bounds()
    if not bounds.has(name):
        return false
    return value >= bounds[name][0] and value <= bounds[name][1]


pub def initial_physiology_state() -> dict[str, any] !{}:
    return {
        "schema": "sema.metabolic-immune-state/v1",
        "model_time_days": 0.0,
        "values": [98.0, 10.0, 120.0, 0.02, 0.01, 0.35, 0.0],
        "integration_steps_accepted": 0,
        "integration_steps_rejected": 0,
        "integration_error_bound": 0.0,
        "technical_pass": true,
        "scientific_validated": false,
    }


pub def physiology_equations() -> list[str] !{}:
    return [
        "dG/dt = R0 + meal - exercise - (EG0 + SI I) G",
        "dI/dt = (beta + graft) sigma G^2 / (alpha + G^2) + dose - k I",
        "dbeta/dt = (r1 G - d0 - r2 G^2 - immune_kill E - hypoxia_loss) beta",
        "dC/dt = cytokine_release (challenge + E) (1-C) - cytokine_clearance C",
        "dE/dt = immune_activation C (1-E) - immune_clearance (0.15+R) E",
        "dR/dt = regulatory_recovery (0.35-R)",
        "dgraft/dt = engraftment (target-graft) - rejection E (1-shield) graft",
    ]


equation metabolic_immune_rhs(t, state, glucose_inflow, insulin_sensitivity, glucose_effectiveness, insulin_secretion, insulin_clearance, secretion_half_saturation, beta_death, beta_growth, beta_glucotoxicity, immune_activation, immune_clearance, immune_kill, cytokine_release, cytokine_clearance, regulatory_recovery, graft_engraftment, graft_rejection, glucose_target_millimolar, oxygen_kilopascal, cytokine_challenge, meal_intensity, exercise_intensity, exogenous_insulin, immune_shielding, graft_target_mg) -> any:
    glucose := state[0]
    insulin := state[1]
    beta_mass := state[2]
    cytokine := state[3]
    immune_effector := state[4]
    regulatory := state[5]
    graft_mass := state[6]
    glucose_target := glucose_target_millimolar * 18.018
    hypoxia := max(0.0, min(1.0, (5.0 - oxygen_kilopascal) / 5.0))
    effective_sensitivity := insulin_sensitivity * (1.0 + 0.8 * exercise_intensity)
    meal_appearance := 120.0 * meal_intensity + 2.4 * (glucose_target - glucose)
    exercise_disposal := 70.0 * exercise_intensity
    secretion := (beta_mass + graft_mass) * insulin_secretion * glucose^2 / (secretion_half_saturation + glucose^2)
    beta_growth_rate := beta_growth * glucose - beta_death - beta_glucotoxicity * glucose^2
    immune_loss := immune_kill * immune_effector
    hypoxia_loss := 0.18 * hypoxia
    return [
        glucose_inflow + meal_appearance - exercise_disposal - (glucose_effectiveness + effective_sensitivity * insulin) * glucose,
        secretion + exogenous_insulin - insulin_clearance * insulin,
        (beta_growth_rate - immune_loss - hypoxia_loss) * beta_mass,
        cytokine_release * (cytokine_challenge + immune_effector) * (1.0 - cytokine) - cytokine_clearance * cytokine,
        immune_activation * cytokine * (1.0 - immune_effector) - immune_clearance * (0.15 + regulatory) * immune_effector,
        regulatory_recovery * (0.35 - regulatory),
        graft_engraftment * (graft_target_mg - graft_mass) - (graft_rejection * immune_effector * (1.0 - immune_shielding) + hypoxia_loss) * graft_mass,
    ]


equation integrate_metabolic_immune_state(state, horizon_days, rates) -> any:
    return ode(metabolic_immune_rhs, 0.0, state, horizon_days, 0.00000001, 0.0000000001, 20000, rates, "rk45")


def physiology_rates(parameters: dict[str, f64], signals: dict[str, f64]):
    return [
        parameters["glucose_inflow_mg_dl_day"],
        parameters["insulin_sensitivity_ml_micro_u_day"],
        parameters["glucose_effectiveness_per_day"],
        parameters["insulin_secretion_micro_u_ml_day_mg"],
        parameters["insulin_clearance_per_day"],
        parameters["secretion_half_saturation_mg2_dl2"],
        parameters["beta_death_per_day"],
        parameters["beta_growth_dl_mg_day"],
        parameters["beta_glucotoxicity_dl2_mg2_day"],
        parameters["immune_activation_per_day"],
        parameters["immune_clearance_per_day"],
        parameters["immune_kill_per_day"],
        parameters["cytokine_release_per_day"],
        parameters["cytokine_clearance_per_day"],
        parameters["regulatory_recovery_per_day"],
        parameters["graft_engraftment_per_day"],
        parameters["graft_rejection_per_day"],
        signals["glucose"],
        signals["oxygen"],
        signals["cytokine"],
        signals["meal_intensity"],
        signals["exercise_intensity"],
        signals["exogenous_insulin_micro_u_ml_day"],
        signals["immune_shielding"],
        signals["graft_target_mg"],
    ]


def bounded_physiology_values(values: list[f64]):
    return [
        max(20.0, min(600.0, values[0])),
        max(0.0, min(1000.0, values[1])),
        max(0.01, min(1000.0, values[2])),
        max(0.0, min(1.0, values[3])),
        max(0.0, min(1.0, values[4])),
        max(0.0, min(1.0, values[5])),
        max(0.0, min(1000.0, values[6])),
    ]


pub def step_physiology_state(state: dict[str, any], dt_s: f64, signals: dict[str, f64], parameters: dict[str, f64]) -> dict[str, any] !{}:
    sem "Advance published glucose-insulin-beta equations and a bounded immune/graft extension on explicit model time"
    require state["schema"] == "sema.metabolic-immune-state/v1"
    require len(state["values"]) == 7 and dt_s >= 0.01 and dt_s <= 0.25
    horizon_days = dt_s * signals["physiology_seconds_per_real_second"] / 86400.0
    solved = integrate_metabolic_immune_state(state["values"], horizon_days, physiology_rates(parameters, signals))
    approximation = solved[0]
    raw_values = approximation.value
    values = bounded_physiology_values(raw_values)
    technical_pass = approximation.converged and approximation.residual <= 1.0 and raw_values[0] >= 20.0 and raw_values[0] <= 600.0 and raw_values[1] >= 0.0 and raw_values[1] <= 1000.0 and raw_values[2] > 0.0 and raw_values[2] <= 1000.0 and raw_values[3] >= 0.0 and raw_values[3] <= 1.0 and raw_values[4] >= 0.0 and raw_values[4] <= 1.0 and raw_values[5] >= 0.0 and raw_values[5] <= 1.0 and raw_values[6] >= 0.0 and raw_values[6] <= 1000.0
    return {
        "schema": state["schema"],
        "model_time_days": state["model_time_days"] + horizon_days,
        "values": values,
        "integration_steps_accepted": solved[1],
        "integration_steps_rejected": solved[2],
        "integration_error_bound": approximation.residual,
        "technical_pass": technical_pass,
        "scientific_validated": false,
    }


pub def physiology_public_state(state: dict[str, any], signals: dict[str, f64], parameters: dict[str, f64]) -> dict[str, any] !{}:
    values = state["values"]
    total_beta = values[2] + values[6]
    return {
        "schema": "sema.metabolic-immune-observation/v1",
        "model_id": "topp-2000-plus-bounded-immune-graft-v1",
        "model_time_days": state["model_time_days"],
        "state_names": ["glucose", "insulin", "native_beta_mass", "cytokine", "immune_effector", "regulatory_t_cell", "graft_beta_mass"],
        "state_units": ["mg/dL", "microU/mL", "mg", "fraction", "fraction", "fraction", "mg"],
        "state": values,
        "glucose_millimolar": values[0] / 18.018,
        "insulin_micro_u_ml": values[1],
        "native_beta_mass_mg": values[2],
        "graft_beta_mass_mg": values[6],
        "beta_function_fraction": max(0.0, min(1.5, total_beta / 120.0)),
        "cytokine_fraction": values[3],
        "immune_effector_fraction": values[4],
        "regulatory_fraction": values[5],
        "oxygen_kilopascal": signals["oxygen"],
        "meal_intensity": signals["meal_intensity"],
        "exercise_intensity": signals["exercise_intensity"],
        "immune_shielding": signals["immune_shielding"],
        "equations": physiology_equations(),
        "parameters": parameters,
        "integration_method": "adaptive RK45",
        "integration_steps_accepted": state["integration_steps_accepted"],
        "integration_steps_rejected": state["integration_steps_rejected"],
        "integration_error_bound": state["integration_error_bound"],
        "sources": ["Topp et al. 2000 PMID:11013117", "Oresic et al. 2012 DOI:10.1371/journal.pone.0051909"],
        "technical_pass": state["technical_pass"],
        "scientific_validated": false,
    }
```

### `src/portable.sema`

```sema
"""Measured Phase 9 ABI, CPU/MPS, process-loss, and checkpoint evidence."""

assure silver


pub struct PortabilityResult:
    schema: str
    profile_id: str
    profile_identity_sha256: str
    config_sha256: str
    source_result_sha256: str
    source_artifact_sha256: str
    backend_identity_sha256: str
    backend_source_sha256: str
    sema_contract_source_sha256: str
    numpy_version: str
    torch_version: str
    python_version: str
    cpu_backend: str
    cpu_device: str
    gpu_backend: str
    gpu_device: str
    mps_available: bool
    mps_evidence_status: str
    precision: str
    batch: int
    voxels: int
    steps: int
    repeats: int
    concentration_residual_micromolar: f64
    cpu_mass_relative_residual: f64
    gpu_mass_relative_residual: f64
    cpu_p95_latency_ms: f64
    gpu_p95_latency_ms: f64
    cpu_throughput_voxel_steps_per_s: f64
    gpu_throughput_voxel_steps_per_s: f64
    gpu_allocated_bytes: int
    gpu_host_transfer_bytes: int
    abi_scope: str
    bulk_elements: int
    bulk_payload_bytes: int
    bulk_calls: int
    bulk_p95_latency_ms: f64
    bulk_checksum_residual: f64
    bulk_pointer_equal: bool
    bulk_shares_memory: bool
    cpu_zero_copy: bool
    gpu_zero_copy: bool
    sema_bridge_zero_copy_validated: bool
    bulk_abi_pass: bool
    distributed_evidence_kind: str
    multiprocessing_start_method: str
    distributed_worker_count: int
    distributed_partition_batch: int
    distributed_total_steps: int
    worker_pids: list[int]
    survivor_worker_ids: list[int]
    survivor_worker_pids: list[int]
    survivor_worker_exitcodes: list[int]
    killed_worker_id: int
    killed_worker_pid: int
    killed_worker_exitcode: int
    killed_worker_signal: str
    recovery_worker_pid: int
    recovery_worker_exitcode: int
    recovery_resumed_step: int
    stable_checkpoint_step: int
    partial_checkpoint_step: int
    partial_checkpoint_bytes: int
    partial_checkpoint_intended_bytes: int
    rejected_checkpoint_count: int
    rejected_checkpoint_error_codes: list[str]
    checkpoint_manifest_sha256: str
    distributed_residual_micromolar: f64
    corrupt_checkpoint_blocked: bool
    partial_checkpoint_blocked: bool
    worker_loss_failure_validated: bool
    same_node_distributed_process_pass: bool
    distributed_validated: bool
    cross_node_distributed_validated: bool
    checkpoint_pass: bool
    device_loss_evidence_kind: str
    device_loss_injection_attempted: bool
    device_loss_injection_observed: bool
    device_loss_recovery_pass: bool
    device_loss_recovery_residual_micromolar: f64
    device_loss_failure_validated: bool
    physical_device_loss_observed: bool
    physical_device_loss_validated: bool
    scientific_parity_pass: bool
    cpu_profile_qualified: bool
    gpu_profile_qualified: bool
    single_node_portability_pass: bool
    local_technical_pass: bool
    portable_core_validated: bool
    direct_parity_pass: bool
    phase9_admitted: bool
    phase9_validated: bool
    scientific_validated: bool
    evidence_class: str
    direct_oracle_result_sha256: str
    direct_oracle_artifact_sha256: str
    direct_oracle_path: str
    direct_residual: f64
    result_sha256: str
    result_path: str
    invariant schema == "sema.portability-result/v2"
    invariant len(profile_id) > 0
    invariant len(profile_identity_sha256) == 64
    invariant len(config_sha256) == 64
    invariant len(source_result_sha256) == 64
    invariant len(source_artifact_sha256) == 64
    invariant len(backend_identity_sha256) == 64
    invariant len(backend_source_sha256) == 64
    invariant len(sema_contract_source_sha256) == 64
    invariant len(numpy_version) > 0 and len(torch_version) > 0 and len(python_version) > 0
    invariant cpu_backend == "NumPy" and cpu_device == "cpu"
    invariant gpu_backend == "PyTorch" and gpu_device == "mps"
    invariant mps_evidence_status == "real_measured" or mps_evidence_status == "unavailable"
    invariant precision == "float32"
    invariant batch > 0 and voxels > 2 and steps > 0 and repeats > 2
    invariant concentration_residual_micromolar >= 0.0
    invariant cpu_mass_relative_residual >= 0.0 and gpu_mass_relative_residual >= 0.0
    invariant cpu_p95_latency_ms > 0.0 and gpu_p95_latency_ms >= 0.0
    invariant cpu_throughput_voxel_steps_per_s > 0.0 and gpu_throughput_voxel_steps_per_s >= 0.0
    invariant gpu_allocated_bytes >= 0 and gpu_host_transfer_bytes >= 0
    invariant abi_scope == "python_buffer_protocol_adapter"
    invariant bulk_elements > 0 and bulk_payload_bytes > 0 and bulk_calls > 2
    invariant bulk_p95_latency_ms > 0.0 and bulk_checksum_residual >= 0.0
    invariant not sema_bridge_zero_copy_validated
    invariant distributed_evidence_kind == "local_multiprocess_partitioned"
    invariant multiprocessing_start_method == "spawn" or multiprocessing_start_method == "fork"
    invariant distributed_worker_count == 2 and len(worker_pids) == distributed_worker_count
    invariant len(survivor_worker_ids) == distributed_worker_count - 1
    invariant len(survivor_worker_pids) == len(survivor_worker_ids)
    invariant len(survivor_worker_exitcodes) == len(survivor_worker_ids)
    invariant survivor_worker_exitcodes[0] == 0
    invariant distributed_partition_batch >= distributed_worker_count
    invariant distributed_total_steps > partial_checkpoint_step
    invariant killed_worker_pid > 0 and recovery_worker_pid > 0
    invariant killed_worker_pid != recovery_worker_pid
    invariant killed_worker_exitcode < 0 and recovery_worker_exitcode == 0
    invariant killed_worker_signal == "SIGTERM"
    invariant recovery_resumed_step == stable_checkpoint_step
    invariant partial_checkpoint_step > stable_checkpoint_step
    invariant partial_checkpoint_bytes > 0 and partial_checkpoint_bytes < partial_checkpoint_intended_bytes
    invariant rejected_checkpoint_count == len(rejected_checkpoint_error_codes)
    invariant len(checkpoint_manifest_sha256) == 64
    invariant distributed_residual_micromolar >= 0.0
    invariant same_node_distributed_process_pass == (checkpoint_pass and worker_loss_failure_validated)
    invariant distributed_validated == (same_node_distributed_process_pass and cross_node_distributed_validated)
    invariant not cross_node_distributed_validated
    invariant device_loss_evidence_kind == "adapter_injected_mps_dispatch_loss" or device_loss_evidence_kind == "unavailable_mps_not_injected"
    invariant device_loss_recovery_residual_micromolar >= 0.0
    invariant not physical_device_loss_observed and not physical_device_loss_validated
    invariant local_technical_pass == (single_node_portability_pass and cpu_zero_copy and same_node_distributed_process_pass and checkpoint_pass and worker_loss_failure_validated and device_loss_injection_observed and device_loss_recovery_pass)
    invariant phase9_admitted == (local_technical_pass and direct_parity_pass and cross_node_distributed_validated and physical_device_loss_validated and sema_bridge_zero_copy_validated)
    invariant phase9_validated == phase9_admitted and portable_core_validated == phase9_admitted
    invariant not scientific_validated
    invariant evidence_class == "local_technical_evidence" or evidence_class == "implemented_unvalidated"
    invariant len(direct_oracle_result_sha256) == 64
    invariant len(direct_oracle_artifact_sha256) == 64
    invariant len(direct_oracle_path) > 0 and direct_residual >= 0.0
    invariant len(result_sha256) == 64 and len(result_path) > 0


pub bridge python.inline portable_backend from "foreign/python/portable_backend.py":
    deps "python>=3.12,<3.13", "numpy==2.4.1", "torch==2.13.0"
    expose:
        def run_profile(config_path: str, oracle_path: str, output_path: str) -> PortabilityResult !{ffi.call}:
            sem "Measure digest-bound bulk ABI, equal-tolerance CPU/MPS, and bounded process/checkpoint recovery evidence"
```

### `src/profiles.sema`

```sema
"""Honest contracts for QM/MM, mesoscopic, cellular, and performance phases."""

from biological_computer.domain import PhaseEvidence, PhaseState

assure silver


pub struct QmMmPartition:
    id: str
    qm_atom_indices: list[int]
    mm_atom_indices: list[int]
    boundary_atom_indices: list[int]
    total_charge_e: int
    spin_multiplicity: int
    embedding: str
    backend_profile_id: str
    invariant len(id) > 0
    invariant len(qm_atom_indices) > 0 and len(qm_atom_indices) <= 10000
    invariant len(mm_atom_indices) > 0 and len(mm_atom_indices) <= 10000000
    invariant len(boundary_atom_indices) <= 1024
    invariant spin_multiplicity > 0
    invariant len(embedding) > 0
    invariant len(backend_profile_id) > 0


pub struct ParameterizationEdge:
    id: str
    source_model_id: str
    target_model_id: str
    parameter_names: list[str]
    values: list[f64]
    uncertainties: list[f64]
    units: list[str]
    evidence_ids: list[str]
    invariant len(id) > 0
    invariant len(source_model_id) > 0
    invariant len(target_model_id) > 0
    invariant len(parameter_names) > 0 and len(parameter_names) <= 1024
    invariant len(parameter_names) == len(values)
    invariant len(values) == len(uncertainties)
    invariant len(uncertainties) == len(units)
    invariant len(evidence_ids) <= 128


pub struct PlatformBenchmark:
    profile_id: str
    hardware: str
    operating_system: str
    backend: str
    precision: str
    model_digest: str
    tolerance_profile: str
    simulated_ns_per_day: f64
    p50_step_ms: f64
    p95_step_ms: f64
    resident_memory_bytes: int
    transfer_bytes: int
    observable_error: f64
    evidence_ids: list[str]
    invariant len(profile_id) > 0
    invariant len(hardware) > 0
    invariant len(operating_system) > 0
    invariant len(backend) > 0
    invariant len(precision) > 0
    invariant len(model_digest) == 64
    invariant len(tolerance_profile) > 0
    invariant simulated_ns_per_day >= 0.0
    invariant p50_step_ms >= 0.0
    invariant p95_step_ms >= p50_step_ms
    invariant resident_memory_bytes >= 0
    invariant transfer_bytes >= 0
    invariant observable_error >= 0.0
    invariant len(evidence_ids) <= 128



pub enum NativeKernelKind:
    sema_aot | rust_native | c_abi | cpp_abi | ecosystem_bridge


pub enum AcceleratorKind:
    cpu | apple_metal | apple_mps | mlx | cuda | hip | webgl2 | webgpu


pub struct KernelDemand:
    operation: str
    precision: str
    tolerance_profile: str
    minimum_throughput_per_s: f64
    maximum_p95_ms: f64
    maximum_observable_error: f64
    maximum_resident_memory_bytes: int
    invariant len(operation) > 0
    invariant len(precision) > 0
    invariant len(tolerance_profile) > 0
    invariant minimum_throughput_per_s >= 0.0
    invariant maximum_p95_ms >= 0.0
    invariant maximum_observable_error >= 0.0
    invariant maximum_resident_memory_bytes >= 0


pub struct NativeAccelerationProfile:
    profile_id: str
    kernel_id: str
    native_kind: NativeKernelKind
    accelerator: AcceleratorKind
    device_name: str
    precision: str
    tolerance_profile: str
    available: bool
    qualified: bool
    zero_copy: bool
    unified_memory: bool
    supported_operations: list[str]
    measured_throughput_per_s: f64
    measured_p95_ms: f64
    observable_error: f64
    resident_memory_bytes: int
    host_device_transfer_bytes: int
    artifact_sha256: str
    model_sha256: str
    oracle_evidence_ids: list[str]
    benchmark_evidence_ids: list[str]
    invariant len(profile_id) > 0
    invariant len(kernel_id) > 0
    invariant len(device_name) > 0
    invariant len(precision) > 0
    invariant len(tolerance_profile) > 0
    invariant len(supported_operations) > 0 and len(supported_operations) <= 64
    invariant measured_throughput_per_s >= 0.0
    invariant measured_p95_ms >= 0.0
    invariant observable_error >= 0.0
    invariant resident_memory_bytes >= 0
    invariant host_device_transfer_bytes >= 0
    invariant len(artifact_sha256) == 64
    invariant len(model_sha256) == 64
    invariant len(oracle_evidence_ids) <= 128
    invariant len(benchmark_evidence_ids) <= 128


pub struct AccelerationDecision:
    selected: bool
    profile_id: str
    native_kind: NativeKernelKind
    accelerator: AcceleratorKind
    zero_copy: bool
    reason: str
    invariant len(reason) > 0


def operation_supported(operation: str, supported_operations: list[str]):
    for supported in supported_operations:
        if supported == operation:
            return true
    return false


def acceleration_priority(accelerator: AcceleratorKind):
    if accelerator == AcceleratorKind.cuda:
        return 100
    if accelerator == AcceleratorKind.mlx:
        return 95
    if accelerator == AcceleratorKind.apple_mps:
        return 90
    if accelerator == AcceleratorKind.apple_metal:
        return 85
    if accelerator == AcceleratorKind.hip:
        return 80
    if accelerator == AcceleratorKind.webgpu:
        return 75
    if accelerator == AcceleratorKind.webgl2:
        return 70
    return 50


def acceleration_profile_eligible(profile: NativeAccelerationProfile, demand: KernelDemand):
    if not profile.available or not profile.qualified:
        return false
    if len(profile.oracle_evidence_ids) == 0 or len(profile.benchmark_evidence_ids) == 0:
        return false
    if profile.precision != demand.precision or profile.tolerance_profile != demand.tolerance_profile:
        return false
    if not operation_supported(demand.operation, profile.supported_operations):
        return false
    if profile.measured_throughput_per_s < demand.minimum_throughput_per_s:
        return false
    if profile.measured_p95_ms > demand.maximum_p95_ms:
        return false
    if profile.observable_error > demand.maximum_observable_error:
        return false
    return profile.resident_memory_bytes <= demand.maximum_resident_memory_bytes


pub def select_native_acceleration(demand: KernelDemand, profiles: list[NativeAccelerationProfile]) -> AccelerationDecision !{}:
    mut best_p95_ms = 0.0
    mut best_throughput_per_s = 0.0
    mut best_transfer_bytes = 0
    mut best_priority = -1
    mut decision = AccelerationDecision(selected=false, profile_id="", native_kind=NativeKernelKind.sema_aot, accelerator=AcceleratorKind.cpu, zero_copy=false, reason="no measured and oracle-qualified native profile satisfies the kernel demand")
    for profile in profiles:
        if not acceleration_profile_eligible(profile, demand):
            continue
        priority = acceleration_priority(profile.accelerator)
        mut better = not decision.selected
        if decision.selected and profile.measured_p95_ms < best_p95_ms:
            better = true
        if decision.selected and profile.measured_p95_ms == best_p95_ms and profile.measured_throughput_per_s > best_throughput_per_s:
            better = true
        if decision.selected and profile.measured_p95_ms == best_p95_ms and profile.measured_throughput_per_s == best_throughput_per_s and profile.host_device_transfer_bytes < best_transfer_bytes:
            better = true
        if decision.selected and profile.measured_p95_ms == best_p95_ms and profile.measured_throughput_per_s == best_throughput_per_s and profile.host_device_transfer_bytes == best_transfer_bytes and profile.zero_copy and not decision.zero_copy:
            better = true
        if decision.selected and profile.measured_p95_ms == best_p95_ms and profile.measured_throughput_per_s == best_throughput_per_s and profile.host_device_transfer_bytes == best_transfer_bytes and profile.zero_copy == decision.zero_copy and priority > best_priority:
            better = true
        if better:
            best_p95_ms = profile.measured_p95_ms
            best_throughput_per_s = profile.measured_throughput_per_s
            best_transfer_bytes = profile.host_device_transfer_bytes
            best_priority = priority
            decision = AccelerationDecision(selected=true, profile_id=profile.profile_id, native_kind=profile.native_kind, accelerator=profile.accelerator, zero_copy=profile.zero_copy, reason="selected by measured p95 latency, throughput, transfer cost, zero-copy, then accelerator tie-break")
    return decision

def indices_unique(values: list[int]):
    mut left = 0
    for value in values:
        mut right = 0
        for other in values:
            if left != right and value == other:
                return false
            right = right + 1
        left = left + 1
    return true


def lists_disjoint(left_values: list[int], right_values: list[int]):
    for left in left_values:
        for right in right_values:
            if left == right:
                return false
    return true


pub def qmmm_partition_valid(partition: QmMmPartition, atom_count: int) -> bool !{}:
    require atom_count > 0
    if not indices_unique(partition.qm_atom_indices) or not indices_unique(partition.mm_atom_indices):
        return false
    if not lists_disjoint(partition.qm_atom_indices, partition.mm_atom_indices):
        return false
    for index in partition.qm_atom_indices:
        if index < 0 or index >= atom_count:
            return false
    for index in partition.mm_atom_indices:
        if index < 0 or index >= atom_count:
            return false
    return len(partition.qm_atom_indices) + len(partition.mm_atom_indices) == atom_count


pub def parameterization_valid(edge: ParameterizationEdge) -> bool !{}:
    if len(edge.evidence_ids) == 0:
        return false
    for uncertainty in edge.uncertainties:
        if uncertainty < 0.0:
            return false
    for unit in edge.units:
        if len(unit) == 0:
            return false
    return true


pub def benchmark_comparable(reference: PlatformBenchmark, candidate: PlatformBenchmark) -> bool !{}:
    return reference.model_digest == candidate.model_digest and reference.tolerance_profile == candidate.tolerance_profile and reference.backend == candidate.backend


def unavailable_phase(phase: int, profile_id: str, backend: str):
    require len(backend) > 0
    return PhaseEvidence(phase=phase, state=PhaseState.blocked, profile_id=profile_id, positive_evidence=[], negative_evidence=[], blockers=[backend + " backend has not been qualified"])
```

### `src/programming.sema`

```sema
"""Typed, transactional biological programming plans for viewers and agents."""

from biological_computer.design import compile_design_command, design_capabilities, design_spec_valid
from biological_computer.physiology import initial_physiology_parameters, physiology_parameter_bounds, physiology_parameter_value_valid

assure silver


def initial_signal_values():
    return {
        "glucose": 5.5,
        "oxygen": 8.0,
        "cytokine": 0.0,
        "morphology": 1.0,
        "amplitude": 1.0,
        "attraction": 0.0,
        "molecular_temperature": 1.0,
        "bond_stiffness": 1.0,
        "meal_intensity": 0.0,
        "exercise_intensity": 0.0,
        "exogenous_insulin_micro_u_ml_day": 0.0,
        "immune_shielding": 0.0,
        "graft_target_mg": 0.0,
        "physiology_seconds_per_real_second": 300.0,
    }


pub def initial_program_state() -> dict[str, any] !{}:
    return {
        "schema": "sema.biological-program-state/v2",
        "state_version": 0,
        "signals": initial_signal_values(),
        "parameters": initial_physiology_parameters(),
        "last_summary": [],
    }


def normalized_signal(name: str):
    if name == "thermal" or name == "thermal motion" or name == "temperature":
        return "molecular_temperature"
    if name == "bond stiffness" or name == "bonds":
        return "bond_stiffness"
    return name


pub def signal_bounds() -> dict[str, list[f64]] !{}:
    return {
        "glucose": [2.5, 25.0],
        "oxygen": [1.0, 30.0],
        "cytokine": [0.0, 2.0],
        "morphology": [0.2, 3.0],
        "amplitude": [0.2, 3.0],
        "attraction": [0.0, 2.0],
        "molecular_temperature": [0.0, 4.0],
        "bond_stiffness": [0.0, 4.0],
        "meal_intensity": [0.0, 4.0],
        "exercise_intensity": [0.0, 2.0],
        "exogenous_insulin_micro_u_ml_day": [0.0, 5000.0],
        "immune_shielding": [0.0, 1.0],
        "graft_target_mg": [0.0, 500.0],
        "physiology_seconds_per_real_second": [1.0, 86400.0],
    }


def signal_value_valid(name: str, value: f64):
    bounds = signal_bounds()
    if not bounds.has(name):
        return false
    return value >= bounds[name][0] and value <= bounds[name][1]


def signal_operation(name: str, value: f64):
    return {"kind": "set_signal", "name": normalized_signal(name), "value": value}


def design_command_result(text: str):
    compiled = compile_design_command(text)
    if not compiled["ok"]:
        return compiled
    return {"ok": true, "operations": [{"kind": "design_species", "design": compiled}]}


def design_command_valid(design: any) !{}:
    if not (design is dict) or not all(design.has(field) for field in ["ok", "kind", "name"]):
        return false
    if not design["ok"]:
        return false
    if design["kind"] == "design":
        return design.has("spec") and design_spec_valid(design["spec"])
    return design["kind"] == "set_mechanism" and design.has("mechanism")


pub def compile_biological_command(command: str) -> dict[str, any] !{}:
    if len(command) == 0 or len(command) > 320:
        return {"ok": false, "error": "ProgramCompileError", "detail": "command must contain 1..320 characters"}
    plain_command = command.lower().strip()
    mut text = plain_command
    if text == "reset" or text == "reset simulation" or text == "restore baseline":
        return {"ok": true, "operations": [{"kind": "reset_program"}]}
    if text == "inhibit cytokine release":
        return {"ok": true, "operations": [{"kind": "set_parameter", "name": "cytokine_release_per_day", "value": 0.8}]}
    if text == "stiffen bonds":
        return {"ok": true, "operations": [signal_operation("bond_stiffness", 1.5)]}
    if text == "increase thermal motion":
        return {"ok": true, "operations": [signal_operation("molecular_temperature", 1.5)]}
    if text == "make cell wider":
        return {"ok": true, "operations": [signal_operation("morphology", 1.25)]}
    if text == "increase receptor attraction":
        return {"ok": true, "operations": [signal_operation("attraction", 1.3)]}
    if text == "simulate meal":
        return {"ok": true, "operations": [signal_operation("meal_intensity", 1.0), signal_operation("glucose", 8.0)]}
    if text == "simulate exercise":
        return {"ok": true, "operations": [signal_operation("exercise_intensity", 1.0), signal_operation("glucose", 5.5)]}
    if text == "simulate autoimmune attack":
        return {"ok": true, "operations": [signal_operation("cytokine", 1.2)]}
    if text == "transplant beta cells":
        return {"ok": true, "operations": [signal_operation("graft_target_mg", 120.0)]}
    if text == "shield transplanted cells":
        return {"ok": true, "operations": [signal_operation("immune_shielding", 0.9)]}
    if text == "dose insulin":
        return {"ok": true, "operations": [signal_operation("exogenous_insulin_micro_u_ml_day", 600.0)]}
    if text.startswith("set "):
        text = text.slice(4, text.len())
    if text.startswith("increase "):
        text = text.slice(9, text.len())
    if text.startswith("decrease "):
        text = text.slice(9, text.len())
    # No rule of the bounded grammar below begins with these two prefixes, so routing them here is
    # observationally the same as falling through the match, and keeps the delegation out of a case arm.
    if plain_command.startswith("design ") or plain_command.startswith("set mechanism of "):
        return design_command_result(plain_command)
    match text:
        # Match the two-signal glucose/oxygen phrase shown in the programming console.
        case re"^glucose to (?P<glucose>-?[0-9]+(\.[0-9]+)?) and oxygen to (?P<oxygen>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("glucose", float(glucose)), signal_operation("oxygen", float(oxygen))]}
        # Match a glucose setting followed by one finite signed decimal.
        case re"^glucose to (?P<value>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("glucose", float(value))]}
        # Match an oxygen setting followed by one finite signed decimal.
        case re"^oxygen to (?P<value>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("oxygen", float(value))]}
        # Match a cytokine setting followed by one finite signed decimal.
        case re"^cytokine to (?P<value>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("cytokine", float(value))]}
        # Match a morphology setting followed by one finite signed decimal.
        case re"^morphology to (?P<value>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("morphology", float(value))]}
        # Match an amplitude setting followed by one finite signed decimal.
        case re"^amplitude to (?P<value>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("amplitude", float(value))]}
        # Match an attraction setting followed by one finite signed decimal.
        case re"^attraction to (?P<value>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("attraction", float(value))]}
        # Match a thermal-motion setting followed by one finite signed decimal.
        case re"^thermal motion to (?P<value>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("molecular_temperature", float(value))]}
        # Match a temperature setting followed by one finite signed decimal.
        case re"^temperature to (?P<value>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("molecular_temperature", float(value))]}
        # Match a bond-stiffness setting followed by one finite signed decimal.
        case re"^bond stiffness to (?P<value>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [signal_operation("bond_stiffness", float(value))]}
        # Match a topology removal command with two bounded integer atom indexes.
        case re"^remove bond (?P<left:int>[0-9]+) (?P<right:int>[0-9]+)$":
            return {"ok": true, "operations": [{"kind": "remove_bond", "left": left, "right": right}]}
        # Match a topology addition command with two bounded integer atom indexes.
        case re"^add bond (?P<left:int>[0-9]+) (?P<right:int>[0-9]+)$":
            return {"ok": true, "operations": [{"kind": "add_bond", "left": left, "right": right}]}
        # Match a move command and parse its three signed decimal offsets.
        case re"^move atom (?P<atom_index:int>[0-9]+) by (?P<dx>-?[0-9]+(\.[0-9]+)?) (?P<dy>-?[0-9]+(\.[0-9]+)?) (?P<dz>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [{"kind": "translate_atom", "atom_index": atom_index, "delta_angstrom": [float(dx), float(dy), float(dz)]}]}
        # Match a translate command and parse its three signed decimal offsets.
        case re"^translate atom (?P<atom_index:int>[0-9]+) by (?P<dx>-?[0-9]+(\.[0-9]+)?) (?P<dy>-?[0-9]+(\.[0-9]+)?) (?P<dz>-?[0-9]+(\.[0-9]+)?)$":
            return {"ok": true, "operations": [{"kind": "translate_atom", "atom_index": atom_index, "delta_angstrom": [float(dx), float(dy), float(dz)]}]}
        case _:
            return {"ok": false, "error": "ProgramCompileError", "detail": "command does not match the bounded biological programming grammar"}


def program_operation_valid(operation: dict[str, any]) !{}:
    if not operation.has("kind"):
        return false
    if operation["kind"] == "reset_program":
        return true
    if operation["kind"] == "set_signal":
        if not operation.has("name") or not operation.has("value"):
            return false
        name = normalized_signal(operation["name"])
        return signal_value_valid(name, operation["value"])
    if operation["kind"] == "set_parameter":
        if not operation.has("name") or not operation.has("value"):
            return false
        return physiology_parameter_value_valid(operation["name"], operation["value"])
    if operation["kind"] == "remove_bond" or operation["kind"] == "add_bond":
        return operation.has("left") and operation.has("right")
    if operation["kind"] == "design_species":
        return operation.has("design") and design_command_valid(operation["design"])
    if operation["kind"] == "translate_atom":
        return operation.has("atom_index") and operation.has("delta_angstrom")
    return false


pub def apply_biological_program(state: dict[str, any], payload: dict[str, any]) -> dict[str, any] !{}:
    if not payload.has("program_state_version") or not payload.has("operations"):
        return {"ok": false, "error": "ProgramInvalid", "detail": "program_state_version and operations are required"}
    if payload["program_state_version"] != state["state_version"]:
        return {"ok": false, "error": "ProgramStateConflict", "detail": "program state version does not match"}
    operations = payload["operations"]
    if len(operations) == 0 or len(operations) > 16:
        return {"ok": false, "error": "ProgramInvalid", "detail": "operations must contain 1..16 bounded instructions"}
    if len(operations) > 1 and any(operation.has("kind") and operation["kind"] == "reset_program" for operation in operations):
        return {"ok": false, "error": "ProgramInvalid", "detail": "reset_program must be the only instruction"}
    mut next_signals = {name: value for name, value in state["signals"].items()}
    mut next_parameters = {name: value for name, value in state["parameters"].items()}
    mut molecular_operations: list[dict[str, any]] = []
    mut design_operations: list[dict[str, any]] = []
    mut summary: list[str] = []
    for operation in operations:
        if not program_operation_valid(operation):
            return {"ok": false, "error": "ProgramInvalid", "detail": "an instruction is unsupported or malformed"}
        if operation["kind"] == "reset_program":
            next_signals = initial_signal_values()
            next_parameters = initial_physiology_parameters()
            summary.append("source_baseline_restored")
            continue
        if operation["kind"] == "set_signal":
            name = normalized_signal(operation["name"])
            value = operation["value"]
            if not signal_value_valid(name, value):
                return {"ok": false, "error": "ProgramInvalid", "detail": "a signal setting is outside its declared biological bound"}
            next_signals[name] = value
            summary.append(name + "=" + str(value))
            if name == "molecular_temperature":
                molecular_operations.append({"kind": "set_thermal_scale", "value": value})
            if name == "bond_stiffness":
                molecular_operations.append({"kind": "set_bond_stiffness", "value": value})
        elif operation["kind"] == "set_parameter":
            name = operation["name"]
            value = operation["value"]
            if not physiology_parameter_value_valid(name, value):
                return {"ok": false, "error": "ProgramInvalid", "detail": "an equation parameter is outside its declared bound"}
            next_parameters[name] = value
            summary.append(name + "=" + str(value))
        elif operation["kind"] == "design_species":
            design_operations.append(operation["design"])
            summary.append("design_species=" + operation["design"]["name"])
        else:
            molecular_operations.append(operation)
            summary.append(operation["kind"])
    next_state = {
        "schema": state["schema"],
        "state_version": state["state_version"] + 1,
        "signals": next_signals,
        "parameters": next_parameters,
        "last_summary": summary,
    }
    return {"ok": true, "state": next_state, "molecular_operations": molecular_operations, "design_operations": design_operations, "summary": summary, "reset_molecular": operations[0]["kind"] == "reset_program"}


pub def programming_capabilities() -> dict[str, any] !{}:
    return {
        "schema": "sema.biological-programming-capabilities/v1",
        "backend": "Sema",
        "max_operations": 16,
        "max_command_chars": 320,
        "operations": ["set_signal", "set_parameter", "translate_atom", "add_bond", "remove_bond", "reset_program", "design_species"],
        "signals": signal_bounds(),
        "parameters": physiology_parameter_bounds(),
        "examples": [
            "increase glucose to 8 and oxygen to 12",
            "inhibit cytokine release",
            "stiffen bonds",
            "translate atom 12 by 0.5 0 0",
            "remove bond 12 13",
            "design peptide ACDEFG as probe-1 targeting insulin",
            "design helix EALKAEALKA as shield-1 targeting interleukin_1_beta",
            "design molecule sulfonylurea+benzene as agonist-1 targeting insulin",
            "set mechanism of probe-1 to secretion_agonist",
        ],
        "design_commands": design_capabilities()["commands"],
    }


test "program reset restores the Sema baseline and rejects mixed instructions":
    state = initial_program_state()
    changed = apply_biological_program(state, {
        "program_state_version": 0,
        "operations": [signal_operation("glucose", 8.0)],
    })
    ensure changed["ok"]
    reset = apply_biological_program(changed["state"], {
        "program_state_version": 1,
        "operations": [{"kind": "reset_program"}],
    })
    ensure reset["ok"]
    ensure reset["reset_molecular"]
    ensure reset["state"]["signals"]["glucose"] == 5.5
    ensure reset["state"]["signals"]["bond_stiffness"] == 1.0
    mixed = apply_biological_program(reset["state"], {
        "program_state_version": 2,
        "operations": [{"kind": "reset_program"}, signal_operation("cytokine", 0.5)],
    })
    ensure not mixed["ok"]
```

### `src/qmmm_multicode.sema`

```sema
"""Pinned 6S34 insulin fixed-partition QM/MM evidence with honest second-code gating."""

assure silver


struct QmmmMulticodeResult:
    schema: str
    profile_id: str
    config_sha256: str
    backend_source_path: str
    backend_source_sha256: str
    sema_contract_source_path: str
    sema_contract_source_sha256: str
    oracle_source_path: str
    oracle_source_sha256: str
    structure_path: str
    structure_sha256: str
    pdb_id: str
    partition_id: str
    partition_identity_sha256: str
    qm_atom_ids: list[str]
    boundary_identities: Any
    link_atom_ids: list[str]
    embedding_site_identities: Any
    embedding_model: str
    embedding_total_charge_e: f64
    qm_charge_e: int
    spin_multiplicity: int
    source_reaction_coordinate_angstrom: f64
    reaction_coordinates_angstrom: list[f64]
    primary_backend: str
    primary_version: str
    primary_method: str
    primary_basis: str
    primary_status: str
    primary_executed: bool
    primary_energies_hartree: list[f64]
    primary_forces_hartree_per_angstrom: list[f64]
    primary_mulliken_charges_e: Any
    primary_scf_iterations: list[int]
    primary_converged: bool
    primary_charge_sum_residual_e: f64
    secondary_backend: str
    secondary_requested_version: str
    secondary_observed_version: str
    secondary_status: str
    secondary_failure_code: str
    secondary_unavailable_reason: str
    secondary_executed: bool
    secondary_energies_hartree: list[f64]
    secondary_forces_hartree_per_angstrom: list[f64]
    secondary_atomic_charges_e: Any
    secondary_converged: bool
    partition_identity_pass: bool
    primary_technical_pass: bool
    multicode_energy_parity_pass: bool
    multicode_force_parity_pass: bool
    multicode_charge_parity_pass: bool
    multicode_reaction_coordinate_parity_pass: bool
    multicode_technical_pass: bool
    insulin_partition_validated: bool
    phase7_validated: bool
    multicode_residuals_available: bool
    maximum_energy_residual_hartree: f64
    maximum_force_residual_hartree_per_angstrom: f64
    maximum_atomic_charge_residual_e: f64
    scientific_validated: bool
    evidence_class: str
    platform: str
    result_sha256: str
    direct_oracle_result_sha256: str
    direct_oracle_path: str
    direct_residual: f64
    direct_parity_pass: bool
    result_path: str
    invariant schema == "sema.qmmm-multicode-result/v2"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(backend_source_sha256) == 64
    invariant len(sema_contract_source_sha256) == 64
    invariant len(oracle_source_sha256) == 64
    invariant len(structure_sha256) == 64
    invariant pdb_id == "6S34"
    invariant len(partition_identity_sha256) == 64
    invariant len(qm_atom_ids) == 2
    invariant len(boundary_identities) == 2
    invariant len(link_atom_ids) == 2
    invariant len(embedding_site_identities) > 0
    invariant qm_charge_e == 0
    invariant spin_multiplicity == 1
    invariant source_reaction_coordinate_angstrom > 0.0
    invariant len(reaction_coordinates_angstrom) > 0 and len(reaction_coordinates_angstrom) <= 5
    invariant primary_backend == "PySCF"
    invariant primary_version == "2.11.0"
    invariant primary_status == "real_measured" or primary_status == "execution_failed"
    invariant len(primary_energies_hartree) == len(reaction_coordinates_angstrom)
    invariant len(primary_forces_hartree_per_angstrom) == len(reaction_coordinates_angstrom)
    invariant len(primary_mulliken_charges_e) == len(reaction_coordinates_angstrom)
    invariant primary_charge_sum_residual_e >= 0.0
    invariant secondary_backend == "Psi4"
    invariant secondary_status == "real_measured" or secondary_status == "unavailable" or secondary_status == "version_mismatch" or secondary_status == "execution_failed"
    invariant not multicode_technical_pass or (secondary_executed and secondary_converged)
    invariant not multicode_technical_pass or (multicode_energy_parity_pass and multicode_force_parity_pass and multicode_charge_parity_pass and multicode_reaction_coordinate_parity_pass)
    invariant multicode_residuals_available == multicode_reaction_coordinate_parity_pass
    invariant multicode_residuals_available or maximum_energy_residual_hartree == -1.0
    invariant multicode_residuals_available or maximum_force_residual_hartree_per_angstrom == -1.0
    invariant multicode_residuals_available or maximum_atomic_charge_residual_e == -1.0
    invariant not multicode_residuals_available or maximum_energy_residual_hartree >= 0.0
    invariant not multicode_residuals_available or maximum_force_residual_hartree_per_angstrom >= 0.0
    invariant not multicode_residuals_available or maximum_atomic_charge_residual_e >= 0.0
    invariant phase7_validated == (multicode_technical_pass and direct_parity_pass)
    invariant not scientific_validated
    invariant len(result_sha256) == 64
    invariant len(direct_oracle_result_sha256) == 64
    invariant len(direct_oracle_path) > 0
    invariant direct_residual >= 0.0
    invariant len(result_path) > 0


bridge python.inline qmmm_multicode_backend from "foreign/python/qmmm_multicode_backend.py":
    deps "python>=3.12,<3.13", "numpy==2.4.1", "pyscf==2.11.0"
    expose:
        def run_profile(config_path: str, oracle_path: str, output_path: str) -> QmmmMulticodeResult !{ffi.call}:
            sem "Run pinned 6S34 insulin fixed-partition QM/MM and require a real independent second code before the Phase 7 multicode gate can pass"


pub def run_profile(
    config_path: str,
    oracle_path: str,
    output_path: str,
) -> QmmmMulticodeResult !{ffi.call, fs.read, fs.write}:
    return qmmm_multicode_backend.run_profile(config_path, oracle_path, output_path)
```

### `src/qmmm.sema`

```sema
"""Fixed-partition electrostatic-embedding QM/MM technical evidence."""

assure silver


pub struct QmmmResult:
    schema: str
    profile_id: str
    config_sha256: str
    backend: str
    backend_version: str
    method: str
    basis: str
    embedding: str
    qm_atoms: int
    mm_point_charges: int
    charge_e: int
    spin_2s: int
    link_atoms: int
    boundary_treatment: str
    reaction_coordinate: str
    coordinate_angstrom: list[f64]
    energies_hartree: list[f64]
    forces_hartree_per_bohr: list[f64]
    reaction_span_kj_mol: f64
    energy_symmetry_residual_hartree: f64
    force_antisymmetry_residual_hartree_per_bohr: f64
    center_force_hartree_per_bohr: f64
    gradient_residual_hartree_per_bohr: f64
    symmetry_pass: bool
    gradient_pass: bool
    technical_pass: bool
    evidence_class: str
    adaptive_partition: bool
    multicode_validated: bool
    result_sha256: str
    direct_oracle_result_sha256: str
    direct_oracle_path: str
    direct_energy_residual_hartree: f64
    direct_force_residual_hartree_per_bohr: f64
    direct_gradient_residual_hartree_per_bohr: f64
    direct_parity_pass: bool
    result_path: str
    invariant schema == "sema.qmmm-result/v1"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(backend) > 0 and len(backend_version) > 0
    invariant len(method) > 0 and len(basis) > 0
    invariant len(embedding) > 0
    invariant qm_atoms > 0
    invariant mm_point_charges > 0
    invariant spin_2s >= 0
    invariant link_atoms >= 0
    invariant len(boundary_treatment) > 0
    invariant len(reaction_coordinate) > 0
    invariant len(coordinate_angstrom) > 2
    invariant len(coordinate_angstrom) == len(energies_hartree)
    invariant len(coordinate_angstrom) == len(forces_hartree_per_bohr)
    invariant reaction_span_kj_mol >= 0.0
    invariant energy_symmetry_residual_hartree >= 0.0
    invariant force_antisymmetry_residual_hartree_per_bohr >= 0.0
    invariant center_force_hartree_per_bohr >= 0.0
    invariant gradient_residual_hartree_per_bohr >= 0.0
    invariant len(result_sha256) == 64
    invariant len(direct_oracle_result_sha256) == 64
    invariant len(direct_oracle_path) > 0
    invariant direct_energy_residual_hartree >= 0.0
    invariant direct_force_residual_hartree_per_bohr >= 0.0
    invariant direct_gradient_residual_hartree_per_bohr >= 0.0
    invariant len(result_path) > 0
    invariant evidence_class == "validated_fixed_partition_technical" or evidence_class ==    "failed_fixed_partition_technical"


pub bridge python.inline qmmm_backend from "foreign/python/qmmm_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def run_profile(config_path: str, oracle_path: str, output_path: str) -> QmmmResult !{ffi.call}:
            sem "Run a fixed quantum partition with electrostatic embedding and direct energy-force parity"
```

### `src/rare_event.sema`

```sema
"""Bounded well-tempered metadynamics with an exact symmetry reference."""

assure silver


pub struct RareEventResult:
    schema: str
    benchmark_id: str
    method: str
    method_reference_doi: str
    engine: str
    engine_version: str
    platform: str
    config_sha256: str
    system_sha256: str
    result_sha256: str
    result_path: str
    replay_class: str
    reference_replay_class: str
    evidence_class: str
    replicas: int
    grid_min_nm: f64
    grid_max_nm: f64
    grid_width: int
    free_energy_mean_kj_mol: list[f64]
    free_energy_sem_kj_mol: list[f64]
    left_population_mean: f64
    left_population_sem: f64
    free_energy_difference_mean_kj_mol: f64
    free_energy_difference_sem_kj_mol: f64
    min_transitions: int
    reference_left_population: f64
    reference_free_energy_difference_kj_mol: f64
    converged: bool
    invariant schema == "sema.rare-event-result/v1"
    invariant len(benchmark_id) > 0
    invariant engine == "OpenMM"
    invariant len(engine_version) > 0
    invariant platform == "CPU"
    invariant len(config_sha256) == 64
    invariant len(system_sha256) == 64
    invariant len(result_sha256) == 64
    invariant len(result_path) > 0
    invariant replay_class == "statistical"
    invariant reference_replay_class == "exact"
    invariant evidence_class == "validated_technical" or evidence_class == "exploratory"
    invariant replicas >= 2 and replicas <= 8
    invariant grid_min_nm < grid_max_nm
    invariant grid_width > 2 and grid_width <= 1024
    invariant len(free_energy_mean_kj_mol) == grid_width
    invariant len(free_energy_sem_kj_mol) == grid_width
    invariant left_population_mean >= 0.0 and left_population_mean <= 1.0
    invariant left_population_sem >= 0.0
    invariant min_transitions >= 0
    invariant reference_left_population == 0.5
    invariant reference_free_energy_difference_kj_mol == 0.0


pub bridge python.inline rare_event_backend from "foreign/python/rare_event_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def run_metadynamics(config_path: str, output_path: str) -> RareEventResult !{ffi.call}:
            sem "Validate well-tempered metadynamics against an exact symmetric population reference"
```

### `src/readdy_calibration.sema`

```sema
"""Preregistered ReaDDy calibration qualification with held-out, fail-closed evidence."""

assure silver


pub struct ReaddyCalibrationResult:
    schema: str
    profile_id: str
    config_sha256: str
    execution_config_sha256: str
    evidence_sha256: str
    evidence_rebound_without_execution: bool
    result_sha256: str
    source_digests: dict[str, str]
    package_manifest: dict[str, any]
    unit_mapping: dict[str, any]
    target: dict[str, f64]
    training_design: dict[str, any]
    calibration_lock: dict[str, any]
    heldout_design: dict[str, any]
    heldout_evidence_admission: dict[str, any]
    heldout_rates: dict[str, any]
    condition_summaries: list[dict[str, any]]
    statistics: dict[str, any]
    gates: dict[str, bool]
    qualification_pass: bool
    calibration_evidence_status: str
    failure_type: str
    blockers: list[str]
    phase8_scientific_validation: bool
    scientific_validated: bool
    scientific_validation_scope: str
    training_evidence_manifest: list[dict[str, str]]
    heldout_evidence_manifest: list[dict[str, str]]
    runtime_seconds: f64
    invariant schema == "sema.readdy-calibration-result/v1"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(execution_config_sha256) == 64
    invariant len(evidence_sha256) == 64
    invariant len(result_sha256) == 64
    invariant len(source_digests["phase8_profile_sha256"]) == 64
    invariant len(source_digests["molecular_result_sha256"]) == 64
    invariant calibration_lock["heldout_inspected_before_lock"] == false
    invariant heldout_design["disjoint_from_training"] == true
    invariant heldout_design["parameters_locked_before_execution"] == heldout_evidence_admission["chronology_proven"]
    invariant not qualification_pass or heldout_evidence_admission["chronology_proven"]
    invariant calibration_evidence_status == "qualified" or calibration_evidence_status == "failed" or calibration_evidence_status == "chronology_unproven"
    invariant heldout_evidence_admission["chronology_proven"] or calibration_evidence_status == "chronology_unproven"
    invariant heldout_evidence_admission["chronology_proven"] or failure_type == "ReaddyCalibrationChronologyUnproven"
    invariant phase8_scientific_validation == false
    invariant scientific_validated == false
    invariant qualification_pass or len(failure_type) > 0
    invariant qualification_pass or len(blockers) > 0
    invariant runtime_seconds >= 0.0


pub bridge python.inline readdy_calibration_backend from "foreign/python/readdy_calibration_backend.py":
    deps "python>=3.12,<3.13", "numpy==2.4.1", "readdy==2.0.14"
    expose:
        def run_profile(config_path: str, direct_path: str, output_path: str) -> ReaddyCalibrationResult !{ffi.call}:
            sem "Verify digest-bound direct evidence and emit byte-identical Sema qualification output without refitting or rerunning held-out conditions"
```

### `src/reference.sema`

```sema
"""Pinned condition-matched public molecular reference and published-timescale reproduction."""

assure silver


pub struct MolecularReferenceResult:
    schema: str
    reference_id: str
    config_sha256: str
    artifact_sha256: str
    target_config_sha256: str
    result_sha256: str
    result_path: str
    license: str
    primary_reference: str
    engine: str
    force_field: str
    water_model: str
    integrator: str
    temperature_k: f64
    observable: str
    replicas: int
    samples_per_replica: int
    clusters: int
    primary_lag_frames: int
    slow_timescale_ps: f64
    fast_timescale_ps: f64
    slow_timescale_sem_ps: f64
    fast_timescale_sem_ps: f64
    right_population_mean: f64
    right_population_sem: f64
    right_population_by_replica: list[f64]
    ensemble_transitions: int
    ensemble_rhat: f64
    ensemble_converged: bool
    effective_samples: f64
    lag_relative_spread_max: f64
    kmeans_iterations: int
    kmeans_final_shift: f64
    reproduced: bool
    condition_matched: bool
    evidence_class: str
    invariant schema == "sema.molecular-reference-result/v1"
    invariant len(reference_id) > 0
    invariant len(config_sha256) == 64
    invariant len(artifact_sha256) == 64
    invariant len(target_config_sha256) == 64
    invariant len(result_sha256) == 64
    invariant len(result_path) > 0
    invariant license == "CC-BY-4.0"
    invariant engine == "ACEMD"
    invariant force_field == "AMBER ff-99SB-ILDN"
    invariant water_model == "TIP3P"
    invariant integrator == "Langevin"
    invariant temperature_k == 300.0
    invariant replicas == 3
    invariant samples_per_replica == 250000
    invariant clusters == 40
    invariant primary_lag_frames == 100
    invariant slow_timescale_ps > 0.0
    invariant fast_timescale_ps > 0.0
    invariant slow_timescale_sem_ps >= 0.0
    invariant fast_timescale_sem_ps >= 0.0
    invariant right_population_mean >= 0.0 and right_population_mean <= 1.0
    invariant right_population_sem >= 0.0
    invariant len(right_population_by_replica) == replicas
    invariant ensemble_transitions >= 0
    invariant ensemble_rhat >= 0.0
    invariant effective_samples >= 0.0
    invariant lag_relative_spread_max >= 0.0
    invariant kmeans_iterations > 0 and kmeans_iterations <= 50
    invariant kmeans_final_shift >= 0.0
    invariant evidence_class == "condition_matched_public_reference" or evidence_class == "published_related_reference" or evidence_class == "failed_reference_reproduction"


pub bridge python.inline molecular_reference from "foreign/python/reference_backend.py":
    deps "python>=3.12,<3.13"
    expose:
        def run_reference(config_path: str, output_path: str) -> MolecularReferenceResult !{ffi.call}:
            sem "Reproduce published alanine relaxation timescales from a hash-pinned public ensemble"
```

### `src/rerun.sema`

```sema
"""Non-authoritative Rerun recording projection for canonical molecular frames."""

assure silver


pub struct RerunRecording:
    schema: str
    path: str
    frames: int
    bytes: int
    sha256: str
    source_frames_sha256: str
    source_result_sha256: str
    coarse_result_sha256: str
    ensemble_result_sha256: str
    ensemble_sampling_converged: bool
    rare_event_result_sha256: str
    rare_event_technical_converged: bool
    mace_result_sha256: str
    mace_technical_pass: bool
    mace_uncertainty_available: bool
    mace_molecular_validated: bool
    model_sha256: str
    parameter_sha256: str
    equation_terms: int
    invariant schema == "sema.rerun-recording/v1"
    invariant len(path) > 0
    invariant frames > 0 and frames <= 101
    invariant bytes > 0 and bytes <= 16777216
    invariant len(sha256) == 64
    invariant len(source_frames_sha256) == 64
    invariant len(source_result_sha256) == 64
    invariant len(coarse_result_sha256) == 64
    invariant len(ensemble_result_sha256) == 64
    invariant len(rare_event_result_sha256) == 64
    invariant len(mace_result_sha256) == 64
    invariant mace_technical_pass == true
    invariant mace_uncertainty_available == false
    invariant mace_molecular_validated == false
    invariant len(model_sha256) == 64
    invariant len(parameter_sha256) == 64
    invariant equation_terms > 0 and equation_terms <= 32


pub bridge python.inline rerun_projection from "foreign/python/rerun_projection.py":
    deps "python>=3.12,<3.13"
    expose:
        def record_run(
            frames_path: str,
            coarse_path: str,
            ensemble_path: str,
            rare_event_path: str,
            mace_path: str,
            input_path: str,
            output_path: str,
            source_result_sha256: str,
        ) -> RerunRecording !{ffi.call}:
            sem "Project canonical backend frames into a labeled non-authoritative Rerun recording"
```

### `src/resolution.sema`

```sema
"""Approximation, negligibility, resolution-graph, and transactional transition contracts."""

from biological_computer.domain import EvidenceRecord, ModelScale

assure silver


pub enum EdgeKind:
    compose | couple | refine | coarsen | restrict | prolong | observe | parameterize


pub enum TransitionState:
    requested | prepared | validated | committed | blocked


pub struct ApproximationContract:
    id: str
    source_model_id: str
    target_model_id: str
    transform: str
    preserved_observables: list[str]
    marginalized_degrees: list[str]
    calibration_domain: str
    maximum_error: f64
    refine_threshold: f64
    evidence_ids: list[str]
    valid: bool
    invariant len(id) > 0
    invariant len(source_model_id) > 0
    invariant len(target_model_id) > 0
    invariant len(transform) > 0
    invariant len(preserved_observables) > 0 and len(preserved_observables) <= 64
    invariant len(marginalized_degrees) > 0 and len(marginalized_degrees) <= 128
    invariant len(calibration_domain) > 0
    invariant maximum_error >= 0.0
    invariant refine_threshold >= 0.0
    invariant len(evidence_ids) <= 128


struct NegligibilityCertificate:
    id: str
    interaction_family: str
    target_observable: str
    comparison_scale: str
    upper_bound_ratio: f64
    error_floor_ratio: f64
    activation_condition: str
    evidence_ids: list[str]
    valid: bool
    invariant len(id) > 0
    invariant len(interaction_family) > 0
    invariant len(target_observable) > 0
    invariant len(comparison_scale) > 0
    invariant upper_bound_ratio >= 0.0
    invariant error_floor_ratio >= 0.0
    invariant len(activation_condition) > 0
    invariant len(evidence_ids) <= 128


struct ResolutionNode:
    id: str
    scale: ModelScale
    model_version: str
    resolved_degrees: list[str]
    target_observables: list[str]
    active: bool
    invariant len(id) > 0
    invariant len(model_version) > 0
    invariant len(resolved_degrees) > 0 and len(resolved_degrees) <= 256
    invariant len(target_observables) > 0 and len(target_observables) <= 64


pub struct ResolutionEdge:
    id: str
    kind: EdgeKind
    source_node_id: str
    target_node_id: str
    approximation: ApproximationContract
    restriction: str
    prolongation: str
    checkpoint_only: bool
    invariant len(id) > 0
    invariant len(source_node_id) > 0
    invariant len(target_node_id) > 0
    invariant source_node_id != target_node_id
    invariant len(restriction) > 0
    invariant len(prolongation) > 0


pub struct TransitionRecord:
    sequence: int
    edge_id: str
    from_state_version: int
    to_state_version: int
    state: TransitionState
    reason: str
    evidence_ids: list[str]
    lost_information: list[str]
    occurred_at_s: f64
    invariant sequence >= 0
    invariant len(edge_id) > 0
    invariant from_state_version >= 0
    invariant to_state_version >= from_state_version
    invariant len(reason) > 0
    invariant len(evidence_ids) <= 128
    invariant len(lost_information) <= 128
    invariant occurred_at_s >= 0.0


def approximation_valid(contract: ApproximationContract):
    return contract.valid and len(contract.evidence_ids) > 0 and contract.maximum_error <= contract.refine_threshold


def negligibility_valid(certificate: NegligibilityCertificate):
    return certificate.valid and len(certificate.evidence_ids) > 0 and certificate.upper_bound_ratio <= certificate.error_floor_ratio


def edge_valid(edge: ResolutionEdge):
    if edge.kind == EdgeKind.coarsen or edge.kind == EdgeKind.restrict:
        return approximation_valid(edge.approximation) and len(edge.approximation.marginalized_degrees) > 0
    if edge.kind == EdgeKind.refine or edge.kind == EdgeKind.prolong:
        return approximation_valid(edge.approximation) and len(edge.prolongation) > 0
    return approximation_valid(edge.approximation)


pub def prepare_transition(sequence: int, edge: ResolutionEdge, state_version: int, occurred_at_s: f64) -> TransitionRecord !{}:
    require sequence >= 0 and state_version >= 0
    if not edge_valid(edge):
        return TransitionRecord(sequence=sequence, edge_id=edge.id, from_state_version=state_version, to_state_version=state_version, state=TransitionState.blocked, reason="edge lacks valid approximation evidence", evidence_ids=edge.approximation.evidence_ids, lost_information=edge.approximation.marginalized_degrees, occurred_at_s=occurred_at_s)
    return TransitionRecord(sequence=sequence, edge_id=edge.id, from_state_version=state_version, to_state_version=state_version + 1, state=TransitionState.prepared, reason="candidate state prepared without mutating active state", evidence_ids=edge.approximation.evidence_ids, lost_information=edge.approximation.marginalized_degrees, occurred_at_s=occurred_at_s)


pub def validate_transition(record: TransitionRecord, evidence: list[EvidenceRecord], observable_error: f64, threshold: f64) -> TransitionRecord !{}:
    require observable_error >= 0.0 and threshold >= 0.0
    if record.state != TransitionState.prepared:
        return record
    mut accepted_ids = []
    for item in evidence:
        if item.accepted:
            accepted_ids.append(item.id)
    if len(accepted_ids) == 0 or observable_error > threshold:
        return TransitionRecord(sequence=record.sequence, edge_id=record.edge_id, from_state_version=record.from_state_version, to_state_version=record.from_state_version, state=TransitionState.blocked, reason="held-out observable validation failed", evidence_ids=accepted_ids, lost_information=record.lost_information, occurred_at_s=record.occurred_at_s)
    return TransitionRecord(sequence=record.sequence, edge_id=record.edge_id, from_state_version=record.from_state_version, to_state_version=record.to_state_version, state=TransitionState.validated, reason="held-out observable validation passed", evidence_ids=accepted_ids, lost_information=record.lost_information, occurred_at_s=record.occurred_at_s)


pub def commit_transition(record: TransitionRecord) -> TransitionRecord !{}:
    if record.state != TransitionState.validated:
        return TransitionRecord(sequence=record.sequence, edge_id=record.edge_id, from_state_version=record.from_state_version, to_state_version=record.from_state_version, state=TransitionState.blocked, reason="only validated transitions may commit", evidence_ids=record.evidence_ids, lost_information=record.lost_information, occurred_at_s=record.occurred_at_s)
    return TransitionRecord(sequence=record.sequence, edge_id=record.edge_id, from_state_version=record.from_state_version, to_state_version=record.to_state_version, state=TransitionState.committed, reason="validated candidate committed atomically", evidence_ids=record.evidence_ids, lost_information=record.lost_information, occurred_at_s=record.occurred_at_s)
```

### `src/statistics.sema`

```sema
"""Bounded ensemble diagnostics, coarse-state comparison, and PMF correction algebra."""

import math

assure silver


pub struct BasinPopulations:
    alpha: f64
    beta: f64
    other: f64
    samples: int
    invariant alpha >= 0.0 and alpha <= 1.0
    invariant beta >= 0.0 and beta <= 1.0
    invariant other >= 0.0 and other <= 1.0
    invariant samples > 0


pub struct EnsembleDiagnostics:
    samples: int
    replicas: int
    mean: f64
    variance: f64
    lag1_autocorrelation: f64
    effective_sample_size: f64
    converged: bool
    invariant samples > 1 and samples <= 1000000
    invariant replicas > 0 and replicas <= 1024
    invariant variance >= 0.0
    invariant lag1_autocorrelation >= -1.0 and lag1_autocorrelation <= 1.0
    invariant effective_sample_size >= 0.0 and effective_sample_size <= f64(samples)


pub struct DistributionComparison:
    total_variation: f64
    threshold: f64
    passed: bool
    invariant total_variation >= 0.0 and total_variation <= 1.0
    invariant threshold >= 0.0 and threshold <= 1.0


pub struct PmfCorrections:
    restraint_kj_mol: f64
    jacobian_kj_mol: f64
    finite_box_kj_mol: f64
    standard_state_kj_mol: f64


pub struct PmfResult:
    raw_delta_g_kj_mol: f64
    corrected_delta_g_kj_mol: f64
    corrections: PmfCorrections
    window_overlap_min: f64
    effective_sample_size: f64
    replicas: int
    converged: bool
    validated: bool
    invariant window_overlap_min >= 0.0 and window_overlap_min <= 1.0
    invariant effective_sample_size >= 0.0
    invariant replicas > 0 and replicas <= 1024


pub def basin_populations(phi_values: list[f64], psi_values: list[f64]) -> BasinPopulations !{}:
    require len(phi_values) == len(psi_values)
    require len(phi_values) > 0 and len(phi_values) <= 1000000
    mut alpha_count = 0
    mut beta_count = 0
    mut index = 0
    for phi in phi_values:
        psi = psi_values[index]
        if phi >= -2.1 and phi <= -0.5 and psi >= -1.4 and psi <= 0.8:
            alpha_count = alpha_count + 1
        elif phi >= -3.2 and phi <= -1.2 and (psi >= 1.0 or psi <= -2.4):
            beta_count = beta_count + 1
        index = index + 1
    count = f64(len(phi_values))
    alpha = f64(alpha_count) / count
    beta = f64(beta_count) / count
    return BasinPopulations(alpha=alpha, beta=beta, other=1.0 - alpha - beta, samples=len(phi_values))


pub def compare_populations(fine: BasinPopulations, coarse: BasinPopulations, threshold: f64) -> DistributionComparison !{}:
    require threshold >= 0.0 and threshold <= 1.0
    variation = 0.5 * (abs(fine.alpha - coarse.alpha) + abs(fine.beta - coarse.beta) + abs(fine.other - coarse.other))
    return DistributionComparison(total_variation=variation, threshold=threshold, passed=variation <= threshold)


def sample_mean(values: list[f64]):
    require len(values) > 0 and len(values) <= 1000000
    return sum(values) / f64(len(values))


def sample_variance(values: list[f64], average: f64):
    require len(values) > 1 and len(values) <= 1000000
    mut total = 0.0
    for value in values:
        delta = value - average
        total = total + delta * delta
    return total / f64(len(values) - 1)


def lag1_autocorrelation(values: list[f64], average: f64, variance: f64):
    require len(values) > 1 and len(values) <= 1000000
    if variance == 0.0:
        return 0.0
    mut covariance = 0.0
    mut index = 1
    for value in values:
        if index < len(values):
            covariance = covariance + (value - average) * (values[index] - average)
        index = index + 1
    raw = covariance / (f64(len(values) - 1) * variance)
    return max(-1.0, min(1.0, raw))


def effective_sample_size(samples: int, autocorrelation: f64):
    require samples > 1
    require autocorrelation >= -1.0 and autocorrelation <= 1.0
    if autocorrelation <= 0.0:
        return f64(samples)
    return max(1.0, min(f64(samples), f64(samples) * (1.0 - autocorrelation) / (1.0 + autocorrelation)))


pub def diagnose_ensemble(values: list[f64], replicas: int, minimum_effective_samples: f64) -> EnsembleDiagnostics !{}:
    require replicas > 0 and replicas <= 1024
    require minimum_effective_samples > 0.0
    average = sample_mean(values)
    variance = sample_variance(values, average)
    autocorrelation = lag1_autocorrelation(values, average, variance)
    effective = effective_sample_size(len(values), autocorrelation)
    return EnsembleDiagnostics(samples=len(values), replicas=replicas, mean=average, variance=variance, lag1_autocorrelation=autocorrelation, effective_sample_size=effective, converged=replicas >= 2 and effective >= minimum_effective_samples)


def probability_free_energy(probability: f64, temperature_k: f64):
    require probability > 0.0 and probability <= 1.0
    require temperature_k > 0.0
    return -0.00831446261815324 * temperature_k * math.log(probability)


pub def corrected_pmf(raw_delta_g_kj_mol: f64, corrections: PmfCorrections, window_overlap_min: f64, effective_samples: f64, replicas: int, converged: bool) -> PmfResult !{}:
    require window_overlap_min >= 0.0 and window_overlap_min <= 1.0
    require effective_samples >= 0.0
    corrected = raw_delta_g_kj_mol + corrections.restraint_kj_mol + corrections.jacobian_kj_mol + corrections.finite_box_kj_mol + corrections.standard_state_kj_mol
    validated = converged and replicas >= 2 and effective_samples >= 100.0 and window_overlap_min >= 0.03
    return PmfResult(raw_delta_g_kj_mol=raw_delta_g_kj_mol, corrected_delta_g_kj_mol=corrected, corrections=corrections, window_overlap_min=window_overlap_min, effective_sample_size=effective_samples, replicas=replicas, converged=converged, validated=validated)
```

### `src/viewer.sema`

```sema
"""Native scene verification, composition binding, and bounded viewer export."""

from std.crypto import file_sha256, sha256_json, sha256_text
from std.json import decode as decode_json, encode as encode_json, read as read_json
from biological_computer.api import biological_api_contract

assure silver


pub struct ViewerSceneArtifact:
    schema: str
    path: str
    bytes: int
    scene_sha256: str
    file_sha256: str
    source_result_sha256: str
    source_frames_sha256: str
    atoms: int
    bonds: int
    frames: int
    volume_result_sha256: str
    volume_frames: int
    cellular_voxels: int
    tissue_voxels: int
    scene_instances: int
    protein_atoms: int
    scenarios: int
    invariant schema == "sema.multiscale-viewer/v4"
    invariant len(path) > 0
    invariant bytes > 0 and bytes <= 4194304
    invariant len(scene_sha256) == 64 and len(file_sha256) == 64
    invariant len(source_result_sha256) == 64 and len(source_frames_sha256) == 64
    invariant atoms > 0 and atoms <= 256 and bonds > 0 and bonds <= 512
    invariant frames > 0 and frames <= 101
    invariant len(volume_result_sha256) == 64
    invariant volume_frames > 1 and volume_frames <= 64
    invariant cellular_voxels > 0 and cellular_voxels <= 131072
    invariant tissue_voxels > 0 and tissue_voxels <= 131072
    invariant scene_instances > 0 and scene_instances <= 16384
    invariant protein_atoms > 0 and protein_atoms <= 4096
    invariant scenarios > 0 and scenarios <= 16


def ala2_topology_bonds():
    return [
        [4, 1], [4, 5], [1, 0], [1, 2], [1, 3], [4, 6], [14, 8],
        [14, 15], [8, 10], [8, 9], [8, 6], [10, 11], [10, 12], [10, 13],
        [7, 6], [14, 16], [18, 19], [18, 20], [18, 21], [18, 16], [17, 16],
    ]


def parse_pinned_topology(pdb_text: str) !{}:
    sem "Parse the source-bound alanine PDB metadata in native Sema and attach its curated OpenMM topology"
    require len(pdb_text) > 0 and len(pdb_text) <= 1048576
    atoms = []
    for line in pdb_text.split("\n"):
        if not line.startswith("ATOM") or len(line) < 78:
            continue
        residue_name = line.substring(17, 3).strip()
        if residue_name == "HOH" or residue_name == "WAT":
            continue
        name = line.substring(12, 4).strip()
        element = line.substring(76, 2).strip()
        if len(element) == 0:
            element = name.substring(0, 1)
        atoms.append({
            "source_index": int(line.substring(6, 5).strip()) - 1,
            "element": element,
            "residue_name": residue_name,
            "residue_id": line.substring(22, 4).strip(),
            "name": name,
        })
    bonds = ala2_topology_bonds()
    ensure len(atoms) == 22 and len(bonds) == 21
    ensure all(bond[0] < len(atoms) and bond[1] < len(atoms) for bond in bonds)
    return {"atoms": atoms, "bonds": bonds}

def atom_style(element: str):
    if element == "H":
        return {"color": "#edf3f6", "radius_angstrom": 1.2}
    if element == "C":
        return {"color": "#424c56", "radius_angstrom": 1.7}
    if element == "N":
        return {"color": "#396ec6", "radius_angstrom": 1.55}
    if element == "O":
        return {"color": "#e7554f", "radius_angstrom": 1.52}
    if element == "S":
        return {"color": "#e4b84e", "radius_angstrom": 1.8}
    return {"color": "#9a7fb4", "radius_angstrom": 1.6}


def decorate_topology(raw: dict[str, any]):
    ensure len(raw["atoms"]) > 0 and len(raw["atoms"]) <= 256 and len(raw["bonds"]) > 0
    atoms = []
    mut index = 0
    for atom in raw["atoms"]:
        style = atom_style(atom["element"])
        atoms.append({
            "index": index,
            "source_index": atom["source_index"],
            "element": atom["element"],
            "label": atom["residue_name"] + ":" + atom["residue_id"] + ":" + atom["name"],
            "color": style["color"],
            "radius_angstrom": style["radius_angstrom"],
        })
        index = index + 1
    return {"atoms": atoms, "bonds": raw["bonds"]}


def load_frames(source: dict[str, any]) !{fs.read}:
    frames_path = "runs/cpu/" + path.basename(source["frames_path"])
    ensure path.is_relative_to(frames_path, "runs/cpu")
    ensure file_sha256(frames_path) == source["frames_sha256"]
    payload = fs.read_text(frames_path)?
    frames = [decode_json(line) for line in payload.split("\n") if len(line) > 0]
    ensure len(frames) == source["frames"] and len(frames) > 0 and len(frames) <= 101
    return frames


def measurement_sources():
    return [{
        "id": "idr0116-deboer-npod",
        "title": "Large-scale electron microscopy database for human type 1 diabetes",
        "sample": "Homo sapiens pancreatic islet tissue",
        "modality": "scanning-transmission electron microscopy",
        "fidelity": "measured",
        "data_doi": "10.17867/10000168",
        "publication_doi": "10.1038/s41467-020-16287-5",
        "license": "CC-BY-4.0",
        "image_id": 13457674,
        "image_name": "6229-2015-246.ome.tiff",
        "pixel_size_nm": 2.52784054231644,
        "dimensions_px": [47284, 47229],
        "preview_url": "https://cdn.ncbi.nlm.nih.gov/pmc/blobs/8148/7235089/e8391cb31b2a/41467_2020_16287_Fig1_HTML.jpg",
        "local_preview_url": "/data/idr0116-deboer-npod-preview.jpg",
        "deep_zoom_url": "https://idr.openmicroscopy.org/webclient/?show=image-13457674",
        "attribution": "de Boer et al., Nature Communications 11, 2475 (2020), IDR0116",
        "warning": "Static measured external reference; it does not depict or supply geometry for the simulated live state",
        "role": "external_reference_only",
        "geometry_input": false,
    }]


def composition_profiles():
    return {
        "beta": {"name": "β cell", "hormone": "insulin / IAPP", "markers": ["INS", "IAPP", "PCSK1", "SLC30A8"], "granule": "dense crystalline core; sulfur-rich insulin", "elements": ["N", "S"], "structures": ["RCSB 6S34"], "evidence": "10.1038/s41467-020-16287-5"},
        "alpha": {"name": "α cell", "hormone": "glucagon", "markers": ["GCG", "TTR", "LOXL4", "IRX2"], "granule": "dense round core; phosphorus-enriched", "elements": ["N", "P"], "structures": ["RCSB 1GCN"], "evidence": "10.1038/s41467-020-16287-5"},
        "delta": {"name": "δ cell", "hormone": "somatostatin", "markers": ["SST", "HHEX", "RBP4", "GHSR"], "granule": "homogeneous low-density endocrine granule", "elements": ["N"], "structures": [], "evidence": "10.1038/s41467-020-16287-5"},
        "pp": {"name": "PP / γ cell", "hormone": "pancreatic polypeptide", "markers": ["PPY", "PNLIPRP1", "CARTPT"], "granule": "small electron-dense endocrine granule", "elements": ["N"], "structures": [], "evidence": "10.1038/s41467-020-16287-5"},
        "acinar": {"name": "Acinar cell", "hormone": "digestive enzyme cargo", "markers": ["PRSS1", "AMY2A", "CPA1", "REG1A"], "granule": "large apical zymogen granules", "elements": ["N"], "structures": [], "evidence": "10.1038/s41467-020-16287-5"},
        "adipocyte": {"name": "Adipocyte", "hormone": "adipokine / lipid cargo", "markers": ["PLIN1", "ADIPOQ", "FABP4", "LPL"], "granule": "dominant neutral-lipid droplet; peripheral nucleus", "elements": ["C", "O"], "structures": [], "evidence": "model descriptor"},
        "immune": {"name": "Innate immune cell", "hormone": "granule and cytokine cargo", "markers": ["PTPRC", "S100A8", "S100A9", "FCGR3B"], "granule": "heterogeneous lysosomal / secretory granules", "elements": ["N", "S"], "structures": [], "evidence": "10.1038/s41467-020-16287-5"},
        "vessel": {"name": "Microvascular segment", "hormone": "blood plasma and endothelial membrane", "markers": ["PECAM1", "VWF", "KDR", "CD34"], "granule": "Weibel-Palade bodies in endothelial wall", "elements": ["N", "P", "S"], "structures": [], "evidence": "10.2337/db09-1177"},
    }


pub def prepare_viewer() -> ViewerSceneArtifact !{ffi.call, fs.read, fs.write}:
    sem "Verify scientific artifacts in native Sema and publish a composition-bound scene"
    result = read_json("runs/cpu/cpu-result.json")
    ensure result["schema"] == "sema.openmm-benchmark/v1"
    result_digest = result["result_sha256"]
    result_identity = {key: value for key, value in result.items() if key != "result_sha256" and key != "frames_path" and key != "initial_forces_path" and key != "minimized_forces_path"}
    ensure sha256_json(result_identity) == result_digest
    frames = load_frames(result)
    raw_topology = parse_pinned_topology(fs.read_text(".sema/cache/inputs/" + result["input_sha256"] + ".pdb")?)
    topology = decorate_topology(raw_topology)
    ensure all(len(frame["peptide_positions_nm"]) == len(topology["atoms"]) for frame in frames)
    volume_path = "runs/volumes/cellular-tissue.json"
    expected_volume_file_sha256 = "675c5208e7a100e78924995fb38a3f56510f551f6e4c59ac3402382445f0f14b"
    expected_volume_result_sha256 = "3a141fa21788f76ea589105ec65052e17b5185685283ee62e47a450dde0b0bf5"
    volume_file_digest = file_sha256(volume_path)
    ensure volume_file_digest == expected_volume_file_sha256
    volume_result = read_json(volume_path)
    ensure volume_result["schema"] == "sema.biological-volume-result/v1" and volume_result["phase10_technical_pass"]
    ensure volume_result["source_binding_pass"] and volume_result["result_sha256"] == expected_volume_result_sha256
    volume_identity = {key: value for key, value in volume_result.items() if key != "result_sha256"}
    recomputed_volume_result_sha256 = sha256_json(volume_identity)
    ensure recomputed_volume_result_sha256 == volume_result["result_sha256"]
    ensure volume_result["source_result_sha256"] == volume_result["volumes"]["source"]["result_sha256"]
    volume_sidecar_digest = fs.read_text(volume_path + ".sha256")?.split(" ")[0]
    ensure volume_sidecar_digest == volume_file_digest
    volumes = volume_result["volumes"]
    ensure volumes["schema"] == "sema.biological-volume-frames/v2"
    ensure volumes["cellular"]["schema"] == "sema.segment-volume/v1" and volumes["tissue"]["schema"] == "sema.segment-volume/v1"
    scene_model = volumes["scene_model"]
    ensure scene_model["schema"] == "sema.biological-scene-model/v1"
    ensure scene_model["tissue"]["cell_count"] <= scene_model["budgets"]["max_visible_instances"]
    cellular_contexts = scene_model["cellular"]["contexts"]
    ensure len(cellular_contexts) == 8 and len(scene_model["detail_bindings"]) == 112
    context_ids = [context["id"] for context in cellular_contexts]
    ensure all(context_id in context_ids for context_id in ["beta", "alpha", "delta", "pp", "acinar", "adipocyte", "immune", "vessel"])
    for context in cellular_contexts:
        ensure context["kind"] == "cell" or context["kind"] == "vessel"
        ensure context["radius_um"] > 0.0 and context["nucleus_radius_um"] > 0.0
        ensure len(context["shape"]) == 3 and len(context["nucleus_offset_um"]) == 3
        ensure context["counts"]["granule"] > 0 and context["counts"]["mitochondrion"] > 0
        ensure context["counts"]["receptor"] > 0 and context["counts"]["protein"] > 0
        ensure context["molecular_fidelity"] == "derived" or context["molecular_fidelity"] == "illustrative"
    physical_objects = scene_model["physical_objects"]
    ensure physical_objects["schema"] == "sema.cellular-physical-object-profiles/v1"
    ensure physical_objects["fidelity"] == "derived_unvalidated" and not physical_objects["scientific_validated"]
    ensure len(physical_objects["profiles"]) == 12
    ensure all(profile["radius_nm"] > 0.0 and profile["molecular_entities"] > 0 for profile in physical_objects["profiles"])
    visual_frames = []
    for frame in frames:
        visual_frames.append({
            "step": frame["step"],
            "physical_time_ps": frame["physical_time_ps"],
            "positions_angstrom": [[coordinate * 10.0 for coordinate in position] for position in frame["peptide_positions_nm"]],
            "forces_kj_mol_nm": frame["peptide_forces_kj_mol_nm"],
            "potential_energy_kj_mol": frame["potential_energy_kj_mol"],
            "kinetic_energy_kj_mol": frame["kinetic_energy_kj_mol"],
            "max_force_kj_mol_nm": frame["max_force_kj_mol_nm"],
            "phi_rad": frame["phi_rad"],
            "psi_rad": frame["psi_rad"],
            "energy_terms_kj_mol": frame["energy_terms_kj_mol"],
        })
    volume_frames = {key: value for key, value in volumes.items() if key != "scene_model"}
    scene = {
        "schema": "sema.multiscale-viewer/v4",
        "scenario_id": result["benchmark_id"],
        "source": {
            "mode": "canonical_recording_replay",
            "live_compute": false,
            "geometry_origin": "reconstructed_molecular_reference_plus_simulated_cellular_tissue",
            "result_sha256": result_digest,
            "frames_sha256": result["frames_sha256"],
            "model_sha256": result["system_sha256"],
            "parameter_sha256": result["config_sha256"],
            "equation_version": 2,
            "parameter_version": 2,
            "volume_result_sha256": volume_result["result_sha256"],
            "volume_file_sha256": file_sha256("runs/volumes/cellular-tissue.json"),
            "volume_payload_sha256": volume_result["volume_payload_sha256"],
            "volume_profile_id": volume_result["profile_id"],
            "rendered_cellular_tissue_geometry_origin": "simulated",
            "rendered_cellular_tissue_geometry_fidelity": "derived_unvalidated",
            "external_reference_role": "external_reference_only",
            "external_reference_geometry_input": false,
        },
        "topology": topology,
        "frames": visual_frames,
        "volumes": volume_frames,
        "scene_model": scene_model,
        "measurement_sources": measurement_sources(),
        "api_contract": biological_api_contract(),
        "composition_profiles": composition_profiles(),
        "lod": [
            {"id": "atomic", "scale_label": "0.1–10 nm", "available": true, "fidelity": "canonical", "origin": "reconstructed", "representation": "element-colored atoms plus strain-coded covalent cylinders", "warning": "RCSB 6S34 neighborhood; edited motion is a bounded mechanical model"},
            {"id": "molecular", "scale_label": "1 nm–1 µm", "available": true, "fidelity": "canonical", "origin": "reconstructed", "representation": "ball-and-stick insulin topology with distinct atom and bond channels", "warning": "RCSB 6S34 assembly geometry; live motion is not molecular dynamics"},
            {"id": "cellular", "scale_label": "1–100 µm", "available": true, "fidelity": "derived_unvalidated", "origin": "simulated", "representation": "composition-constrained simulated cell and organelle geometry", "warning": "Rendered geometry is simulated, derived, and unvalidated; measured IDR0116 imagery is external reference only and is not a geometry input"},
            {"id": "tissue", "scale_label": "0.1–1 mm", "available": true, "fidelity": "derived_unvalidated", "origin": "simulated", "representation": "simulated endocrine, exocrine, immune, matrix, and vascular tissue geometry", "warning": "Rendered geometry is simulated, derived, and unvalidated; measured IDR0116 imagery is external reference only and is not a geometry input"},
        ],
    }
    scene["scene_sha256"] = sha256_json(scene)
    payload = encode_json(scene)
    ensure len(payload) <= 4194304
    output_path = "viewer/public/data/scene.json"
    fs.write_text(output_path, payload)?
    file_digest = sha256_text(payload)
    fs.write_text(output_path + ".sha256", file_digest + "  scene.json\n")?
    return ViewerSceneArtifact(
        schema=scene["schema"],
        path=output_path,
        bytes=len(payload),
        scene_sha256=scene["scene_sha256"],
        file_sha256=file_digest,
        source_result_sha256=result_digest,
        source_frames_sha256=result["frames_sha256"],
        atoms=len(topology["atoms"]),
        bonds=len(topology["bonds"]),
        frames=len(frames),
        volume_result_sha256=volume_result["result_sha256"],
        volume_frames=volume_result["frames"],
        cellular_voxels=volume_result["cellular_voxels"],
        tissue_voxels=volume_result["tissue_voxels"],
        scene_instances=scene_model["tissue"]["cell_count"],
        protein_atoms=scene_model["molecular"]["positions_angstrom"]["items"],
        scenarios=len(scene_model["scenarios"]),
    )
```

### `src/visualization.sema`

```sema
"""Non-authoritative multiscale visual bindings and live equation-frame contracts."""

assure silver


pub enum FidelityClass:
    canonical | derived | interpolated | illustrative | unknown


pub enum VisualScale:
    field_quantum | atomic | molecular | cellular | tissue


pub enum GeometryOrigin:
    measured | simulated | reconstructed | illustrative | unknown


pub enum EquationUpdateKind:
    state_step | parameter_transition | structural_transition



pub struct EntityFocusPath:
    path_id: str
    entity_ids: list[str]
    selected_depth: int
    invariant len(path_id) > 0
    invariant len(entity_ids) > 0 and len(entity_ids) <= 8
    invariant selected_depth >= 0 and selected_depth < len(entity_ids)


pub struct ComplexityScenario:
    id: str
    glucose_millimolar: f64
    oxygen_fraction: f64
    cytokine_fraction: f64
    insulin_demand_fraction: f64
    illustrative: bool
    invariant len(id) > 0
    invariant glucose_millimolar >= 0.0 and glucose_millimolar <= 40.0
    invariant oxygen_fraction >= 0.0 and oxygen_fraction <= 1.0
    invariant cytokine_fraction >= 0.0 and cytokine_fraction <= 1.0
    invariant insulin_demand_fraction >= 0.0 and insulin_demand_fraction <= 1.0
    invariant illustrative

enum BiologicalEditKind:
    signal | morphology | motility | thermal | bond_strength | bond_form | bond_break | reset


enum BiologicalEditTarget:
    all | beta_cell | alpha_cell | delta_cell | acinar_cell | adipocyte | immune_cell | vessel | granule | mitochondrion | receptor | protein


struct BiologicalEditOperation:
    kind: BiologicalEditKind
    target: BiologicalEditTarget
    scalar: f64
    atom_index_a: int
    atom_index_b: int
    compiled_equation: str
    invariant scalar >= 0.0 and scalar <= 4.0
    invariant atom_index_a >= -1 and atom_index_b >= -1
    invariant len(compiled_equation) > 0 and len(compiled_equation) <= 160


struct BiologicalEditPlan:
    schema: str
    request_id: str
    natural_language: str
    compiler_id: str
    source_state_version: int
    operations: list[BiologicalEditOperation]
    invariant schema == "sema.biological-edit-plan/v1"
    invariant len(request_id) > 0
    invariant len(natural_language) > 0 and len(natural_language) <= 320
    invariant len(compiler_id) > 0
    invariant source_state_version > 0
    invariant len(operations) > 0 and len(operations) <= 8


struct BiologicalEditBudget:
    max_operations: int
    max_structural_edits: int
    atom_count: int
    max_visible_instances: int
    candidate_visible_instances: int
    invariant max_operations > 0 and max_operations <= 8
    invariant max_structural_edits >= 0 and max_structural_edits <= 16
    invariant atom_count > 0
    invariant max_visible_instances > 0
    invariant candidate_visible_instances >= 0


struct BiologicalEditDecision:
    request_id: str
    admissible: bool
    live_computed: bool
    scientific_fidelity: FidelityClass
    accepted_operations: int
    reason: str
    invariant len(request_id) > 0
    invariant accepted_operations >= 0 and accepted_operations <= 8
    invariant len(reason) > 0


def biological_edit_operation_valid(operation: BiologicalEditOperation, atom_count: int):
    require atom_count > 0
    if operation.kind == BiologicalEditKind.bond_form or operation.kind == BiologicalEditKind.bond_break:
        return operation.atom_index_a >= 0 and operation.atom_index_a < atom_count and operation.atom_index_b >= 0 and operation.atom_index_b < atom_count and operation.atom_index_a != operation.atom_index_b
    if operation.kind == BiologicalEditKind.reset:
        return operation.scalar == 0.0
    return operation.scalar > 0.0


def admit_biological_edit(plan: BiologicalEditPlan, budget: BiologicalEditBudget):
    if len(plan.operations) > budget.max_operations:
        return BiologicalEditDecision(request_id=plan.request_id, admissible=false, live_computed=false, scientific_fidelity=FidelityClass.illustrative, accepted_operations=0, reason="compiled edit exceeds the operation budget")
    if budget.candidate_visible_instances > budget.max_visible_instances:
        return BiologicalEditDecision(request_id=plan.request_id, admissible=false, live_computed=false, scientific_fidelity=FidelityClass.illustrative, accepted_operations=0, reason="edited population exceeds the visible-instance budget")
    mut structural_edits = 0
    for operation in plan.operations:
        if not biological_edit_operation_valid(operation, budget.atom_count):
            return BiologicalEditDecision(request_id=plan.request_id, admissible=false, live_computed=false, scientific_fidelity=FidelityClass.illustrative, accepted_operations=0, reason="compiled edit contains an invalid bounded operation")
        if operation.kind == BiologicalEditKind.bond_form or operation.kind == BiologicalEditKind.bond_break:
            structural_edits = structural_edits + 1
    if structural_edits > budget.max_structural_edits:
        return BiologicalEditDecision(request_id=plan.request_id, admissible=false, live_computed=false, scientific_fidelity=FidelityClass.illustrative, accepted_operations=0, reason="compiled edit exceeds the structural-change budget")
    return BiologicalEditDecision(request_id=plan.request_id, admissible=true, live_computed=true, scientific_fidelity=FidelityClass.illustrative, accepted_operations=len(plan.operations), reason="bounded edit admitted to the live computed visual simulation")


pub struct FieldOfViewBudget:
    field_of_view_m: f64
    candidate_instances: int
    required_upload_bytes: int
    desired_update_hz: int
    max_visible_instances: int
    max_upload_bytes: int
    max_update_hz: int
    invariant field_of_view_m >= 0.000000001 and field_of_view_m <= 0.001
    invariant candidate_instances >= 0
    invariant required_upload_bytes >= 0
    invariant desired_update_hz > 0
    invariant max_visible_instances > 0
    invariant max_upload_bytes > 0
    invariant max_update_hz > 0


pub struct MultiscaleComputeDecision:
    scale: VisualScale
    field_of_view_m: f64
    visible_instances: int
    update_hz: int
    admissible: bool
    reason: str
    invariant field_of_view_m >= 0.000000001 and field_of_view_m <= 0.001
    invariant visible_instances >= 0
    invariant update_hz > 0
    invariant len(reason) > 0


def visual_scale_for_field(field_of_view_m: f64):
    require field_of_view_m >= 0.000000001 and field_of_view_m <= 0.001
    if field_of_view_m <= 0.00000001:
        return VisualScale.atomic
    if field_of_view_m <= 0.000001:
        return VisualScale.molecular
    if field_of_view_m <= 0.0001:
        return VisualScale.cellular
    return VisualScale.tissue


pub def decide_multiscale_compute(budget: FieldOfViewBudget) -> MultiscaleComputeDecision !{}:
    scale = visual_scale_for_field(budget.field_of_view_m)
    visible_instances = min(budget.candidate_instances, budget.max_visible_instances)
    update_hz = min(budget.desired_update_hz, budget.max_update_hz)
    if budget.required_upload_bytes > budget.max_upload_bytes:
        return MultiscaleComputeDecision(scale=scale, field_of_view_m=budget.field_of_view_m, visible_instances=0, update_hz=update_hz, admissible=false, reason="GPU upload budget exceeded")
    if budget.candidate_instances > budget.max_visible_instances:
        return MultiscaleComputeDecision(scale=scale, field_of_view_m=budget.field_of_view_m, visible_instances=visible_instances, update_hz=update_hz, admissible=true, reason="field-of-view population bounded by instance budget")
    return MultiscaleComputeDecision(scale=scale, field_of_view_m=budget.field_of_view_m, visible_instances=visible_instances, update_hz=update_hz, admissible=true, reason="field-of-view population admitted")


pub def focus_path_valid(path: EntityFocusPath) -> bool !{}:
    for entity_id in path.entity_ids:
        if len(entity_id) == 0:
            return false
    return true

pub struct EquationTermSample:
    term_id: str
    symbol: str
    value: f64
    unit_symbol: str
    owner_model_id: str
    invariant len(term_id) > 0
    invariant len(symbol) > 0
    invariant len(unit_symbol) > 0
    invariant len(owner_model_id) > 0


pub struct EquationStateSample:
    entity_id: str
    model_id: str
    model_version: int
    equation_id: str
    equation_version: int
    parameter_version: int
    update_kind: EquationUpdateKind
    terms: list[EquationTermSample]
    residuals: list[EquationTermSample]
    active_constraints: list[str]
    transition_id: str
    cause: str
    invariant len(entity_id) > 0
    invariant len(model_id) > 0
    invariant model_version > 0
    invariant len(equation_id) > 0
    invariant equation_version > 0
    invariant parameter_version > 0
    invariant len(cause) > 0


pub struct VisualPrimitiveBinding:
    primitive_id: str
    entity_id: str
    observation_id: str
    source_state_version: int
    scale: VisualScale
    fidelity: FidelityClass
    origin: GeometryOrigin
    source_algorithm: str
    source_parameters: list[str]
    invariant len(primitive_id) > 0
    invariant len(entity_id) > 0
    invariant len(observation_id) > 0
    invariant source_state_version > 0
    invariant len(source_algorithm) > 0


pub struct VisualObservationEnvelope:
    schema: str
    scenario_id: str
    run_id: str
    observation_id: str
    physical_time_s: f64
    scheduler_tick: int
    state_version: int
    resolution_version: int
    model_version: int
    equation_version: int
    parameter_version: int
    source_frame_age_ms: f64
    bindings: list[VisualPrimitiveBinding]
    equation_states: list[EquationStateSample]
    dropped_frames: int
    interpolation_ratio: f64
    invariant schema == "sema.biological-visual-observation/v1"
    invariant len(scenario_id) > 0
    invariant len(run_id) > 0
    invariant len(observation_id) > 0
    invariant physical_time_s >= 0.0
    invariant scheduler_tick >= 0
    invariant state_version > 0
    invariant resolution_version > 0
    invariant model_version > 0
    invariant equation_version > 0
    invariant parameter_version > 0
    invariant source_frame_age_ms >= 0.0
    invariant dropped_frames >= 0
    invariant interpolation_ratio >= 0.0 and interpolation_ratio <= 1.0


def distinct_binding_ids(bindings: list[VisualPrimitiveBinding]):
    mut seen: list[str] = []
    for binding in bindings:
        for primitive_id in seen:
            if primitive_id == binding.primitive_id:
                return false
        seen.append(binding.primitive_id)
    return true


def equations_cover_canonical_bindings(
    bindings: list[VisualPrimitiveBinding],
    equations: list[EquationStateSample],
):
    for binding in bindings:
        if binding.fidelity == FidelityClass.canonical:
            mut found = false
            for equation in equations:
                if equation.entity_id == binding.entity_id:
                    found = true
            if not found:
                return false
    return true


pub def validate_visual_observation(frame: VisualObservationEnvelope) -> bool !{}:
    if not distinct_binding_ids(frame.bindings):
        return false
    for binding in frame.bindings:
        if binding.source_state_version != frame.state_version:
            return false
        if binding.fidelity == FidelityClass.illustrative and binding.origin != GeometryOrigin.illustrative:
            return false
        if binding.fidelity == FidelityClass.unknown and binding.origin != GeometryOrigin.unknown:
            return false
    for equation in frame.equation_states:
        if equation.model_version != frame.model_version:
            return false
        if equation.equation_version != frame.equation_version:
            return false
        if equation.parameter_version != frame.parameter_version:
            return false
    return equations_cover_canonical_bindings(frame.bindings, frame.equation_states)


def unknown_binding(
    primitive_id: str,
    entity_id: str,
    observation_id: str,
    state_version: int,
    scale: VisualScale,
    reason: str,
):
    require len(reason) > 0
    return VisualPrimitiveBinding(
        primitive_id=primitive_id,
        entity_id=entity_id,
        observation_id=observation_id,
        source_state_version=state_version,
        scale=scale,
        fidelity=FidelityClass.unknown,
        origin=GeometryOrigin.unknown,
        source_algorithm=reason,
        source_parameters=[],
    )


pub enum VisualRepresentation:
    particles | topology_bonds | occupancy_envelope | scalar_volume | segmented_volume | instanced_cells | instanced_organelles | instanced_vessels | instanced_proteins


pub struct SemanticScaleSource:
    source_id: str
    scale: VisualScale
    minimum_length_m: f64
    maximum_length_m: f64
    available: bool
    fidelity: FidelityClass
    origin: GeometryOrigin
    observation_id: str
    representation_ids: list[VisualRepresentation]
    source_algorithm: str
    invariant len(source_id) > 0
    invariant minimum_length_m > 0.0
    invariant maximum_length_m >= minimum_length_m
    invariant len(representation_ids) <= 8
    invariant len(source_algorithm) > 0


struct ScaleDetailBinding:
    id: str
    parent_scale: VisualScale
    parent_selector: str
    child_scale: VisualScale
    child_model_id: str
    default_child_kind: str
    default_child_index: int
    binding: str
    fidelity: FidelityClass
    evidence_ids: list[str]
    invariant len(id) > 0
    invariant len(parent_selector) > 0
    invariant len(default_child_kind) > 0
    invariant len(binding) > 0
    invariant len(child_model_id) > 0
    invariant default_child_index >= 0
    invariant len(evidence_ids) > 0 and len(evidence_ids) <= 128


struct MultiscaleCouplingEdge:
    id: str
    source_scale: VisualScale
    target_scale: VisualScale
    source_observable: str
    target_observable: str
    coupling_expression: str
    unit_symbol: str
    maximum_error: f64
    evidence_ids: list[str]
    validated: bool
    invariant len(id) > 0
    invariant len(source_observable) > 0
    invariant len(target_observable) > 0
    invariant len(coupling_expression) > 0
    invariant len(unit_symbol) > 0
    invariant maximum_error >= 0.0
    invariant len(evidence_ids) <= 128


def detail_refinement_admissible(binding: ScaleDetailBinding, parent_entity_id: str):
    return binding.parent_selector == parent_entity_id and binding.parent_scale != binding.child_scale and len(binding.evidence_ids) > 0


def coupling_claim_admissible(edge: MultiscaleCouplingEdge):
    return edge.validated and len(edge.evidence_ids) > 0


pub struct ViewportQuery:
    query_id: str
    requested_scale: VisualScale
    field_of_view_m: f64
    observation_id: str
    state_version: int
    resolution_version: int
    invariant len(query_id) > 0
    invariant field_of_view_m > 0.0
    invariant len(observation_id) > 0
    invariant state_version >= 0
    invariant resolution_version >= 0


pub struct SemanticZoomDecision:
    query_id: str
    requested_scale: VisualScale
    rendered_scale: VisualScale
    renderable: bool
    fidelity: FidelityClass
    origin: GeometryOrigin
    source_id: str
    source_observation_id: str
    representation_ids: list[VisualRepresentation]
    reason: str
    invariant len(query_id) > 0
    invariant len(representation_ids) <= 8
    invariant len(reason) > 0


pub def decide_semantic_zoom(query: ViewportQuery, sources: list[SemanticScaleSource]) -> SemanticZoomDecision !{}:
    for source in sources:
        if source.scale != query.requested_scale:
            continue
        if not source.available:
            return SemanticZoomDecision(query_id=query.query_id, requested_scale=query.requested_scale, rendered_scale=query.requested_scale, renderable=false, fidelity=FidelityClass.unknown, origin=GeometryOrigin.unknown, source_id=source.source_id, source_observation_id="", representation_ids=[], reason="requested scale has no admissible geometry source")
        if query.field_of_view_m < source.minimum_length_m or query.field_of_view_m > source.maximum_length_m:
            return SemanticZoomDecision(query_id=query.query_id, requested_scale=query.requested_scale, rendered_scale=query.requested_scale, renderable=false, fidelity=FidelityClass.unknown, origin=GeometryOrigin.unknown, source_id=source.source_id, source_observation_id=source.observation_id, representation_ids=[], reason="viewport field of view is outside the source scale interval")
        if source.observation_id != query.observation_id:
            return SemanticZoomDecision(query_id=query.query_id, requested_scale=query.requested_scale, rendered_scale=query.requested_scale, renderable=false, fidelity=FidelityClass.unknown, origin=GeometryOrigin.unknown, source_id=source.source_id, source_observation_id=source.observation_id, representation_ids=[], reason="scale source is stale for the current observation")
        if source.fidelity == FidelityClass.unknown or source.origin == GeometryOrigin.unknown or len(source.representation_ids) == 0:
            return SemanticZoomDecision(query_id=query.query_id, requested_scale=query.requested_scale, rendered_scale=query.requested_scale, renderable=false, fidelity=FidelityClass.unknown, origin=GeometryOrigin.unknown, source_id=source.source_id, source_observation_id=source.observation_id, representation_ids=[], reason="scale source lacks explicit fidelity, origin, or representation")
        return SemanticZoomDecision(query_id=query.query_id, requested_scale=query.requested_scale, rendered_scale=source.scale, renderable=true, fidelity=source.fidelity, origin=source.origin, source_id=source.source_id, source_observation_id=source.observation_id, representation_ids=source.representation_ids, reason="requested semantic scale is evidence-bound")
    return SemanticZoomDecision(query_id=query.query_id, requested_scale=query.requested_scale, rendered_scale=query.requested_scale, renderable=false, fidelity=FidelityClass.unknown, origin=GeometryOrigin.unknown, source_id="", source_observation_id="", representation_ids=[], reason="requested scale is absent from the resolution graph")
```

### `src/volume.sema`

```sema
"""Versioned cellular and tissue segment-volume frames for bounded live replay."""

from std.crypto import file_sha256

assure silver


pub struct BiologicalVolumeResult:
    schema: str
    profile_id: str
    config_sha256: str
    source_result_sha256: str
    result_sha256: str
    result_path: str
    frames: int
    frame_interval_s: f64
    cellular_voxels: int
    tissue_voxels: int
    cellular_segments: int
    tissue_segments: int
    scene_instances: int
    insulin_atoms: int
    scenario_count: int
    volume_payload_bytes: int
    deterministic_pass: bool
    source_binding_pass: bool
    phase10_technical_pass: bool
    scientific_validated: bool
    evidence_class: str
    invariant schema == "sema.biological-volume-result/v1"
    invariant len(profile_id) > 0
    invariant len(config_sha256) == 64
    invariant len(source_result_sha256) == 64
    invariant len(result_sha256) == 64
    invariant len(result_path) > 0
    invariant frames > 1 and frames <= 64
    invariant frame_interval_s > 0.0
    invariant cellular_voxels > 0 and cellular_voxels <= 131072
    invariant tissue_voxels > 0 and tissue_voxels <= 131072
    invariant cellular_segments > 0 and cellular_segments <= 32
    invariant tissue_segments > 0 and tissue_segments <= 16
    invariant scene_instances > 0 and scene_instances <= 16384
    invariant insulin_atoms > 0 and insulin_atoms <= 4096
    invariant scenario_count > 0 and scenario_count <= 16
    invariant volume_payload_bytes > 0 and volume_payload_bytes <= 4194304
    invariant evidence_class == "bounded_simulated_volume" or evidence_class == "failed_simulated_volume"


bridge python.inline volume_backend from "foreign/python/volume_backend.py":
    deps "python>=3.12,<3.13" "numpy>=2.4.1" "openmm>=8.5.0,<8.6.0"
    expose:
        def run_profile(config_path: str, output_path: str) -> BiologicalVolumeResult !{ffi.call}:
            sem "Generate source-bound segmented cellular and tissue volume frames for deterministic replay"
            ensure result.deterministic_pass
            ensure result.source_binding_pass
            ensure result.phase10_technical_pass
            ensure result.scientific_validated == false


pub def run_volume_profile(config_path: str, output_path: str) -> BiologicalVolumeResult !{ffi.call, fs.read, fs.write}:
    sem "Run the numerical volume kernel, then bind its artifact with a native Sema digest"
    ensure path.is_relative_to(output_path, "runs/volumes")
    generated = volume_backend.run_profile(config_path, output_path)
    digest = file_sha256(output_path)
    fs.write_text(output_path + ".sha256", digest + "  " + path.basename(output_path) + "\n")?
    return generated
```

## Reflected API

# `agent`

Proposal-only agent contract for bounded biological programming.

# `def propose_agent_program`

```sema
def propose_agent_program(payload: dict[str, any]) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def agent_capabilities`

```sema
def agent_capabilities() -> dict[str, any] !{}
```

**Returns** `dict[str, any]`

**Effects** `!{}`



# `api`

Canonical HTTP contract emitted with every biological-computer scene.

# `def biological_api_contract`

```sema
def biological_api_contract() -> dict[str, any] !{}
```

**Returns** `dict[str, any]`

**Effects** `!{}`



# `assurance`

Behavioral assurance gates for the multiscale biological-computer contracts.

# `def digest`

```sema
def digest()
```

# `def evidence`

```sema
def evidence(id: str, accepted: bool)
```

**Parameters**

| name | type |
|---|---|
| `id` | `str` |
| `accepted` | `bool` |

# `def alanine_topology`

```sema
def alanine_topology()
```

# `def approximation`

```sema
def approximation(valid: bool, maximum_error: f64)
```

**Parameters**

| name | type |
|---|---|
| `valid` | `bool` |
| `maximum_error` | `f64` |

# `def coarse_edge`

```sema
def coarse_edge(contract: ApproximationContract)
```

**Parameters**

| name | type |
|---|---|
| `contract` | `ApproximationContract` |

# `def learned_manifest`

```sema
def learned_manifest(output_unit: str)
```

**Parameters**

| name | type |
|---|---|
| `output_unit` | `str` |

# `def hybrid_term`

```sema
def hybrid_term()
```

# `def calibrated_uncertainty`

```sema
def calibrated_uncertainty()
```

# `def assess`

```sema
def assess(manifest: LearnedModelManifest, applicability: ApplicabilityDecision, gate: f64, uncertainty: PredictionUncertainty)
```

**Parameters**

| name | type |
|---|---|
| `manifest` | `LearnedModelManifest` |
| `applicability` | `ApplicabilityDecision` |
| `gate` | `f64` |
| `uncertainty` | `PredictionUncertainty` |

# `def search_boundary`

```sema
def search_boundary()
```

# `def interaction_candidate`

```sema
def interaction_candidate(compute_units: int)
```

**Parameters**

| name | type |
|---|---|
| `compute_units` | `int` |



# `binding`

Bounded, deterministic ligand/target docking and designed-species physiology coupling.

Every number produced here is an empirical rank, never a measurement. The scoring function and
its calibration constants are published on each result so a reader can see exactly how a score
becomes a free energy, and every payload carries `scientific_validated: false`.

# `def lj_parameters`

```sema
def lj_parameters(atomic_number: int)
```

**Parameters**

| name | type |
|---|---|
| `atomic_number` | `int` |

OPLS-AA style [sigma in Angstrom, epsilon in kJ/mol]; unmapped elements fall back to carbon.

# `def partial_charge`

```sema
def partial_charge(atomic_number: int, degree: int, polar_neighbours: int)
```

**Parameters**

| name | type |
|---|---|
| `atomic_number` | `int` |
| `degree` | `int` |
| `polar_neighbours` | `int` |

Bounded element-plus-bond-context charge in elementary charge units; no QM, no force-field fit.

# `def partial_charges`

```sema
def partial_charges(atomic_numbers: list[int], bond_pairs: list[int])
```

**Parameters**

| name | type |
|---|---|
| `atomic_numbers` | `list[int]` |
| `bond_pairs` | `list[int]` |

# `def bounding_box`

```sema
def bounding_box(x: list[f64], y: list[f64], z: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `x` | `list[f64]` |
| `y` | `list[f64]` |
| `z` | `list[f64]` |

# `def neighbour_grid`

```sema
def neighbour_grid(x: list[f64], y: list[f64], z: list[f64], cell_size: f64, minimum: list[f64], maximum: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `x` | `list[f64]` |
| `y` | `list[f64]` |
| `z` | `list[f64]` |
| `cell_size` | `f64` |
| `minimum` | `list[f64]` |
| `maximum` | `list[f64]` |

Uniform bucket grid in compressed-row form: `starts[cell]..starts[cell + 1]` indexes `entries`.

# `def probe_metrics`

```sema
def probe_metrics(grid: dict[str, any], x: list[f64], y: list[f64], z: list[f64], point: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `grid` | `dict[str, any]` |
| `x` | `list[f64]` |
| `y` | `list[f64]` |
| `z` | `list[f64]` |
| `point` | `list[f64]` |

One grid walk yielding [atoms within 8 A, atoms within 3 A, distance to the closest atom].

# `def pocket_site`

```sema
def pocket_site(grid: dict[str, any], x: list[f64], y: list[f64], z: list[f64]) -> dict[str, any]
```

**Parameters**

| name | type |
|---|---|
| `grid` | `dict[str, any]` |
| `x` | `list[f64]` |
| `y` | `list[f64]` |
| `z` | `list[f64]` |

**Returns** `dict[str, any]`

Highest-buriedness placeable grid point, refined on a local sub-lattice and averaged over its cluster.

A probe is placeable when its closest target atom sits in
[POCKET_MIN_CLEARANCE_ANGSTROM, POCKET_MAX_CLEARANCE_ANGSTROM]: close enough to be a surface
cavity rather than bulk solvent, open enough for a ligand heavy atom to occupy. Without that
filter the verbatim argmax lands in the protein core (measured on 6S34: clearance 0.67 Angstrom),
where every pose clashes.

# `def quaternion_from_axis_angle`

```sema
def quaternion_from_axis_angle(axis: list[f64], angle: f64)
```

**Parameters**

| name | type |
|---|---|
| `axis` | `list[f64]` |
| `angle` | `f64` |

# `def quaternion_multiply`

```sema
def quaternion_multiply(left: list[f64], right: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `left` | `list[f64]` |
| `right` | `list[f64]` |

# `def rotation_from_quaternion`

```sema
def rotation_from_quaternion(q: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `q` | `list[f64]` |

Row-major 3x3 rotation matrix from a unit quaternion [w, x, y, z].

# `def golden_spiral_axis`

```sema
def golden_spiral_axis(index: int, count: int)
```

**Parameters**

| name | type |
|---|---|
| `index` | `int` |
| `count` | `int` |

Deterministic quasi-uniform unit axis; the spiral increment is the golden angle pi (3 - sqrt 5).

# `def translation_lattice`

```sema
def translation_lattice(half_extent: f64)
```

**Parameters**

| name | type |
|---|---|
| `half_extent` | `f64` |

Nine deterministic offsets: the pocket point plus the eight corners of a cube around it.

# `def posed_coordinates`

```sema
def posed_coordinates(probe: dict[str, any], rotation: list[f64], center: list[f64], translation: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `probe` | `dict[str, any]` |
| `rotation` | `list[f64]` |
| `center` | `list[f64]` |
| `translation` | `list[f64]` |

# `def score_pose`

```sema
def score_pose(field: dict[str, any], probe: dict[str, any], pose: list[list[f64]])
```

**Parameters**

| name | type |
|---|---|
| `field` | `dict[str, any]` |
| `probe` | `dict[str, any]` |
| `pose` | `list[list[f64]]` |

Interaction terms [lennard_jones, coulomb, hydrophobic, clash] in kJ/mol for one rigid pose.

Cost is O(n_ligand * k) where k is the number of shell atoms in the grid cells overlapping an
8 Angstrom sphere. The grid holds the pocket shell only, so k tracks local packing density and
never the target atom count: a 3948-atom target costs the same as a 796-atom one.

# `def pose_energy`

```sema
def pose_energy(field: dict[str, any], probe: dict[str, any], pose: list[list[f64]])
```

**Parameters**

| name | type |
|---|---|
| `field` | `dict[str, any]` |
| `probe` | `dict[str, any]` |
| `pose` | `list[list[f64]]` |

# `def refined_state`

```sema
def refined_state(field: dict[str, any], probe: dict[str, any], center: list[f64], base: list[f64], start: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `field` | `dict[str, any]` |
| `probe` | `dict[str, any]` |
| `center` | `list[f64]` |
| `base` | `list[f64]` |
| `start` | `list[f64]` |

Bounded local coordinate descent over three translations and three body-frame rotations.

# `def descent_quaternion`

```sema
def descent_quaternion(base: list[f64], state: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `base` | `list[f64]` |
| `state` | `list[f64]` |

Enumerated orientation composed with the descent's body-frame x, y, then z rotations.

# `def structure_positions`

```sema
def structure_positions(structure: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `structure` | `dict[str, any]` |

# `def structure_bonds`

```sema
def structure_bonds(structure: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `structure` | `dict[str, any]` |

# `def docking_rejection`

```sema
def docking_rejection(target: dict[str, any], ligand: dict[str, any], budget: int) -> str !{}
```

**Parameters**

| name | type |
|---|---|
| `target` | `dict[str, any]` |
| `ligand` | `dict[str, any]` |
| `budget` | `int` |

**Returns** `str`

**Effects** `!{}`

Empty string when the pair is dockable, otherwise the reason a caller should report as 422.

# `def clamped_budget`

```sema
def clamped_budget(budget: int)
```

**Parameters**

| name | type |
|---|---|
| `budget` | `int` |

# `def target_field`

```sema
def target_field(target: dict[str, any], center: list[f64], pose_reach: f64)
```

**Parameters**

| name | type |
|---|---|
| `target` | `dict[str, any]` |
| `center` | `list[f64]` |
| `pose_reach` | `f64` |

Pocket shell: every target atom a posed ligand atom could reach, with its grid and Verlet lists.

# `def ligand_probe`

```sema
def ligand_probe(ligand: dict[str, any]) -> dict[str, any]
```

**Parameters**

| name | type |
|---|---|
| `ligand` | `dict[str, any]` |

**Returns** `dict[str, any]`

Ligand recentred on its centroid; the internal geometry is never re-optimised (rigid ligand).

# `def pose_contacts`

```sema
def pose_contacts(field: dict[str, any], pose: list[list[f64]])
```

**Parameters**

| name | type |
|---|---|
| `field` | `dict[str, any]` |
| `pose` | `list[list[f64]]` |

The MAX_CONTACTS shortest ligand/target contacts under CONTACT_DISTANCE_ANGSTROM, nearest first.

# `def buried_ligand_fraction`

```sema
def buried_ligand_fraction(field: dict[str, any], pose: list[list[f64]])
```

**Parameters**

| name | type |
|---|---|
| `field` | `dict[str, any]` |
| `pose` | `list[list[f64]]` |

# `def free_energy_kj_mol`

```sema
def free_energy_kj_mol(score: f64) -> f64 !{}
```

**Parameters**

| name | type |
|---|---|
| `score` | `f64` |

**Returns** `f64`

**Effects** `!{}`

# `def dissociation_constant_micromolar`

```sema
def dissociation_constant_micromolar(delta_g_kj_mol: f64) -> f64 !{}
```

**Parameters**

| name | type |
|---|---|
| `delta_g_kj_mol` | `f64` |

**Returns** `f64`

**Effects** `!{}`

Kd = exp(dG / RT) * 1e6 uM at 310.15 K, clamped to the published reporting window.

# `def dock_ligand`

```sema
def dock_ligand(target: dict[str, any], ligand: dict[str, any], budget: int) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `target` | `dict[str, any]` |
| `ligand` | `dict[str, any]` |
| `budget` | `int` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def occupancy_fraction`

```sema
def occupancy_fraction(kd_micromolar: f64, concentration_micromolar: f64) -> f64 !{}
```

**Parameters**

| name | type |
|---|---|
| `kd_micromolar` | `f64` |
| `concentration_micromolar` | `f64` |

**Returns** `f64`

**Effects** `!{}`

# `def binding_mechanisms`

```sema
def binding_mechanisms() -> list[str] !{}
```

**Returns** `list[str]`

**Effects** `!{}`

# `def bounded_multiplier`

```sema
def bounded_multiplier(name: str, multiplier: f64)
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |
| `multiplier` | `f64` |

Cap a multiplier so the published baseline parameter stays inside its physiology bound.

# `def species_effect`

```sema
def species_effect(mechanism: str, occupancy: f64) -> dict[str, f64] !{}
```

**Parameters**

| name | type |
|---|---|
| `mechanism` | `str` |
| `occupancy` | `f64` |

**Returns** `dict[str, f64]`

**Effects** `!{}`

Physiology couplings keyed by effect kind.

`parameter:<name>` multiplies that physiology parameter, `signal_max:<name>` raises the signal
to at least the value, `signal_add:<name>` adds to it. Occupancy is clamped to [0, 1] and every
value here is already bounded against the published baseline, so applying it to the source
parameters can never leave `physiology_parameter_bounds()`; `apply_species_effects` clamps again
against whatever the live parameters happen to be.

# `def signal_ceiling`

```sema
def signal_ceiling(name: str)
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |

Upper bounds mirror the signal table in programming.sema; species may never exceed them.

# `def apply_species_effects`

```sema
def apply_species_effects(parameters: dict[str, f64], signals: dict[str, f64], registry: dict[str, any]) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `parameters` | `dict[str, f64]` |
| `signals` | `dict[str, f64]` |
| `registry` | `dict[str, any]` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def initial_species_registry`

```sema
def initial_species_registry() -> dict[str, any] !{}
```

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def species_registration_error`

```sema
def species_registration_error(registry: dict[str, any], spec: dict[str, any], docking: dict[str, any], concentration_micromolar: f64, mechanism: str) -> dict[str, str] !{}
```

**Parameters**

| name | type |
|---|---|
| `registry` | `dict[str, any]` |
| `spec` | `dict[str, any]` |
| `docking` | `dict[str, any]` |
| `concentration_micromolar` | `f64` |
| `mechanism` | `str` |

**Returns** `dict[str, str]`

**Effects** `!{}`

`{"error": "", "detail": ""}` when the species may be introduced, otherwise the typed refusal.

# `def register_species`

```sema
def register_species(registry: dict[str, any], spec: dict[str, any], structure: dict[str, any], docking: dict[str, any], concentration_micromolar: f64, mechanism: str, introduced_at_days: f64) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `registry` | `dict[str, any]` |
| `spec` | `dict[str, any]` |
| `structure` | `dict[str, any]` |
| `docking` | `dict[str, any]` |
| `concentration_micromolar` | `f64` |
| `mechanism` | `str` |
| `introduced_at_days` | `f64` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def species_public_state`

```sema
def species_public_state(registry: dict[str, any]) -> list[dict[str, any]] !{}
```

**Parameters**

| name | type |
|---|---|
| `registry` | `dict[str, any]` |

**Returns** `list[dict[str, any]]`

**Effects** `!{}`

# `def binding_capabilities`

```sema
def binding_capabilities() -> dict[str, any] !{}
```

**Returns** `dict[str, any]`

**Effects** `!{}`



# `coarse`

Periodic phi/psi coarse-state mapping with explicit sampling diagnostics.

# `struct CoarseStateResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `analysis_id` | `str` |  |
| `config_sha256` | `str` |  |
| `source_frames_sha256` | `str` |  |
| `source_model_sha256` | `str` |  |
| `source_parameter_sha256` | `str` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |
| `samples` | `int` |  |
| `basin_ids` | `list[str]` |  |
| `counts` | `list[int]` |  |
| `transition_counts` | `list[int]` |  |
| `transitions` | `int` |  |
| `observed_basins` | `int` |  |
| `lag_frames` | `int` |  |
| `pseudocount` | `f64` |  |
| `free_energy_kj_mol` | `list[f64]` |  |
| `effective_samples` | `f64` |  |
| `mapping_validated` | `bool` |  |
| `sampling_converged` | `bool` |  |
| `evidence_class` | `str` |  |

# `bridge coarse_backend`



# `cortex`

Governed proposal-only Cortex bridge with native Sema contract revalidation.

# `bridge cortex_sdk_backend`

# `def cortex_units`

```sema
def cortex_units()
```

# `def cortex_operation_error`

```sema
def cortex_operation_error(operation: any) !{}
```

**Parameters**

| name | type |
|---|---|
| `operation` | `any` |

**Effects** `!{}`

# `def cortex_proposal_error`

```sema
def cortex_proposal_error(proposal: any) !{}
```

**Parameters**

| name | type |
|---|---|
| `proposal` | `any` |

**Effects** `!{}`

# `def propose_cortex`

```sema
def propose_cortex(payload: any) -> dict[str, any] !{ffi.call}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `any` |

**Returns** `dict[str, any]`

**Effects** `!{ffi.call}`

# `def cortex_capabilities`

```sema
def cortex_capabilities() -> dict[str, any] !{}
```

**Returns** `dict[str, any]`

**Effects** `!{}`



# `design`

Bounded de-novo molecular design: natural-language specs turned into computed geometry.

Everything here is exploratory engineering, never a measurement. Structures are built from
published internal coordinates by natural-extension-reference-frame placement and a bounded
steepest-descent relaxation, so every coordinate is computed rather than copied from a table of
positions. Designed structures therefore carry `fidelity: "engineered_unvalidated"`,
`biological_match: "designed_de_novo"` and `scientific_validated: false` downstream: no claim is
made that any of these molecules exists, folds, or binds.

# `def design_target_keys`

```sema
def design_target_keys()
```

# `def design_mechanisms`

```sema
def design_mechanisms()
```

# `def design_fragment_names`

```sema
def design_fragment_names()
```

# `def listed`

```sema
def listed(values: list[str], value: str)
```

**Parameters**

| name | type |
|---|---|
| `values` | `list[str]` |
| `value` | `str` |

# `def element_name`

```sema
def element_name(atomic_number: int)
```

**Parameters**

| name | type |
|---|---|
| `atomic_number` | `int` |

# `def atomic_radius`

```sema
def atomic_radius(atomic_number: int, radius_kind: str)
```

**Parameters**

| name | type |
|---|---|
| `atomic_number` | `int` |
| `radius_kind` | `str` |

# `def unit_vector`

```sema
def unit_vector(vector: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `vector` | `list[f64]` |

# `def cross`

```sema
def cross(left: list[f64], right: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `left` | `list[f64]` |
| `right` | `list[f64]` |

# `def difference`

```sema
def difference(from_point: list[f64], to_point: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `from_point` | `list[f64]` |
| `to_point` | `list[f64]` |

# `def point_at`

```sema
def point_at(positions: list[f64], atom_index: int)
```

**Parameters**

| name | type |
|---|---|
| `positions` | `list[f64]` |
| `atom_index` | `int` |

# `def place_atom`

```sema
def place_atom(first: list[f64], second: list[f64], third: list[f64], bond_angstrom: f64, angle_degree: f64, dihedral_degree: f64)
```

**Parameters**

| name | type |
|---|---|
| `first` | `list[f64]` |
| `second` | `list[f64]` |
| `third` | `list[f64]` |
| `bond_angstrom` | `f64` |
| `angle_degree` | `f64` |
| `dihedral_degree` | `f64` |

# `def rotation_between`

```sema
def rotation_between(source: list[f64], target: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `source` | `list[f64]` |
| `target` | `list[f64]` |

Rodrigues rotation matrix (row-major, flat 9) carrying unit `source` onto unit `target`.

# `def rotated`

```sema
def rotated(matrix: list[f64], vector: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `matrix` | `list[f64]` |
| `vector` | `list[f64]` |

# `def residue_three_letter`

```sema
def residue_three_letter(code: str)
```

**Parameters**

| name | type |
|---|---|
| `code` | `str` |

# `def residue_charge`

```sema
def residue_charge(code: str)
```

**Parameters**

| name | type |
|---|---|
| `code` | `str` |

Side-chain formal charge at pH 7.4; the free N- and C-termini cancel and are omitted.

# `def residue_sidechains`

```sema
def residue_sidechains()
```

Truncated side chains beyond C-beta as internal coordinates.

Every row is `[atom name, atomic number, torsion reference, angle reference, bonded parent,
bond length in angstrom, valence angle in degrees, torsion in degrees]`; references -3, -2 and
-1 are backbone N, CA and CB and a non-negative reference is an earlier row of the same
residue. At most four heavy atoms are emitted per side chain, so anything past the delta shell
is truncated - the structure declares this through `sidechain_model`.

# `def fragment_template`

```sema
def fragment_template(name: str) -> dict[str, any]
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |

**Returns** `dict[str, any]`

Literature internal coordinates for one attachable fragment.

Rings are generated from their bond length and ring size; every other atom is an
`[name, atomic number, torsion reference, angle reference, bonded parent, bond, angle,
torsion]` row placed by the same reference-frame routine as the peptide backbone. References
-2 and -1 are the two virtual seed points that define the incoming bond direction, a
non-negative reference indexes an atom already placed in this fragment, and a zero bond length
means the atom is the fragment head sitting at the local origin. `head` bonds to the previous
fragment and `tail` carries the growing chain onward.

# `def build_fragment`

```sema
def build_fragment(name: str)
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |

Instantiate one fragment in a local frame with its head at the origin and its head-to-tail
axis on +x, so the chain builder can drop it onto a growth direction with one rotation.

# `def new_build`

```sema
def new_build()
```

# `def add_atom`

```sema
def add_atom(built: dict[str, any], position: list[f64], atomic_number: int, label: str, mobile: bool, group: int) !{}
```

**Parameters**

| name | type |
|---|---|
| `built` | `dict[str, any]` |
| `position` | `list[f64]` |
| `atomic_number` | `int` |
| `label` | `str` |
| `mobile` | `bool` |
| `group` | `int` |

**Effects** `!{}`

# `def add_bond`

```sema
def add_bond(built: dict[str, any], left: int, right: int) !{}
```

**Parameters**

| name | type |
|---|---|
| `built` | `dict[str, any]` |
| `left` | `int` |
| `right` | `int` |

**Effects** `!{}`

# `def build_peptide`

```sema
def build_peptide(spec: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `spec` | `dict[str, any]` |

**Effects** `!{}`

Grow the backbone and truncated side chains residue by residue from standard internal
coordinates; only the side-chain atoms are later relaxed so the backbone torsions stay exact.

# `def build_molecule`

```sema
def build_molecule(spec: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `spec` | `dict[str, any]` |

**Effects** `!{}`

Attach fragment templates head to tail along a zig-zagging growth axis so the initial guess
is an extended chain rather than a stack; the relaxation then resolves the linkage geometry.

# `def restraint_field`

```sema
def restraint_field(built: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `built` | `dict[str, any]` |

Harmonic 1-2 bonds at their as-built length plus 1-3 Urey-Bradley terms.

Inside a fragment or a residue the 1-3 rest length is the template distance, so the published
fragment geometry is preserved exactly. Across a head-to-tail link there is no template angle,
so the rest length comes from the law of cosines on the two bond lengths and the ideal valence
angle for the central atom's coordination number.

# `def rebuild_neighbours`

```sema
def rebuild_neighbours(field: dict[str, any], positions: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `field` | `dict[str, any]` |
| `positions` | `list[f64]` |

Verlet candidate list: only pairs inside the repulsive core plus a skin can ever clash, and
a pair of frozen atoms contributes a constant energy so it never changes the line search.

# `def relaxation_energy`

```sema
def relaxation_energy(field: dict[str, any], positions: list[f64], forces: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `field` | `dict[str, any]` |
| `positions` | `list[f64]` |
| `forces` | `list[f64]` |

Harmonic restraints plus a purely repulsive r^-12 core truncated and shifted to zero at
`CLASH_CORE_ANGSTROM`. Fills `forces` with -dE/dx and returns the energy in kJ/mol.

# `def minimise`

```sema
def minimise(field: dict[str, any], positions: list[f64], max_steps: int, epsilon: f64)
```

**Parameters**

| name | type |
|---|---|
| `field` | `dict[str, any]` |
| `positions` | `list[f64]` |
| `max_steps` | `int` |
| `epsilon` | `f64` |

Bounded steepest descent with a backtracking step: accept a trial move only when it lowers
the energy, otherwise shrink the step. Deterministic and capped at `max_steps` evaluations.

# `def minimum_free_separation`

```sema
def minimum_free_separation(field: dict[str, any], positions: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `field` | `dict[str, any]` |
| `positions` | `list[f64]` |

Closest approach over heavy-atom pairs that are more than two bonds apart; 1-2 and 1-3 pairs
are covalent geometry (a ring's meta carbons sit at 2.4 angstrom by construction) and excluded.

# `def relax_build`

```sema
def relax_build(built: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `built` | `dict[str, any]` |

# `def design_compile_error`

```sema
def design_compile_error(detail: str)
```

**Parameters**

| name | type |
|---|---|
| `detail` | `str` |

# `def spec_core`

```sema
def spec_core(name: str, label: str, design_class: str, conformation: str, sequence: str, fragments: list[str], target_key: str, mechanism: str, charge_e: f64)
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |
| `label` | `str` |
| `design_class` | `str` |
| `conformation` | `str` |
| `sequence` | `str` |
| `fragments` | `list[str]` |
| `target_key` | `str` |
| `mechanism` | `str` |
| `charge_e` | `f64` |

# `def sealed_spec`

```sema
def sealed_spec(core: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `core` | `dict[str, any]` |

**Effects** `!{}`

# `def targeting_suffix`

```sema
def targeting_suffix(target_key: str)
```

**Parameters**

| name | type |
|---|---|
| `target_key` | `str` |

# `def peptide_spec`

```sema
def peptide_spec(form: str, raw_sequence: str, name: str, target_key: str) !{}
```

**Parameters**

| name | type |
|---|---|
| `form` | `str` |
| `raw_sequence` | `str` |
| `name` | `str` |
| `target_key` | `str` |

**Effects** `!{}`

# `def molecule_spec`

```sema
def molecule_spec(raw_fragments: str, name: str, target_key: str) !{}
```

**Parameters**

| name | type |
|---|---|
| `raw_fragments` | `str` |
| `name` | `str` |
| `target_key` | `str` |

**Effects** `!{}`

# `def compile_design_command`

```sema
def compile_design_command(command: str) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `command` | `str` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def design_name_valid`

```sema
def design_name_valid(name: str)
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |

# `def design_spec_valid`

```sema
def design_spec_valid(spec: dict[str, any]) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `spec` | `dict[str, any]` |

**Returns** `bool`

**Effects** `!{}`

# `def design_capabilities`

```sema
def design_capabilities() -> dict[str, any] !{}
```

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def build_designed_structure`

```sema
def build_designed_structure(spec: dict[str, any]) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `spec` | `dict[str, any]` |

**Returns** `dict[str, any]`

**Effects** `!{}`



# `discovery`

Bounded computational-discovery lineage, gates, and honest result classes.

# `enum CandidateKind`

**Variants**

- `molecule`
- `bond`
- `interaction`
- `circuit`
- `equation_change`
- `experiment`

# `enum CandidateStatus`

**Variants**

- `proposed`
- `rejected`
- `admitted`
- `simulated`
- `ranked`
- `blocked`

# `enum CandidateClaim`

**Variants**

- `unseen_in_bounded_search`
- `predicted_interaction`
- `simulated_association`
- `experimentally_supported`
- `clinical`

# `struct SearchBoundary`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `description` | `str` |  |
| `allowed_kinds` | `list[CandidateKind]` |  |
| `max_candidates` | `int` |  |
| `max_rounds` | `int` |  |
| `max_compute_units` | `int` |  |
| `prior_art_sources` | `list[str]` |  |
| `safety_policy_id` | `str` |  |

# `struct DiscoveryBatch`

**Fields**

| field | type | descriptor |
|---|---|---|
| `boundary_id` | `str` |  |
| `round_index` | `int` |  |
| `candidate_ids` | `list[str]` |  |
| `requested_compute_units` | `int` |  |

# `struct CandidateHypothesis`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `parent_ids` | `list[str]` |  |
| `kind` | `CandidateKind` |  |
| `representation_digest` | `str` |  |
| `rationale` | `str` |  |
| `provenance_ids` | `list[str]` |  |
| `prior_art_scope_id` | `str` |  |
| `model_id` | `str` |  |
| `model_version` | `int` |  |
| `equation_graph_id` | `str` |  |
| `equation_version` | `int` |  |
| `uncertainty` | `f64` |  |
| `requested_compute_units` | `int` |  |
| `status` | `CandidateStatus` |  |
| `rejection_reasons` | `list[str]` |  |

# `struct CandidateEvidence`

**Fields**

| field | type | descriptor |
|---|---|---|
| `candidate_id` | `str` |  |
| `observation_ids` | `list[str]` |  |
| `oracle_evidence_ids` | `list[str]` |  |
| `prior_art_evidence_ids` | `list[str]` |  |
| `objective_names` | `list[str]` |  |
| `objective_values` | `list[f64]` |  |
| `uncertainty` | `f64` |  |
| `information_gain` | `f64` |  |
| `claim` | `CandidateClaim` |  |
| `status` | `CandidateStatus` |  |

# `def within_boundary`

```sema
def within_boundary(candidate: CandidateHypothesis, boundary: SearchBoundary)
```

**Parameters**

| name | type |
|---|---|
| `candidate` | `CandidateHypothesis` |
| `boundary` | `SearchBoundary` |

# `def validate_discovery_batch`

```sema
def validate_discovery_batch(batch: DiscoveryBatch, candidates: list[CandidateHypothesis], boundary: SearchBoundary) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `batch` | `DiscoveryBatch` |
| `candidates` | `list[CandidateHypothesis]` |
| `boundary` | `SearchBoundary` |

**Returns** `bool`

**Effects** `!{}`

# `def reject_candidate`

```sema
def reject_candidate(candidate: CandidateHypothesis, reason: str)
```

**Parameters**

| name | type |
|---|---|
| `candidate` | `CandidateHypothesis` |
| `reason` | `str` |

# `def admit_candidate`

```sema
def admit_candidate(candidate: CandidateHypothesis, boundary: SearchBoundary, chemistry_valid: bool, topology_valid: bool, applicability_valid: bool, evidence_valid: bool, safety_valid: bool) -> CandidateHypothesis !{}
```

**Parameters**

| name | type |
|---|---|
| `candidate` | `CandidateHypothesis` |
| `boundary` | `SearchBoundary` |
| `chemistry_valid` | `bool` |
| `topology_valid` | `bool` |
| `applicability_valid` | `bool` |
| `evidence_valid` | `bool` |
| `safety_valid` | `bool` |

**Returns** `CandidateHypothesis`

**Effects** `!{}`

# `def may_report_claim`

```sema
def may_report_claim(evidence: CandidateEvidence) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `evidence` | `CandidateEvidence` |

**Returns** `bool`

**Effects** `!{}`



# `domain`

Typed physical identities, topology, backend profiles, observations, and phase evidence.

# `enum PhaseState`

**Variants**

- `not_started`
- `implemented_unvalidated`
- `validated`
- `blocked`

# `enum EntityKind`

**Variants**

- `particle`
- `atom`
- `residue`
- `molecule`
- `ensemble`
- `coarse_state`
- `field`
- `membrane`
- `organelle`
- `cell`
- `tissue`

# `enum ModelScale`

**Variants**

- `quantum`
- `atomistic`
- `coarse`
- `mesoscopic`
- `network`
- `cellular`
- `tissue`

# `enum ResultClass`

**Variants**

- `validated`
- `calibrated`
- `exploratory`
- `unknown`
- `invalid`
- `failed`

# `enum ReplayClass`

**Variants**

- `exact`
- `deterministic_tolerance`
- `statistical`
- `unavailable`

# `enum EvidenceKind`

**Variants**

- `computational`
- `structural`
- `ensemble`
- `experimental`
- `performance`
- `negative`

# `enum InteractionMethod`

**Variants**

- `classical_fixed_topology`
- `reactive_force_field`
- `learned_potential`
- `quantum`
- `qmmm`
- `particle_reaction_diffusion`

# `enum PropertyValueKind`

**Variants**

- `scalar`
- `vector`
- `tensor`
- `per_atom`
- `categorical`
- `distribution`

# `enum ReactionState`

**Variants**

- `proposed`
- `parameterized`
- `computed`
- `validated`
- `blocked`

# `struct Vector3`

**Fields**

| field | type | descriptor |
|---|---|---|
| `x` | `f64` |  |
| `y` | `f64` |  |
| `z` | `f64` |  |

# `struct Atom`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `index` | `int` |  |
| `element` | `str` |  |
| `residue` | `str` |  |
| `mass_da` | `f64` |  |
| `charge_e` | `f64` |  |
| `position_nm` | `Vector3` |  |

# `struct Bond`

**Fields**

| field | type | descriptor |
|---|---|---|
| `left_index` | `int` |  |
| `right_index` | `int` |  |
| `order` | `int` |  |

# `struct PeriodicBox`

**Fields**

| field | type | descriptor |
|---|---|---|
| `x_nm` | `f64` |  |
| `y_nm` | `f64` |  |
| `z_nm` | `f64` |  |

# `struct MolecularTopology`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `atoms` | `list[Atom]` |  |
| `bonds` | `list[Bond]` |  |
| `box` | `PeriodicBox` |  |
| `source_sha256` | `str` |  |

# `struct BackendProfile`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `engine` | `str` |  |
| `version` | `str` |  |
| `platform` | `str` |  |
| `precision` | `str` |  |
| `properties` | `list[str]` |  |
| `artifact_sha256` | `str` |  |
| `replay` | `ReplayClass` |  |

# `struct EvidenceRecord`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `kind` | `EvidenceKind` |  |
| `source` | `str` |  |
| `summary` | `str` |  |
| `artifact_sha256` | `str` |  |
| `observed_at_s` | `f64` |  |
| `accepted` | `bool` |  |

# `struct InteractionTerm`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `family` | `str` |  |
| `owner_model_id` | `str` |  |
| `active` | `bool` |  |
| `target_observable` | `str` |  |
| `evidence_ids` | `list[str]` |  |

# `struct MolecularProperty`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `entity_id` | `str` |  |
| `property_name` | `str` |  |
| `scope_id` | `str` |  |
| `value_kind` | `PropertyValueKind` |  |
| `values` | `list[f64]` |  |
| `labels` | `list[str]` |  |
| `shape` | `list[int]` |  |
| `unit_symbol` | `str` |  |
| `uncertainty` | `f64` |  |
| `conditions` | `list[str]` |  |
| `method_profile_id` | `str` |  |
| `evidence_ids` | `list[str]` |  |
| `valid` | `bool` |  |

# `struct InteractionProfile`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `method` | `InteractionMethod` |  |
| `engine` | `str` |  |
| `version` | `str` |  |
| `parameter_sha256` | `str` |  |
| `scope_id` | `str` |  |
| `supported_elements` | `list[str]` |  |
| `properties` | `list[str]` |  |
| `minimum_atoms` | `int` |  |
| `maximum_atoms` | `int` |  |
| `conditions` | `list[str]` |  |
| `supports_topology_change` | `bool` |  |
| `qualified` | `bool` |  |
| `uncertainty_policy` | `str` |  |
| `evidence_ids` | `list[str]` |  |

# `struct ReactionProposal`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `reactant_topology_sha256` | `str` |  |
| `product_topology_sha256` | `str` |  |
| `elements` | `list[str]` |  |
| `atom_map` | `list[int]` |  |
| `total_charge` | `int` |  |
| `spin_multiplicity` | `int` |  |
| `profile_id` | `str` |  |
| `scope_id` | `str` |  |
| `conditions` | `list[str]` |  |
| `evidence_ids` | `list[str]` |  |

# `struct ReactionDecision`

**Fields**

| field | type | descriptor |
|---|---|---|
| `proposal_id` | `str` |  |
| `state` | `ReactionState` |  |
| `admissible` | `bool` |  |
| `profile_id` | `str` |  |
| `reason` | `str` |  |

# `struct ObservationFrame`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `run_id` | `str` |  |
| `state_version` | `int` |  |
| `step` | `int` |  |
| `physical_time_ps` | `f64` |  |
| `potential_energy_kj_mol` | `f64` |  |
| `kinetic_energy_kj_mol` | `f64` |  |
| `max_force_kj_mol_nm` | `f64` |  |
| `phi_rad` | `f64` |  |
| `psi_rad` | `f64` |  |
| `backend_profile_id` | `str` |  |
| `evidence_ids` | `list[str]` |  |

# `struct PhaseEvidence`

**Fields**

| field | type | descriptor |
|---|---|---|
| `phase` | `int` |  |
| `state` | `PhaseState` |  |
| `profile_id` | `str` |  |
| `positive_evidence` | `list[str]` |  |
| `negative_evidence` | `list[str]` |  |
| `blockers` | `list[str]` |  |

# `def distinct_atom_ids`

```sema
def distinct_atom_ids(atoms: list[Atom])
```

**Parameters**

| name | type |
|---|---|
| `atoms` | `list[Atom]` |

# `def bonds_reference_atoms`

```sema
def bonds_reference_atoms(topology: MolecularTopology)
```

**Parameters**

| name | type |
|---|---|
| `topology` | `MolecularTopology` |

# `def topology_valid`

```sema
def topology_valid(topology: MolecularTopology) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `topology` | `MolecularTopology` |

**Returns** `bool`

**Effects** `!{}`

# `def interaction_ownership_valid`

```sema
def interaction_ownership_valid(terms: list[InteractionTerm]) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `terms` | `list[InteractionTerm]` |

**Returns** `bool`

**Effects** `!{}`

# `def profile_supports_elements`

```sema
def profile_supports_elements(profile: InteractionProfile, elements: list[str])
```

**Parameters**

| name | type |
|---|---|
| `profile` | `InteractionProfile` |
| `elements` | `list[str]` |

# `def reaction_atom_map_valid`

```sema
def reaction_atom_map_valid(proposal: ReactionProposal)
```

**Parameters**

| name | type |
|---|---|
| `proposal` | `ReactionProposal` |

# `def molecular_property_admissible`

```sema
def molecular_property_admissible(property: MolecularProperty, profile: InteractionProfile)
```

**Parameters**

| name | type |
|---|---|
| `property` | `MolecularProperty` |
| `profile` | `InteractionProfile` |

# `def admit_reaction`

```sema
def admit_reaction(proposal: ReactionProposal, profile: InteractionProfile)
```

**Parameters**

| name | type |
|---|---|
| `proposal` | `ReactionProposal` |
| `profile` | `InteractionProfile` |

# `def phase_validated`

```sema
def phase_validated(phase: PhaseEvidence) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `phase` | `PhaseEvidence` |

**Returns** `bool`

**Effects** `!{}`

# `def blocked_phase`

```sema
def blocked_phase(phase: int, profile_id: str, reason: str)
```

**Parameters**

| name | type |
|---|---|
| `phase` | `int` |
| `profile_id` | `str` |
| `reason` | `str` |



# `dynamics`

Sema-owned multiscale dynamics, model admission, control, and solver evidence.

# `struct ControlIntent`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `natural_language` | `str` |  |
| `target_tissue_response` | `f64` |  |
| `maximum_cellular_gain` | `f64` |  |
| `effort_penalty` | `f64` |  |
| `horizon_s` | `f64` |  |
| `evidence_ids` | `list[str]` |  |

# `struct Phase8AdmissionEvidence`

**Fields**

| field | type | descriptor |
|---|---|---|
| `phase8_technical_pass` | `bool` |  |
| `readdy_chronology_proven` | `bool` |  |
| `readdy_qualification_pass` | `bool` |  |
| `readdy_convergence_pass` | `bool` |  |
| `readdy_spatial_pass` | `bool` |  |
| `readdy_admission_pass` | `bool` |  |
| `physicell_custom_insulin_pass` | `bool` |  |
| `physicell_target_rate_pass` | `bool` |  |
| `physicell_uncertainty_pass` | `bool` |  |
| `physicell_scientific_pass` | `bool` |  |

# `def phase8_admission_evidence_complete`

```sema
def phase8_admission_evidence_complete(evidence: Phase8AdmissionEvidence) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `evidence` | `Phase8AdmissionEvidence` |

**Returns** `bool`

**Effects** `!{}`

# `struct AdaptationSummary`

**Fields**

| field | type | descriptor |
|---|---|---|
| `active_model_id` | `str` |  |
| `candidate_model_id` | `str` |  |
| `selected_model_id` | `str` |  |
| `activated` | `bool` |  |
| `admission_status` | `str` |  |
| `admitted` | `bool` |  |
| `exploratory` | `bool` |  |
| `evidence_reliability` | `f64` |  |
| `parameter_apply_authorized` | `bool` |  |
| `reason` | `str` |  |
| `evidence_ids` | `list[str]` |  |

# `struct DynamicsResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `contract_id` | `str` |  |
| `semantics` | `str` |  |
| `formal_equations` | `list[str]` |  |
| `state_names` | `list[str]` |  |
| `state_units` | `list[str]` |  |
| `final_state` | `list[f64]` |  |
| `cellular_gain` | `f64` |  |
| `target_tissue_response` | `f64` |  |
| `tissue_target_error` | `f64` |  |
| `initial_molecular_mass_micromolar` | `f64` |  |
| `final_molecular_mass_micromolar` | `f64` |  |
| `molecular_mass_relative_residual` | `f64` |  |
| `integration_error_bound` | `f64` |  |
| `integration_steps_accepted` | `int` |  |
| `integration_steps_rejected` | `int` |  |
| `integration_method` | `str` |  |
| `optimizer_status` | `str` |  |
| `optimizer_scope` | `str` |  |
| `optimizer_objective` | `f64` |  |
| `optimizer_iterations` | `int` |  |
| `adaptation` | `AdaptationSummary` |  |
| `evidence_ids` | `list[str]` |  |
| `admission_status` | `str` |  |
| `admitted` | `bool` |  |
| `exploratory` | `bool` |  |
| `parameter_apply_authorized` | `bool` |  |
| `technical_pass` | `bool` |  |
| `scientific_validated` | `bool` |  |

# `struct PopulationState`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `total_cells` | `int` |  |
| `viable_cells` | `int` |  |
| `dead_cells` | `int` |  |
| `mutated_cells` | `int` |  |
| `adapted_cells` | `int` |  |
| `injected_micromolar` | `f64` |  |
| `applied_force_pn` | `f64` |  |
| `stress_fraction` | `f64` |  |
| `injected_molecule` | `str` |  |
| `mutation_label` | `str` |  |
| `last_intervention` | `str` |  |
| `affected_index` | `int` |  |
| `affected_kind` | `str` |  |
| `event_count` | `int` |  |
| `scientific_validated` | `bool` |  |

# `struct DynamicsStep`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `sequence` | `int` |  |
| `state_version` | `int` |  |
| `equation_id` | `str` |  |
| `equation_version` | `int` |  |
| `model_id` | `str` |  |
| `semantics` | `str` |  |
| `state` | `list[f64]` |  |
| `target_tissue_response` | `f64` |  |
| `cellular_gain` | `f64` |  |
| `molecular_integrity` | `f64` |  |
| `dt_s` | `f64` |  |
| `molecular_mass_relative_residual` | `f64` |  |
| `integration_error_bound` | `f64` |  |
| `integration_steps_accepted` | `int` |  |
| `integration_steps_rejected` | `int` |  |
| `optimizer_status` | `str` |  |
| `optimizer_scope` | `str` |  |
| `evidence_ids` | `list[str]` |  |
| `physiology` | `dict[str, any]` |  |
| `population` | `PopulationState` |  |
| `admission_status` | `str` |  |
| `admitted` | `bool` |  |
| `exploratory` | `bool` |  |
| `parameter_apply_authorized` | `bool` |  |
| `technical_pass` | `bool` |  |
| `scientific_validated` | `bool` |  |

# `def initial_population_state`

```sema
def initial_population_state(total_cells: int) -> PopulationState !{}
```

**Parameters**

| name | type |
|---|---|
| `total_cells` | `int` |

**Returns** `PopulationState`

**Effects** `!{}`

# `def apply_biological_intervention`

```sema
def apply_biological_intervention(state: PopulationState, kind: str, target_index: int, target_kind: str, magnitude: f64, amount: f64, molecule: str, mutation: str, seed_cells: int) -> PopulationState !{}
```

**Parameters**

| name | type |
|---|---|
| `state` | `PopulationState` |
| `kind` | `str` |
| `target_index` | `int` |
| `target_kind` | `str` |
| `magnitude` | `f64` |
| `amount` | `f64` |
| `molecule` | `str` |
| `mutation` | `str` |
| `seed_cells` | `int` |

**Returns** `PopulationState`

**Effects** `!{}`

# `def advance_population_dynamics`

```sema
def advance_population_dynamics(state: PopulationState, dt_s: f64, cellular_signal: f64, tissue_response: f64, beta_function_fraction: f64, immune_effector_fraction: f64)
```

**Parameters**

| name | type |
|---|---|
| `state` | `PopulationState` |
| `dt_s` | `f64` |
| `cellular_signal` | `f64` |
| `tissue_response` | `f64` |
| `beta_function_fraction` | `f64` |
| `immune_effector_fraction` | `f64` |

# `def dynamics_equations`

```sema
def dynamics_equations() -> list[str] !{}
```

**Returns** `list[str]`

**Effects** `!{}`

# `def exploratory_unadmitted_association_preview`

```sema
def exploratory_unadmitted_association_preview(profile_id: str, evidence_id: str)
```

**Parameters**

| name | type |
|---|---|
| `profile_id` | `str` |
| `evidence_id` | `str` |

# `def admit_association_model`

```sema
def admit_association_model(profile_id: str, association_rate: f64, dissociation_rate: f64, reference_error: f64, candidate_error: f64, evidence_id: str, observed_at: f64, admission_evidence: Phase8AdmissionEvidence) -> AdaptationSummary !{}
```

**Parameters**

| name | type |
|---|---|
| `profile_id` | `str` |
| `association_rate` | `f64` |
| `dissociation_rate` | `f64` |
| `reference_error` | `f64` |
| `candidate_error` | `f64` |
| `evidence_id` | `str` |
| `observed_at` | `f64` |
| `admission_evidence` | `Phase8AdmissionEvidence` |

**Returns** `AdaptationSummary`

**Effects** `!{}`

# `def run_multiscale_dynamics`

```sema
def run_multiscale_dynamics(profile_id: str, monomer_micromolar: f64, dimer_micromolar: f64, association_rate: f64, dissociation_rate: f64, intent: ControlIntent, adaptation: AdaptationSummary) !{}
```

**Parameters**

| name | type |
|---|---|
| `profile_id` | `str` |
| `monomer_micromolar` | `f64` |
| `dimer_micromolar` | `f64` |
| `association_rate` | `f64` |
| `dissociation_rate` | `f64` |
| `intent` | `ControlIntent` |
| `adaptation` | `AdaptationSummary` |

**Effects** `!{}`

# `def preview_unadmitted_multiscale_dynamics`

```sema
def preview_unadmitted_multiscale_dynamics(profile_id: str, monomer_micromolar: f64, dimer_micromolar: f64, association_rate: f64, dissociation_rate: f64, intent: ControlIntent, adaptation: AdaptationSummary) -> DynamicsResult !{}
```

**Parameters**

| name | type |
|---|---|
| `profile_id` | `str` |
| `monomer_micromolar` | `f64` |
| `dimer_micromolar` | `f64` |
| `association_rate` | `f64` |
| `dissociation_rate` | `f64` |
| `intent` | `ControlIntent` |
| `adaptation` | `AdaptationSummary` |

**Returns** `DynamicsResult`

**Effects** `!{}`

# `def compute_multiscale_dynamics_step`

```sema
def compute_multiscale_dynamics_step(sequence: int, state_version: int, model_id: str, adaptation: AdaptationSummary, state: list[f64], population: PopulationState, physiology: dict[str, any], dt_s: f64, target_tissue_response: f64, maximum_cellular_gain: f64, effort_penalty: f64, molecular_integrity: f64, association_rate: f64, dissociation_rate: f64, evidence_ids: list[str], admitted_execution: bool) !{}
```

**Parameters**

| name | type |
|---|---|
| `sequence` | `int` |
| `state_version` | `int` |
| `model_id` | `str` |
| `adaptation` | `AdaptationSummary` |
| `state` | `list[f64]` |
| `population` | `PopulationState` |
| `physiology` | `dict[str, any]` |
| `dt_s` | `f64` |
| `target_tissue_response` | `f64` |
| `maximum_cellular_gain` | `f64` |
| `effort_penalty` | `f64` |
| `molecular_integrity` | `f64` |
| `association_rate` | `f64` |
| `dissociation_rate` | `f64` |
| `evidence_ids` | `list[str]` |
| `admitted_execution` | `bool` |

**Effects** `!{}`

# `def step_multiscale_dynamics`

```sema
def step_multiscale_dynamics(sequence: int, state_version: int, model_id: str, adaptation: AdaptationSummary, state: list[f64], population: PopulationState, physiology: dict[str, any], dt_s: f64, target_tissue_response: f64, maximum_cellular_gain: f64, effort_penalty: f64, molecular_integrity: f64, association_rate: f64, dissociation_rate: f64, evidence_ids: list[str]) -> DynamicsStep !{}
```

**Parameters**

| name | type |
|---|---|
| `sequence` | `int` |
| `state_version` | `int` |
| `model_id` | `str` |
| `adaptation` | `AdaptationSummary` |
| `state` | `list[f64]` |
| `population` | `PopulationState` |
| `physiology` | `dict[str, any]` |
| `dt_s` | `f64` |
| `target_tissue_response` | `f64` |
| `maximum_cellular_gain` | `f64` |
| `effort_penalty` | `f64` |
| `molecular_integrity` | `f64` |
| `association_rate` | `f64` |
| `dissociation_rate` | `f64` |
| `evidence_ids` | `list[str]` |

**Returns** `DynamicsStep`

**Effects** `!{}`

# `def preview_unadmitted_multiscale_dynamics_step`

```sema
def preview_unadmitted_multiscale_dynamics_step(sequence: int, state_version: int, model_id: str, adaptation: AdaptationSummary, state: list[f64], population: PopulationState, physiology: dict[str, any], dt_s: f64, target_tissue_response: f64, maximum_cellular_gain: f64, effort_penalty: f64, molecular_integrity: f64, association_rate: f64, dissociation_rate: f64, evidence_ids: list[str]) -> DynamicsStep !{}
```

**Parameters**

| name | type |
|---|---|
| `sequence` | `int` |
| `state_version` | `int` |
| `model_id` | `str` |
| `adaptation` | `AdaptationSummary` |
| `state` | `list[f64]` |
| `population` | `PopulationState` |
| `physiology` | `dict[str, any]` |
| `dt_s` | `f64` |
| `target_tissue_response` | `f64` |
| `maximum_cellular_gain` | `f64` |
| `effort_penalty` | `f64` |
| `molecular_integrity` | `f64` |
| `association_rate` | `f64` |
| `dissociation_rate` | `f64` |
| `evidence_ids` | `list[str]` |

**Returns** `DynamicsStep`

**Effects** `!{}`



# `ensemble`

Independent stochastic replica evidence with explicit uncertainty and replay class.

# `struct EnsembleResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `ensemble_id` | `str` |  |
| `config_sha256` | `str` |  |
| `coarse_config_sha256` | `str` |  |
| `benchmark_config_sha256` | `str` |  |
| `source_model_sha256` | `str` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |
| `platform` | `str` |  |
| `replay_class` | `str` |  |
| `evidence_class` | `str` |  |
| `replicas` | `int` |  |
| `samples_per_replica` | `int` |  |
| `seeds` | `list[int]` |  |
| `initial_state_sha256` | `list[str]` |  |
| `distinct_initial_states` | `int` |  |
| `basin_ids` | `list[str]` |  |
| `occupancy_mean` | `list[f64]` |  |
| `occupancy_sem` | `list[f64]` |  |
| `transition_counts` | `list[int]` |  |
| `transitions` | `int` |  |
| `observed_basins` | `int` |  |
| `free_energy_mean_kj_mol` | `list[f64]` |  |
| `free_energy_sem_kj_mol` | `list[f64]` |  |
| `effective_samples` | `f64` |  |
| `rhat_defined` | `bool` |  |
| `rhat_max` | `f64` |  |
| `converged` | `bool` |  |

# `bridge ensemble_backend`



# `insulin`

Human insulin solution-thermodynamics model with pinned experimental evidence.

# `struct InsulinThermodynamicsResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `artifact_sha256` | `str` |  |
| `pmid` | `str` |  |
| `doi` | `str` |  |
| `subject` | `str` |  |
| `assay` | `str` |  |
| `temperature_k` | `f64` |  |
| `buffer` | `str` |  |
| `ph` | `f64` |  |
| `zinc_added` | `bool` |  |
| `ligand_added` | `bool` |  |
| `independent_experiments` | `int` |  |
| `kd_micromolar` | `f64` |  |
| `kd_sem_micromolar` | `f64` |  |
| `reported_dissociation_free_energy_kj_mol` | `f64` |  |
| `reported_dissociation_free_energy_sem_kj_mol` | `f64` |  |
| `modeled_dissociation_free_energy_kj_mol` | `f64` |  |
| `modeled_dissociation_free_energy_sem_kj_mol` | `f64` |  |
| `modeled_binding_free_energy_kj_mol` | `f64` |  |
| `free_energy_residual_kj_mol` | `f64` |  |
| `uncertainty_residual_kj_mol` | `f64` |  |
| `combined_z_score` | `f64` |  |
| `condition_pass` | `bool` |  |
| `thermodynamic_pass` | `bool` |  |
| `validated` | `bool` |  |
| `evidence_class` | `str` |  |
| `new_atomistic_simulation` | `bool` |  |
| `result_sha256` | `str` |  |
| `direct_oracle_result_sha256` | `str` |  |
| `direct_oracle_path` | `str` |  |
| `direct_parity_pass` | `bool` |  |
| `result_path` | `str` |  |

# `bridge insulin_backend`



# `insulin_pmf`

Bounded explicit-solvent insulin-dimer association PMF evidence with strict validation gates.

# `struct InsulinPmfResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `source_sha256` | `str` |  |
| `system_sha256` | `str` |  |
| `sample_sha256` | `list[str]` |  |
| `evidence_sha256` | `str` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |
| `pdb_id` | `str` |  |
| `backend` | `str` |  |
| `backend_version` | `str` |  |
| `platform` | `str` |  |
| `force_field` | `str` |  |
| `water_model` | `str` |  |
| `temperature_k` | `f64` |  |
| `atoms` | `int` |  |
| `protein_atoms` | `int` |  |
| `windows` | `int` |  |
| `replicas_per_window` | `int` |  |
| `samples_per_replica` | `int` |  |
| `total_dynamics_steps` | `int` |  |
| `window_centers_nm` | `list[f64]` |  |
| `force_constants_kj_mol_nm2` | `list[f64]` |  |
| `initial_centroid_distance_nm` | `f64` |  |
| `minimized_energy_kj_mol` | `f64` |  |
| `minimum_adjacent_overlap` | `f64` |  |
| `adjacent_overlap` | `list[f64]` |  |
| `overlap_matrix` | `list[f64]` |  |
| `rhat_by_window` | `list[f64]` |  |
| `rhat_max` | `f64` |  |
| `integrated_autocorrelation_by_replica` | `list[f64]` |  |
| `maximum_integrated_autocorrelation` | `f64` |  |
| `ess_by_replica` | `list[f64]` |  |
| `total_ess` | `f64` |  |
| `mbar_free_energies_reduced` | `list[f64]` |  |
| `mbar_iterations` | `int` |  |
| `mbar_residual` | `f64` |  |
| `estimator_converged` | `bool` |  |
| `overlap_pass` | `bool` |  |
| `rhat_pass` | `bool` |  |
| `autocorrelation_pass` | `bool` |  |
| `ess_pass` | `bool` |  |
| `sampling_converged` | `bool` |  |
| `sampling_uncertainty_available` | `bool` |  |
| `parameter_uncertainty_available` | `bool` |  |
| `model_form_uncertainty_available` | `bool` |  |
| `restraint_correction_available` | `bool` |  |
| `finite_size_correction_available` | `bool` |  |
| `standard_state_correction_available` | `bool` |  |
| `experimental_uncertainty_available` | `bool` |  |
| `sampling_uncertainty_kj_mol` | `list[f64]` |  |
| `parameter_uncertainty_kj_mol` | `list[f64]` |  |
| `model_form_uncertainty_kj_mol` | `list[f64]` |  |
| `restraint_correction_kj_mol` | `list[f64]` |  |
| `finite_size_correction_kj_mol` | `list[f64]` |  |
| `standard_state_correction_kj_mol` | `list[f64]` |  |
| `experimental_uncertainty_kj_mol` | `list[f64]` |  |
| `standard_state_delta_g_available` | `bool` |  |
| `standard_state_delta_g_kj_mol` | `list[f64]` |  |
| `independent_reference_pass` | `bool` |  |
| `scientific_validated` | `bool` |  |
| `technical_pass` | `bool` |  |
| `failure_type` | `str` |  |
| `blockers` | `list[str]` |  |
| `resumed_replicas` | `int` |  |
| `runtime_seconds` | `f64` |  |
| `direct_oracle_result_sha256` | `str` |  |
| `direct_oracle_path` | `str` |  |
| `direct_parity_pass` | `bool` |  |

# `bridge insulin_pmf_backend`



# `insulin_structure`

Pinned zinc-free human-insulin dimer construction and explicit-solvent technical evidence.

# `struct InsulinAtomisticResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `source_sha256` | `str` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |
| `pdb_id` | `str` |  |
| `assembly` | `int` |  |
| `license` | `str` |  |
| `doi` | `str` |  |
| `backend` | `str` |  |
| `backend_version` | `str` |  |
| `platform` | `str` |  |
| `force_field` | `str` |  |
| `water_model` | `str` |  |
| `temperature_k` | `f64` |  |
| `ph` | `f64` |  |
| `ionic_strength_molar` | `f64` |  |
| `monomers` | `int` |  |
| `protein_residues` | `int` |  |
| `protein_atoms` | `int` |  |
| `atoms` | `int` |  |
| `solvent_atoms` | `int` |  |
| `disulfide_bonds` | `int` |  |
| `interface_contact_angstrom` | `f64` |  |
| `initial_energy_kj_mol` | `f64` |  |
| `final_energy_kj_mol` | `f64` |  |
| `max_force_kj_mol_nm` | `f64` |  |
| `steps` | `int` |  |
| `system_sha256` | `str` |  |
| `final_positions_sha256` | `str` |  |
| `structural_pass` | `bool` |  |
| `technical_pass` | `bool` |  |
| `association_validated` | `bool` |  |
| `evidence_class` | `str` |  |
| `direct_oracle_result_sha256` | `str` |  |
| `direct_oracle_path` | `str` |  |
| `direct_parity_pass` | `bool` |  |

# `bridge insulin_structure_backend`



# `live`

Persistent Sema HTTP service for evidence-bound live viewer dynamics.

# `struct LiveProfile`

**Fields**

| field | type | descriptor |
|---|---|---|
| `model_id` | `str` |  |
| `association_rate` | `f64` |  |
| `dissociation_rate` | `f64` |  |
| `initial_state` | `list[f64]` |  |
| `evidence_ids` | `list[str]` |  |
| `scene_sha256` | `str` |  |
| `population_cells` | `int` |  |
| `admission_evidence` | `Phase8AdmissionEvidence` |  |
| `adaptation` | `AdaptationSummary` |  |

# `def load_live_profile`

```sema
def load_live_profile() !{fs.read}
```

**Effects** `!{fs.read}`

# `def response`

```sema
def response(status: int, body: any) !{}
```

**Parameters**

| name | type |
|---|---|
| `status` | `int` |
| `body` | `any` |

**Effects** `!{}`

# `def error_response`

```sema
def error_response(status: int, code: str, detail: str) !{}
```

**Parameters**

| name | type |
|---|---|
| `status` | `int` |
| `code` | `str` |
| `detail` | `str` |

**Effects** `!{}`

# `def active_species_registry`

```sema
def active_species_registry(profile: LiveProfile, session: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

# `def species_adjusted_program`

```sema
def species_adjusted_program(program: dict[str, any], registry: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `program` | `dict[str, any]` |
| `registry` | `dict[str, any]` |

**Effects** `!{}`

# `def status_response`

```sema
def status_response(profile: LiveProfile, session: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{}`

# `def step_input_error`

```sema
def step_input_error(payload: any) !{}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `any` |

**Effects** `!{}`

# `def canonical_step_request_identity`

```sema
def canonical_step_request_identity(payload: dict[str, any], profile: LiveProfile, session: dict[str, any], admission_branch: str, step_state: any, step_population: any, step_physiology: any, step_species: any) !{}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |
| `admission_branch` | `str` |
| `step_state` | `any` |
| `step_population` | `any` |
| `step_physiology` | `any` |
| `step_species` | `any` |

**Effects** `!{}`

# `def live_step_response_body`

```sema
def live_step_response_body(step: any, generation: int, molecular_generation: int) !{}
```

**Parameters**

| name | type |
|---|---|
| `step` | `any` |
| `generation` | `int` |
| `molecular_generation` | `int` |

**Effects** `!{}`

# `def exploratory_step_response`

```sema
def exploratory_step_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{}`

# `def step_response`

```sema
def step_response(payload: any, profile: LiveProfile, session: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `any` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{}`

# `def has_intervention_fields`

```sema
def has_intervention_fields(payload: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |

# `def intervention_response`

```sema
def intervention_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{}`

# `def store_species`

```sema
def store_species(profile: LiveProfile, session: dict[str, any], registry: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |
| `registry` | `dict[str, any]` |

# `def docking_identity`

```sema
def docking_identity(target: dict[str, any], ligand: dict[str, any], budget: int) !{}
```

**Parameters**

| name | type |
|---|---|
| `target` | `dict[str, any]` |
| `ligand` | `dict[str, any]` |
| `budget` | `int` |

**Effects** `!{}`

# `def dock_design`

```sema
def dock_design(session: dict[str, any], name: str, budget: int) !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |
| `name` | `str` |
| `budget` | `int` |

**Effects** `!{fs.read}`

# `def design_result_body`

```sema
def design_result_body(design: dict[str, any], species: any, summary: list[str])
```

**Parameters**

| name | type |
|---|---|
| `design` | `dict[str, any]` |
| `species` | `any` |
| `summary` | `list[str]` |

# `def registration_error_response`

```sema
def registration_error_response(registration: dict[str, str]) !{}
```

**Parameters**

| name | type |
|---|---|
| `registration` | `dict[str, str]` |

**Effects** `!{}`

# `def set_design_mechanism`

```sema
def set_design_mechanism(compiled: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `compiled` | `dict[str, any]` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{}`

# `def apply_design_command`

```sema
def apply_design_command(compiled: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `compiled` | `dict[str, any]` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{}`

# `def design_mutation_identity`

```sema
def design_mutation_identity(payload: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |

**Effects** `!{}`

# `def design_response`

```sema
def design_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{}`

# `def dock_response`

```sema
def dock_response(payload: dict[str, any], session: dict[str, any]) !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |
| `session` | `dict[str, any]` |

**Effects** `!{fs.read}`

# `def introduce_response`

```sema
def introduce_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{fs.read}`

# `def invalidate_molecular_step_caches`

```sema
def invalidate_molecular_step_caches(session: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |

# `def advance_molecular_generation`

```sema
def advance_molecular_generation(session: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |

# `def molecular_mutation_identity`

```sema
def molecular_mutation_identity(kind: str, payload: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `kind` | `str` |
| `payload` | `dict[str, any]` |

**Effects** `!{}`

# `def retained_molecular_mutation`

```sema
def retained_molecular_mutation(identity: str, session: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `identity` | `str` |
| `session` | `dict[str, any]` |

# `def retain_molecular_mutation`

```sema
def retain_molecular_mutation(identity: str, body: dict[str, any], session: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `identity` | `str` |
| `body` | `dict[str, any]` |
| `session` | `dict[str, any]` |

# `def molecule_response`

```sema
def molecule_response(payload: dict[str, any], session: dict[str, any]) !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |
| `session` | `dict[str, any]` |

**Effects** `!{fs.read}`

# `def molecule_step_response`

```sema
def molecule_step_response(payload: dict[str, any], session: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |
| `session` | `dict[str, any]` |

**Effects** `!{}`

# `def direct_molecular_operations`

```sema
def direct_molecular_operations(operations: list[dict[str, any]])
```

**Parameters**

| name | type |
|---|---|
| `operations` | `list[dict[str, any]]` |

# `def program_response`

```sema
def program_response(payload: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `payload` | `dict[str, any]` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{fs.read}`

# `def capabilities_response`

```sema
def capabilities_response() !{}
```

**Effects** `!{}`

# `def live_response`

```sema
def live_response(request: dict[str, any], profile: LiveProfile, session: dict[str, any]) !{ffi.call, fs.read}
```

**Parameters**

| name | type |
|---|---|
| `request` | `dict[str, any]` |
| `profile` | `LiveProfile` |
| `session` | `dict[str, any]` |

**Effects** `!{ffi.call, fs.read}`

# `def serve_live`

```sema
def serve_live(port: int) -> None !{ffi.call, fs.read, net.listen}
```

**Parameters**

| name | type |
|---|---|
| `port` | `int` |

**Returns** `None`

**Effects** `!{ffi.call, fs.read, net.listen}`



# `mace`

Pinned MACE-MP technical adapter with independent direct parity.

# `struct MaceProfileResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `platform` | `str` |  |
| `device` | `str` |  |
| `default_dtype` | `str` |  |
| `mace_torch_version` | `str` |  |
| `torch_version` | `str` |  |
| `checkpoint_url` | `str` |  |
| `checkpoint_sha256` | `str` |  |
| `checkpoint_bytes` | `int` |  |
| `checkpoint_license` | `str` |  |
| `training_domain` | `str` |  |
| `provenance_sha256` | `str` |  |
| `config_sha256` | `str` |  |
| `system_sha256` | `str` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |
| `direct_oracle_file_sha256` | `str` |  |
| `direct_oracle_result_sha256` | `str` |  |
| `atoms` | `int` |  |
| `base_energy_ev` | `f64` |  |
| `displaced_energy_ev` | `f64` |  |
| `ablation_energy_delta_ev` | `f64` |  |
| `max_force_ev_per_angstrom` | `f64` |  |
| `finite_difference_force_residual_ev_per_angstrom` | `f64` |  |
| `translation_energy_residual_ev` | `f64` |  |
| `translation_force_residual_ev_per_angstrom` | `f64` |  |
| `direct_energy_residual_ev` | `f64` |  |
| `direct_force_residual_ev_per_angstrom` | `f64` |  |
| `finite_difference_pass` | `bool` |  |
| `translation_pass` | `bool` |  |
| `ablation_pass` | `bool` |  |
| `direct_parity_pass` | `bool` |  |
| `technical_pass` | `bool` |  |
| `reference_kind` | `str` |  |
| `replay_class` | `str` |  |
| `domain_status` | `str` |  |
| `uncertainty_available` | `bool` |  |
| `molecular_validated` | `bool` |  |
| `evidence_class` | `str` |  |

# `bridge mace_backend`



# `mace_off`

MACE-OFF23 molecular holdout, calibrated uncertainty, OOD, and ablation evidence.

# `struct MaceOffResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `dataset_sha256` | `str` |  |
| `model_sha256` | `list[str]` |  |
| `provenance_sha256` | `str` |  |
| `checkpoint_license` | `str` |  |
| `dataset_license` | `str` |  |
| `level_of_theory` | `str` |  |
| `calibration_configurations` | `int` |  |
| `heldout_configurations` | `int` |  |
| `unique_molecules` | `int` |  |
| `heldout_energy_rmse_mev_per_atom` | `f64` |  |
| `heldout_force_rmse_mev_per_angstrom` | `f64` |  |
| `symbolic_only_force_rmse_mev_per_angstrom` | `f64` |  |
| `hybrid_force_rmse_mev_per_angstrom` | `f64` |  |
| `conformal_scale` | `f64` |  |
| `conformal_coverage` | `f64` |  |
| `ood_minimum_distance_angstrom` | `f64` |  |
| `ood_uncertainty_ratio` | `f64` |  |
| `in_domain_force_disagreement_mev_per_angstrom` | `f64` |  |
| `ood_force_disagreement_mev_per_angstrom` | `f64` |  |
| `ood_blocked` | `bool` |  |
| `translation_energy_residual_ev` | `f64` |  |
| `translation_force_residual_ev_per_angstrom` | `f64` |  |
| `accuracy_pass` | `bool` |  |
| `uncertainty_pass` | `bool` |  |
| `symmetry_pass` | `bool` |  |
| `ood_pass` | `bool` |  |
| `ablation_pass` | `bool` |  |
| `molecular_validated` | `bool` |  |
| `evidence_class` | `str` |  |
| `direct_oracle_result_sha256` | `str` |  |
| `direct_energy_residual` | `f64` |  |
| `direct_force_residual` | `f64` |  |
| `direct_parity_pass` | `bool` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |

# `bridge mace_off_backend`



# `main`

Sema-owned biological workflow with evidence-gated foreign kernels and non-authoritative projections.

# `def phase10_summary`

```sema
def phase10_summary(result: Phase10QualificationResult)
```

**Parameters**

| name | type |
|---|---|
| `result` | `Phase10QualificationResult` |

# `def main`

```sema
def main() !{ffi.call, fs.read, fs.write, net.listen}
```

**Effects** `!{ffi.call, fs.read, fs.write, net.listen}`



# `mesoscopic`

Uncertainty-preserving molecular-to-reaction-diffusion parameter transfer.

# `struct MesoscopicResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `source_result_sha256` | `str` |  |
| `source_artifact_sha256` | `str` |  |
| `source_kd_micromolar` | `f64` |  |
| `source_kd_sem_micromolar` | `f64` |  |
| `association_rate_per_micromolar_s` | `f64` |  |
| `dissociation_rate_per_s` | `f64` |  |
| `voxels` | `int` |  |
| `steps` | `int` |  |
| `dt_s` | `f64` |  |
| `simulated_time_s` | `f64` |  |
| `initial_mass_micromolar` | `f64` |  |
| `final_mass_micromolar` | `f64` |  |
| `mass_relative_residual` | `f64` |  |
| `expected_monomer_micromolar` | `f64` |  |
| `expected_dimer_micromolar` | `f64` |  |
| `observed_monomer_micromolar` | `f64` |  |
| `observed_dimer_micromolar` | `f64` |  |
| `observed_kd_micromolar` | `f64` |  |
| `kd_relative_residual` | `f64` |  |
| `spatial_cv` | `f64` |  |
| `dimer_uncertainty_min_micromolar` | `f64` |  |
| `dimer_uncertainty_max_micromolar` | `f64` |  |
| `rate_roundtrip_relative_residual` | `f64` |  |
| `sbml_sha256` | `str` |  |
| `bngl_sha256` | `str` |  |
| `uncertainty_pass` | `bool` |  |
| `interchange_pass` | `bool` |  |
| `transfer_pass` | `bool` |  |
| `reverse_discrepancy_signaled` | `bool` |  |
| `adapter_backend_sha256` | `str` |  |
| `readdy_status` | `str` |  |
| `readdy_unavailable_reason` | `str` |  |
| `readdy_version` | `str` |  |
| `readdy_source_commit` | `str` |  |
| `readdy_wheel_filename` | `str` |  |
| `readdy_wheel_sha256` | `str` |  |
| `readdy_module_sha256` | `str` |  |
| `readdy_platform` | `str` |  |
| `readdy_executed` | `bool` |  |
| `readdy_target_rate_evidence` | `bool` |  |
| `readdy_concentration_evidence` | `bool` |  |
| `readdy_spatial_evidence` | `bool` |  |
| `readdy_uncertainty_evidence` | `bool` |  |
| `readdy_association_events` | `int` |  |
| `readdy_dissociation_events` | `int` |  |
| `readdy_lower_uncertainty_dissociation_events` | `int` |  |
| `readdy_upper_uncertainty_dissociation_events` | `int` |  |
| `readdy_final_monomer_particles` | `int` |  |
| `readdy_final_dimer_particles` | `int` |  |
| `readdy_mass_relative_residual` | `f64` |  |
| `readdy_mean_displacement_micrometers` | `f64` |  |
| `readdy_observation_sha256` | `str` |  |
| `readdy_observation_json` | `str` |  |
| `readdy_validated` | `bool` |  |
| `physicell_status` | `str` |  |
| `physicell_unavailable_reason` | `str` |  |
| `physicell_version` | `str` |  |
| `physicell_source_commit` | `str` |  |
| `physicell_source_url` | `str` |  |
| `physicell_executable` | `str` |  |
| `physicell_executed` | `bool` |  |
| `physicell_target_rate_evidence` | `bool` |  |
| `physicell_concentration_evidence` | `bool` |  |
| `physicell_spatial_evidence` | `bool` |  |
| `physicell_uncertainty_evidence` | `bool` |  |
| `physicell_validated` | `bool` |  |
| `scientific_validated` | `bool` |  |
| `evidence_class` | `str` |  |
| `result_sha256` | `str` |  |
| `direct_oracle_result_sha256` | `str` |  |
| `direct_oracle_path` | `str` |  |
| `direct_residual` | `f64` |  |
| `direct_parity_pass` | `bool` |  |
| `phase8_technical_pass` | `bool` |  |
| `sbml_path` | `str` |  |
| `bngl_path` | `str` |  |
| `result_path` | `str` |  |

# `bridge mesoscopic_backend`



# `models`

Typed symbolic, learned, and hybrid equation terms with fail-closed evidence gates.

# `enum TermImplementation`

**Variants**

- `symbolic`
- `learned`
- `hybrid`

# `enum LearnedRole`

**Variants**

- `energy`
- `force`
- `rate`
- `transition_probability`
- `structure_proposal`
- `closure`
- `parameter`

# `enum ApplicabilityDecision`

**Variants**

- `applicable`
- `out_of_domain`
- `unknown`

# `enum PredictionStatus`

**Variants**

- `proposed`
- `admissible`
- `blocked`

# `struct LearnedModelManifest`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `family` | `str` |  |
| `version` | `str` |  |
| `role` | `LearnedRole` |  |
| `architecture_sha256` | `str` |  |
| `weights_sha256` | `str` |  |
| `training_data_sha256` | `str` |  |
| `validation_data_sha256` | `str` |  |
| `license_id` | `str` |  |
| `preprocessing` | `str` |  |
| `input_units` | `list[str]` |  |
| `output_unit` | `str` |  |
| `chemical_domain` | `str` |  |
| `thermodynamic_domain` | `str` |  |
| `symmetry_contract` | `str` |  |
| `calibration_method` | `str` |  |
| `uncertainty_method` | `str` |  |
| `ood_method` | `str` |  |
| `backend_profile_id` | `str` |  |
| `evidence_ids` | `list[str]` |  |
| `validated` | `bool` |  |

# `struct EquationTermDescriptor`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `owner_model_id` | `str` |  |
| `implementation` | `TermImplementation` |  |
| `role` | `LearnedRole` |  |
| `input_units` | `list[str]` |  |
| `output_unit` | `str` |  |
| `symbolic_expression` | `str` |  |
| `learned_model_id` | `str` |  |
| `combination_rule` | `str` |  |
| `authoritative_outputs` | `list[str]` |  |

# `struct PredictionUncertainty`

**Fields**

| field | type | descriptor |
|---|---|---|
| `aleatoric` | `f64` |  |
| `epistemic` | `f64` |  |
| `lower` | `f64` |  |
| `upper` | `f64` |  |
| `coverage` | `f64` |  |
| `calibrated` | `bool` |  |

# `struct HybridPrediction`

**Fields**

| field | type | descriptor |
|---|---|---|
| `term_id` | `str` |  |
| `manifest_id` | `str` |  |
| `symbolic_value` | `f64` |  |
| `learned_value` | `f64` |  |
| `gate` | `f64` |  |
| `combined_value` | `f64` |  |
| `output_unit` | `str` |  |
| `uncertainty` | `PredictionUncertainty` |  |
| `applicability` | `ApplicabilityDecision` |  |
| `ood_score` | `f64` |  |
| `symbolic_residual` | `f64` |  |
| `evidence_ids` | `list[str]` |  |
| `status` | `PredictionStatus` |  |
| `reason` | `str` |  |

# `def additive_hybrid_value`

```sema
def additive_hybrid_value(symbolic_value: f64, learned_correction: f64, gate: f64) !{}
```

**Parameters**

| name | type |
|---|---|
| `symbolic_value` | `f64` |
| `learned_correction` | `f64` |
| `gate` | `f64` |

**Effects** `!{}`

# `def manifest_qualified`

```sema
def manifest_qualified(manifest: LearnedModelManifest)
```

**Parameters**

| name | type |
|---|---|
| `manifest` | `LearnedModelManifest` |

# `def term_matches_manifest`

```sema
def term_matches_manifest(term: EquationTermDescriptor, manifest: LearnedModelManifest)
```

**Parameters**

| name | type |
|---|---|
| `term` | `EquationTermDescriptor` |
| `manifest` | `LearnedModelManifest` |

# `def term_descriptor_valid`

```sema
def term_descriptor_valid(term: EquationTermDescriptor)
```

**Parameters**

| name | type |
|---|---|
| `term` | `EquationTermDescriptor` |

# `def assess_hybrid_prediction`

```sema
def assess_hybrid_prediction(term: EquationTermDescriptor, manifest: LearnedModelManifest, symbolic_value: f64, learned_value: f64, gate: f64, uncertainty: PredictionUncertainty, applicability: ApplicabilityDecision, ood_score: f64, symbolic_residual: f64, maximum_uncertainty: f64, maximum_residual: f64, evidence_ids: list[str]) -> HybridPrediction !{}
```

**Parameters**

| name | type |
|---|---|
| `term` | `EquationTermDescriptor` |
| `manifest` | `LearnedModelManifest` |
| `symbolic_value` | `f64` |
| `learned_value` | `f64` |
| `gate` | `f64` |
| `uncertainty` | `PredictionUncertainty` |
| `applicability` | `ApplicabilityDecision` |
| `ood_score` | `f64` |
| `symbolic_residual` | `f64` |
| `maximum_uncertainty` | `f64` |
| `maximum_residual` | `f64` |
| `evidence_ids` | `list[str]` |

**Returns** `HybridPrediction`

**Effects** `!{}`

# `def prediction_admissible`

```sema
def prediction_admissible(prediction: HybridPrediction) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `prediction` | `HybridPrediction` |

**Returns** `bool`

**Effects** `!{}`



# `molecular`

Headless, bounded molecular state, topology, and dynamics owned by Sema.

# `def molecular_manifest`

```sema
def molecular_manifest() !{fs.read}
```

**Effects** `!{fs.read}`

# `def structure_key_supported`

```sema
def structure_key_supported(key: str) -> bool !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `key` | `str` |

**Returns** `bool`

**Effects** `!{fs.read}`

# `def structure_entry`

```sema
def structure_entry(key: str) !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `key` | `str` |

**Effects** `!{fs.read}`

# `def validate_record`

```sema
def validate_record(record: dict[str, any], encoding: str, components: int, maximum_items: int)
```

**Parameters**

| name | type |
|---|---|
| `record` | `dict[str, any]` |
| `encoding` | `str` |
| `components` | `int` |
| `maximum_items` | `int` |

# `def atomic_radius`

```sema
def atomic_radius(atomic_number: int, radius_kind: str)
```

**Parameters**

| name | type |
|---|---|
| `atomic_number` | `int` |
| `radius_kind` | `str` |

# `def atomic_name`

```sema
def atomic_name(atomic_number: int)
```

**Parameters**

| name | type |
|---|---|
| `atomic_number` | `int` |

# `def decoded_traces`

```sema
def decoded_traces(source: list[dict[str, any]]) !{}
```

**Parameters**

| name | type |
|---|---|
| `source` | `list[dict[str, any]]` |

**Effects** `!{}`

# `def active_bond_pairs`

```sema
def active_bond_pairs(session: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |

# `def topology_digest`

```sema
def topology_digest(session: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |

**Effects** `!{}`

# `def molecular_session_integrity`

```sema
def molecular_session_integrity(session: dict[str, any]) -> f64 !{}
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |

**Returns** `f64`

**Effects** `!{}`

# `def molecular_public_state`

```sema
def molecular_public_state(session: dict[str, any]) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def load_molecular_session`

```sema
def load_molecular_session(key: str) -> dict[str, any] !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `key` | `str` |

**Returns** `dict[str, any]`

**Effects** `!{fs.read}`

# `def clone_molecular_session`

```sema
def clone_molecular_session(session: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |

# `def find_bond_index`

```sema
def find_bond_index(session: dict[str, any], left: int, right: int)
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |
| `left` | `int` |
| `right` | `int` |

# `def operation_valid`

```sema
def operation_valid(session: dict[str, any], operation: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |
| `operation` | `dict[str, any]` |

# `def apply_operation`

```sema
def apply_operation(session: dict[str, any], operation: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |
| `operation` | `dict[str, any]` |

**Effects** `!{}`

# `def apply_molecular_program`

```sema
def apply_molecular_program(session: dict[str, any], payload: dict[str, any]) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |
| `payload` | `dict[str, any]` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def step_molecular_session`

```sema
def step_molecular_session(session: dict[str, any], dt_s: f64) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `session` | `dict[str, any]` |
| `dt_s` | `f64` |

**Returns** `dict[str, any]`

**Effects** `!{}`



# `openmm`

Pinned OpenMM bridge contracts for the first scientific vertical.

# `struct BackendProbe`

**Fields**

| field | type | descriptor |
|---|---|---|
| `available` | `bool` |  |
| `engine` | `str` |  |
| `version` | `str` |  |
| `platforms` | `list[str]` |  |
| `detail` | `str` |  |

# `struct OpenMMRun`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `benchmark_id` | `str` |  |
| `profile_id` | `str` |  |
| `engine_version` | `str` |  |
| `platform` | `str` |  |
| `platform_properties` | `list[str]` |  |
| `config_sha256` | `str` |  |
| `input_sha256` | `str` |  |
| `system_sha256` | `str` |  |
| `atom_count` | `int` |  |
| `bond_count` | `int` |  |
| `steps` | `int` |  |
| `frames` | `int` |  |
| `initial_potential_energy_kj_mol` | `f64` |  |
| `initial_max_force_kj_mol_nm` | `f64` |  |
| `initial_force_sha256` | `str` |  |
| `minimized_potential_energy_kj_mol` | `f64` |  |
| `minimized_max_force_kj_mol_nm` | `f64` |  |
| `minimized_force_sha256` | `str` |  |
| `nve_initial_total_energy_kj_mol` | `f64` |  |
| `nve_final_total_energy_kj_mol` | `f64` |  |
| `nve_drift_kj_mol` | `f64` |  |
| `frames_sha256` | `str` |  |
| `state_arrays_sha256` | `str` |  |
| `frames_path` | `str` |  |
| `initial_forces_path` | `str` |  |
| `minimized_forces_path` | `str` |  |
| `result_sha256` | `str` |  |

# `bridge openmm_adapter`

# `bridge openmm_backend`



# `phase10`

Fail-closed qualification of measured Phase 10 renderer and interaction evidence.

# `struct Phase10QualificationResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `evidence_sha256` | `str` |  |
| `scene_sha256` | `str` |  |
| `bundle_sha256` | `str` |  |
| `external_reference_sha256` | `str` |  |
| `scientific_result_sha256` | `str` |  |
| `screenshot_sha256` | `list[str]` |  |
| `scale_count` | `int` |  |
| `minimum_average_fps` | `f64` |  |
| `interaction_hz` | `int` |  |
| `canonical_update_hz` | `int` |  |
| `pick_p95_ms` | `f64` |  |
| `dropped_frames` | `int` |  |
| `gpu_allocated_bytes` | `int` |  |
| `gpu_resource_count` | `int` |  |
| `context_loss_recovered` | `bool` |  |
| `semantic_validation_pass` | `bool` |  |
| `viewer_disabled_parity_pass` | `bool` |  |
| `pixel_equality_observed` | `bool` |  |
| `visual_regression_replay_pass` | `bool` |  |
| `capture_provenance_status` | `str` |  |
| `profile_validated` | `bool` |  |
| `scientific_validated` | `bool` |  |

# `def covers_four_scales`

```sema
def covers_four_scales(records: list[any], key: str)
```

**Parameters**

| name | type |
|---|---|
| `records` | `list[any]` |
| `key` | `str` |

# `def qualify_phase10`

```sema
def qualify_phase10(config_path: str) -> Phase10QualificationResult !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `config_path` | `str` |

**Returns** `Phase10QualificationResult`

**Effects** `!{fs.read}`



# `physicell`

Pinned official PhysiCell 1.14.2 Apple-arm64 executable and stock XML field-coupling evidence.

# `struct PhysiCellFieldMetrics`

**Fields**

| field | type | descriptor |
|---|---|---|
| `mean_micromolar` | `f64` |  |
| `minimum_micromolar` | `f64` |  |
| `maximum_micromolar` | `f64` |  |
| `spatial_cv` | `f64` |  |
| `field_mass_micromolar_micrometer3` | `f64` |  |

# `struct PhysiCellSubstrateCellMetrics`

**Fields**

| field | type | descriptor |
|---|---|---|
| `uptake_rates_per_min` | `list[list[f64]]` |  |
| `net_export_rates_micromolar_micrometer3_per_min` | `list[list[f64]]` |  |
| `internalized_total_micromolar_micrometer3` | `list[f64]` |  |

# `struct PhysiCellSnapshot`

**Fields**

| field | type | descriptor |
|---|---|---|
| `voxels` | `int` |  |
| `cells` | `int` |  |
| `total_volume_micrometer3` | `f64` |  |
| `substrates` | `list[str]` |  |
| `fields` | `dict[str, PhysiCellFieldMetrics]` |  |
| `cell_substrates` | `PhysiCellSubstrateCellMetrics` |  |

# `struct PhysiCellScenario`

**Fields**

| field | type | descriptor |
|---|---|---|
| `name` | `str` |  |
| `coupled` | `bool` |  |
| `configured_monomer_micromolar` | `f64` |  |
| `configured_dimer_micromolar` | `f64` |  |
| `initial` | `PhysiCellSnapshot` |  |
| `final` | `PhysiCellSnapshot` |  |

# `struct PhysiCellScenarioExecution`

**Fields**

| field | type | descriptor |
|---|---|---|
| `name` | `str` |  |
| `wall_runtime_s` | `f64` |  |
| `captured_output_bytes` | `int` |  |
| `output_files` | `int` |  |
| `output_bytes` | `int` |  |
| `initial_xml_sha256` | `str` |  |
| `initial_mat_sha256` | `str` |  |
| `initial_cell_mat_sha256` | `str` |  |
| `final_xml_sha256` | `str` |  |
| `final_mat_sha256` | `str` |  |
| `final_cell_mat_sha256` | `str` |  |

# `struct PhysiCellExecution`

**Fields**

| field | type | descriptor |
|---|---|---|
| `scenario_executions` | `list[PhysiCellScenarioExecution]` |  |
| `total_wall_runtime_s` | `f64` |  |
| `total_output_bytes` | `int` |  |
| `total_output_files` | `int` |  |

# `struct PhysiCellResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `config_path` | `str` |  |
| `phase8_result_sha256` | `str` |  |
| `phase8_artifact_sha256` | `str` |  |
| `release_version` | `str` |  |
| `release_asset_sha256` | `str` |  |
| `release_asset_bytes` | `int` |  |
| `release_asset_id` | `int` |  |
| `tag_commit` | `str` |  |
| `tag_ref_sha` | `str` |  |
| `tag_commit_verified` | `bool` |  |
| `license` | `str` |  |
| `workflow_sha256` | `str` |  |
| `fetch_manifest_schema` | `str` |  |
| `fetch_manifest_path` | `str` |  |
| `fetch_manifest_sha256` | `str` |  |
| `fetch_evidence_sha256` | `str` |  |
| `fetch_remote_verified` | `bool` |  |
| `fetch_manifest_pass` | `bool` |  |
| `binary_sha256` | `str` |  |
| `binary_bytes` | `int` |  |
| `binary_architectures` | `list[str]` |  |
| `host_architecture` | `str` |  |
| `arm64_dependencies` | `list[str]` |  |
| `initial_concentration_residual_micromolar` | `f64` |  |
| `uniform_spatial_cv` | `f64` |  |
| `mass_relative_residual` | `f64` |  |
| `coupled_monomer_mean_delta_micromolar` | `f64` |  |
| `coupled_dimer_mean_delta_micromolar` | `f64` |  |
| `coupled_spatial_cv` | `f64` |  |
| `coupled_external_monomer_mass_delta_micromolar_micrometer3` | `f64` |  |
| `coupled_internalized_monomer_delta_micromolar_micrometer3` | `f64` |  |
| `coupled_external_dimer_mass_delta_micromolar_micrometer3` | `f64` |  |
| `coupled_internalized_dimer_delta_micromolar_micrometer3` | `f64` |  |
| `coupled_mass_transfer_relative_residual` | `f64` |  |
| `executable_pass` | `bool` |  |
| `platform_pass` | `bool` |  |
| `config_xml_field_coupling_pass` | `bool` |  |
| `field_output_pass` | `bool` |  |
| `concentration_transfer_pass` | `bool` |  |
| `spatial_transfer_pass` | `bool` |  |
| `mass_transfer_pass` | `bool` |  |
| `uncertainty_bound_transfer_pass` | `bool` |  |
| `cell_secretion_uptake_coupling_pass` | `bool` |  |
| `failure_contract_pass` | `bool` |  |
| `missing_failure_typed` | `bool` |  |
| `corrupt_failure_typed` | `bool` |  |
| `wrong_arch_failure_typed` | `bool` |  |
| `timeout_failure_typed` | `bool` |  |
| `oversized_output_failure_typed` | `bool` |  |
| `manifest_missing_failure_typed` | `bool` |  |
| `manifest_unverified_failure_typed` | `bool` |  |
| `manifest_tampered_failure_typed` | `bool` |  |
| `corrupt_asset_failure_typed` | `bool` |  |
| `corrupt_binary_failure_typed` | `bool` |  |
| `timeout_descendants_reaped` | `bool` |  |
| `oversized_output_descendants_reaped` | `bool` |  |
| `typed_failure_classes` | `list[str]` |  |
| `target_rate_evidence` | `bool` |  |
| `insulin_reaction_supported` | `bool` |  |
| `scientific_uncertainty_evidence` | `bool` |  |
| `scientific_validated` | `bool` |  |
| `technical_qualified` | `bool` |  |
| `evidence_class` | `str` |  |
| `unsupported_semantics` | `list[str]` |  |
| `integration_guidance` | `list[str]` |  |
| `scenarios` | `list[PhysiCellScenario]` |  |
| `execution` | `PhysiCellExecution` |  |
| `result_sha256` | `str` |  |
| `mode` | `str` |  |
| `direct_parity_pass` | `bool` |  |
| `direct_result_sha256` | `str` |  |
| `direct_residual` | `f64` |  |
| `direct_artifact_sha256` | `str` |  |
| `artifact_directory` | `str` |  |
| `result_path` | `str` |  |

# `bridge physicell_backend`



# `physiology`

Evidence-bound glucose, insulin, beta-cell, immune, and graft physiology.

# `def initial_physiology_parameters`

```sema
def initial_physiology_parameters() -> dict[str, f64] !{}
```

**Returns** `dict[str, f64]`

**Effects** `!{}`

# `def physiology_parameter_bounds`

```sema
def physiology_parameter_bounds() -> dict[str, list[f64]] !{}
```

**Returns** `dict[str, list[f64]]`

**Effects** `!{}`

# `def physiology_parameter_value_valid`

```sema
def physiology_parameter_value_valid(name: str, value: f64) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |
| `value` | `f64` |

**Returns** `bool`

**Effects** `!{}`

# `def initial_physiology_state`

```sema
def initial_physiology_state() -> dict[str, any] !{}
```

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def physiology_equations`

```sema
def physiology_equations() -> list[str] !{}
```

**Returns** `list[str]`

**Effects** `!{}`

# `def physiology_rates`

```sema
def physiology_rates(parameters: dict[str, f64], signals: dict[str, f64])
```

**Parameters**

| name | type |
|---|---|
| `parameters` | `dict[str, f64]` |
| `signals` | `dict[str, f64]` |

# `def bounded_physiology_values`

```sema
def bounded_physiology_values(values: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `values` | `list[f64]` |

# `def step_physiology_state`

```sema
def step_physiology_state(state: dict[str, any], dt_s: f64, signals: dict[str, f64], parameters: dict[str, f64]) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `state` | `dict[str, any]` |
| `dt_s` | `f64` |
| `signals` | `dict[str, f64]` |
| `parameters` | `dict[str, f64]` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def physiology_public_state`

```sema
def physiology_public_state(state: dict[str, any], signals: dict[str, f64], parameters: dict[str, f64]) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `state` | `dict[str, any]` |
| `signals` | `dict[str, f64]` |
| `parameters` | `dict[str, f64]` |

**Returns** `dict[str, any]`

**Effects** `!{}`



# `portable`

Measured Phase 9 ABI, CPU/MPS, process-loss, and checkpoint evidence.

# `struct PortabilityResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `profile_identity_sha256` | `str` |  |
| `config_sha256` | `str` |  |
| `source_result_sha256` | `str` |  |
| `source_artifact_sha256` | `str` |  |
| `backend_identity_sha256` | `str` |  |
| `backend_source_sha256` | `str` |  |
| `sema_contract_source_sha256` | `str` |  |
| `numpy_version` | `str` |  |
| `torch_version` | `str` |  |
| `python_version` | `str` |  |
| `cpu_backend` | `str` |  |
| `cpu_device` | `str` |  |
| `gpu_backend` | `str` |  |
| `gpu_device` | `str` |  |
| `mps_available` | `bool` |  |
| `mps_evidence_status` | `str` |  |
| `precision` | `str` |  |
| `batch` | `int` |  |
| `voxels` | `int` |  |
| `steps` | `int` |  |
| `repeats` | `int` |  |
| `concentration_residual_micromolar` | `f64` |  |
| `cpu_mass_relative_residual` | `f64` |  |
| `gpu_mass_relative_residual` | `f64` |  |
| `cpu_p95_latency_ms` | `f64` |  |
| `gpu_p95_latency_ms` | `f64` |  |
| `cpu_throughput_voxel_steps_per_s` | `f64` |  |
| `gpu_throughput_voxel_steps_per_s` | `f64` |  |
| `gpu_allocated_bytes` | `int` |  |
| `gpu_host_transfer_bytes` | `int` |  |
| `abi_scope` | `str` |  |
| `bulk_elements` | `int` |  |
| `bulk_payload_bytes` | `int` |  |
| `bulk_calls` | `int` |  |
| `bulk_p95_latency_ms` | `f64` |  |
| `bulk_checksum_residual` | `f64` |  |
| `bulk_pointer_equal` | `bool` |  |
| `bulk_shares_memory` | `bool` |  |
| `cpu_zero_copy` | `bool` |  |
| `gpu_zero_copy` | `bool` |  |
| `sema_bridge_zero_copy_validated` | `bool` |  |
| `bulk_abi_pass` | `bool` |  |
| `distributed_evidence_kind` | `str` |  |
| `multiprocessing_start_method` | `str` |  |
| `distributed_worker_count` | `int` |  |
| `distributed_partition_batch` | `int` |  |
| `distributed_total_steps` | `int` |  |
| `worker_pids` | `list[int]` |  |
| `survivor_worker_ids` | `list[int]` |  |
| `survivor_worker_pids` | `list[int]` |  |
| `survivor_worker_exitcodes` | `list[int]` |  |
| `killed_worker_id` | `int` |  |
| `killed_worker_pid` | `int` |  |
| `killed_worker_exitcode` | `int` |  |
| `killed_worker_signal` | `str` |  |
| `recovery_worker_pid` | `int` |  |
| `recovery_worker_exitcode` | `int` |  |
| `recovery_resumed_step` | `int` |  |
| `stable_checkpoint_step` | `int` |  |
| `partial_checkpoint_step` | `int` |  |
| `partial_checkpoint_bytes` | `int` |  |
| `partial_checkpoint_intended_bytes` | `int` |  |
| `rejected_checkpoint_count` | `int` |  |
| `rejected_checkpoint_error_codes` | `list[str]` |  |
| `checkpoint_manifest_sha256` | `str` |  |
| `distributed_residual_micromolar` | `f64` |  |
| `corrupt_checkpoint_blocked` | `bool` |  |
| `partial_checkpoint_blocked` | `bool` |  |
| `worker_loss_failure_validated` | `bool` |  |
| `same_node_distributed_process_pass` | `bool` |  |
| `distributed_validated` | `bool` |  |
| `cross_node_distributed_validated` | `bool` |  |
| `checkpoint_pass` | `bool` |  |
| `device_loss_evidence_kind` | `str` |  |
| `device_loss_injection_attempted` | `bool` |  |
| `device_loss_injection_observed` | `bool` |  |
| `device_loss_recovery_pass` | `bool` |  |
| `device_loss_recovery_residual_micromolar` | `f64` |  |
| `device_loss_failure_validated` | `bool` |  |
| `physical_device_loss_observed` | `bool` |  |
| `physical_device_loss_validated` | `bool` |  |
| `scientific_parity_pass` | `bool` |  |
| `cpu_profile_qualified` | `bool` |  |
| `gpu_profile_qualified` | `bool` |  |
| `single_node_portability_pass` | `bool` |  |
| `local_technical_pass` | `bool` |  |
| `portable_core_validated` | `bool` |  |
| `direct_parity_pass` | `bool` |  |
| `phase9_admitted` | `bool` |  |
| `phase9_validated` | `bool` |  |
| `scientific_validated` | `bool` |  |
| `evidence_class` | `str` |  |
| `direct_oracle_result_sha256` | `str` |  |
| `direct_oracle_artifact_sha256` | `str` |  |
| `direct_oracle_path` | `str` |  |
| `direct_residual` | `f64` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |

# `bridge portable_backend`



# `profiles`

Honest contracts for QM/MM, mesoscopic, cellular, and performance phases.

# `struct QmMmPartition`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `qm_atom_indices` | `list[int]` |  |
| `mm_atom_indices` | `list[int]` |  |
| `boundary_atom_indices` | `list[int]` |  |
| `total_charge_e` | `int` |  |
| `spin_multiplicity` | `int` |  |
| `embedding` | `str` |  |
| `backend_profile_id` | `str` |  |

# `struct ParameterizationEdge`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `source_model_id` | `str` |  |
| `target_model_id` | `str` |  |
| `parameter_names` | `list[str]` |  |
| `values` | `list[f64]` |  |
| `uncertainties` | `list[f64]` |  |
| `units` | `list[str]` |  |
| `evidence_ids` | `list[str]` |  |

# `struct PlatformBenchmark`

**Fields**

| field | type | descriptor |
|---|---|---|
| `profile_id` | `str` |  |
| `hardware` | `str` |  |
| `operating_system` | `str` |  |
| `backend` | `str` |  |
| `precision` | `str` |  |
| `model_digest` | `str` |  |
| `tolerance_profile` | `str` |  |
| `simulated_ns_per_day` | `f64` |  |
| `p50_step_ms` | `f64` |  |
| `p95_step_ms` | `f64` |  |
| `resident_memory_bytes` | `int` |  |
| `transfer_bytes` | `int` |  |
| `observable_error` | `f64` |  |
| `evidence_ids` | `list[str]` |  |

# `enum NativeKernelKind`

**Variants**

- `sema_aot`
- `rust_native`
- `c_abi`
- `cpp_abi`
- `ecosystem_bridge`

# `enum AcceleratorKind`

**Variants**

- `cpu`
- `apple_metal`
- `apple_mps`
- `mlx`
- `cuda`
- `hip`
- `webgl2`
- `webgpu`

# `struct KernelDemand`

**Fields**

| field | type | descriptor |
|---|---|---|
| `operation` | `str` |  |
| `precision` | `str` |  |
| `tolerance_profile` | `str` |  |
| `minimum_throughput_per_s` | `f64` |  |
| `maximum_p95_ms` | `f64` |  |
| `maximum_observable_error` | `f64` |  |
| `maximum_resident_memory_bytes` | `int` |  |

# `struct NativeAccelerationProfile`

**Fields**

| field | type | descriptor |
|---|---|---|
| `profile_id` | `str` |  |
| `kernel_id` | `str` |  |
| `native_kind` | `NativeKernelKind` |  |
| `accelerator` | `AcceleratorKind` |  |
| `device_name` | `str` |  |
| `precision` | `str` |  |
| `tolerance_profile` | `str` |  |
| `available` | `bool` |  |
| `qualified` | `bool` |  |
| `zero_copy` | `bool` |  |
| `unified_memory` | `bool` |  |
| `supported_operations` | `list[str]` |  |
| `measured_throughput_per_s` | `f64` |  |
| `measured_p95_ms` | `f64` |  |
| `observable_error` | `f64` |  |
| `resident_memory_bytes` | `int` |  |
| `host_device_transfer_bytes` | `int` |  |
| `artifact_sha256` | `str` |  |
| `model_sha256` | `str` |  |
| `oracle_evidence_ids` | `list[str]` |  |
| `benchmark_evidence_ids` | `list[str]` |  |

# `struct AccelerationDecision`

**Fields**

| field | type | descriptor |
|---|---|---|
| `selected` | `bool` |  |
| `profile_id` | `str` |  |
| `native_kind` | `NativeKernelKind` |  |
| `accelerator` | `AcceleratorKind` |  |
| `zero_copy` | `bool` |  |
| `reason` | `str` |  |

# `def operation_supported`

```sema
def operation_supported(operation: str, supported_operations: list[str])
```

**Parameters**

| name | type |
|---|---|
| `operation` | `str` |
| `supported_operations` | `list[str]` |

# `def acceleration_priority`

```sema
def acceleration_priority(accelerator: AcceleratorKind)
```

**Parameters**

| name | type |
|---|---|
| `accelerator` | `AcceleratorKind` |

# `def acceleration_profile_eligible`

```sema
def acceleration_profile_eligible(profile: NativeAccelerationProfile, demand: KernelDemand)
```

**Parameters**

| name | type |
|---|---|
| `profile` | `NativeAccelerationProfile` |
| `demand` | `KernelDemand` |

# `def select_native_acceleration`

```sema
def select_native_acceleration(demand: KernelDemand, profiles: list[NativeAccelerationProfile]) -> AccelerationDecision !{}
```

**Parameters**

| name | type |
|---|---|
| `demand` | `KernelDemand` |
| `profiles` | `list[NativeAccelerationProfile]` |

**Returns** `AccelerationDecision`

**Effects** `!{}`

# `def indices_unique`

```sema
def indices_unique(values: list[int])
```

**Parameters**

| name | type |
|---|---|
| `values` | `list[int]` |

# `def lists_disjoint`

```sema
def lists_disjoint(left_values: list[int], right_values: list[int])
```

**Parameters**

| name | type |
|---|---|
| `left_values` | `list[int]` |
| `right_values` | `list[int]` |

# `def qmmm_partition_valid`

```sema
def qmmm_partition_valid(partition: QmMmPartition, atom_count: int) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `partition` | `QmMmPartition` |
| `atom_count` | `int` |

**Returns** `bool`

**Effects** `!{}`

# `def parameterization_valid`

```sema
def parameterization_valid(edge: ParameterizationEdge) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `edge` | `ParameterizationEdge` |

**Returns** `bool`

**Effects** `!{}`

# `def benchmark_comparable`

```sema
def benchmark_comparable(reference: PlatformBenchmark, candidate: PlatformBenchmark) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `reference` | `PlatformBenchmark` |
| `candidate` | `PlatformBenchmark` |

**Returns** `bool`

**Effects** `!{}`

# `def unavailable_phase`

```sema
def unavailable_phase(phase: int, profile_id: str, backend: str)
```

**Parameters**

| name | type |
|---|---|
| `phase` | `int` |
| `profile_id` | `str` |
| `backend` | `str` |



# `programming`

Typed, transactional biological programming plans for viewers and agents.

# `def initial_signal_values`

```sema
def initial_signal_values()
```

# `def initial_program_state`

```sema
def initial_program_state() -> dict[str, any] !{}
```

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def normalized_signal`

```sema
def normalized_signal(name: str)
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |

# `def signal_bounds`

```sema
def signal_bounds() -> dict[str, list[f64]] !{}
```

**Returns** `dict[str, list[f64]]`

**Effects** `!{}`

# `def signal_value_valid`

```sema
def signal_value_valid(name: str, value: f64)
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |
| `value` | `f64` |

# `def signal_operation`

```sema
def signal_operation(name: str, value: f64)
```

**Parameters**

| name | type |
|---|---|
| `name` | `str` |
| `value` | `f64` |

# `def design_command_result`

```sema
def design_command_result(text: str)
```

**Parameters**

| name | type |
|---|---|
| `text` | `str` |

# `def design_command_valid`

```sema
def design_command_valid(design: any) !{}
```

**Parameters**

| name | type |
|---|---|
| `design` | `any` |

**Effects** `!{}`

# `def compile_biological_command`

```sema
def compile_biological_command(command: str) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `command` | `str` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def program_operation_valid`

```sema
def program_operation_valid(operation: dict[str, any]) !{}
```

**Parameters**

| name | type |
|---|---|
| `operation` | `dict[str, any]` |

**Effects** `!{}`

# `def apply_biological_program`

```sema
def apply_biological_program(state: dict[str, any], payload: dict[str, any]) -> dict[str, any] !{}
```

**Parameters**

| name | type |
|---|---|
| `state` | `dict[str, any]` |
| `payload` | `dict[str, any]` |

**Returns** `dict[str, any]`

**Effects** `!{}`

# `def programming_capabilities`

```sema
def programming_capabilities() -> dict[str, any] !{}
```

**Returns** `dict[str, any]`

**Effects** `!{}`



# `qmmm`

Fixed-partition electrostatic-embedding QM/MM technical evidence.

# `struct QmmmResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `backend` | `str` |  |
| `backend_version` | `str` |  |
| `method` | `str` |  |
| `basis` | `str` |  |
| `embedding` | `str` |  |
| `qm_atoms` | `int` |  |
| `mm_point_charges` | `int` |  |
| `charge_e` | `int` |  |
| `spin_2s` | `int` |  |
| `link_atoms` | `int` |  |
| `boundary_treatment` | `str` |  |
| `reaction_coordinate` | `str` |  |
| `coordinate_angstrom` | `list[f64]` |  |
| `energies_hartree` | `list[f64]` |  |
| `forces_hartree_per_bohr` | `list[f64]` |  |
| `reaction_span_kj_mol` | `f64` |  |
| `energy_symmetry_residual_hartree` | `f64` |  |
| `force_antisymmetry_residual_hartree_per_bohr` | `f64` |  |
| `center_force_hartree_per_bohr` | `f64` |  |
| `gradient_residual_hartree_per_bohr` | `f64` |  |
| `symmetry_pass` | `bool` |  |
| `gradient_pass` | `bool` |  |
| `technical_pass` | `bool` |  |
| `evidence_class` | `str` |  |
| `adaptive_partition` | `bool` |  |
| `multicode_validated` | `bool` |  |
| `result_sha256` | `str` |  |
| `direct_oracle_result_sha256` | `str` |  |
| `direct_oracle_path` | `str` |  |
| `direct_energy_residual_hartree` | `f64` |  |
| `direct_force_residual_hartree_per_bohr` | `f64` |  |
| `direct_gradient_residual_hartree_per_bohr` | `f64` |  |
| `direct_parity_pass` | `bool` |  |
| `result_path` | `str` |  |

# `bridge qmmm_backend`



# `qmmm_multicode`

Pinned 6S34 insulin fixed-partition QM/MM evidence with honest second-code gating.

# `struct QmmmMulticodeResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `backend_source_path` | `str` |  |
| `backend_source_sha256` | `str` |  |
| `sema_contract_source_path` | `str` |  |
| `sema_contract_source_sha256` | `str` |  |
| `oracle_source_path` | `str` |  |
| `oracle_source_sha256` | `str` |  |
| `structure_path` | `str` |  |
| `structure_sha256` | `str` |  |
| `pdb_id` | `str` |  |
| `partition_id` | `str` |  |
| `partition_identity_sha256` | `str` |  |
| `qm_atom_ids` | `list[str]` |  |
| `boundary_identities` | `Any` |  |
| `link_atom_ids` | `list[str]` |  |
| `embedding_site_identities` | `Any` |  |
| `embedding_model` | `str` |  |
| `embedding_total_charge_e` | `f64` |  |
| `qm_charge_e` | `int` |  |
| `spin_multiplicity` | `int` |  |
| `source_reaction_coordinate_angstrom` | `f64` |  |
| `reaction_coordinates_angstrom` | `list[f64]` |  |
| `primary_backend` | `str` |  |
| `primary_version` | `str` |  |
| `primary_method` | `str` |  |
| `primary_basis` | `str` |  |
| `primary_status` | `str` |  |
| `primary_executed` | `bool` |  |
| `primary_energies_hartree` | `list[f64]` |  |
| `primary_forces_hartree_per_angstrom` | `list[f64]` |  |
| `primary_mulliken_charges_e` | `Any` |  |
| `primary_scf_iterations` | `list[int]` |  |
| `primary_converged` | `bool` |  |
| `primary_charge_sum_residual_e` | `f64` |  |
| `secondary_backend` | `str` |  |
| `secondary_requested_version` | `str` |  |
| `secondary_observed_version` | `str` |  |
| `secondary_status` | `str` |  |
| `secondary_failure_code` | `str` |  |
| `secondary_unavailable_reason` | `str` |  |
| `secondary_executed` | `bool` |  |
| `secondary_energies_hartree` | `list[f64]` |  |
| `secondary_forces_hartree_per_angstrom` | `list[f64]` |  |
| `secondary_atomic_charges_e` | `Any` |  |
| `secondary_converged` | `bool` |  |
| `partition_identity_pass` | `bool` |  |
| `primary_technical_pass` | `bool` |  |
| `multicode_energy_parity_pass` | `bool` |  |
| `multicode_force_parity_pass` | `bool` |  |
| `multicode_charge_parity_pass` | `bool` |  |
| `multicode_reaction_coordinate_parity_pass` | `bool` |  |
| `multicode_technical_pass` | `bool` |  |
| `insulin_partition_validated` | `bool` |  |
| `phase7_validated` | `bool` |  |
| `multicode_residuals_available` | `bool` |  |
| `maximum_energy_residual_hartree` | `f64` |  |
| `maximum_force_residual_hartree_per_angstrom` | `f64` |  |
| `maximum_atomic_charge_residual_e` | `f64` |  |
| `scientific_validated` | `bool` |  |
| `evidence_class` | `str` |  |
| `platform` | `str` |  |
| `result_sha256` | `str` |  |
| `direct_oracle_result_sha256` | `str` |  |
| `direct_oracle_path` | `str` |  |
| `direct_residual` | `f64` |  |
| `direct_parity_pass` | `bool` |  |
| `result_path` | `str` |  |

# `bridge qmmm_multicode_backend`

# `def run_profile`

```sema
def run_profile(config_path: str, oracle_path: str, output_path: str) -> QmmmMulticodeResult !{ffi.call, fs.read, fs.write}
```

**Parameters**

| name | type |
|---|---|
| `config_path` | `str` |
| `oracle_path` | `str` |
| `output_path` | `str` |

**Returns** `QmmmMulticodeResult`

**Effects** `!{ffi.call, fs.read, fs.write}`



# `rare_event`

Bounded well-tempered metadynamics with an exact symmetry reference.

# `struct RareEventResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `benchmark_id` | `str` |  |
| `method` | `str` |  |
| `method_reference_doi` | `str` |  |
| `engine` | `str` |  |
| `engine_version` | `str` |  |
| `platform` | `str` |  |
| `config_sha256` | `str` |  |
| `system_sha256` | `str` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |
| `replay_class` | `str` |  |
| `reference_replay_class` | `str` |  |
| `evidence_class` | `str` |  |
| `replicas` | `int` |  |
| `grid_min_nm` | `f64` |  |
| `grid_max_nm` | `f64` |  |
| `grid_width` | `int` |  |
| `free_energy_mean_kj_mol` | `list[f64]` |  |
| `free_energy_sem_kj_mol` | `list[f64]` |  |
| `left_population_mean` | `f64` |  |
| `left_population_sem` | `f64` |  |
| `free_energy_difference_mean_kj_mol` | `f64` |  |
| `free_energy_difference_sem_kj_mol` | `f64` |  |
| `min_transitions` | `int` |  |
| `reference_left_population` | `f64` |  |
| `reference_free_energy_difference_kj_mol` | `f64` |  |
| `converged` | `bool` |  |

# `bridge rare_event_backend`



# `readdy_calibration`

Preregistered ReaDDy calibration qualification with held-out, fail-closed evidence.

# `struct ReaddyCalibrationResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `execution_config_sha256` | `str` |  |
| `evidence_sha256` | `str` |  |
| `evidence_rebound_without_execution` | `bool` |  |
| `result_sha256` | `str` |  |
| `source_digests` | `dict[str, str]` |  |
| `package_manifest` | `dict[str, any]` |  |
| `unit_mapping` | `dict[str, any]` |  |
| `target` | `dict[str, f64]` |  |
| `training_design` | `dict[str, any]` |  |
| `calibration_lock` | `dict[str, any]` |  |
| `heldout_design` | `dict[str, any]` |  |
| `heldout_evidence_admission` | `dict[str, any]` |  |
| `heldout_rates` | `dict[str, any]` |  |
| `condition_summaries` | `list[dict[str, any]]` |  |
| `statistics` | `dict[str, any]` |  |
| `gates` | `dict[str, bool]` |  |
| `qualification_pass` | `bool` |  |
| `calibration_evidence_status` | `str` |  |
| `failure_type` | `str` |  |
| `blockers` | `list[str]` |  |
| `phase8_scientific_validation` | `bool` |  |
| `scientific_validated` | `bool` |  |
| `scientific_validation_scope` | `str` |  |
| `training_evidence_manifest` | `list[dict[str, str]]` |  |
| `heldout_evidence_manifest` | `list[dict[str, str]]` |  |
| `runtime_seconds` | `f64` |  |

# `bridge readdy_calibration_backend`



# `reference`

Pinned condition-matched public molecular reference and published-timescale reproduction.

# `struct MolecularReferenceResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `reference_id` | `str` |  |
| `config_sha256` | `str` |  |
| `artifact_sha256` | `str` |  |
| `target_config_sha256` | `str` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |
| `license` | `str` |  |
| `primary_reference` | `str` |  |
| `engine` | `str` |  |
| `force_field` | `str` |  |
| `water_model` | `str` |  |
| `integrator` | `str` |  |
| `temperature_k` | `f64` |  |
| `observable` | `str` |  |
| `replicas` | `int` |  |
| `samples_per_replica` | `int` |  |
| `clusters` | `int` |  |
| `primary_lag_frames` | `int` |  |
| `slow_timescale_ps` | `f64` |  |
| `fast_timescale_ps` | `f64` |  |
| `slow_timescale_sem_ps` | `f64` |  |
| `fast_timescale_sem_ps` | `f64` |  |
| `right_population_mean` | `f64` |  |
| `right_population_sem` | `f64` |  |
| `right_population_by_replica` | `list[f64]` |  |
| `ensemble_transitions` | `int` |  |
| `ensemble_rhat` | `f64` |  |
| `ensemble_converged` | `bool` |  |
| `effective_samples` | `f64` |  |
| `lag_relative_spread_max` | `f64` |  |
| `kmeans_iterations` | `int` |  |
| `kmeans_final_shift` | `f64` |  |
| `reproduced` | `bool` |  |
| `condition_matched` | `bool` |  |
| `evidence_class` | `str` |  |

# `bridge molecular_reference`



# `rerun`

Non-authoritative Rerun recording projection for canonical molecular frames.

# `struct RerunRecording`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `path` | `str` |  |
| `frames` | `int` |  |
| `bytes` | `int` |  |
| `sha256` | `str` |  |
| `source_frames_sha256` | `str` |  |
| `source_result_sha256` | `str` |  |
| `coarse_result_sha256` | `str` |  |
| `ensemble_result_sha256` | `str` |  |
| `ensemble_sampling_converged` | `bool` |  |
| `rare_event_result_sha256` | `str` |  |
| `rare_event_technical_converged` | `bool` |  |
| `mace_result_sha256` | `str` |  |
| `mace_technical_pass` | `bool` |  |
| `mace_uncertainty_available` | `bool` |  |
| `mace_molecular_validated` | `bool` |  |
| `model_sha256` | `str` |  |
| `parameter_sha256` | `str` |  |
| `equation_terms` | `int` |  |

# `bridge rerun_projection`



# `resolution`

Approximation, negligibility, resolution-graph, and transactional transition contracts.

# `enum EdgeKind`

**Variants**

- `compose`
- `couple`
- `refine`
- `coarsen`
- `restrict`
- `prolong`
- `observe`
- `parameterize`

# `enum TransitionState`

**Variants**

- `requested`
- `prepared`
- `validated`
- `committed`
- `blocked`

# `struct ApproximationContract`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `source_model_id` | `str` |  |
| `target_model_id` | `str` |  |
| `transform` | `str` |  |
| `preserved_observables` | `list[str]` |  |
| `marginalized_degrees` | `list[str]` |  |
| `calibration_domain` | `str` |  |
| `maximum_error` | `f64` |  |
| `refine_threshold` | `f64` |  |
| `evidence_ids` | `list[str]` |  |
| `valid` | `bool` |  |

# `struct NegligibilityCertificate`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `interaction_family` | `str` |  |
| `target_observable` | `str` |  |
| `comparison_scale` | `str` |  |
| `upper_bound_ratio` | `f64` |  |
| `error_floor_ratio` | `f64` |  |
| `activation_condition` | `str` |  |
| `evidence_ids` | `list[str]` |  |
| `valid` | `bool` |  |

# `struct ResolutionNode`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `scale` | `ModelScale` |  |
| `model_version` | `str` |  |
| `resolved_degrees` | `list[str]` |  |
| `target_observables` | `list[str]` |  |
| `active` | `bool` |  |

# `struct ResolutionEdge`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `kind` | `EdgeKind` |  |
| `source_node_id` | `str` |  |
| `target_node_id` | `str` |  |
| `approximation` | `ApproximationContract` |  |
| `restriction` | `str` |  |
| `prolongation` | `str` |  |
| `checkpoint_only` | `bool` |  |

# `struct TransitionRecord`

**Fields**

| field | type | descriptor |
|---|---|---|
| `sequence` | `int` |  |
| `edge_id` | `str` |  |
| `from_state_version` | `int` |  |
| `to_state_version` | `int` |  |
| `state` | `TransitionState` |  |
| `reason` | `str` |  |
| `evidence_ids` | `list[str]` |  |
| `lost_information` | `list[str]` |  |
| `occurred_at_s` | `f64` |  |

# `def approximation_valid`

```sema
def approximation_valid(contract: ApproximationContract)
```

**Parameters**

| name | type |
|---|---|
| `contract` | `ApproximationContract` |

# `def negligibility_valid`

```sema
def negligibility_valid(certificate: NegligibilityCertificate)
```

**Parameters**

| name | type |
|---|---|
| `certificate` | `NegligibilityCertificate` |

# `def edge_valid`

```sema
def edge_valid(edge: ResolutionEdge)
```

**Parameters**

| name | type |
|---|---|
| `edge` | `ResolutionEdge` |

# `def prepare_transition`

```sema
def prepare_transition(sequence: int, edge: ResolutionEdge, state_version: int, occurred_at_s: f64) -> TransitionRecord !{}
```

**Parameters**

| name | type |
|---|---|
| `sequence` | `int` |
| `edge` | `ResolutionEdge` |
| `state_version` | `int` |
| `occurred_at_s` | `f64` |

**Returns** `TransitionRecord`

**Effects** `!{}`

# `def validate_transition`

```sema
def validate_transition(record: TransitionRecord, evidence: list[EvidenceRecord], observable_error: f64, threshold: f64) -> TransitionRecord !{}
```

**Parameters**

| name | type |
|---|---|
| `record` | `TransitionRecord` |
| `evidence` | `list[EvidenceRecord]` |
| `observable_error` | `f64` |
| `threshold` | `f64` |

**Returns** `TransitionRecord`

**Effects** `!{}`

# `def commit_transition`

```sema
def commit_transition(record: TransitionRecord) -> TransitionRecord !{}
```

**Parameters**

| name | type |
|---|---|
| `record` | `TransitionRecord` |

**Returns** `TransitionRecord`

**Effects** `!{}`



# `statistics`

Bounded ensemble diagnostics, coarse-state comparison, and PMF correction algebra.

# `struct BasinPopulations`

**Fields**

| field | type | descriptor |
|---|---|---|
| `alpha` | `f64` |  |
| `beta` | `f64` |  |
| `other` | `f64` |  |
| `samples` | `int` |  |

# `struct EnsembleDiagnostics`

**Fields**

| field | type | descriptor |
|---|---|---|
| `samples` | `int` |  |
| `replicas` | `int` |  |
| `mean` | `f64` |  |
| `variance` | `f64` |  |
| `lag1_autocorrelation` | `f64` |  |
| `effective_sample_size` | `f64` |  |
| `converged` | `bool` |  |

# `struct DistributionComparison`

**Fields**

| field | type | descriptor |
|---|---|---|
| `total_variation` | `f64` |  |
| `threshold` | `f64` |  |
| `passed` | `bool` |  |

# `struct PmfCorrections`

**Fields**

| field | type | descriptor |
|---|---|---|
| `restraint_kj_mol` | `f64` |  |
| `jacobian_kj_mol` | `f64` |  |
| `finite_box_kj_mol` | `f64` |  |
| `standard_state_kj_mol` | `f64` |  |

# `struct PmfResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `raw_delta_g_kj_mol` | `f64` |  |
| `corrected_delta_g_kj_mol` | `f64` |  |
| `corrections` | `PmfCorrections` |  |
| `window_overlap_min` | `f64` |  |
| `effective_sample_size` | `f64` |  |
| `replicas` | `int` |  |
| `converged` | `bool` |  |
| `validated` | `bool` |  |

# `def basin_populations`

```sema
def basin_populations(phi_values: list[f64], psi_values: list[f64]) -> BasinPopulations !{}
```

**Parameters**

| name | type |
|---|---|
| `phi_values` | `list[f64]` |
| `psi_values` | `list[f64]` |

**Returns** `BasinPopulations`

**Effects** `!{}`

# `def compare_populations`

```sema
def compare_populations(fine: BasinPopulations, coarse: BasinPopulations, threshold: f64) -> DistributionComparison !{}
```

**Parameters**

| name | type |
|---|---|
| `fine` | `BasinPopulations` |
| `coarse` | `BasinPopulations` |
| `threshold` | `f64` |

**Returns** `DistributionComparison`

**Effects** `!{}`

# `def sample_mean`

```sema
def sample_mean(values: list[f64])
```

**Parameters**

| name | type |
|---|---|
| `values` | `list[f64]` |

# `def sample_variance`

```sema
def sample_variance(values: list[f64], average: f64)
```

**Parameters**

| name | type |
|---|---|
| `values` | `list[f64]` |
| `average` | `f64` |

# `def lag1_autocorrelation`

```sema
def lag1_autocorrelation(values: list[f64], average: f64, variance: f64)
```

**Parameters**

| name | type |
|---|---|
| `values` | `list[f64]` |
| `average` | `f64` |
| `variance` | `f64` |

# `def effective_sample_size`

```sema
def effective_sample_size(samples: int, autocorrelation: f64)
```

**Parameters**

| name | type |
|---|---|
| `samples` | `int` |
| `autocorrelation` | `f64` |

# `def diagnose_ensemble`

```sema
def diagnose_ensemble(values: list[f64], replicas: int, minimum_effective_samples: f64) -> EnsembleDiagnostics !{}
```

**Parameters**

| name | type |
|---|---|
| `values` | `list[f64]` |
| `replicas` | `int` |
| `minimum_effective_samples` | `f64` |

**Returns** `EnsembleDiagnostics`

**Effects** `!{}`

# `def probability_free_energy`

```sema
def probability_free_energy(probability: f64, temperature_k: f64)
```

**Parameters**

| name | type |
|---|---|
| `probability` | `f64` |
| `temperature_k` | `f64` |

# `def corrected_pmf`

```sema
def corrected_pmf(raw_delta_g_kj_mol: f64, corrections: PmfCorrections, window_overlap_min: f64, effective_samples: f64, replicas: int, converged: bool) -> PmfResult !{}
```

**Parameters**

| name | type |
|---|---|
| `raw_delta_g_kj_mol` | `f64` |
| `corrections` | `PmfCorrections` |
| `window_overlap_min` | `f64` |
| `effective_samples` | `f64` |
| `replicas` | `int` |
| `converged` | `bool` |

**Returns** `PmfResult`

**Effects** `!{}`



# `viewer`

Native scene verification, composition binding, and bounded viewer export.

# `struct ViewerSceneArtifact`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `path` | `str` |  |
| `bytes` | `int` |  |
| `scene_sha256` | `str` |  |
| `file_sha256` | `str` |  |
| `source_result_sha256` | `str` |  |
| `source_frames_sha256` | `str` |  |
| `atoms` | `int` |  |
| `bonds` | `int` |  |
| `frames` | `int` |  |
| `volume_result_sha256` | `str` |  |
| `volume_frames` | `int` |  |
| `cellular_voxels` | `int` |  |
| `tissue_voxels` | `int` |  |
| `scene_instances` | `int` |  |
| `protein_atoms` | `int` |  |
| `scenarios` | `int` |  |

# `def ala2_topology_bonds`

```sema
def ala2_topology_bonds()
```

# `def parse_pinned_topology`

```sema
def parse_pinned_topology(pdb_text: str) !{}
```

**Parameters**

| name | type |
|---|---|
| `pdb_text` | `str` |

**Effects** `!{}`

# `def atom_style`

```sema
def atom_style(element: str)
```

**Parameters**

| name | type |
|---|---|
| `element` | `str` |

# `def decorate_topology`

```sema
def decorate_topology(raw: dict[str, any])
```

**Parameters**

| name | type |
|---|---|
| `raw` | `dict[str, any]` |

# `def load_frames`

```sema
def load_frames(source: dict[str, any]) !{fs.read}
```

**Parameters**

| name | type |
|---|---|
| `source` | `dict[str, any]` |

**Effects** `!{fs.read}`

# `def measurement_sources`

```sema
def measurement_sources()
```

# `def composition_profiles`

```sema
def composition_profiles()
```

# `def prepare_viewer`

```sema
def prepare_viewer() -> ViewerSceneArtifact !{ffi.call, fs.read, fs.write}
```

**Returns** `ViewerSceneArtifact`

**Effects** `!{ffi.call, fs.read, fs.write}`



# `visualization`

Non-authoritative multiscale visual bindings and live equation-frame contracts.

# `enum FidelityClass`

**Variants**

- `canonical`
- `derived`
- `interpolated`
- `illustrative`
- `unknown`

# `enum VisualScale`

**Variants**

- `field_quantum`
- `atomic`
- `molecular`
- `cellular`
- `tissue`

# `enum GeometryOrigin`

**Variants**

- `measured`
- `simulated`
- `reconstructed`
- `illustrative`
- `unknown`

# `enum EquationUpdateKind`

**Variants**

- `state_step`
- `parameter_transition`
- `structural_transition`

# `struct EntityFocusPath`

**Fields**

| field | type | descriptor |
|---|---|---|
| `path_id` | `str` |  |
| `entity_ids` | `list[str]` |  |
| `selected_depth` | `int` |  |

# `struct ComplexityScenario`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `glucose_millimolar` | `f64` |  |
| `oxygen_fraction` | `f64` |  |
| `cytokine_fraction` | `f64` |  |
| `insulin_demand_fraction` | `f64` |  |
| `illustrative` | `bool` |  |

# `enum BiologicalEditKind`

**Variants**

- `signal`
- `morphology`
- `motility`
- `thermal`
- `bond_strength`
- `bond_form`
- `bond_break`
- `reset`

# `enum BiologicalEditTarget`

**Variants**

- `all`
- `beta_cell`
- `alpha_cell`
- `delta_cell`
- `acinar_cell`
- `adipocyte`
- `immune_cell`
- `vessel`
- `granule`
- `mitochondrion`
- `receptor`
- `protein`

# `struct BiologicalEditOperation`

**Fields**

| field | type | descriptor |
|---|---|---|
| `kind` | `BiologicalEditKind` |  |
| `target` | `BiologicalEditTarget` |  |
| `scalar` | `f64` |  |
| `atom_index_a` | `int` |  |
| `atom_index_b` | `int` |  |
| `compiled_equation` | `str` |  |

# `struct BiologicalEditPlan`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `request_id` | `str` |  |
| `natural_language` | `str` |  |
| `compiler_id` | `str` |  |
| `source_state_version` | `int` |  |
| `operations` | `list[BiologicalEditOperation]` |  |

# `struct BiologicalEditBudget`

**Fields**

| field | type | descriptor |
|---|---|---|
| `max_operations` | `int` |  |
| `max_structural_edits` | `int` |  |
| `atom_count` | `int` |  |
| `max_visible_instances` | `int` |  |
| `candidate_visible_instances` | `int` |  |

# `struct BiologicalEditDecision`

**Fields**

| field | type | descriptor |
|---|---|---|
| `request_id` | `str` |  |
| `admissible` | `bool` |  |
| `live_computed` | `bool` |  |
| `scientific_fidelity` | `FidelityClass` |  |
| `accepted_operations` | `int` |  |
| `reason` | `str` |  |

# `def biological_edit_operation_valid`

```sema
def biological_edit_operation_valid(operation: BiologicalEditOperation, atom_count: int)
```

**Parameters**

| name | type |
|---|---|
| `operation` | `BiologicalEditOperation` |
| `atom_count` | `int` |

# `def admit_biological_edit`

```sema
def admit_biological_edit(plan: BiologicalEditPlan, budget: BiologicalEditBudget)
```

**Parameters**

| name | type |
|---|---|
| `plan` | `BiologicalEditPlan` |
| `budget` | `BiologicalEditBudget` |

# `struct FieldOfViewBudget`

**Fields**

| field | type | descriptor |
|---|---|---|
| `field_of_view_m` | `f64` |  |
| `candidate_instances` | `int` |  |
| `required_upload_bytes` | `int` |  |
| `desired_update_hz` | `int` |  |
| `max_visible_instances` | `int` |  |
| `max_upload_bytes` | `int` |  |
| `max_update_hz` | `int` |  |

# `struct MultiscaleComputeDecision`

**Fields**

| field | type | descriptor |
|---|---|---|
| `scale` | `VisualScale` |  |
| `field_of_view_m` | `f64` |  |
| `visible_instances` | `int` |  |
| `update_hz` | `int` |  |
| `admissible` | `bool` |  |
| `reason` | `str` |  |

# `def visual_scale_for_field`

```sema
def visual_scale_for_field(field_of_view_m: f64)
```

**Parameters**

| name | type |
|---|---|
| `field_of_view_m` | `f64` |

# `def decide_multiscale_compute`

```sema
def decide_multiscale_compute(budget: FieldOfViewBudget) -> MultiscaleComputeDecision !{}
```

**Parameters**

| name | type |
|---|---|
| `budget` | `FieldOfViewBudget` |

**Returns** `MultiscaleComputeDecision`

**Effects** `!{}`

# `def focus_path_valid`

```sema
def focus_path_valid(path: EntityFocusPath) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `path` | `EntityFocusPath` |

**Returns** `bool`

**Effects** `!{}`

# `struct EquationTermSample`

**Fields**

| field | type | descriptor |
|---|---|---|
| `term_id` | `str` |  |
| `symbol` | `str` |  |
| `value` | `f64` |  |
| `unit_symbol` | `str` |  |
| `owner_model_id` | `str` |  |

# `struct EquationStateSample`

**Fields**

| field | type | descriptor |
|---|---|---|
| `entity_id` | `str` |  |
| `model_id` | `str` |  |
| `model_version` | `int` |  |
| `equation_id` | `str` |  |
| `equation_version` | `int` |  |
| `parameter_version` | `int` |  |
| `update_kind` | `EquationUpdateKind` |  |
| `terms` | `list[EquationTermSample]` |  |
| `residuals` | `list[EquationTermSample]` |  |
| `active_constraints` | `list[str]` |  |
| `transition_id` | `str` |  |
| `cause` | `str` |  |

# `struct VisualPrimitiveBinding`

**Fields**

| field | type | descriptor |
|---|---|---|
| `primitive_id` | `str` |  |
| `entity_id` | `str` |  |
| `observation_id` | `str` |  |
| `source_state_version` | `int` |  |
| `scale` | `VisualScale` |  |
| `fidelity` | `FidelityClass` |  |
| `origin` | `GeometryOrigin` |  |
| `source_algorithm` | `str` |  |
| `source_parameters` | `list[str]` |  |

# `struct VisualObservationEnvelope`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `scenario_id` | `str` |  |
| `run_id` | `str` |  |
| `observation_id` | `str` |  |
| `physical_time_s` | `f64` |  |
| `scheduler_tick` | `int` |  |
| `state_version` | `int` |  |
| `resolution_version` | `int` |  |
| `model_version` | `int` |  |
| `equation_version` | `int` |  |
| `parameter_version` | `int` |  |
| `source_frame_age_ms` | `f64` |  |
| `bindings` | `list[VisualPrimitiveBinding]` |  |
| `equation_states` | `list[EquationStateSample]` |  |
| `dropped_frames` | `int` |  |
| `interpolation_ratio` | `f64` |  |

# `def distinct_binding_ids`

```sema
def distinct_binding_ids(bindings: list[VisualPrimitiveBinding])
```

**Parameters**

| name | type |
|---|---|
| `bindings` | `list[VisualPrimitiveBinding]` |

# `def equations_cover_canonical_bindings`

```sema
def equations_cover_canonical_bindings(bindings: list[VisualPrimitiveBinding], equations: list[EquationStateSample])
```

**Parameters**

| name | type |
|---|---|
| `bindings` | `list[VisualPrimitiveBinding]` |
| `equations` | `list[EquationStateSample]` |

# `def validate_visual_observation`

```sema
def validate_visual_observation(frame: VisualObservationEnvelope) -> bool !{}
```

**Parameters**

| name | type |
|---|---|
| `frame` | `VisualObservationEnvelope` |

**Returns** `bool`

**Effects** `!{}`

# `def unknown_binding`

```sema
def unknown_binding(primitive_id: str, entity_id: str, observation_id: str, state_version: int, scale: VisualScale, reason: str)
```

**Parameters**

| name | type |
|---|---|
| `primitive_id` | `str` |
| `entity_id` | `str` |
| `observation_id` | `str` |
| `state_version` | `int` |
| `scale` | `VisualScale` |
| `reason` | `str` |

# `enum VisualRepresentation`

**Variants**

- `particles`
- `topology_bonds`
- `occupancy_envelope`
- `scalar_volume`
- `segmented_volume`
- `instanced_cells`
- `instanced_organelles`
- `instanced_vessels`
- `instanced_proteins`

# `struct SemanticScaleSource`

**Fields**

| field | type | descriptor |
|---|---|---|
| `source_id` | `str` |  |
| `scale` | `VisualScale` |  |
| `minimum_length_m` | `f64` |  |
| `maximum_length_m` | `f64` |  |
| `available` | `bool` |  |
| `fidelity` | `FidelityClass` |  |
| `origin` | `GeometryOrigin` |  |
| `observation_id` | `str` |  |
| `representation_ids` | `list[VisualRepresentation]` |  |
| `source_algorithm` | `str` |  |

# `struct ScaleDetailBinding`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `parent_scale` | `VisualScale` |  |
| `parent_selector` | `str` |  |
| `child_scale` | `VisualScale` |  |
| `child_model_id` | `str` |  |
| `default_child_kind` | `str` |  |
| `default_child_index` | `int` |  |
| `binding` | `str` |  |
| `fidelity` | `FidelityClass` |  |
| `evidence_ids` | `list[str]` |  |

# `struct MultiscaleCouplingEdge`

**Fields**

| field | type | descriptor |
|---|---|---|
| `id` | `str` |  |
| `source_scale` | `VisualScale` |  |
| `target_scale` | `VisualScale` |  |
| `source_observable` | `str` |  |
| `target_observable` | `str` |  |
| `coupling_expression` | `str` |  |
| `unit_symbol` | `str` |  |
| `maximum_error` | `f64` |  |
| `evidence_ids` | `list[str]` |  |
| `validated` | `bool` |  |

# `def detail_refinement_admissible`

```sema
def detail_refinement_admissible(binding: ScaleDetailBinding, parent_entity_id: str)
```

**Parameters**

| name | type |
|---|---|
| `binding` | `ScaleDetailBinding` |
| `parent_entity_id` | `str` |

# `def coupling_claim_admissible`

```sema
def coupling_claim_admissible(edge: MultiscaleCouplingEdge)
```

**Parameters**

| name | type |
|---|---|
| `edge` | `MultiscaleCouplingEdge` |

# `struct ViewportQuery`

**Fields**

| field | type | descriptor |
|---|---|---|
| `query_id` | `str` |  |
| `requested_scale` | `VisualScale` |  |
| `field_of_view_m` | `f64` |  |
| `observation_id` | `str` |  |
| `state_version` | `int` |  |
| `resolution_version` | `int` |  |

# `struct SemanticZoomDecision`

**Fields**

| field | type | descriptor |
|---|---|---|
| `query_id` | `str` |  |
| `requested_scale` | `VisualScale` |  |
| `rendered_scale` | `VisualScale` |  |
| `renderable` | `bool` |  |
| `fidelity` | `FidelityClass` |  |
| `origin` | `GeometryOrigin` |  |
| `source_id` | `str` |  |
| `source_observation_id` | `str` |  |
| `representation_ids` | `list[VisualRepresentation]` |  |
| `reason` | `str` |  |

# `def decide_semantic_zoom`

```sema
def decide_semantic_zoom(query: ViewportQuery, sources: list[SemanticScaleSource]) -> SemanticZoomDecision !{}
```

**Parameters**

| name | type |
|---|---|
| `query` | `ViewportQuery` |
| `sources` | `list[SemanticScaleSource]` |

**Returns** `SemanticZoomDecision`

**Effects** `!{}`



# `volume`

Versioned cellular and tissue segment-volume frames for bounded live replay.

# `struct BiologicalVolumeResult`

**Fields**

| field | type | descriptor |
|---|---|---|
| `schema` | `str` |  |
| `profile_id` | `str` |  |
| `config_sha256` | `str` |  |
| `source_result_sha256` | `str` |  |
| `result_sha256` | `str` |  |
| `result_path` | `str` |  |
| `frames` | `int` |  |
| `frame_interval_s` | `f64` |  |
| `cellular_voxels` | `int` |  |
| `tissue_voxels` | `int` |  |
| `cellular_segments` | `int` |  |
| `tissue_segments` | `int` |  |
| `scene_instances` | `int` |  |
| `insulin_atoms` | `int` |  |
| `scenario_count` | `int` |  |
| `volume_payload_bytes` | `int` |  |
| `deterministic_pass` | `bool` |  |
| `source_binding_pass` | `bool` |  |
| `phase10_technical_pass` | `bool` |  |
| `scientific_validated` | `bool` |  |
| `evidence_class` | `str` |  |

# `bridge volume_backend`

# `def run_volume_profile`

```sema
def run_volume_profile(config_path: str, output_path: str) -> BiologicalVolumeResult !{ffi.call, fs.read, fs.write}
```

**Parameters**

| name | type |
|---|---|
| `config_path` | `str` |
| `output_path` | `str` |

**Returns** `BiologicalVolumeResult`

**Effects** `!{ffi.call, fs.read, fs.write}`
