colmugx/posoco/puppetry does not have a README file

    EventSubscriber

    pub(open) trait EventSubscriber {
    fn subscriber_id(Self) -> String
    fn provenance(Self) -> String
    async fn on_event(Self, EventEnvelope) -> Unit raise SubscriberError
    }

    Port: post-commit event subscriber. Receives one envelope at a time, in strict seq order, after the journal barrier succeeds.

    Subscribers must not:
    • mutate the envelope (it's passed by value, but the inner KernelEvent is immutable anyway)
    • reach into the journal (the trait exposes no writer)
    • re-enter the Harness via structural commands (ADR §11 reentrancy rule)

    Subscribers may:
    • read the envelope and any derived state
    • raise SubscriberError to fail the run (correctness-critical default)
    • maintain internal mutable state (e.g. a log buffer)

    HarnessLifecycleNode

    pub(open) trait HarnessLifecycleNode {
    fn node_id(Self) -> String
    fn provenance(Self) -> String
    async fn startup(Self) -> Unit raise LifecycleNodeError
    async fn shutdown(Self) -> Unit raise LifecycleNodeError
    }

    Port: top-level lifecycle node registered with the Harness.

    Each node has a stable node_id and a human-readable provenance. The Harness calls startup once in registration order at product startup, and shutdown once in reverse order at product shutdown.

    Both methods may raise LifecycleNodeError for typed failure paths. Untyped raise Error (e.g. from an async panic) is caught by the collection layer and converted to a typed LifecycleNodeError::Internal.

    JournalContributor

    pub(open) trait JournalContributor {
    fn contributor_id(Self) -> String
    fn provenance(Self) -> String
    fn contribute(Self, PreCommitContext) -> JournalContribution raise ContributionError
    }

    Port: pre-commit contributor. Receives an immutable PreCommitContext, returns a JournalContribution of proposed entries or a typed error.

    Contributors never receive a RunJournal reference; they cannot write directly. If they need a domain entry persisted, they must propose it here and let the coordinator commit it atomically.

    M2 does not ship any production contributor; the trait exists so M4/M5 extensions (e.g. memory persistence, observation logging) can register without modifying the Harness pump.

    RunJournal

    pub(open) trait RunJournal {
    fn append(Self, Array[JournalEntry]) -> Int raise HarnessError
    fn revision(Self) -> Int
    fn entries_for_run(Self,
    RunId
    ) -> Array[JournalEntry]
    fn entries_for_savepoint(Self,
    RunId
    , String) -> Array[JournalEntry]
    }

    Port: append-only journal with monotonic revision and identity validation.

    M2 ships InMemoryJournal. M5 will add JSONL/SQLite by implementing this.

    The trait intentionally exposes ONLY:
    • append: commit a frozen batch (advances revision)
    • revision: read current committed revision
    • entries_for_run: read projection (replay)
    • entries_for_savepoint: read a single savepoint's entries

    It does NOT expose:
    • any mutation of committed entries
    • any writer handle that subscribers could obtain
    • any "propose" or "contribute" method (that's the coordinator's job)

    ContributionError

    pub(all) suberror ContributionError {
    Internal(contributor_id~ : String, detail~ : String)
    Inconsistent(contributor_id~ : String, detail~ : String)
    }

    Typed error a contributor returns (or raises) when it cannot produce a contribution. The coordinator surfaces this as SavepointFailed with ContributorRaised cause.

    HarnessError

    pub(all) suberror HarnessError {
    IllegalPhaseTransition(from~ : HarnessPhase, to~ : HarnessPhase, operation~ : OperationClass, detail~ : String)
    OperationNotAllowedInPhase(phase~ : HarnessPhase, operation~ : OperationClass, detail~ : String)
    LeaseHeld(operation_id~ : String, held_by~ : String)
    LeaseNotHeld(operation_id~ : String, detail~ : String)
    AfterShutdown(command~ : String)
    SnapshotInvalid(detail~ : String)
    StaleIdentity(kind~ : String, expected~ : String, actual~ : String)
    QueueFull(kind~ : String, depth~ : Int)
    SuspensionPayloadMismatch(suspension_id~ : String, expected_kind~ : String)
    SuspensionIdMismatch(target_run_id~ :
    RunId
    , expected~ : String, actual~ : String)
    AbortNoActiveRun(run_id~ :
    RunId
    )
    SavepointFailed(kind~ : String, cause~ : SavepointFailureCause)
    ContributionInvalid(contributor_id~ : String, detail~ : String)
    SubscriberJournalMutation(subscriber_id~ : String)
    LifecycleStartupFailed(node_id~ : String, cause~ : String, rollback_failures~ : Array[(String, String)])
    LifecycleShutdownFailed(node_id~ : String, cause~ : String, other_failures~ : Array[(String, String)])
    LifecycleDuplicate(node_id~ : String)
    SubscriberFailed(subscriber_id~ : String, cause~ : String, committed_revision~ : Int)
    PumpLoopExceeded(iterations~ : Int)
    DuplicateOrLateCompletion(effect_id~ :
    EffectId
    , detail~ : String)
    ReducerInvariantViolation(category~ :
    InvariantCategory
    )
    }

    Typed errors raised by the Harness. Single suberror type because MoonBit can raise only one error type per function — all Harness subsystems contribute variants here (phase/journal/lifecycle/event/control).

    Variants are grouped by subsystem; new subsystems append, they do not rename existing variants.

    LifecycleNodeError

    pub(all) suberror LifecycleNodeError {
    Internal(node_id~ : String, detail~ : String)
    Inconsistent(node_id~ : String, detail~ : String)
    InvalidState(node_id~ : String, detail~ : String)
    }

    Typed error a node can raise from startup/shutdown.

    SubscriberError

    pub(all) suberror SubscriberError {
    Internal(subscriber_id~ : String, detail~ : String)
    ContractViolation(subscriber_id~ : String, detail~ : String)
    }

    Typed error a subscriber can raise.

    AbortCommand

    pub(all) struct AbortCommand {
    command_id : CommandId
    target_run_id :
    RunId

    detail : String?
    } derive(Eq,
    Debug
    )

    An abort command. Idempotent: the first call converts to RunInput::CancelRequested; subsequent calls return AbortAlreadyRequested.

    AbortCommand::command_id

    fn AbortCommand::command_id(self : AbortCommand) -> CommandId

    AbortCommand::detail

    fn AbortCommand::detail(self : AbortCommand) -> String?

    AbortCommand::target_run_id

    CommandId

    pub(all) struct CommandId {
    value : String
    } derive(Eq, Hash,
    Debug
    )

    Stable identifier for a control command. Used in diagnostics and in the queue's FIFO ordering (frozen at enqueue, consumed in command_id order within a safe point).
    impl Show for CommandId

    CommandId::new

    fn CommandId::new(value : String) -> Result[CommandId, String]

    CommandId::to_string

    fn CommandId::to_string(self : CommandId) -> String

    CommandId::unchecked

    fn CommandId::unchecked(value : String) -> CommandId

    ControlMailbox

    pub struct ControlMailbox {
    steer_queue :
    Queue
    [SteerCommand]
    follow_up_queue :
    Queue
    [FollowUpCommand]
    steer_depth : Int
    follow_up_depth : Int
    resume_pending : Map[String, ResumeCommand]
    abort_requested : Bool
    active_run_id :
    RunId
    ?
    active_turn_id : TurnId?
    idle_cond :
    Cond

    quiescent_status : QuiescentStatus
    max_depth : Int
    }

    The control mailbox bundle. One instance per Harness; tracks the currently-active run_id (so stale commands targeting an old run are rejected at enqueue time without needing to consult the phase gate).

    The steer and follow-up queues are @aqueue.Queue (MPMC, async-safe) so that a sibling task in the same TaskGroup can enqueue commands while the pump is mid-run (e.g. blocked on a model HTTP call). The pump drains them at safe points via try_get (non-blocking). resume_pending stays a Map because resume is addressed by suspension_id, not FIFO.

    ControlMailbox::abort_requested

    fn ControlMailbox::abort_requested(self : ControlMailbox) -> Bool

    ControlMailbox::active_run_id

    ControlMailbox::active_turn_id

    fn ControlMailbox::active_turn_id(self : ControlMailbox) -> TurnId?

    ControlMailbox::bind_run

    fn ControlMailbox::bind_run(self : ControlMailbox, run_id :
    RunId
    , turn_id : TurnId) -> Unit

    Bind the mailbox to a new active run/turn. Called by the Harness when acquiring a prompt lease. Clears any leftover state from the previous run.

    ControlMailbox::clear_run

    fn ControlMailbox::clear_run(self : ControlMailbox) -> Unit

    Clear the active run binding. Called by the Harness when the run reaches terminal. Any queued commands targeting the now-terminal run are dropped.

    ControlMailbox::consume_one_follow_up

    fn ControlMailbox::consume_one_follow_up(self : ControlMailbox) -> FollowUpCommand?

    Consume one follow-up command (OneAtATime policy). Returns the oldest if any, else None. The Harness calls this at a turn boundary.

    ControlMailbox::consume_steers

    fn ControlMailbox::consume_steers(self : ControlMailbox) -> Array[SteerCommand]

    Consume all steer commands at one safe point. The Harness calls this after a complete tool batch commits and before allocating the next model_step_id. Returns the commands in FIFO order; the queue is drained.

    Uses try_get (non-blocking) in a loop until the queue is empty.

    ControlMailbox::enqueue_abort

    fn ControlMailbox::enqueue_abort(self : ControlMailbox, cmd : AbortCommand) -> EnqueueResult

    Enqueue an abort. Idempotent: the first call sets abort_requested and returns Accepted; subsequent calls return AbortAlreadyRequested. Rejects if no active run.

    ControlMailbox::enqueue_follow_up

    fn ControlMailbox::enqueue_follow_up(self : ControlMailbox, cmd : FollowUpCommand) -> EnqueueResult

    Enqueue a follow-up command. Rejects if no active run or stale ids.

    ControlMailbox::enqueue_resume

    fn ControlMailbox::enqueue_resume(self : ControlMailbox, cmd : ResumeCommand) -> EnqueueResult

    Enqueue a resume command. Rejects if no active run or run id mismatch. Multiple resumes for the same suspension_id: the first wins, subsequent are rejected as stale.

    ControlMailbox::enqueue_steer

    fn ControlMailbox::enqueue_steer(self : ControlMailbox, cmd : SteerCommand) -> EnqueueResult

    Enqueue a steer command. Rejects if:
    • no active run (RejectedStale)
    • target_run_id / target_turn_id don't match active
    • queue full

    Uses try_put (non-blocking) on the underlying @aqueue.Queue. The queue is Unbounded, so we enforce max_depth manually via the steer_depth counter to preserve RejectedQueueFull semantics.

    ControlMailbox::follow_up_depth

    fn ControlMailbox::follow_up_depth(self : ControlMailbox) -> Int

    ControlMailbox::new

    ControlMailbox::quiescent_status

    fn ControlMailbox::quiescent_status(self : ControlMailbox) -> QuiescentStatus

    Current quiescent status. Set by the Harness via set_quiescent.

    ControlMailbox::set_quiescent

    fn ControlMailbox::set_quiescent(self : ControlMailbox, status : QuiescentStatus) -> Unit

    Update the quiescent status and wake all waiters. Called by the Harness when it reaches Idle / Suspended / Terminal / Shutdown. The status is read by wait_idle upon wake.

    ControlMailbox::steer_depth

    fn ControlMailbox::steer_depth(self : ControlMailbox) -> Int

    ControlMailbox::take_resume

    fn ControlMailbox::take_resume(self : ControlMailbox, suspension_id : String) -> ResumeCommand?

    Take the resume command for a given suspension_id. Returns None if no resume is pending for this suspension (the run stays suspended).

    ControlMailbox::wait_idle

    async fn ControlMailbox::wait_idle(self : ControlMailbox) -> QuiescentStatus

    Wait until the mailbox reaches a quiescent status. Implemented via @cond_var.Cond::wait — NOT polling, NOT sleep. Multiple waiters all wake on set_quiescent.

    Returns the quiescent status (never Idle-but-still-active — the Harness only sets quiescent when truly quiescent).

    EnqueueResult

    pub(all) enum EnqueueResult {
    Accepted(command_id~ : CommandId)
    RejectedStale(command_id~ : CommandId, reason~ : String)
    RejectedQueueFull(command_id~ : CommandId, depth~ : Int)
    AbortAlreadyRequested(command_id~ : CommandId)
    } derive(Eq,
    Debug
    )

    Result of enqueuing a control command.

    EventDispatcher

    pub struct EventDispatcher {
    subscribers : Array[&EventSubscriber]
    next_seq : Int
    last_committed_revision : Int
    run_id :
    RunId

    turn_id : TurnId
    session_id :
    SessionId

    }

    Post-commit event dispatcher. Holds the per-run seq counter and the subscriber list. The Harness constructs one dispatcher per Run; seq starts at 1 for each Run (seq 0 is reserved for "no events yet").

    ADR §5 step 6: dispatcher runs ONLY after commit succeeds.

    EventDispatcher::dispatch

    async fn EventDispatcher::dispatch(self : EventDispatcher, event :
    KernelEvent
    , committed_revision : Int) -> Unit raise HarnessError

    Dispatch a single KernelEvent to all subscribers. Assigns the next seq, builds the envelope, and awaits each subscriber in order.

    Raises HarnessError::SubscriberFailed if any subscriber raises. The dispatcher stops at the first failure (correctness-critical default).

    EventDispatcher::next_seq

    fn EventDispatcher::next_seq(self : EventDispatcher) -> Int

    Current seq counter value (next envelope gets this seq).

    EventDispatcher::register

    fn EventDispatcher::register(self : EventDispatcher, subscriber : &EventSubscriber) -> Unit

    Register a subscriber. Subscribers are dispatched in registration order. Must be called BEFORE any dispatch (the dispatcher does not support concurrent subscription during a run).

    EventDispatcher::subscriber_count

    fn EventDispatcher::subscriber_count(self : EventDispatcher) -> Int

    EventEnvelope

    pub(all) struct EventEnvelope {
    run_id :
    RunId

    turn_id : TurnId
    session_id :
    SessionId

    seq : Int
    committed_revision : Int
    event :
    KernelEvent

    } derive(Eq,
    Debug
    )

    A KernelEvent wrapped with run/session identity, monotonic sequence number, and the journal revision at which the event's savepoint committed. Subscribers receive envelopes, never raw KernelEvents.

    EventEnvelope::committed_revision

    fn EventEnvelope::committed_revision(self : EventEnvelope) -> Int

    EventEnvelope::is_terminal

    fn EventEnvelope::is_terminal(self : EventEnvelope) -> Bool

    Whether this envelope wraps a terminal event (RunCompleted / RunFailed / RunCancelled).

    EventEnvelope::new

    fn EventEnvelope::new(run_id~ :
    RunId
    , turn_id~ : TurnId, session_id~ :
    SessionId
    , seq~ : Int, committed_revision~ : Int, event~ :
    KernelEvent
    ) -> EventEnvelope

    Construct an envelope. Internal — only the Harness dispatcher builds envelopes (it owns the seq counter).

    EventEnvelope::run_id

    EventEnvelope::seq

    fn EventEnvelope::seq(self : EventEnvelope) -> Int

    EventEnvelope::session_id

    EventEnvelope::turn_id

    fn EventEnvelope::turn_id(self : EventEnvelope) -> TurnId

    ExecutionContext

    Context passed to execute_one: the host runtime that actually calls the model/tool adapters, the model id for observability, and the catalog snapshot to source tool definitions from for CallModel effects.

    The snapshot is carried here (not re-resolved from a registry) because the reducer already validated against catalog_version; the executor forwards the same definitions so the model sees what was validated (ADR §2.7, §6.3 — forbidden to substitute an empty tool list).

    FailOnNthJournal

    pub struct FailOnNthJournal {
    inner : InMemoryJournal
    fail_on : Int
    call_count : Int
    }

    Test adapter: wraps an InMemoryJournal and fails on the Nth append call with a typed barrier failure. Used by the C-JOURNAL-APPEND-FAIL fixture.

    The wrapped journal is NOT mutated when the failure triggers (the outer adapter raises before delegating).

    FailOnNthJournal::new

    fn FailOnNthJournal::new(inner : InMemoryJournal, fail_on : Int) -> FailOnNthJournal

    FollowUpCommand

    pub(all) struct FollowUpCommand {
    command_id : CommandId
    target_run_id :
    RunId

    source_turn_id : TurnId
    payload : Json
    } derive(Eq,
    Debug
    )

    A follow-up command. Creates a new turn under the same run_id at a turn boundary.

    FollowUpCommand::command_id

    fn FollowUpCommand::command_id(self : FollowUpCommand) -> CommandId

    FollowUpCommand::payload

    fn FollowUpCommand::payload(self : FollowUpCommand) -> Json

    FollowUpCommand::source_turn_id

    fn FollowUpCommand::source_turn_id(self : FollowUpCommand) -> TurnId

    FollowUpCommand::target_run_id

    FrozenBatch

    pub(all) struct FrozenBatch {
    savepoint_id : String
    savepoint_kind : SavepointKind
    expected_revision : Int
    entries : Array[JournalEntry]
    frozen_entry_keys : Array[String]
    } derive(Eq,
    Debug
    )

    Frozen pending batch. Built by prepare_batch; committed by commit. Once frozen, neither contributors nor subscribers can mutate it.

    expected_revision is the revision the journal SHOULD be at when this batch commits. If the journal has advanced past this revision (e.g. concurrent commit elsewhere — impossible in M2 single-writer but the check is here for M5), the commit fails with BarrierFailed.

    FrozenBatch::entries

    fn FrozenBatch::entries(self : FrozenBatch) -> Array[JournalEntry]

    FrozenBatch::expected_revision

    fn FrozenBatch::expected_revision(self : FrozenBatch) -> Int

    FrozenBatch::length

    fn FrozenBatch::length(self : FrozenBatch) -> Int

    FrozenBatch::savepoint_id

    fn FrozenBatch::savepoint_id(self : FrozenBatch) -> String

    FrozenBatch::savepoint_kind

    fn FrozenBatch::savepoint_kind(self : FrozenBatch) -> SavepointKind

    Harness

    pub struct Harness {
    config : HarnessConfig
    phase_gate : PhaseGate
    mailbox : ControlMailbox
    lifecycle : LifecycleCollection
    last_completed_transcript :
    CanonicalTranscript
    ?
    }

    The Harness. Construct once via Harness::new; call startup once before any prompt; call shutdown once at product exit.

    The Harness owns:
    • PhaseGate (mutable)
    • ControlMailbox (mutable; includes the idle barrier)
    • LifecycleCollection (mutable)

    The Harness borrows:
    • &HostRuntime (from config; the root adapter owns compatibility conversion)
    • &RunJournal (from config)
    • &JournalContributor[] (from config)
    • &EventSubscriber[] (from config)
    • ToolCatalogSnapshot (owned copy; snapshot immutable after capture)

    Harness::is_quiescent

    fn Harness::is_quiescent(self : Harness) -> Bool

    Harness::last_completed_transcript

    Return the last terminal transcript captured by the Harness. None means no run has completed since construction or the current run is suspended.

    Harness::new

    fn Harness::new(config : HarnessConfig) -> Harness

    Harness::phase

    fn Harness::phase(self : Harness) -> HarnessPhase

    Harness::prompt

    async fn Harness::prompt(self : Harness, run_id :
    RunId
    , turn_id : TurnId, session_id :
    SessionId
    , initial_messages : Array[
    CanonicalMessage
    ], operation_id : String) -> PromptResult raise HarnessError

    Prompt the Harness with an initial user message. Only legal when the phase is Idle.

    Steps (ADR §6.1):
    1. Acquire prompt lease via the phase gate.
    2. Capture TurnSnapshot.
    3. Bind ControlMailbox to the new run/turn.
    4. Commit InputAccepted savepoint BEFORE any model effect.
    5. Transition to Active.
    6. Run the pump until terminal or suspended.
    7. On terminal, dispatch terminal event, release lease, return.

    run_id / turn_id are caller-supplied (host generates them; the Harness does not allocate). This keeps cross-process resume (M5) possible without a central id factory.

    Harness::shutdown

    async fn Harness::shutdown(self : Harness) -> Unit raise HarnessError

    Shut all started nodes in reverse order. Idempotent.

    Harness::startup

    async fn Harness::startup(self : Harness) -> Unit raise HarnessError

    Register all configured lifecycle nodes and start them in registration order. Idempotent: a second call is a no-op.

    Harness::wait_idle

    async fn Harness::wait_idle(self : Harness) -> QuiescentStatus

    Wait until the Harness reaches a quiescent status. Returns Idle, Suspended, Terminal, or Shutdown (typed, distinct). Implemented via @cond_var.Cond::wait — NOT polling.

    HarnessConfig

    pub(all) struct HarnessConfig {
    host : &
    HostRuntime

    model_id : ModelId
    catalog :
    ToolCatalogSnapshot

    journal : &RunJournal
    contributors : Array[&JournalContributor]
    subscribers : Array[&EventSubscriber]
    lifecycle_nodes : Array[&HarnessLifecycleNode]
    default_budget :
    Budget

    max_iterations : Int
    }

    Inputs to build a Harness. All fields are required; the Harness owns the lifetime of every reference.

    The host side is supplied as a single &HostRuntime (REPAIR D3/D4): the root compatibility facade implements HostRuntime; Puppetry only sees canonical Kernel values, so no root → puppetry → root package cycle exists.

    HarnessPhase

    pub(all) enum HarnessPhase {
    Idle
    Active
    Suspended
    Terminalizing
    ShuttingDown
    Shutdown
    } derive(Eq,
    Debug
    )

    Product-level macro phase. Distinct from M1 Phase (which is per-Run micro-state owned by the reducer).

    Allowed transitions (ADR §4 diagram):
    • Idle → Active (prompt / continue accepted)
    • Active → Suspended (reducer enters Suspended)
    • Suspended → Active (resume)
    • Active → Terminalizing (terminal outcome committed)
    • Suspended → Terminalizing (abort)
    • Terminalizing → Idle (terminal event dispatched + cleanup)
    • Idle/Suspended/Active → ShuttingDown (host shutdown call; Active defers)
    • ShuttingDown → Shutdown (lifecycle rollback complete)

    HarnessPhase::is_accepting

    fn HarnessPhase::is_accepting(self : HarnessPhase) -> Bool

    Whether the Harness will accept ANY new host command. Once Shutdown is reached, all commands fail with HarnessError::AfterShutdown.

    HarnessPhase::is_quiescent

    fn HarnessPhase::is_quiescent(self : HarnessPhase) -> Bool

    Whether this phase is quiescent — the union of Idle, Suspended and Shutdown per ADR §4. wait_idle wakes when the Harness reaches any of these (with distinct typed status, never conflating Suspended with a terminal outcome).

    InMemoryJournal

    pub struct InMemoryJournal {
    entries : Array[JournalEntry]
    seen_ids : Map[String, Bool]
    terminal_runs : Map[String, Bool]
    }

    Append-only in-memory journal. Stores entries in an Array; revision is derived from the array length (entry N has revision N).

    Thread-safety: M2 runs single-threaded; the Harness is the only writer. M5's durable adapter will add its own concurrency control.

    InMemoryJournal::append_impl

    fn InMemoryJournal::append_impl(self : InMemoryJournal, batch : Array[JournalEntry]) -> Int raise HarnessError

    Internal: append implementation. Split from the trait method so other in-file helpers (e.g. FailOnNthJournal) can call it directly without going through trait dispatch.

    InMemoryJournal::entries_for_run_impl

    InMemoryJournal::entries_for_savepoint_impl

    fn InMemoryJournal::entries_for_savepoint_impl(self : InMemoryJournal, run_id :
    RunId
    , savepoint_id : String) -> Array[JournalEntry]

    InMemoryJournal::new

    InMemoryJournal::revision_impl

    fn InMemoryJournal::revision_impl(self : InMemoryJournal) -> Int

    JournalContribution

    pub(all) struct JournalContribution {
    contributor_id : String
    provenance : String
    proposed_entries : Array[JournalEntry]
    } derive(Eq,
    Debug
    )

    Typed contribution from a JournalContributor. Carries:
    • contributor_id: stable identifier of the proposing contributor
    • provenance: human-readable provenance string for diagnostics
    • proposed_entries: entries the contributor wants added to this savepoint

    The contributor does NOT specify the committed revision (the coordinator assigns it). It does NOT mark entries as committed (the journal does).

    JournalContribution::contributor_id

    fn JournalContribution::contributor_id(self : JournalContribution) -> String

    JournalContribution::empty

    fn JournalContribution::empty(contributor_id : String, provenance : String) -> JournalContribution

    Construct an empty contribution (contributor chooses to add nothing).

    JournalContribution::proposed_entries

    JournalContribution::provenance

    fn JournalContribution::provenance(self : JournalContribution) -> String

    JournalContribution::with_entries

    fn JournalContribution::with_entries(contributor_id : String, provenance : String, entries : Array[JournalEntry]) -> JournalContribution

    Construct a contribution with proposed entries. The contributor must assign entry_seq values that do not collide with base_entries or other contributions; the coordinator validates.

    JournalEntry

    pub(all) struct JournalEntry {
    identity : JournalEntryIdentity
    revision : Int
    summary : String
    payload : Json
    } derive(Eq,
    Debug
    )

    A single journal entry. Carries identity + a redacted summary string + an opaque canonical payload (Json). The journal never interprets the payload — it's pure storage.

    Payload size is bounded; oversize entries fail validation at the coordinator (pre-write).

    JournalEntry::identity

    JournalEntry::payload

    fn JournalEntry::payload(self : JournalEntry) -> Json

    JournalEntry::revision

    fn JournalEntry::revision(self : JournalEntry) -> Int

    JournalEntry::summary

    fn JournalEntry::summary(self : JournalEntry) -> String

    JournalEntryIdentity

    pub(all) struct JournalEntryIdentity {
    run_id :
    RunId

    turn_id : TurnId
    session_id :
    SessionId

    savepoint_id : String
    entry_seq : Int
    kind : SavepointKind
    } derive(Eq,
    Debug
    )

    Stable identifier for a journal entry. The (run_id, savepoint_id, entry_seq) triple uniquely locates an entry within the journal.

    JournalEntryIdentity::entry_seq

    fn JournalEntryIdentity::entry_seq(self : JournalEntryIdentity) -> Int

    JournalEntryIdentity::kind

    JournalEntryIdentity::run_id

    JournalEntryIdentity::savepoint_id

    fn JournalEntryIdentity::savepoint_id(self : JournalEntryIdentity) -> String

    JournalEntryIdentity::session_id

    JournalEntryIdentity::turn_id

    LifecycleCollection

    pub struct LifecycleCollection {
    nodes : Array[&HarnessLifecycleNode]
    node_ids : Map[String, Bool]
    started : Map[String, Bool]
    shut_down : Map[String, Bool]
    is_sealed : Bool
    }

    Ordered collection of HarnessLifecycleNode references. Tracks registration order, duplicate ids, and exactly-once start/stop state.

    Construction: LifecycleCollection::new() then register in startup order. Once startup_all has been called, no further registrations are accepted (the collection is sealed).

    LifecycleCollection::new

    LifecycleCollection::register

    fn LifecycleCollection::register(self : LifecycleCollection, node : &HarnessLifecycleNode) -> Unit raise HarnessError

    Register a node. Raises HarnessError::LifecycleDuplicate if the node id is already registered. Once startup_all has been called, further registrations raise InvalidState.

    LifecycleCollection::shut_down_node_count

    fn LifecycleCollection::shut_down_node_count(self : LifecycleCollection) -> Int

    LifecycleCollection::shutdown_all

    async fn LifecycleCollection::shutdown_all(self : LifecycleCollection) -> Unit raise HarnessError

    Shut down all started nodes in reverse registration order. Aggregates failures; the returned error (if any) carries all of them.

    Idempotent: if already shut down, returns immediately.

    LifecycleCollection::size

    Number of registered nodes.

    LifecycleCollection::started_node_count

    fn LifecycleCollection::started_node_count(self : LifecycleCollection) -> Int

    LifecycleCollection::startup_all

    async fn LifecycleCollection::startup_all(self : LifecycleCollection) -> Unit raise HarnessError

    Start all registered nodes in registration order. On failure, rolls back already-started nodes in reverse order; rollback failures are aggregated into the returned error.

    Idempotent: if already started, returns immediately.

    LifecycleShutdownError

    pub(all) struct LifecycleShutdownError {
    failing_node_id : String
    cause : String
    other_failures : Array[(String, String)]
    } derive(Eq,
    Debug
    )

    LifecycleStartupError

    pub(all) struct LifecycleStartupError {
    failing_node_id : String
    cause : String
    rollback_failures : Array[(String, String)]
    } derive(Eq,
    Debug
    )

    Typed lifecycle error. Carries the failing node id + cause string plus any rollback/aggregate failures observed while handling the primary failure.

    ModelId

    pub(all) struct ModelId {
    value : String
    } derive(Eq, Hash,
    Debug
    )

    Identifier for a model binding. M1 supports a single model per Run (host-supplied); M2 may add multi-model routing. The Kernel reducer never references this; it only sees the model step id. The executor carries it purely so telemetry/events can name the model that produced a completion.

    ModelId::new

    fn ModelId::new(value : String) -> Result[ModelId, String]

    ModelId::to_string

    fn ModelId::to_string(self : ModelId) -> String

    ModelId::unchecked

    fn ModelId::unchecked(value : String) -> ModelId

    NoopContributor

    pub(all) struct NoopContributor {
    id : String
    }

    Default contributor that proposes nothing. Used when no extension needs pre-commit hooks; also a baseline for tests.

    NoopContributor::new

    NoopContributor::with_id

    fn NoopContributor::with_id(id : String) -> NoopContributor

    NoopSubscriber

    pub(all) struct NoopSubscriber {
    id : String
    }

    Default subscriber that drops every event. Useful as a baseline and as a baseline for tests.

    NoopSubscriber::new

    NoopSubscriber::with_id

    fn NoopSubscriber::with_id(id : String) -> NoopSubscriber

    OperationClass

    pub(all) enum OperationClass {
    Prompt
    InFlight
    Structural
    } derive(Eq,
    Debug
    )

    Class of operation the phase gate is asked to authorise. ADR §6.8 reserves a Structural slot for M5 (branch/compact/retry); M2 implements zero structural operations but the gate already knows how to reject them outside Idle.

    OperationLease

    pub(all) struct OperationLease {
    operation_id : String
    acquired_phase : HarnessPhase
    run_id :
    RunId

    turn_id : TurnId
    } derive(Eq,
    Debug
    )

    A structural lease. At most one is held at any time (ADR §4 rule 1). Acquired by prompt/continue/resume; released on terminal outcome, abort, or shutdown. Records the owner operation id and the phase at which the lease was acquired so release can validate provenance.

    OperationLease::acquired_phase

    fn OperationLease::acquired_phase(self : OperationLease) -> HarnessPhase

    OperationLease::operation_id

    fn OperationLease::operation_id(self : OperationLease) -> String

    OperationLease::run_id

    OperationLease::turn_id

    fn OperationLease::turn_id(self : OperationLease) -> TurnId

    PhaseGate

    pub struct PhaseGate {
    phase : HarnessPhase
    lease : OperationLease?
    active_run_id :
    RunId
    ?
    active_turn_id : TurnId?
    active_suspension_id : String?
    }

    The phase gate. Holds the current macro-phase and (optionally) the outstanding lease. All transitions go through transition / acquire / release, which validate and raise typed errors on misuse.

    Construction: PhaseGate::idle() is the only public constructor.

    PhaseGate::acquire_prompt

    fn PhaseGate::acquire_prompt(self : PhaseGate, operation_id : String, run_id :
    RunId
    , turn_id : TurnId) -> (PhaseGate, OperationLease) raise HarnessError

    Acquire a structural lease for a new prompt/continue. Returns the updated gate and the lease on success. Raises typed errors for:
    • lease already held (LeaseHeld)
    • phase does not accept Prompt (OperationNotAllowedInPhase)

    The lease binds the gate to the given run_id / turn_id; subsequent InFlight commands must target these IDs. The gate's lease / active_run_id / active_turn_id fields are updated atomically with the lease creation.

    PhaseGate::acquire_resume

    fn PhaseGate::acquire_resume(self : PhaseGate, operation_id : String, expected_suspension_id : String) -> (PhaseGate, OperationLease) raise HarnessError

    Acquire a lease for resume from Suspended. The run_id must match the suspended run; the turn_id is inherited (resume does not allocate a new turn). Returns the updated gate and the lease.

    The lease replaces the previous prompt lease (the original prompt's operation_id is no longer the holder). This is correct because resume is a new authorisation point: subsequent abort/release must use the resume operation_id, not the prompt's.

    PhaseGate::active_run_id

    Run id currently bound to the gate. None when Idle.

    PhaseGate::active_suspension_id

    fn PhaseGate::active_suspension_id(self : PhaseGate) -> String?

    Suspension id when Suspended; None otherwise.

    PhaseGate::active_turn_id

    fn PhaseGate::active_turn_id(self : PhaseGate) -> TurnId?

    Turn id currently bound to the gate.

    PhaseGate::authorise

    fn PhaseGate::authorise(self : PhaseGate, operation : OperationClass) -> Result[Unit, HarnessError]

    Decide whether an operation class is allowed in the current phase. Returns Ok if allowed, or a typed HarnessError describing the rejection (never a bare bool — the rejection reason is part of the contract).

    PhaseGate::enter_suspended

    fn PhaseGate::enter_suspended(self : PhaseGate, suspension_id : String) -> PhaseGate raise HarnessError

    Enter Suspended phase with a suspension id. Called by the Harness when the reducer transitions to Suspended. Keeps run/turn identity.

    PhaseGate::idle

    fn PhaseGate::idle() -> PhaseGate

    PhaseGate::is_quiescent

    fn PhaseGate::is_quiescent(self : PhaseGate) -> Bool

    Whether the gate is in a quiescent phase (delegates to HarnessPhase).

    PhaseGate::lease

    fn PhaseGate::lease(self : PhaseGate) -> OperationLease?

    Currently-held lease, if any.

    PhaseGate::phase

    fn PhaseGate::phase(self : PhaseGate) -> HarnessPhase

    Current macro-phase. Read-only accessor.

    PhaseGate::release

    fn PhaseGate::release(self : PhaseGate, operation_id : String) -> Unit raise HarnessError

    Release the lease. Validates that the caller is the owner; releasing a lease you don't own (or one that's already released) raises a typed error. Idempotent release is the caller's responsibility, not the gate's.

    PhaseGate::rotate_turn

    fn PhaseGate::rotate_turn(self : PhaseGate, new_turn_id : TurnId) -> PhaseGate raise HarnessError

    Replace the active turn id. Used by follow_up at turn boundary to allocate a new turn under the same run.

    PhaseGate::transition

    fn PhaseGate::transition(self : PhaseGate, to : HarnessPhase) -> PhaseGate raise HarnessError

    Apply a transition. Internal — the Harness (T06) is the only caller and it has already acquired/released the lease as appropriate. Raises typed error on illegal transitions.

    The legal edges are encoded here once; everything else is rejected.

    PreCommitContext

    pub(all) struct PreCommitContext {
    run_id :
    RunId

    turn_id : TurnId
    session_id :
    SessionId

    savepoint_id : String
    savepoint_kind : SavepointKind
    base_entries : Array[JournalEntry]
    current_revision : Int
    catalog_version :
    CatalogVersion

    } derive(Eq,
    Debug
    )

    Immutable context handed to each JournalContributor at pre-commit time. Contributors read this to decide what (if anything) to propose.

    The context carries NO mutable references and NO journal writer. A contributor that needs to add a domain entry must return it via JournalContribution; it cannot reach into the journal directly.

    PreCommitContext::base_entries

    PreCommitContext::catalog_version

    PreCommitContext::current_revision

    fn PreCommitContext::current_revision(self : PreCommitContext) -> Int

    PreCommitContext::run_id

    PreCommitContext::savepoint_id

    fn PreCommitContext::savepoint_id(self : PreCommitContext) -> String

    PreCommitContext::savepoint_kind

    fn PreCommitContext::savepoint_kind(self : PreCommitContext) -> SavepointKind

    PreCommitContext::session_id

    PreCommitContext::turn_id

    PromptResult

    pub(all) enum PromptResult {
    Accepted(run_id~ :
    RunId
    , turn_id~ : TurnId)
    LeaseBusy(held_by~ : String)
    Rejected(error~ : HarnessError)
    }

    Result of prompt.

    QueuePolicy

    pub(all) enum QueuePolicy {
    All
    OneAtATime
    } derive(Eq,
    Debug
    )

    How a mailbox consumes its queue at a single safe point.
    impl Show for QueuePolicy

    QuiescentStatus

    pub(all) enum QuiescentStatus {
    Idle
    Suspended(run_id~ :
    RunId
    , suspension_id~ : String, requirement_kind~ : String)
    Terminal(outcome~ :
    RunOutcome
    )
    Shutdown
    } derive(Eq,
    Debug
    )

    Typed quiescent status returned by wait_idle. Distinct from HarnessPhase because it carries suspension details and the terminal outcome (ADR §6.7).

    ResumeCommand

    pub(all) struct ResumeCommand {
    command_id : CommandId
    target_run_id :
    RunId

    suspension_id : String
    payload : Json
    } derive(Eq,
    Debug
    )

    A resume command. Targets a specific suspension under a specific run.

    ResumeCommand::command_id

    fn ResumeCommand::command_id(self : ResumeCommand) -> CommandId

    ResumeCommand::payload

    fn ResumeCommand::payload(self : ResumeCommand) -> Json

    ResumeCommand::suspension_id

    fn ResumeCommand::suspension_id(self : ResumeCommand) -> String

    ResumeCommand::target_run_id

    SavepointFailureCause

    pub(all) enum SavepointFailureCause {
    ContributorRaised(contributor_id~ : String, detail~ : String)
    ValidationFailed(detail~ : String)
    BarrierFailed(detail~ : String)
    } derive(Eq,
    Debug
    )

    Why a savepoint failed (ADR §5 failure handling).

    SavepointKind

    pub(all) enum SavepointKind {
    InputAccepted
    AssistantCommitted
    ToolCommitted
    RunSuspended
    RunTerminal
    } derive(Eq,
    Debug
    )

    The savepoint kind an entry belongs to. Each savepoint commits atomically: all entries with the same (run_id, savepoint_id, kind) either all commit or none do.

    SteerCommand

    pub(all) struct SteerCommand {
    command_id : CommandId
    target_run_id :
    RunId

    target_turn_id : TurnId
    observed_tool_batch_id : String
    observed_model_step_id :
    ModelStepId

    payload : Json
    } derive(Eq,
    Debug
    )

    A steer command. Carries run/turn/batch/model-step IDs observed at enqueue; consumed only if they match the active run's state at the safe point.

    SteerCommand::command_id

    fn SteerCommand::command_id(self : SteerCommand) -> CommandId

    SteerCommand::observed_model_step_id

    SteerCommand::observed_tool_batch_id

    fn SteerCommand::observed_tool_batch_id(self : SteerCommand) -> String

    SteerCommand::payload

    fn SteerCommand::payload(self : SteerCommand) -> Json

    SteerCommand::target_run_id

    SteerCommand::target_turn_id

    fn SteerCommand::target_turn_id(self : SteerCommand) -> TurnId

    TurnId

    pub(all) struct TurnId {
    value : String
    } derive(Eq, Hash,
    Debug
    )

    Identifier for a single turn within a Run. A Run may contain multiple turns (initial prompt + follow-ups); turns never outlive their Run. follow_up allocates a new TurnId under the same RunId.
    impl Show for TurnId

    TurnId::new

    fn TurnId::new(value : String) -> Result[TurnId, String]

    TurnId::to_string

    fn TurnId::to_string(self : TurnId) -> String

    TurnId::unchecked

    fn TurnId::unchecked(value : String) -> TurnId

    TurnSnapshot

    pub struct TurnSnapshot {
    run_id :
    RunId

    turn_id : TurnId
    session_id :
    SessionId

    catalog_version :
    CatalogVersion

    tool_definitions : Array[
    CanonicalToolDef
    ]
    model_id : String
    call_options : Json
    budget :
    Budget

    deadline : Int?
    hook_provenance : Array[String]
    lifecycle_provenance : Array[String]
    subscriber_provenance : Array[String]
    fingerprint : String
    } derive(Eq,
    Debug
    )

    Immutable capture of a turn's configuration. Constructed once via TurnSnapshot::capture; the struct fields are read-only and the inner Arrays/Maps are owned by the snapshot (caller cannot mutate them).

    TurnSnapshot::budget

    TurnSnapshot::call_options

    fn TurnSnapshot::call_options(self : TurnSnapshot) -> Json

    TurnSnapshot::capture

    Capture a TurnSnapshot from the given input. The snapshot owns a deep copy of the catalog definitions and call options; the caller's original arrays/maps are not aliased.

    Raises HarnessError::SnapshotInvalid for:
    • empty model_id
    • empty catalog (zero tools is legal but warned)
    • negative budget dimensions
    • deadline in the past (caller's responsibility to check, but we still reject if deadline < 0)

    TurnSnapshot::catalog_version

    TurnSnapshot::deadline

    fn TurnSnapshot::deadline(self : TurnSnapshot) -> Int?

    TurnSnapshot::fingerprint

    fn TurnSnapshot::fingerprint(self : TurnSnapshot) -> String

    TurnSnapshot::hook_provenance

    fn TurnSnapshot::hook_provenance(self : TurnSnapshot) -> Array[String]

    TurnSnapshot::lifecycle_provenance

    fn TurnSnapshot::lifecycle_provenance(self : TurnSnapshot) -> Array[String]

    TurnSnapshot::model_id

    fn TurnSnapshot::model_id(self : TurnSnapshot) -> String

    TurnSnapshot::run_id

    TurnSnapshot::session_id

    TurnSnapshot::subscriber_provenance

    fn TurnSnapshot::subscriber_provenance(self : TurnSnapshot) -> Array[String]

    TurnSnapshot::to_redacted_string

    fn TurnSnapshot::to_redacted_string(self : TurnSnapshot) -> String

    Redacted single-line view for logs and diagnostics. Excludes:
    • tool arguments / call_options payload (may contain secrets)
    • tool definition bodies (only name + owner shown)
    • prompt content (the snapshot never stores prompt text, but we also exclude call_options payload)

    Includes:
    • identity chain (run/turn/session/catalog version)
    • tool names (not arguments)
    • budget dimensions
    • fingerprint

    TurnSnapshot::tool_definitions

    Tool definitions owned by the snapshot. Mutating the returned array does not change the snapshot (the array is a fresh copy on each call, matching RunState::pending_effects convention).

    TurnSnapshot::turn_id

    fn TurnSnapshot::turn_id(self : TurnSnapshot) -> TurnId

    TurnSnapshotInput

    pub(all) struct TurnSnapshotInput {
    run_id :
    RunId

    turn_id : TurnId
    session_id :
    SessionId

    catalog :
    ToolCatalogSnapshot

    model_id : String
    call_options : Json
    budget :
    Budget

    deadline : Int?
    hook_provenance : Array[String]
    lifecycle_provenance : Array[String]
    subscriber_provenance : Array[String]
    } derive(Eq,
    Debug
    )

    Inputs to TurnSnapshot::capture. Kept separate from the snapshot struct so callers cannot accidentally construct a snapshot with un-validated fields; they go through capture, which copies and fingerprints.

    commit_batch

    fn commit_batch(journal : &RunJournal, batch : FrozenBatch) -> Int raise HarnessError

    Commit a frozen batch to the journal. Verifies post-freeze integrity (entry keys unchanged), then delegates to RunJournal.append. Returns the new committed revision.

    Raises:
    • SavepointFailed(_, BarrierFailed(_)) if post-freeze mutation detected or the journal append fails.

    execute_one

    async fn execute_one(effect :
    Effect
    , ctx : ExecutionContext, on_chunk : (Json) -> Unit) ->
    RunInput

    Execute ONE Effect and return ONE structured RunInput. The executor holds no state; every call is independent. The result is fed straight back to reduce.

    Categorisation:
    • CallModel → delegates to HostRuntime::call_model, passing the catalog definitions (forwarding them is mandatory — never an empty array). On Ok(completion) returns ModelCompleted; on Err(failure) returns ModelFailed.
    • ExecuteTool → delegates to HostRuntime::execute_tool. The host owns owner-resolution; a missing owner / stale registration surfaces as a typed ToolOutcome::RuntimeFailure from the host, which the reducer converts to the canonical outcome (ADR §2.4).
    • CancelOutstanding → delegates to HostRuntime::cancel_effects. The reducer treats cancel as fire-and-forget (it has already terminal- transitioned); the driver therefore drops the returned RunInput.

    prepare_batch

    fn prepare_batch(ctx : PreCommitContext, contributors : Array[&JournalContributor]) -> FrozenBatch raise HarnessError

    Prepare a frozen batch for a savepoint. Steps:
    1. Call each contributor in registration order with PreCommitContext.
    2. Validate every contribution entry (kind, identity, dedup).
    3. Merge base entries + validated contributions.
    4. Freeze the batch (compute expected_revision + entry keys).

    Raises:
    • HarnessError::SavepointFailed(_, ContributorRaised(_)) if any contributor raises/returns Err.
    • HarnessError::SavepointFailed(_, ValidationFailed(_)) if any entry fails validation.