← All seeds & suites
ledger ADL 0.5.1 R&D & Biotech

Experiment Ledger

Scientific system of record closing the Design-Build-Test-Learn loop — linking scientist and versioned AI-model designs, sample lineage, calibrated instruments, protocol versions, plan-vs-actual runs, deviations, checksummed results, and published learnings.

Resources (11)
campaign, cycle, design, protocol, instrument, sample, run, event, deviation, result, learning
Roles (5)
lab_tech, ml_engineer, reviewer, scientist, admin
Features (10)
suitepermissionsstate_machinevalidationrules_engineviewsscheduled_tasksaudithistory_eventsindexes

A scientific system of record for R&D labs. experiment-ledger.infinity-sdg.com. An Infinity Software Development Group product built on Kalos/ADL.

Every lab has to answer two questions to be reproducible:

QuestionWhere Experiment Ledger keeps the answer
What did we plan to do?campaign → DBTL cycle → design → run plan (parameters, start time, protocol version)
What actually happened?run actuals → operational events → deviations → results, with raw-data checksums

It closes the Design-Build-Test-Learn loop. A cycle can’t move to Learn until results exist for it, and it can’t close until a learning is published. The next cycle’s designs can come from a scientist or a model. A model-proposed design must record the model’s name and version, so every result traces back to what proposed it.

What it enforces

The rules below are enforced on the server. Users can’t skip them, even by calling the API directly.

  • The plan is frozen once a run starts. Differences are recorded as deviations, never by editing the plan.
  • A run can’t complete while a critical deviation is still open. It can still be marked failed, which is an honest outcome.
  • No run starts on an instrument that is out of calibration. A daily schedule also takes lapsed instruments offline.
  • Results come only from runs that actually ran. A captured value is never edited: you reject it and capture a new one. Raw-data links must carry a SHA-256 checksum.
  • Protocol versions are written once. Each run keeps a copy of the version it followed.
  • Samples keep their lineage. For example, powder → pellet, through a parent link.
  • Every change is audited with the old and new values, who made it and when. Runs, cycles and their state changes also appear in a readable history timeline.

Resources

campaign · cycle · design · protocol · instrument · sample · run · event · deviation · result · learning

Views: planVersusActual, openDeviations, modelProposedDesigns. Roles: scientist, lab_tech, ml_engineer, reviewer, admin.

Demo data

The demo data is a materials-discovery lab with 10 campaigns. The solid-electrolyte campaign tells the full story:

  • Cycle 1 is closed. It has four conductivity runs and two phase-purity runs, each with a recorded deviation. One result was rejected for a bad electrode contact. A model-proposed design crossed 1 mS/cm, and the learning that points to cycle 2 is published.
  • Cycle 2 is mid-test. One run is still going: it has a critical glovebox-oxygen deviation open, so it can’t complete yet, and its first result is flagged. A second run is planned.
  • Elsewhere: the polymer campaign is concluded, the perovskite aging run failed when its lamp power supply tripped, and one furnace’s calibration has lapsed.

Regenerate the seed with python3 seeds/gen_seed.py.

Run it

This repo holds the product: the ADL domain, demo seed and site config. It runs on a Kalos checkout, as one of its *.infinity-sdg.com sub-domain sites.

export KALOS_REPO=~/kalos              # defaults to ../kalos beside this repo
scripts/kalos.sh validate              # static checks (adlref + config + seed)
scripts/kalos.sh start                 # certs + fresh DB + kalosd on :9205
scripts/kalos.sh verify                # boot, seed, exercise over TLS, stop

Each command first copies this repo into adl/v0.5/sub-domains/experiment-ledger/ inside Kalos, and registers the host in subdomains.md if needed. Edit files here, not in the Kalos copy.

Sign in as admin / Admin123!, or as scientist1, labtech1, mleng1 or reviewer1 / Demo123!.

Domain Resource Summary

ResourcePurpose & Lifecycle
campaignA research goal pursued through repeated DBTL cycles. (States: proposed, active, concluded, abandoned)
cycleOne Design-Build-Test-Learn iteration. The state machine IS the loop: design → build → test → learn → closed. A cycle cannot enter learn until at least one result exists for it, and cannot close until a learning has been written — the two controls that keep the loop closed rather than merely documented. (States: design, build, test, learn, closed)
designA candidate to build and test — a composition, formulation or process. Designs come from scientists or from models; a model-proposed design must name the model and its version, so a result can always be traced to what proposed it (AI provenance). (States: proposed, approved, built, rejected)
protocolA versioned procedure. The version string is copied onto every run that uses it, so a run always says which version it followed even after the protocol is amended. (States: draft, released, retired)
instrumentAn automation or analysis instrument. Calibration gates use. (States: available, maintenance, retired)
sampleA physical sample or asset with lineage. parent records what it was derived from (aliquot, transformation, prep), so any measurement can be walked back to its source material. (States: registered, in_use, consumed, disposed)
runThe pivot of the ledger: one execution, holding the PLAN (plannedParams, plannedStart, protocol version) beside the REALITY (actualParams, startedAt, endedAt). Anything that differs is recorded as a deviation, and a run cannot complete with a critical deviation still open. (States: planned, running, completed, failed, cancelled)
eventSomething that happened during operations: an error, a manual intervention, an environmental excursion.
deviationA difference between plan and reality, written down: which parameter, what was planned, what actually happened, and whether it matters. Deviations are the ledger’s answer to “what actually happened?”. (States: open, reviewed, closed)
resultA measurement, with provenance: the run that produced it, the sample it was taken from, where the raw data lives, and a checksum of that data. cycle is a copy on the flat row so the learn step can count results per cycle without traversal. (States: captured, verified, rejected)
learningWhat the cycle taught — the L in DBTL — and what to design next. (States: draft, published)
Inspect domain.yaml (690 lines)
# experiment-ledger/backend/domain.yaml
#
# Experiment Ledger — a scientific system of record.
#
# It answers the two questions every automated or semi-automated lab has to
# answer to be reproducible:
#
#     What did we PLAN to do?        campaign → cycle → design → run (plannedParams)
#     What ACTUALLY happened?        run (actualParams) → event → deviation → result
#
# and closes the Design-Build-Test-Learn (DBTL) loop: every cycle ends in a
# `learning` record that cites the results it rests on, and the next cycle's
# designs can come from a scientist or from a model, with the model's name and
# version kept on the row as provenance.
#
# Built as an ISDG product (resellable to any R&D lab: materials, energy,
# chemistry). The seed data is a materials-discovery lab.
#
# Constructs used (all from the clinical-trial-site sub-domain, same corpus):
#   type: reference / references            canonical cross-resource links
#   stateMachine: guards / sets: now()       §12
#   validation: isCreate() / fieldChanged()  §14  provenance + write-once rules
#   rules: query() / some() + reject|warn    §22  plan-vs-actual controls
#   features: { audit: true }                old AND new value on every change
#   history: events                          §21  human-readable timeline
#   schedules: action: transition            §24
#   indexes / views                          §19 / §26.2
#
# FIELD NAMING. Fields used as query() filter keys are single lowercase words
# (id, cycle, run, design, instrument, status, critical) — filter keys reach
# SQL unquoted on PostgreSQL, so camelCase keys would silently never match.
# Everything else is camelCase.

domain:
  name: ledger
  version: "1.0.0"
  description: >
    Scientific system of record. Connects scientific intent (campaigns, DBTL
    cycles, designs, planned runs) to physical reality (what ran, on which
    instrument, with which parameters, what went differently, and what was
    measured), so every result can be traced back to the plan it answered.

  resources:

    # ══════════════════════════════════════════════════════════════════
    # INTENT — what we planned to build
    # ══════════════════════════════════════════════════════════════════
    campaign:
      description: "A research goal pursued through repeated DBTL cycles."
      object:
        id:        { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        code:      { type: string, required: true, unique: true, maxLength: 24 }
        title:     { type: string, required: true, maxLength: 200 }
        objective: { type: text, required: true }
        area:      { type: string, required: true, enum: [medicine, materials, energy, chemistry, other] }
        lead:      { type: string, required: true, maxLength: 100 }
        startedOn: { type: date }
        concludedOn: { type: date }
        status:    { type: string, required: true, default: proposed }
      validation:
        concludesAfterStart:
          rule: "concludedOn == null || startedOn == null || concludedOn >= startedOn"
          message: "A campaign cannot conclude before it started."
      stateMachine:
        field: status
        initial: proposed
        states:
          proposed:
            transitions:
              activate: { to: active, guards: [scientist, admin], sets: { startedOn: now() } }
              abandon:  { to: abandoned, guards: [scientist, admin] }
          active:
            transitions:
              conclude: { to: concluded, guards: [scientist, admin], sets: { concludedOn: now() } }
              abandon:  { to: abandoned, guards: [scientist, admin] }
          concluded: {}
          abandoned: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [scientist, admin]
        update: [scientist, admin]
        delete: [admin]
      features: { audit: true }
      indexes:
        - { fields: [status] }

    cycle:
      description: >
        One Design-Build-Test-Learn iteration. The state machine IS the loop:
        design → build → test → learn → closed. A cycle cannot enter `learn`
        until at least one result exists for it, and cannot close until a
        learning has been written — the two controls that keep the loop
        closed rather than merely documented.
      object:
        id:         { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        campaign:
          type: reference
          references: "adl.ledger.ledger.campaign"
          required: true
        number:     { type: integer, required: true, min: 1 }
        hypothesis: { type: text, required: true }
        status:     { type: string, required: true, default: design }
      validation:
        numberIsWrittenOnce:
          rule: "isCreate() || !fieldChanged('number')"
          message: "A cycle number is permanent once assigned."
      stateMachine:
        field: status
        initial: design
        states:
          design:
            transitions:
              start_build: { to: build, guards: [scientist, admin] }
          build:
            transitions:
              start_test: { to: test, guards: [scientist, lab_tech, admin] }
          test:
            transitions:
              start_learn: { to: learn, guards: [scientist, admin] }
          learn:
            transitions:
              close: { to: closed, guards: [scientist, reviewer, admin] }
          closed: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [scientist, admin]
        update: [scientist, admin]
        delete: [admin]
      features: { audit: true }
      history:
        events:
          cycleAdvanced:
            trigger: transition
            label: "Cycle {number} moved to {status}"
            severity: info
      indexes:
        - { fields: [campaign] }
        - { fields: [status] }

    design:
      description: >
        A candidate to build and test — a composition, formulation or process.
        Designs come from scientists or from models; a model-proposed design
        must name the model and its version, so a result can always be traced
        to what proposed it (AI provenance).
      object:
        id:           { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        cycle:
          type: reference
          references: "adl.ledger.ledger.cycle"
          required: true
        code:         { type: string, required: true, unique: true, maxLength: 40 }
        summary:      { type: string, required: true, maxLength: 300 }
        origin:       { type: string, required: true, enum: [scientist, model] }
        modelName:    { type: string, maxLength: 100 }
        modelVersion: { type: string, maxLength: 40 }
        rationale:    { type: text }
        spec:         { type: json }
        predictedScore: { type: decimal, precision: 8, scale: 3 }
        status:       { type: string, required: true, default: proposed }
      validation:
        modelDesignsCarryProvenance:
          rule: "origin != 'model' || (modelName != null && modelVersion != null)"
          message: "A model-proposed design must record the model name and version."
        specIsWrittenOnceApproved:
          rule: "isCreate() || status == 'proposed' || !fieldChanged('spec')"
          message: "An approved design's spec is frozen. Propose a new design instead."
      stateMachine:
        field: status
        initial: proposed
        states:
          proposed:
            transitions:
              approve: { to: approved, guards: [scientist, reviewer, admin] }
              reject:  { to: rejected, guards: [scientist, reviewer, admin] }
          approved:
            transitions:
              mark_built: { to: built, guards: [lab_tech, scientist, admin] }
          built: {}
          rejected: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [scientist, ml_engineer, admin]
        update: [scientist, ml_engineer, admin]
        delete: [admin]
      features: { audit: true }
      indexes:
        - { fields: [cycle] }
        - { fields: [origin] }

    protocol:
      description: >
        A versioned procedure. The version string is copied onto every run
        that uses it, so a run always says which version it followed even
        after the protocol is amended.
      object:
        id:      { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        code:    { type: string, required: true, maxLength: 32 }
        title:   { type: string, required: true, maxLength: 200 }
        version: { type: string, required: true, maxLength: 12 }
        steps:   { type: json }
        status:  { type: string, required: true, default: draft }
      validation:
        versionIsWrittenOnce:
          rule: "isCreate() || !fieldChanged('version')"
          message: "A protocol version is permanent. Create the new version as a new record."
      stateMachine:
        field: status
        initial: draft
        states:
          draft:
            transitions:
              release: { to: released, guards: [scientist, admin] }
          released:
            transitions:
              retire: { to: retired, guards: [scientist, admin] }
          retired: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [scientist, admin]
        update: [scientist, admin]
        delete: [admin]
      features: { audit: true }
      indexes:
        - { fields: [code, version], unique: true }

    # ══════════════════════════════════════════════════════════════════
    # PHYSICAL REALITY — assets, samples, what ran
    # ══════════════════════════════════════════════════════════════════
    instrument:
      description: "An automation or analysis instrument. Calibration gates use."
      object:
        id:       { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        assetTag: { type: string, required: true, unique: true, maxLength: 32 }
        name:     { type: string, required: true, maxLength: 120 }
        kind:     { type: string, required: true, enum: [dispensing_robot, furnace, xrd, impedance_analyzer, tensile_tester, spectrometer, robot_arm, other] }
        location: { type: string, maxLength: 120 }
        calibrationDueOn: { type: date, required: true }
        status:   { type: string, required: true, default: available }
      stateMachine:
        field: status
        initial: available
        states:
          available:
            transitions:
              take_down: { to: maintenance, guards: [lab_tech, admin] }
          maintenance:
            transitions:
              return_to_service: { to: available, guards: [lab_tech, admin] }
              retire: { to: retired, guards: [admin] }
          retired: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [lab_tech, admin]
        update: [lab_tech, admin]
        delete: [admin]
      features: { audit: true }
      indexes:
        - { fields: [calibrationDueOn] }

    sample:
      description: >
        A physical sample or asset with lineage. `parent` records what it was
        derived from (aliquot, transformation, prep), so any measurement can
        be walked back to its source material.
      object:
        id:       { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        barcode:  { type: string, required: true, unique: true, maxLength: 40 }
        design:
          type: reference
          references: "adl.ledger.ledger.design"
        parent:
          type: reference
          references: "adl.ledger.ledger.sample"
        kind:     { type: string, required: true, enum: [precursor, powder, pellet, film, solution, coating, composite, other] }
        location: { type: string, maxLength: 120 }
        quantity: { type: decimal, precision: 12, scale: 4, min: 0 }
        unit:     { type: string, maxLength: 16 }
        status:   { type: string, required: true, default: registered }
      stateMachine:
        field: status
        initial: registered
        states:
          registered:
            transitions:
              use:     { to: in_use, guards: [lab_tech, scientist, admin] }
              dispose: { to: disposed, guards: [lab_tech, admin] }
          in_use:
            transitions:
              consume: { to: consumed, guards: [lab_tech, scientist, admin] }
              dispose: { to: disposed, guards: [lab_tech, admin] }
          consumed: {}
          disposed: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [lab_tech, scientist, admin]
        update: [lab_tech, scientist, admin]
        delete: [admin]
      features: { audit: true }
      indexes:
        - { fields: [design] }
        - { fields: [parent] }

    run:
      description: >
        The pivot of the ledger: one execution, holding the PLAN
        (plannedParams, plannedStart, protocol version) beside the REALITY
        (actualParams, startedAt, endedAt). Anything that differs is recorded
        as a deviation, and a run cannot complete with a critical deviation
        still open.
      object:
        id:       { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        cycle:
          type: reference
          references: "adl.ledger.ledger.cycle"
          required: true
        design:
          type: reference
          references: "adl.ledger.ledger.design"
          required: true
        protocol:
          type: reference
          references: "adl.ledger.ledger.protocol"
          required: true
        protocolVersion: { type: string, required: true, maxLength: 12 }
        instrument:
          type: reference
          references: "adl.ledger.ledger.instrument"
          required: true
        operator:      { type: string, required: true, maxLength: 100 }
        plannedParams: { type: json, required: true }
        actualParams:  { type: json }
        plannedStart:  { type: datetime, required: true }
        startedAt:     { type: datetime }
        endedAt:       { type: datetime }
        failureReason: { type: text }
        status:        { type: string, required: true, default: planned }
      validation:
        planIsFrozenOnceStarted:
          rule: "isCreate() || status == 'planned' || !fieldChanged('plannedParams')"
          message: "The plan is the record of intent. Once a run starts, record differences as deviations — don't edit the plan."
        endsAfterStart:
          rule: "endedAt == null || startedAt == null || endedAt >= startedAt"
          message: "A run cannot end before it started."
      stateMachine:
        field: status
        initial: planned
        states:
          planned:
            transitions:
              start:  { to: running, guards: [lab_tech, scientist, admin], sets: { startedAt: now() } }
              cancel: { to: cancelled, guards: [scientist, admin] }
          running:
            transitions:
              complete: { to: completed, guards: [lab_tech, scientist, admin], sets: { endedAt: now() } }
              fail:
                to: failed
                guards: [lab_tech, scientist, admin]
                requiredFields: [failureReason]
                sets: { endedAt: now() }
          completed: {}
          failed: {}
          cancelled: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [scientist, lab_tech, admin]
        update: [scientist, lab_tech, admin]
        delete: [admin]
      features: { audit: true }
      history:
        events:
          runStarted:   { trigger: transition, transition: start, severity: info }
          runCompleted: { trigger: transition, transition: complete, severity: success }
          runFailed:
            trigger: transition
            transition: fail
            capture: [failureReason]
            label: "Run failed: {failureReason}"
            severity: error
      indexes:
        - { fields: [cycle] }
        - { fields: [design] }
        - { fields: [instrument] }
        - { fields: [status] }

    event:
      description: "Something that happened during operations: an error, a manual intervention, an environmental excursion."
      object:
        id:       { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        run:
          type: reference
          references: "adl.ledger.ledger.run"
        instrument:
          type: reference
          references: "adl.ledger.ledger.instrument"
        kind:     { type: string, required: true, enum: [instrument_error, manual_intervention, environment, sample_issue, note] }
        severity: { type: string, required: true, enum: [info, warning, critical], default: info }
        occurredAt: { type: datetime, required: true }
        detail:   { type: text, required: true }
        reportedBy: { type: string, required: true, maxLength: 100 }
      validation:
        eventHasAContext:
          rule: "run != null || instrument != null"
          message: "An event must name the run or the instrument it happened on."
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [scientist, lab_tech, admin]
        update: [admin]
        delete: [admin]
      features: { audit: true }
      indexes:
        - { fields: [run] }
        - { fields: [occurredAt] }

    deviation:
      description: >
        A difference between plan and reality, written down: which parameter,
        what was planned, what actually happened, and whether it matters.
        Deviations are the ledger's answer to "what actually happened?".
      object:
        id:          { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        run:
          type: reference
          references: "adl.ledger.ledger.run"
          required: true
        parameter:   { type: string, required: true, maxLength: 80 }
        planned:     { type: string, required: true, maxLength: 200 }
        actual:      { type: string, required: true, maxLength: 200 }
        critical:    { type: boolean, required: true, default: false }
        explanation: { type: text }
        reviewedBy:  { type: string, maxLength: 100 }
        status:      { type: string, required: true, default: open }
      stateMachine:
        field: status
        initial: open
        states:
          open:
            transitions:
              review: { to: reviewed, guards: [reviewer, scientist, admin], sets: { reviewedBy: $user.id } }
          reviewed:
            transitions:
              close: { to: closed, guards: [reviewer, admin] }
          closed: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [scientist, lab_tech, admin]
        update: [scientist, lab_tech, reviewer, admin]
        delete: [admin]
      features: { audit: true }
      indexes:
        - { fields: [run] }
        - { fields: [status] }

    result:
      description: >
        A measurement, with provenance: the run that produced it, the sample
        it was taken from, where the raw data lives, and a checksum of that
        data. `cycle` is a copy on the flat row so the learn step can count
        results per cycle without traversal.
      object:
        id:          { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        run:
          type: reference
          references: "adl.ledger.ledger.run"
          required: true
        cycle:
          type: reference
          references: "adl.ledger.ledger.cycle"
          required: true
        sample:
          type: reference
          references: "adl.ledger.ledger.sample"
        measurement: { type: string, required: true, maxLength: 80 }
        value:       { type: decimal, required: true, precision: 18, scale: 6 }
        unit:        { type: string, required: true, maxLength: 24 }
        qc:          { type: string, required: true, enum: [pass, flag, fail], default: pass }
        dataUri:     { type: url }
        checksum:    { type: string, maxLength: 64, pattern: "^[a-f0-9]{64}$" }
        producedBy:  { type: string, required: true, maxLength: 100 }
        status:      { type: string, required: true, default: captured }
      validation:
        rawDataIsChecksummed:
          rule: "dataUri == null || checksum != null"
          message: "Raw data must carry its SHA-256 checksum so it can be verified later."
        valueIsWrittenOnce:
          rule: "isCreate() || !fieldChanged('value')"
          message: "A captured value is never edited. Reject it and capture a new one."
      stateMachine:
        field: status
        initial: captured
        states:
          captured:
            transitions:
              verify: { to: verified, guards: [scientist, reviewer, admin] }
              reject: { to: rejected, guards: [scientist, reviewer, admin] }
          verified: {}
          rejected: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [scientist, lab_tech, ml_engineer, admin]
        update: [scientist, reviewer, admin]
        delete: [admin]
      features: { audit: true }
      indexes:
        - { fields: [run] }
        - { fields: [cycle] }
        - { fields: [sample] }

    learning:
      description: "What the cycle taught — the L in DBTL — and what to design next."
      object:
        id:         { type: uuid, primaryKey: true, protected: true, allowUserProvided: true }
        cycle:
          type: reference
          references: "adl.ledger.ledger.cycle"
          required: true
        conclusion: { type: text, required: true }
        confidence: { type: percentage }
        nextStep:   { type: text }
        author:     { type: string, required: true, maxLength: 100 }
        status:     { type: string, required: true, default: draft }
      stateMachine:
        field: status
        initial: draft
        states:
          draft:
            transitions:
              publish: { to: published, guards: [scientist, reviewer, admin] }
          published: {}
      permissions:
        list:   [scientist, lab_tech, ml_engineer, reviewer, admin]
        get:    [scientist, lab_tech, ml_engineer, reviewer, admin]
        create: [scientist, ml_engineer, admin]
        update: [scientist, ml_engineer, admin]
        delete: [admin]
      features: { audit: true }
      indexes:
        - { fields: [cycle] }

  # ══════════════════════════════════════════════════════════════════
  # PLAN-VS-ACTUAL CONTROLS
  # ══════════════════════════════════════════════════════════════════
  rules:

    noRunOnAnOutOfCalibrationInstrument:
      description: "A run may not start on an instrument whose calibration has lapsed."
      trigger:
        resource: run
        events: [transition]
        transition: start
      condition: "some(query('instrument', { id: $record.instrument }),
                       i => i.calibrationDueOn < today() || i.status != 'available')"
      action: reject
      severity: error
      message: "The instrument is out of calibration or not available. Calibrate or choose another instrument."

    criticalDeviationsBlockCompletion:
      description: >
        A run with an open critical deviation has not finished being
        explained. It can still FAIL (that is a true account), but it cannot
        be marked complete.
      trigger:
        resource: run
        events: [transition]
        transition: complete
      condition: "len(query('deviation', { run: $record.id, status: 'open', critical: true })) > 0"
      action: reject
      severity: error
      message: "Review the open critical deviations on this run before completing it."

    resultsComeFromRunsThatRan:
      description: "A result must come from a run that actually started."
      trigger:
        resource: result
        events: [create]
      condition: "some(query('run', { id: $record.run }), r => r.status == 'planned' || r.status == 'cancelled')"
      action: reject
      severity: error
      message: "This run never started. Results can only be captured for runs that ran."

    learnNeedsResults:
      description: "The loop cannot move to Learn with nothing measured."
      trigger:
        resource: cycle
        events: [transition]
        transition: start_learn
      condition: "len(query('result', { cycle: $record.id })) == 0"
      action: reject
      severity: error
      message: "No results have been captured for this cycle yet."

    closeNeedsALearning:
      description: "A cycle closes only when what it taught has been written down."
      trigger:
        resource: cycle
        events: [transition]
        transition: close
      condition: "len(query('learning', { cycle: $record.id, status: 'published' })) == 0"
      action: reject
      severity: error
      message: "Publish a learning for this cycle before closing it."

    deviationClosesWithAnExplanation:
      description: "Closing a deviation without saying why it happened loses the record."
      trigger:
        resource: deviation
        events: [transition]
        transition: close
      condition: "$record.explanation == null"
      action: reject
      severity: error
      message: "Explain the deviation before closing it."

    criticalEventOnARun:
      description: "A critical event during a run is flagged so a deviation gets written."
      trigger:
        resource: event
        events: [create]
      condition: "$record.severity == 'critical' && $record.run != null"
      action: warn
      severity: warning
      message: "Critical event on a run — record a deviation if the plan was affected."

  schedules:

    takeLapsedInstrumentsOffline:
      description: "Every morning, instruments past their calibration date go to maintenance."
      recurrence: daily at 06:00
      source:
        resource: instrument
        filter: "status == 'available' && calibrationDueOn < today()"
      action: transition
      transition: take_down

  views:

    planVersusActual:
      description: "Every run, with the plan and the reality side by side."
      source: run
      permissions: [scientist, lab_tech, ml_engineer, reviewer, admin]
      columns:
        - { field: operator,        label: "Operator" }
        - { field: protocolVersion, label: "Protocol version" }
        - { field: plannedStart,    label: "Planned start" }
        - { field: startedAt,       label: "Actual start" }
        - { field: endedAt,         label: "Ended" }
        - { field: status,          label: "State" }
        - name: notStarted
          label: "Not started"
          computed: "startedAt == null"
      sort: plannedStart desc
      defaultLimit: 200

    openDeviations:
      description: "What still needs explaining, critical first."
      source: deviation
      filter: "status != 'closed'"
      permissions: [scientist, lab_tech, reviewer, admin]
      columns:
        - { field: parameter, label: "Parameter" }
        - { field: planned,   label: "Planned" }
        - { field: actual,    label: "Actual" }
        - { field: critical,  label: "Critical" }
        - { field: status,    label: "State" }
      sort: critical desc
      defaultLimit: 200

    modelProposedDesigns:
      description: "AI provenance: every design a model proposed, with the model and version."
      source: design
      filter: "origin == 'model'"
      permissions: [scientist, ml_engineer, reviewer, admin]
      columns:
        - { field: code,           label: "Design" }
        - { field: modelName,      label: "Model" }
        - { field: modelVersion,   label: "Version" }
        - { field: predictedScore, label: "Predicted score" }
        - { field: status,         label: "State" }
      sort: predictedScore desc
      defaultLimit: 200

Download seed bundle