Skip to content

Index

baton

The Baton — Marianne's event-driven execution heart.

The baton is the conductor's primary tool. It doesn't decide what to play — the score does. It doesn't decide how to play — the musicians do. The baton controls when and how much: tempo, dynamics, cues, and fermatas.

The baton replaces the current monolithic execution model where JobService.start_job() runs all sheets sequentially. Instead, the baton manages sheets across all jobs in a single event-driven loop, dispatching them to execution when they're ready and the system can handle them.

Package layout::

events.py       — All BatonEvent types (dataclasses)
timer.py        — Timer wheel (priority queue of future events)
state.py        — Baton state models (sheet/instrument/job tracking)
core.py         — Event inbox, main loop, sheet registry
musician.py     — Single-attempt sheet execution (play once, report)
backend_pool.py — Per-instrument backend instance management
adapter.py      — Wires baton into conductor (step 28)

Classes

BatonAdapter

BatonAdapter(*, event_bus=None, max_concurrent_sheets=10, state_sync_callback=None, persist_callback=None, learning_store=None, rate_limit_reporter=None, diagnostic_snapshot_fn=None, flow_pause_callback=None, flow_concert_callback=None)

Bridges the conductor (JobManager) and the baton (BatonCore).

The adapter owns: - A BatonCore instance (event loop, sheet registry, state machine) - A mapping of job_id → Sheet[] (for prompt rendering at dispatch time) - Active musician tasks (asyncio.Task per dispatched sheet)

The adapter does NOT own: - The BackendPool (injected by the manager) - The EventBus (injected by the manager) - The CheckpointState (managed by the manager's state backend)

Usage::

adapter = BatonAdapter(event_bus=bus)
adapter.set_backend_pool(pool)

# Register a job
adapter.register_job("j1", sheets, deps)

# Run the baton (blocks until shutdown)
await adapter.run()

Initialize the BatonAdapter.

Parameters:

Name Type Description Default
event_bus EventBus | None

Optional EventBus for publishing events to subscribers.

None
max_concurrent_sheets int

Global concurrency ceiling for dispatch.

10
state_sync_callback StateSyncCallback | None

Deprecated — kept for backward compat. Phase 2 uses persist_callback instead.

None
persist_callback PersistCallback | None

Called with job_id after significant state transitions (terminal, dispatch) to persist CheckpointState to the registry. Replaces the sync layer.

None
learning_store GlobalLearningStore | None

Optional GlobalLearningStore handle for injecting learned patterns into prompts (#200). None (and store-less paths) cleanly skip the layer.

None
rate_limit_reporter RateLimitReporter | None

Optional async write-through to the daemon's RateLimitCoordinator (#206). Every RateLimitHit the run loop processes is mirrored here so daemon-level consumers (backpressure, submit-time warnings, the scheduler) see the same limits the baton is already enforcing at dispatch. None (tests, standalone use) skips the mirror.

None
diagnostic_snapshot_fn DiagnosticSnapshotFn | None

Optional sync runtime-diagnostics provider (#133): observer file/process events + resource state attached to the retry failure-evidence context so the agent sees what its previous attempt actually did. Fail-open; None skips enrichment (plain #201 evidence).

None
Source code in src/marianne/daemon/baton/adapter.py
def __init__(
    self,
    *,
    event_bus: EventBus | None = None,
    max_concurrent_sheets: int = 10,
    state_sync_callback: StateSyncCallback | None = None,
    persist_callback: PersistCallback | None = None,
    learning_store: GlobalLearningStore | None = None,
    rate_limit_reporter: RateLimitReporter | None = None,
    diagnostic_snapshot_fn: DiagnosticSnapshotFn | None = None,
    flow_pause_callback: FlowPauseCallback | None = None,
    flow_concert_callback: FlowConcertCallback | None = None,
) -> None:
    """Initialize the BatonAdapter.

    Args:
        event_bus: Optional EventBus for publishing events to subscribers.
        max_concurrent_sheets: Global concurrency ceiling for dispatch.
        state_sync_callback: Deprecated — kept for backward compat.
            Phase 2 uses persist_callback instead.
        persist_callback: Called with job_id after significant state
            transitions (terminal, dispatch) to persist CheckpointState
            to the registry. Replaces the sync layer.
        learning_store: Optional GlobalLearningStore handle for injecting
            learned patterns into prompts (#200). None (and store-less
            paths) cleanly skip the layer.
        rate_limit_reporter: Optional async write-through to the daemon's
            RateLimitCoordinator (#206). Every RateLimitHit the run loop
            processes is mirrored here so daemon-level consumers
            (backpressure, submit-time warnings, the scheduler) see the
            same limits the baton is already enforcing at dispatch.
            None (tests, standalone use) skips the mirror.
        diagnostic_snapshot_fn: Optional sync runtime-diagnostics
            provider (#133): observer file/process events + resource
            state attached to the retry failure-evidence context so the
            agent sees what its previous attempt actually did. Fail-open;
            None skips enrichment (plain #201 evidence).
    """
    from marianne.daemon.baton.timer import TimerWheel

    # Shared inbox breaks the circular dependency: TimerWheel needs
    # the inbox to deliver fired events, BatonCore needs the timer
    # to schedule them. Create the inbox first, pass to both.
    inbox: asyncio.Queue[Any] = asyncio.Queue()
    self._timer_wheel = TimerWheel(inbox)
    self._baton = BatonCore(timer=self._timer_wheel, inbox=inbox)
    self._event_bus = event_bus
    self._max_concurrent_sheets = max_concurrent_sheets
    self._persist_callback = persist_callback
    self._learning_store = learning_store
    self._rate_limit_reporter = rate_limit_reporter
    self._diagnostic_snapshot_fn = diagnostic_snapshot_fn
    self._flow_pause_callback = flow_pause_callback
    self._flow_concert_callback = flow_concert_callback
    self._flow_pause_announced: set[str] = set()
    # Deprecated compat attributes — tests set/read these directly
    self._state_sync_callback = state_sync_callback
    self._synced_status: dict[tuple[str, int], str] = {}

    # Job → Sheet mapping for prompt rendering
    self._job_sheets: dict[str, dict[int, Sheet]] = {}

    # Active musician tasks: (job_id, sheet_num) → Task
    self._active_tasks: dict[tuple[str, int], asyncio.Task[Any]] = {}
    self._active_dispatch_epochs: dict[tuple[str, int], int] = {}
    self._flow_fact_tasks: dict[tuple[str, str, int], asyncio.Task[None]] = {}
    self._flow_action_tasks: dict[tuple[str, int, int], asyncio.Task[None]] = {}
    # Acquired instrument/model for each live musician. Sheet state can be
    # relabelled WAITING or advanced to a fallback before this task exits.
    self._active_execution_details: dict[
        tuple[str, int], tuple[str, str | None]
    ] = {}
    # Monotonic dispatch time per live musician, so a drain can say how
    # long each sheet it is waiting on has been running (GH #476).
    self._active_started_at: dict[tuple[str, int], float] = {}
    self._baton.set_active_execution_probe(self._is_execution_active)

    # Idle-based stale detection (#349/#350). Per-job config captured at
    # registration; per-sheet dispatch time (wall clock) is the floor for
    # the idle window so pre-existing workspace files / a quiet start don't
    # false-positive, and re-dispatch (retry) resets the window. The marker
    # set records sheets cancelled *for staleness* so _on_musician_done
    # classifies the synthetic failure as STALE rather than CANCELLED.
    self._stale_configs: dict[str, StaleDetectionConfig] = {}
    self._stale_dispatch_time: dict[tuple[str, int], float] = {}
    self._stale_markers: set[tuple[str, int]] = set()
    # #344: consecutive idle-AND-alive strikes per sheet. The kill is
    # deferred while the subprocess is alive (a silent finalize / network
    # wait looks idle but is not stuck); only after
    # ``max_idle_checks_before_kill`` strikes is an alive sheet killed.
    self._stale_idle_strikes: dict[tuple[str, int], int] = {}
    # #361: sheets currently being polled for a FERMATA resolution marker.
    # The run loop reconciles this against FERMATA status: a newly-FERMATA
    # sheet gets EscalationNeeded published + a FermataCheck scheduled; a
    # sheet that has left FERMATA is discarded. Handles both fresh entry and
    # restart-recovery uniformly.
    self._fermata_polling: set[tuple[str, int]] = set()

    # Last time an inbox high-water WARNING was emitted (#222), so the loop
    # doesn't spam a log line on every event once the queue is deep.
    self._inbox_warn_logged_at: float = 0.0

    # Phase 1 process lifecycle: in-memory PID/PGID tracking per
    # dispatched sheet. Populated by the backend's
    # ``_on_process_group_spawned`` callback (wired by
    # ``_musician_wrapper``), cleared by the wrapper's finally and by
    # ``_on_musician_done``. Read by ``deregister_job`` to drive
    # preemptive killpg. In-memory only — lost on conductor restart,
    # which is Phase 4 recovery's job.
    #
    # Phase 3 replaces this with SheetState.process_pid/pgid; this
    # dict may then be kept as a fast-path cache or removed entirely.
    # See docs/specs/2026-04-16-process-lifecycle-design.md (Change 3).
    self._active_pids: dict[tuple[str, int], tuple[int, int]] = {}
    # GH #487 kill-safety: kernel start ticks of each tracked group
    # leader, captured at _track_process time alongside the (pid, pgid)
    # pair. ``_active_pids`` values stay bare (pid, pgid) 2-tuples for
    # every existing reader/test; the identity lives HERE, keyed the
    # same. The kill consumers verify the leader's identity before
    # killpg: a stale entry whose pgid was recycled by an unrelated
    # process is refused (logged, never signalled), so a missed untrack
    # can never route TERM->KILL into a live unrelated group.
    self._active_pid_ticks: dict[tuple[str, int], int | None] = {}
    self._cleanup_generation_counter = 0
    self._event_generation_counter = 0
    self._cleanup_generations: dict[str, str] = {}
    self._cleanup_results: dict[
        tuple[str, str], ProcessGroupCleanupResult
    ] = {}

    # Interactive-mode sheets per job. Recorded at dispatch when the
    # sheet's merged instrument_config opts into interactive execution.
    # The stale check consults this to SKIP the workspace-mtime idle
    # kill for these sheets — the interactive driver owns idle handling
    # (busy/idle screen detection + nudges); two independent
    # kill-deciders would race. Dead-task detection still applies.
    # Cleared on deregister.
    self._interactive_sheets: dict[str, set[int]] = {}

    # #352 inc-3: live per-sheet output streaming. Instruments emit
    # drain chunks into hub writers wired per dispatch; `mzt watch`
    # consumes via the job.output.stream IPC handler. Ephemeral —
    # rings clear on deregister, lost on restart (stdout_tail persists).
    self._output_hub = OutputStreamHub()

    # BackendPool — injected via set_backend_pool()
    self._backend_pool: BackendPool | None = None
    self._mcp_pool: McpPoolManager | None = None

    # Per-job PromptRenderer — created when prompt_config is provided
    self._job_renderers: dict[str, PromptRenderer] = {}

    # Per-job CrossSheetConfig — enables cross-sheet context (F-210)
    self._job_cross_sheet: dict[str, CrossSheetConfig] = {}
    # Per-job LearningConfig — gates global learned-pattern prompt
    # injection. Outcome recording is owned elsewhere; this map only
    # controls whether prior patterns are fed back into the next prompt.
    self._job_learning_configs: dict[str, LearningConfig] = {}

    # Per-job spec corpus (#204). The manager loads + populates the frozen
    # SpecCorpusConfig off-loop and passes it here; per-sheet tag filtering
    # at dispatch is a pure dict op (no I/O). Only stored when fragments
    # exist, so _build_spec_fragments returns None for spec-less jobs.
    self._job_spec_config: dict[str, SpecCorpusConfig] = {}
    self._job_spec_tags: dict[str, dict[int, list[str]]] = {}

    # Per-job completion events — set when all sheets reach terminal state
    self._completion_events: dict[str, asyncio.Event] = {}

    # Per-job TechniqueRouter — created when the job declares techniques.
    # The router classifies musician output (prose, code, tool calls, A2A)
    # and is consumed by sheet_task() at dispatch time. Jobs without
    # techniques have no router (backward compat — classification skipped).
    self._job_routers: dict[str, TechniqueRouter] = {}

    # Per-job technique declarations — stored when the job declares
    # techniques so the dispatch loop can resolve them per-sheet into a
    # manifest for prompt injection. Jobs without techniques are absent
    # from this map (backward compat — resolution skipped, manifest None).
    self._job_techniques: dict[str, dict[str, Any]] = {}

    # Memory (GH #496): jobs that declare a `memory:` key, and the gate the
    # conductor injects. All logic lives in daemon/baton/memory_gate.py; a job
    # without `memory:` is absent from this map and never touches the gate.
    self._memory_gate: MemoryDispatchGate | None = None
    self._job_memory: dict[str, tuple[MemoryConfig, dict[int, str]]] = {}

    # Internal A2A runtime state. Agent cards are registered per running
    # job; inboxes hold delegated tasks until the target's next A2A-enabled
    # sheet renders its prompt. These structures are in-memory only today;
    # restart persistence requires a checkpoint schema extension.
    self._a2a_registry = AgentCardRegistry()
    self._a2a_inboxes: dict[str, A2AInbox] = {}
    self._a2a_job_agents: dict[str, str] = {}
    # #209: per-job opt-in code execution config (default None = off).
    self._job_code_execution: dict[str, CodeExecutionConfig] = {}

    # #360/#119: per-job, per-sheet skip_when command predicates. Evaluated at
    # dispatch time in _musician_wrapper before any render/backend work;
    # exit 0 → terminal skip. Absent job/sheet → no predicate (no-op).
    self._job_skip_commands: dict[str, dict[int, SkipWhenCommand]] = {}

    # #570: per-job skip_when unchanged predicate structures
    self._job_skip_unchanged: dict[str, dict[int, SkipWhenCommand]] = {}
    self._job_unchanged_enabled: set[str] = set()
    self._job_unchanged_taint: dict[str, set[int]] = {}
    self._job_unchanged_deps: dict[str, dict[int, tuple[int, ...]]] = {}
    self._job_unchanged_skipped: dict[str, set[int]] = {}
    self._job_unchanged_tails: dict[str, dict[int, str]] = {}
    self._job_unchanged_pending: dict[
        tuple[str, int, int | None], tuple[dict[str, str], list[dict[str, str]]]
    ] = {}
    self._job_unchanged_unusable: set[str] = set()
    self._job_ledger_scope: dict[str, str] = {}
    self._job_declared_products: dict[str, dict[int, list[str]]] = {}

    # Per-job completion status: True = all sheets completed, False = has failures
    self._completion_results: dict[str, bool] = {}

    # Running state
    self._running = False
    self._baton_task: asyncio.Task[Any] | None = None

    # Set when the adapter stops (run() exits or shutdown() is called) so
    # waiters on wait_for_completion() don't sit on a completion event that
    # will never fire once the engine is gone (#309). The wait stays free of
    # any total timeout — jobs legitimately run for hours — and leans on
    # per-sheet StaleCheck for genuinely-stuck sheets.
    self._shutdown_event = asyncio.Event()
Attributes
baton property
baton

The underlying BatonCore instance.

output_hub property
output_hub

Live per-sheet output rings + subscriptions (#352 inc-3).

is_running property
is_running

Whether the baton's event loop is running.

max_concurrent_sheets property
max_concurrent_sheets

Live global sheet-dispatch ceiling.

Methods:
set_backend_pool
set_backend_pool(pool)

Inject the BackendPool for backend acquisition.

Must be called before dispatching any sheets.

Parameters:

Name Type Description Default
pool BackendPool

The backend pool from the manager.

required
Source code in src/marianne/daemon/baton/adapter.py
def set_backend_pool(self, pool: BackendPool) -> None:
    """Inject the BackendPool for backend acquisition.

    Must be called before dispatching any sheets.

    Args:
        pool: The backend pool from the manager.
    """
    self._backend_pool = pool
set_cron_handler
set_cron_handler(handler)

Configure the recurring-score callback on the baton core.

Source code in src/marianne/daemon/baton/adapter.py
def set_cron_handler(self, handler: CronHandler) -> None:
    """Configure the recurring-score callback on the baton core."""
    self._baton.set_cron_handler(handler)
schedule_cron_tick
schedule_cron_tick(delay_seconds, event)

Schedule a recurring-score tick on the shared timer wheel.

Source code in src/marianne/daemon/baton/adapter.py
def schedule_cron_tick(
    self,
    delay_seconds: float,
    event: CronTick,
) -> TimerHandle:
    """Schedule a recurring-score tick on the shared timer wheel."""
    return self._timer_wheel.schedule(delay_seconds, event)
cancel_cron_tick
cancel_cron_tick(handle)

Cancel a recurring-score tick that has not fired yet.

Source code in src/marianne/daemon/baton/adapter.py
def cancel_cron_tick(self, handle: TimerHandle) -> bool:
    """Cancel a recurring-score tick that has not fired yet."""
    return self._timer_wheel.cancel(handle)
set_mcp_pool
set_mcp_pool(pool)

Inject the shared MCP pool used for dispatch-time config files.

Source code in src/marianne/daemon/baton/adapter.py
def set_mcp_pool(self, pool: McpPoolManager | None) -> None:
    """Inject the shared MCP pool used for dispatch-time config files."""
    self._mcp_pool = pool
set_memory_gate
set_memory_gate(gate)

Inject the memory dispatch gate; jobs already registered are handed to it.

Source code in src/marianne/daemon/baton/adapter.py
def set_memory_gate(self, gate: MemoryDispatchGate | None) -> None:
    """Inject the memory dispatch gate; jobs already registered are handed to it."""
    self._memory_gate = gate
    if gate is not None:
        for job_id, (memory, names) in self._job_memory.items():
            gate.register_job(job_id, memory, names)
configure_retry
configure_retry(*, base_delay=None, exponential_base=None, max_delay=None, jitter=None, startup_failure_floor=None, startup_failure_window=None)

Thread the score's RetryConfig backoff settings to the baton (#196).

Pass-through to BatonCore.configure_retry. Called once per job at registration (and recovery) so score-level retry: timing reaches the scheduler instead of the hardcoded defaults.

Source code in src/marianne/daemon/baton/adapter.py
def configure_retry(
    self,
    *,
    base_delay: float | None = None,
    exponential_base: float | None = None,
    max_delay: float | None = None,
    jitter: bool | None = None,
    startup_failure_floor: float | None = None,
    startup_failure_window: float | None = None,
) -> None:
    """Thread the score's RetryConfig backoff settings to the baton (#196).

    Pass-through to ``BatonCore.configure_retry``. Called once per job at
    registration (and recovery) so score-level ``retry:`` timing reaches the
    scheduler instead of the hardcoded defaults.
    """
    self._baton.configure_retry(
        base_delay=base_delay,
        exponential_base=exponential_base,
        max_delay=max_delay,
        jitter=jitter,
        startup_failure_floor=startup_failure_floor,
        startup_failure_window=startup_failure_window,
    )
register_job
register_job(job_id, sheets, dependencies, *, max_cost_usd=None, max_sheet_cost_usd=None, max_retries=3, max_completion=5, completion_threshold_percent=0.0, escalation_enabled=False, self_healing_enabled=False, prompt_config=None, learning_config=None, parallel_enabled=None, parallel_max_concurrent=None, parallel_fail_fast=False, cross_sheet=None, pacing_seconds=0.0, live_sheets=None, techniques=None, memory=None, memory_movement_names=None, stale_detection=None, spec_config=None, spec_tags=None, stagger_delay_ms=0, skip_when=None, code_execution=None, agent_card=None, cleanup_generation=None, schedule_id=None, scheduled_due_at=None, loops=None, triggers=None, flow_state=None, flow_variables=None, declared_products=None, ledger_scope=None)

Register a job with the baton for event-driven execution.

Converts Sheet entities to SheetExecutionState and registers them with the baton's sheet registry.

Phase 2: when live_sheets is provided, uses those SheetState objects directly instead of creating new ones. This ensures the baton writes to the same objects that live in _live_states, eliminating the need for a sync layer.

Parameters:

Name Type Description Default
job_id str

Unique job identifier (conductor job_id).

required
sheets list[Sheet]

Sheet entities from build_sheets().

required
dependencies dict[int, list[int]]

Dependency graph {sheet_num: [dep_nums]}.

required
max_cost_usd float | None

Optional per-job cost limit.

None
max_retries int

Max normal retry attempts per sheet.

3
max_completion int

Max completion mode attempts per sheet.

5
escalation_enabled bool

Enter fermata on exhaustion.

False
self_healing_enabled bool

Try self-healing on exhaustion.

False
prompt_config PromptConfig | None

Optional PromptConfig for full prompt rendering. When provided, creates a PromptRenderer for this job that handles the complete 9-layer prompt assembly pipeline.

None
parallel_enabled bool | None

Whether parallel execution is enabled. Explicit False enforces the score-facing serial contract; None retains legacy direct-caller scheduling behavior.

None
parallel_max_concurrent int | None

Score-owned dispatch ceiling when parallel execution is enabled. None preserves legacy/global behavior.

None
parallel_fail_fast bool

Stop starting new sheets in this job after a failure when parallel execution is enabled.

False
cross_sheet CrossSheetConfig | None

Optional CrossSheetConfig for cross-sheet context (F-210). When provided, the adapter collects previous sheet outputs and workspace files at dispatch time.

None
cleanup_generation str | None

Optional manager-issued execution generation. Direct adapter registrations allocate their own local value.

None
Source code in src/marianne/daemon/baton/adapter.py
def register_job(
    self,
    job_id: str,
    sheets: list[Sheet],
    dependencies: dict[int, list[int]],
    *,
    max_cost_usd: float | None = None,
    max_sheet_cost_usd: float | None = None,
    max_retries: int = 3,
    max_completion: int = 5,
    completion_threshold_percent: float = 0.0,
    escalation_enabled: bool = False,
    self_healing_enabled: bool = False,
    prompt_config: PromptConfig | None = None,
    learning_config: LearningConfig | None = None,
    parallel_enabled: bool | None = None,
    parallel_max_concurrent: int | None = None,
    parallel_fail_fast: bool = False,
    cross_sheet: CrossSheetConfig | None = None,
    pacing_seconds: float = 0.0,
    live_sheets: dict[int, SheetExecutionState] | None = None,
    techniques: dict[str, Any] | None = None,
    memory: MemoryConfig | None = None,
    memory_movement_names: dict[int, str] | None = None,
    stale_detection: StaleDetectionConfig | None = None,
    spec_config: SpecCorpusConfig | None = None,
    spec_tags: dict[int, list[str]] | None = None,
    stagger_delay_ms: int = 0,
    skip_when: dict[int, SkipWhenCommand] | None = None,
    code_execution: CodeExecutionConfig | None = None,
    agent_card: AgentCard | None = None,
    cleanup_generation: str | None = None,
    schedule_id: str | None = None,
    scheduled_due_at: float | None = None,
    loops: dict[str, LoopConfig] | None = None,
    triggers: dict[str, SheetTriggerConfig] | None = None,
    flow_state: FlowState | None = None,
    flow_variables: dict[str, Any] | None = None,
    declared_products: dict[int, list[str]] | None = None,
    ledger_scope: str | None = None,
) -> None:
    """Register a job with the baton for event-driven execution.

    Converts Sheet entities to SheetExecutionState and registers
    them with the baton's sheet registry.

    Phase 2: when ``live_sheets`` is provided, uses those SheetState
    objects directly instead of creating new ones. This ensures the
    baton writes to the same objects that live in ``_live_states``,
    eliminating the need for a sync layer.

    Args:
        job_id: Unique job identifier (conductor job_id).
        sheets: Sheet entities from build_sheets().
        dependencies: Dependency graph {sheet_num: [dep_nums]}.
        max_cost_usd: Optional per-job cost limit.
        max_retries: Max normal retry attempts per sheet.
        max_completion: Max completion mode attempts per sheet.
        escalation_enabled: Enter fermata on exhaustion.
        self_healing_enabled: Try self-healing on exhaustion.
        prompt_config: Optional PromptConfig for full prompt rendering.
            When provided, creates a PromptRenderer for this job that
            handles the complete 9-layer prompt assembly pipeline.
        parallel_enabled: Whether parallel execution is enabled. Explicit
            False enforces the score-facing serial contract; None retains
            legacy direct-caller scheduling behavior.
        parallel_max_concurrent: Score-owned dispatch ceiling when parallel
            execution is enabled. None preserves legacy/global behavior.
        parallel_fail_fast: Stop starting new sheets in this job after a
            failure when parallel execution is enabled.
        cross_sheet: Optional CrossSheetConfig for cross-sheet context
            (F-210). When provided, the adapter collects previous sheet
            outputs and workspace files at dispatch time.
        cleanup_generation: Optional manager-issued execution generation.
            Direct adapter registrations allocate their own local value.
    """
    self._ensure_job_state_collections()
    self._flow_pause_announced.discard(job_id)
    self.begin_cleanup_generation(job_id, cleanup_generation)

    # Store sheets for prompt rendering at dispatch time
    self._job_sheets[job_id] = {s.num: s for s in sheets}

    # Capture idle stale-detection config (#349/#350); default = disabled.
    self._stale_configs[job_id] = stale_detection or StaleDetectionConfig()

    # Store cross-sheet config (F-210)
    if cross_sheet is not None:
        self._job_cross_sheet[job_id] = cross_sheet
    if learning_config is not None:
        self._job_learning_configs[job_id] = learning_config
    else:
        self._job_learning_configs.pop(job_id, None)

    # Store spec corpus (#204). Only when fragments exist — an empty
    # corpus stores nothing, so _build_spec_fragments returns None.
    if spec_config is not None and spec_config.fragments:
        self._job_spec_config[job_id] = spec_config
    if spec_tags:
        self._job_spec_tags[job_id] = spec_tags
    if skip_when:
        self._job_skip_commands[job_id] = {
            n: r for n, r in skip_when.items() if r.command is not None
        }
    else:
        self._job_skip_commands.pop(job_id, None)

    self._index_unchanged(
        job_id,
        sheets,
        dependencies,
        skip_when,
        loops,
        declared_products=declared_products,
        ledger_scope=ledger_scope,
        enabled=True,
    )

    # Create PromptRenderer if config is available (F-104)
    if prompt_config is not None:
        from marianne.daemon.baton.prompt import PromptRenderer

        total_sheets = len(sheets)
        total_stages = len({s.movement for s in sheets}) or 1
        self._job_renderers[job_id] = PromptRenderer(
            prompt_config=prompt_config,
            total_sheets=total_sheets,
            total_stages=total_stages,
            parallel_enabled=bool(parallel_enabled),
            job_id=job_id,
            schedule_id=schedule_id,
            scheduled_due_at=scheduled_due_at,
        )

    # Create completion event for this job
    self._completion_events[job_id] = asyncio.Event()

    # Stage 2a: instantiate a TechniqueRouter when techniques are declared.
    # The router is shared across all sheets in the job (it is stateless —
    # pure regex classification, no per-sheet setup). Jobs that declare
    # zero techniques (or omit the argument entirely) do not get a
    # router, so sheet_task() skips classification and output_kind stays
    # None. This preserves backward compatibility for scores written
    # before techniques existed.
    if techniques:
        self._job_routers[job_id] = TechniqueRouter()
        self._job_techniques[job_id] = techniques

    if memory is not None:
        self._job_memory[job_id] = (memory, dict(memory_movement_names or {}))
        if self._memory_gate is not None:
            self._memory_gate.register_job(job_id, memory, memory_movement_names)

    # #209: code execution needs a router to classify output into code
    # blocks, even when no techniques are declared. Store the config and
    # ensure a router exists when opted in.
    if code_execution is not None and code_execution.enabled:
        self._job_code_execution[job_id] = code_execution
        if job_id not in self._job_routers:
            self._job_routers[job_id] = TechniqueRouter()

    self._register_a2a_job(job_id, agent_card)

    # Phase 2: use live_sheets (shared with _live_states) when provided.
    # This makes the baton write directly to the same SheetState objects
    # the manager serves via get_job_status — no sync layer needed.
    if live_sheets is not None:
        # Enrich existing SheetState objects with baton scheduling fields.
        # Identity writes (#452) apply only to non-terminal sheets. The
        # production caller (manager.py) always passes fresh PENDING
        # states, where the writes are idempotent over primary values —
        # but the baton's states ARE the manager's live states (mutation
        # is persistence), so a future re-register over an executed
        # COMPLETED-on-fallback sheet must not rewrite its identity.
        # Scheduling enrichment still applies to every live sheet.
        for sheet in sheets:
            s = live_sheets.get(sheet.num)
            if s is not None and s.status not in _KEEP_IDENTITY:
                s.instrument_name = sheet.instrument_name
                raw_m = sheet.instrument_config.get("model")
                s.model = str(raw_m) if raw_m is not None else None
                s.instrument_model = s.model
                s.remember_primary_identity()
            if s is not None:
                s.max_retries = max_retries
                s.max_completion = max_completion
                s.fallback_chain = list(sheet.instrument_fallbacks)
                s.fallback_configs = [dict(c) for c in sheet.instrument_fallback_configs]
                s.primary_config = dict(sheet.instrument_config)
                s.sheet_timeout_seconds = sheet.timeout_seconds
        states = live_sheets
    else:
        states = sheets_to_execution_states(
            sheets,
            max_retries=max_retries,
            max_completion=max_completion,
        )

    # Register with baton. Adapter-managed records always expose an integer
    # event generation; direct BatonCore callers retain legacy None.
    event_generation = self._next_event_generation()
    self._baton.register_job(
        job_id,
        states,
        dependencies,
        escalation_enabled=escalation_enabled,
        self_healing_enabled=self_healing_enabled,
        pacing_seconds=pacing_seconds,
        max_concurrent=(
            parallel_max_concurrent
            if parallel_enabled is True
            else 1 if parallel_enabled is False else None
        ),
        fail_fast=parallel_fail_fast if parallel_enabled is True else False,
        stagger_delay_ms=stagger_delay_ms if parallel_enabled is not False else 0,
        completion_threshold_percent=completion_threshold_percent,
        event_generation=event_generation,
        workspace=(sheets[0].workspace if sheets else None),  # #201: for healing ErrorContext
        loops=loops,
        triggers=triggers,
        flow_state=flow_state,
        flow_variables=flow_variables,
    )

    # Set cost limits if configured
    if max_cost_usd is not None:
        self._baton.set_job_cost_limit(job_id, max_cost_usd)
    if max_sheet_cost_usd is not None:
        for sheet in sheets:
            self._baton.set_sheet_cost_limit(job_id, sheet.num, max_sheet_cost_usd)

    _logger.info(
        "adapter.job_registered",
        extra={
            "job_id": job_id,
            "sheet_count": len(sheets),
            "dependency_count": len(dependencies),
            "max_retries": max_retries,
            "max_completion": max_completion,
        },
    )

    # Kick the event loop so dispatch_ready runs for the newly registered
    # sheets.  Without this the loop blocks on inbox.get() forever
    # because no musician or timer has produced an event yet. Coalesced (#222).
    self._baton.enqueue_dispatch_retry()
get_router
get_router(job_id)

Return the per-job TechniqueRouter, or None if not activated.

The router is created by :meth:register_job when the job declares one or more techniques. Jobs without techniques (the default for legacy scores) have no router and classification is skipped.

Parameters:

Name Type Description Default
job_id str

The job to look up.

required

Returns:

Type Description
TechniqueRouter | None

The job's TechniqueRouter if one was activated, else None.

Source code in src/marianne/daemon/baton/adapter.py
def get_router(self, job_id: str) -> TechniqueRouter | None:
    """Return the per-job TechniqueRouter, or None if not activated.

    The router is created by :meth:`register_job` when the job declares
    one or more techniques. Jobs without techniques (the default for
    legacy scores) have no router and classification is skipped.

    Args:
        job_id: The job to look up.

    Returns:
        The job's TechniqueRouter if one was activated, else None.
    """
    return self._job_routers.get(job_id)
get_a2a_inbox
get_a2a_inbox(job_id)

Return the per-job A2A inbox, or None when no card is registered.

Source code in src/marianne/daemon/baton/adapter.py
def get_a2a_inbox(self, job_id: str) -> A2AInbox | None:
    """Return the per-job A2A inbox, or None when no card is registered."""
    self._ensure_a2a_state()
    return self._a2a_inboxes.get(job_id)
get_process_group_cleanup_result
get_process_group_cleanup_result(job_id, cleanup_generation=None)

Return the live cleanup evidence for a deregistered job.

The returned result is intentionally live while the SIGTERM grace callback is pending. Callers can therefore observe the later SIGKILL and residual-process check instead of retaining the initial pending snapshot forever.

Source code in src/marianne/daemon/baton/adapter.py
def get_process_group_cleanup_result(
    self,
    job_id: str,
    cleanup_generation: str | None = None,
) -> ProcessGroupCleanupResult | None:
    """Return the live cleanup evidence for a deregistered job.

    The returned result is intentionally live while the SIGTERM grace
    callback is pending.  Callers can therefore observe the later
    SIGKILL and residual-process check instead of retaining the initial
    ``pending`` snapshot forever.
    """
    self._ensure_job_state_collections()
    generation = cleanup_generation or self._cleanup_generations.get(job_id)
    if generation is None:
        return None
    return self._cleanup_results.get((job_id, generation))
begin_cleanup_generation
begin_cleanup_generation(job_id, cleanup_generation=None)

Begin or bind one local execution generation for cleanup evidence.

Source code in src/marianne/daemon/baton/adapter.py
def begin_cleanup_generation(
    self,
    job_id: str,
    cleanup_generation: str | None = None,
) -> str:
    """Begin or bind one local execution generation for cleanup evidence."""
    self._ensure_job_state_collections()
    generation = cleanup_generation
    if generation is None:
        self._cleanup_generation_counter += 1
        generation = f"cleanup-{self._cleanup_generation_counter}"
    current = self._cleanup_generations.get(job_id)
    if current == generation:
        return generation

    self._cleanup_generations[job_id] = generation
    # Mature historical results are no longer observable once a fresh
    # execution begins. Pending results stay alive only until their
    # captured grace callback records and logs its old-generation result.
    for key, result in list(self._cleanup_results.items()):
        if (
            key[0] == job_id
            and key[1] != generation
            and result.escalation_state != "pending"
        ):
            self._cleanup_results.pop(key, None)
    return generation
deregister_job
deregister_job(job_id)

Remove a job from the adapter and baton.

Cleans up all per-job state including active tasks.

Parameters:

Name Type Description Default
job_id str

The job to remove.

required
Source code in src/marianne/daemon/baton/adapter.py
def deregister_job(self, job_id: str) -> ProcessGroupCleanupResult:
    """Remove a job from the adapter and baton.

    Cleans up all per-job state including active tasks.

    Args:
        job_id: The job to remove.
    """
    self._ensure_job_state_collections()
    cleanup_generation = self._cleanup_generations.get(job_id)
    if cleanup_generation is None:
        cleanup_generation = self.begin_cleanup_generation(job_id)

    # Phase 1 item 5: preempt-kill subprocess groups BEFORE cancelling
    # asyncio tasks. Task.cancel() delivers CancelledError through the
    # `await proc.communicate()` in the backend, whose finally block
    # will then kill the same group — but only when the await actually
    # wakes. A process blocked in an uninterruptible syscall would
    # leave the finally stuck. Preempt-SIGTERM forces the process to
    # exit, which unblocks communicate, which runs finally. Belt and
    # suspenders.
    cleanup_result = self._kill_active_pgroups(
        job_id,
        cleanup_generation,
    )
    result_key = (job_id, cleanup_generation)
    previous_cleanup = self._cleanup_results.get(result_key)
    if (
        cleanup_result.tracked_process_groups == 0
        and previous_cleanup is not None
    ):
        cleanup_result = previous_cleanup
    else:
        self._cleanup_results[result_key] = cleanup_result
    self._kill_interactive_sessions(job_id)

    # Cancel active musician tasks, but retain their occupancy records until
    # each task is physically done with cancellation cleanup/backend release.
    keys_to_cancel = [
        key for key in self._active_tasks if key[0] == job_id
    ]
    for key in keys_to_cancel:
        task = self._active_tasks[key]
        task.cancel(msg=f"deregister_job({job_id})")
    if keys_to_cancel:
        _logger.info(
            "adapter.deregister_job.tasks_cancelled",
            extra={
                "job_id": job_id,
                "cancelled_sheets": [k[1] for k in keys_to_cancel],
            },
        )

    # Remove from baton
    self._baton.deregister_job(job_id)

    # Only a pending SIGKILL/residual-check callback needs historical
    # bookkeeping. Terminal cleanup evidence is returned to the caller and
    # must not accumulate per unique recurrence ID in a long-lived daemon.
    if cleanup_result.escalation_state != "pending":
        self._finish_cleanup_tracking(job_id, cleanup_generation)

    # Remove sheet mapping, renderer, cross-sheet config, and completion tracking
    self._job_sheets.pop(job_id, None)
    self._job_renderers.pop(job_id, None)
    self._job_cross_sheet.pop(job_id, None)
    self._job_learning_configs.pop(job_id, None)
    self._job_spec_config.pop(job_id, None)
    self._job_spec_tags.pop(job_id, None)
    self._completion_events.pop(job_id, None)
    self._completion_results.pop(job_id, None)
    self._job_routers.pop(job_id, None)
    self._job_techniques.pop(job_id, None)
    _memory_gate = getattr(self, "_memory_gate", None)
    job_memory = getattr(self, "_job_memory", {})
    if job_memory.pop(job_id, None) is not None and _memory_gate is not None:
        _memory_gate.deregister_job(job_id)
    self._ensure_a2a_state()
    self._a2a_registry.deregister(job_id)
    self._a2a_inboxes.pop(job_id, None)
    self._a2a_job_agents.pop(job_id, None)
    self._job_code_execution.pop(job_id, None)
    self._job_skip_commands.pop(job_id, None)
    self._job_skip_unchanged.pop(job_id, None)
    self._job_unchanged_enabled.discard(job_id)
    self._job_unchanged_taint.pop(job_id, None)
    self._job_unchanged_deps.pop(job_id, None)
    self._job_unchanged_skipped.pop(job_id, None)
    self._job_unchanged_tails.pop(job_id, None)
    self._job_unchanged_unusable.discard(job_id)
    self._job_ledger_scope.pop(job_id, None)
    self._job_declared_products.pop(job_id, None)
    pending_keys = [pk for pk in self._job_unchanged_pending if pk[0] == job_id]
    for pk in pending_keys:
        self._job_unchanged_pending.pop(pk, None)
    self._interactive_sheets.pop(job_id, None)
    # #352 inc-3: drop the job's output rings (memory bound).
    self._output_hub.clear_job(job_id)

    # Idle stale-detection cleanup (#349/#350): drop the job config and any
    # per-sheet idle-window / stale-marker state for this job.
    self._stale_configs.pop(job_id, None)
    stale_keys = [k for k in self._stale_dispatch_time if k[0] == job_id]
    for k in stale_keys:
        self._stale_dispatch_time.pop(k, None)
        self._stale_markers.discard(k)
        self._stale_idle_strikes.pop(k, None)
    for k in [k for k in self._stale_idle_strikes if k[0] == job_id]:
        self._stale_idle_strikes.pop(k, None)
    for k in [k for k in self._fermata_polling if k[0] == job_id]:
        self._fermata_polling.discard(k)

    # Clean up vestigial _synced_status entries (Phase 2: sync layer
    # removed but dict retained for compatibility). Defensive cleanup
    # prevents memory leaks if anything accidentally populates it.
    if hasattr(self, "_synced_status") and self._synced_status:
        self._synced_status = {
            k: v for k, v in self._synced_status.items() if k[0] != job_id
        }

    _logger.info("adapter.job_deregistered", extra={"job_id": job_id})
    return cleanup_result
recover_job
recover_job(job_id, sheets, dependencies, checkpoint, *, max_cost_usd=None, max_sheet_cost_usd=None, max_retries=3, max_completion=5, completion_threshold_percent=0.0, escalation_enabled=False, self_healing_enabled=False, prompt_config=None, learning_config=None, parallel_enabled=None, parallel_max_concurrent=None, parallel_fail_fast=False, cross_sheet=None, pacing_seconds=0.0, live_sheets=None, techniques=None, memory=None, memory_movement_names=None, stale_detection=None, spec_config=None, spec_tags=None, stagger_delay_ms=0, skip_when=None, code_execution=None, agent_card=None, loops=None, triggers=None, flow_variables=None, declared_products=None, ledger_scope=None)

Recover a job from a checkpoint after conductor restart.

Rebuilds baton state from the persisted CheckpointState. Terminal sheets (completed, failed, skipped) keep their status. In-progress sheets are reset to PENDING because their musicians died when the conductor restarted. Attempt counts are preserved to avoid infinite retries.

Design invariant: Checkpoint is the source of truth. The baton rebuilds from checkpoint, not the reverse.

Parameters:

Name Type Description Default
job_id str

Unique job identifier.

required
sheets list[Sheet]

Sheet entities from build_sheets() — same config that produced the original job.

required
dependencies dict[int, list[int]]

Dependency graph {sheet_num: [dep_nums]}.

required
checkpoint CheckpointState

Persisted CheckpointState loaded from workspace.

required
max_cost_usd float | None

Optional per-job cost limit.

None
max_retries int

Max normal retry attempts per sheet.

3
max_completion int

Max completion mode attempts per sheet.

5
escalation_enabled bool

Enter fermata on exhaustion.

False
self_healing_enabled bool

Try self-healing on exhaustion.

False
prompt_config PromptConfig | None

Optional PromptConfig for prompt rendering.

None
parallel_enabled bool | None

Whether parallel execution is enabled. Explicit False restores the score-facing serial contract; None retains legacy direct-caller scheduling behavior.

None
parallel_max_concurrent int | None

Restored score-owned dispatch ceiling.

None
parallel_fail_fast bool

Restored score-owned fail-fast policy.

False
cross_sheet CrossSheetConfig | None

Optional CrossSheetConfig for cross-sheet context (F-210).

None
Source code in src/marianne/daemon/baton/adapter.py
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
def recover_job(
    self,
    job_id: str,
    sheets: list[Sheet],
    dependencies: dict[int, list[int]],
    checkpoint: CheckpointState,
    *,
    max_cost_usd: float | None = None,
    max_sheet_cost_usd: float | None = None,
    max_retries: int = 3,
    max_completion: int = 5,
    completion_threshold_percent: float = 0.0,
    escalation_enabled: bool = False,
    self_healing_enabled: bool = False,
    prompt_config: PromptConfig | None = None,
    learning_config: LearningConfig | None = None,
    parallel_enabled: bool | None = None,
    parallel_max_concurrent: int | None = None,
    parallel_fail_fast: bool = False,
    cross_sheet: CrossSheetConfig | None = None,
    pacing_seconds: float = 0.0,
    live_sheets: dict[int, SheetExecutionState] | None = None,
    techniques: dict[str, Any] | None = None,
    memory: MemoryConfig | None = None,
    memory_movement_names: dict[int, str] | None = None,
    stale_detection: StaleDetectionConfig | None = None,
    spec_config: SpecCorpusConfig | None = None,
    spec_tags: dict[int, list[str]] | None = None,
    stagger_delay_ms: int = 0,
    skip_when: dict[int, SkipWhenCommand] | None = None,
    code_execution: CodeExecutionConfig | None = None,
    agent_card: AgentCard | None = None,
    loops: dict[str, LoopConfig] | None = None,
    triggers: dict[str, SheetTriggerConfig] | None = None,
    flow_variables: dict[str, Any] | None = None,
    declared_products: dict[int, list[str]] | None = None,
    ledger_scope: str | None = None,
) -> None:
    """Recover a job from a checkpoint after conductor restart.

    Rebuilds baton state from the persisted CheckpointState. Terminal
    sheets (completed, failed, skipped) keep their status. In-progress
    sheets are reset to PENDING because their musicians died when the
    conductor restarted. Attempt counts are preserved to avoid infinite
    retries.

    Design invariant: Checkpoint is the source of truth. The baton
    rebuilds from checkpoint, not the reverse.

    Args:
        job_id: Unique job identifier.
        sheets: Sheet entities from build_sheets() — same config
            that produced the original job.
        dependencies: Dependency graph {sheet_num: [dep_nums]}.
        checkpoint: Persisted CheckpointState loaded from workspace.
        max_cost_usd: Optional per-job cost limit.
        max_retries: Max normal retry attempts per sheet.
        max_completion: Max completion mode attempts per sheet.
        escalation_enabled: Enter fermata on exhaustion.
        self_healing_enabled: Try self-healing on exhaustion.
        prompt_config: Optional PromptConfig for prompt rendering.
        parallel_enabled: Whether parallel execution is enabled. Explicit
            False restores the score-facing serial contract; None retains
            legacy direct-caller scheduling behavior.
        parallel_max_concurrent: Restored score-owned dispatch ceiling.
        parallel_fail_fast: Restored score-owned fail-fast policy.
        cross_sheet: Optional CrossSheetConfig for cross-sheet context (F-210).
    """
    self._ensure_job_state_collections()
    self._flow_pause_announced.discard(job_id)

    # Store sheets for prompt rendering
    self._job_sheets[job_id] = {s.num: s for s in sheets}

    # Capture idle stale-detection config (#349/#350); default = disabled.
    # Recovered jobs get fresh idle windows when their sheets re-dispatch.
    self._stale_configs[job_id] = stale_detection or StaleDetectionConfig()

    # Store cross-sheet config (F-210)
    if cross_sheet is not None:
        self._job_cross_sheet[job_id] = cross_sheet
    if learning_config is not None:
        self._job_learning_configs[job_id] = learning_config
    else:
        self._job_learning_configs.pop(job_id, None)

    # Store spec corpus (#204). Only when fragments exist — an empty
    # corpus stores nothing, so _build_spec_fragments returns None.
    if spec_config is not None and spec_config.fragments:
        self._job_spec_config[job_id] = spec_config
    if spec_tags:
        self._job_spec_tags[job_id] = spec_tags
    if skip_when:
        self._job_skip_commands[job_id] = {
            n: r for n, r in skip_when.items() if r.command is not None
        }
    else:
        self._job_skip_commands.pop(job_id, None)

    self._index_unchanged(
        job_id,
        sheets,
        dependencies,
        skip_when,
        loops,
        declared_products=declared_products,
        ledger_scope=ledger_scope,
        enabled=False,
    )

    # Create PromptRenderer if config is available
    if prompt_config is not None:
        from marianne.daemon.baton.prompt import PromptRenderer

        total_sheets = len(sheets)
        total_stages = len({s.movement for s in sheets}) or 1
        self._job_renderers[job_id] = PromptRenderer(
            prompt_config=prompt_config,
            total_sheets=total_sheets,
            total_stages=total_stages,
            parallel_enabled=bool(parallel_enabled),
            job_id=checkpoint.job_id,
            schedule_id=checkpoint.schedule_id,
            scheduled_due_at=checkpoint.scheduled_due_at,
        )

    # Create completion event
    self._completion_events[job_id] = asyncio.Event()

    # Restore technique state for resumed jobs so Stage 1 resolution and
    # Stage 2a classification survive a conductor restart. Without this
    # the resumed job would run without its declared techniques — the
    # manifest would never inject and the router would never classify.
    if techniques:
        self._job_routers[job_id] = TechniqueRouter()
        self._job_techniques[job_id] = techniques

    if memory is not None:
        self._job_memory[job_id] = (memory, dict(memory_movement_names or {}))
        if self._memory_gate is not None:
            self._memory_gate.register_job(job_id, memory, memory_movement_names)
            # Dispatch directories the previous conductor process left behind in this
            # job's workspaces are dead; nothing else would ever remove them.
            self._memory_gate.schedule_config_sweep({s.workspace for s in sheets})

    # #209: restore opt-in code execution across resume so a resumed
    # job still classifies + runs code blocks (router ensured even
    # without techniques).
    if code_execution is not None and code_execution.enabled:
        self._job_code_execution[job_id] = code_execution
        if job_id not in self._job_routers:
            self._job_routers[job_id] = TechniqueRouter()

    self._register_a2a_job(job_id, agent_card)

    # Build SheetExecutionState with recovered statuses and attempt counts
    states: dict[int, SheetExecutionState] = {}
    for sheet in sheets:
        cp_sheet = checkpoint.sheets.get(sheet.num)

        if cp_sheet is not None:
            # On restart, active/transient sheets reset to PENDING:
            # - in_progress/dispatched: musician was killed on restart
            # - waiting: rate limit timers lost on restart
            # - retry_scheduled: retry timers lost on restart
            # - fermata: re-evaluate escalation on restart
            # Terminal sheets (completed, failed, skipped, cancelled)
            # keep their status. Pending/ready stay as-is.
            _RESET_ON_RESTART = frozenset({
                BatonSheetStatus.IN_PROGRESS,
                BatonSheetStatus.DISPATCHED,
                BatonSheetStatus.WAITING,
                BatonSheetStatus.RETRY_SCHEDULED,
                # #361: FERMATA is NOT reset — a composer-decision pause must
                # survive restart (silent re-run of a sheet that already
                # touched production is catastrophic). The run loop's
                # reconcile re-arms marker polling for recovered FERMATA sheets.
            })
            baton_status = (
                BatonSheetStatus.PENDING
                if cp_sheet.status in _RESET_ON_RESTART
                else cp_sheet.status
            )

            # Carry forward attempt counts to avoid infinite retries
            normal_attempts = cp_sheet.attempt_count
            completion_attempts = cp_sheet.completion_attempts
        else:
            # Sheet not in checkpoint — treat as fresh PENDING
            baton_status = BatonSheetStatus.PENDING
            normal_attempts = 0
            completion_attempts = 0

        # Phase 2: update the live SheetState in-place when available,
        # so the baton operates on the same objects as _live_states.
        if live_sheets is not None and sheet.num in live_sheets:
            state = live_sheets[sheet.num]
        else:
            raw_model = sheet.instrument_config.get("model")
            state = SheetExecutionState(
                sheet_num=sheet.num,
                instrument_name=sheet.instrument_name,
                model=str(raw_model) if raw_model is not None else None,
            )

        # Populate instrument identity from the Sheet entity — except for
        # terminal fallen-back sheets (#452). The checkpoint may have
        # instrument_name=None for sheets that were never dispatched
        # (e.g., dependency-cascaded failures), which is what the
        # Sheet-entity write covers. But a COMPLETED/SKIPPED/CANCELLED
        # sheet that fell back finished ON the fallback: the checkpoint
        # holds its true identity (advance_fallback + F-490 sync), and
        # rewriting only the name (the model writes below are guarded)
        # fabricates a never-executed instrument/model pair that then
        # persists durably — the live SheetState IS the checkpoint's.
        if baton_status not in _KEEP_IDENTITY:
            state.instrument_name = sheet.instrument_name
            state.instrument_resolution = (
                sheet.instrument_resolution
                if isinstance(sheet.instrument_resolution, InstrumentResolution)
                else None
            )
        raw_model = sheet.instrument_config.get("model")
        primary_model = str(raw_model) if raw_model is not None else None
        if baton_status not in _KEEP_IDENTITY:
            state.model = primary_model
            state.instrument_model = primary_model
        state.primary_identity = InstrumentIdentity(
            name=sheet.instrument_name, model=primary_model
        )
        state.max_retries = max_retries
        state.max_completion = max_completion
        state.fallback_chain = list(sheet.instrument_fallbacks)
        state.fallback_configs = [dict(c) for c in sheet.instrument_fallback_configs]
        state.primary_config = dict(sheet.instrument_config)
        state.sheet_timeout_seconds = sheet.timeout_seconds
        state.status = baton_status
        state.normal_attempts = normal_attempts
        state.completion_attempts = completion_attempts
        # Reset instrument fallback position for non-terminal sheets.
        # A recovered/resumed sheet must start from the primary
        # instrument, not stay stuck on whatever fallback it died on.
        # Terminal sheets (COMPLETED, SKIPPED) keep their instrument
        # history for diagnostics.
        _TERMINAL = {
            BatonSheetStatus.COMPLETED,
            BatonSheetStatus.SKIPPED,
            BatonSheetStatus.CANCELLED,
        }
        if baton_status not in _TERMINAL:
            state.current_instrument_index = 0
            # GH#190: also clear the stale fallback record so the status
            # display doesn't show a phantom "(was X: rate_limit)" tag for a
            # sheet that now restarts clean from its primary instrument.
            state.instrument_fallback_history = []
            state.fallback_attempts = {}

        states[sheet.num] = state

    # Drop any stale baton entry before re-registering. `register_job`
    # silently no-ops on duplicate job_id (a safety guard for accidental
    # double-registers from other paths), which collides with recover_job's
    # documented invariant ("Checkpoint is the source of truth. The baton
    # rebuilds from checkpoint, not the reverse"). Without this deregister,
    # a `mzt recover` followed by `mzt resume` on a live conductor finds
    # the prior failed sheet states intact in the baton, fires
    # `is_job_complete` immediately, and re-FAILs the job — forcing the
    # operator to restart the conductor before recover takes effect.
    self._baton.deregister_job(job_id)
    event_generation = self._next_event_generation()
    self._baton.register_job(
        job_id,
        states,
        dependencies,
        escalation_enabled=escalation_enabled,
        self_healing_enabled=self_healing_enabled,
        pacing_seconds=pacing_seconds,
        max_concurrent=(
            parallel_max_concurrent
            if parallel_enabled is True
            else 1 if parallel_enabled is False else None
        ),
        fail_fast=parallel_fail_fast if parallel_enabled is True else False,
        stagger_delay_ms=stagger_delay_ms if parallel_enabled is not False else 0,
        completion_threshold_percent=completion_threshold_percent,
        event_generation=event_generation,
        workspace=(sheets[0].workspace if sheets else None),  # #201: for healing ErrorContext
        loops=loops,
        triggers=triggers,
        flow_state=checkpoint.flow,
        flow_variables=flow_variables,
    )

    # Set cost limits if configured
    if max_cost_usd is not None:
        self._baton.set_job_cost_limit(job_id, max_cost_usd)
    if max_sheet_cost_usd is not None:
        for sheet in sheets:
            self._baton.set_sheet_cost_limit(job_id, sheet.num, max_sheet_cost_usd)

    _logger.info(
        "adapter.job_recovered",
        extra={
            "job_id": job_id,
            "sheet_count": len(sheets),
            "recovered_terminal": sum(
                1 for s in states.values()
                if s.status in (
                    BatonSheetStatus.COMPLETED,
                    BatonSheetStatus.FAILED,
                    BatonSheetStatus.SKIPPED,
                )
            ),
            "recovered_pending": sum(
                1 for s in states.values()
                if s.status == BatonSheetStatus.PENDING
            ),
        },
    )

    # Kick the event loop so dispatch_ready runs for recovered sheets. Coalesced (#222).
    self._baton.enqueue_dispatch_retry()
get_sheet
get_sheet(job_id, sheet_num)

Get a Sheet entity for a registered job.

Parameters:

Name Type Description Default
job_id str

The job identifier.

required
sheet_num int

The sheet number.

required

Returns:

Type Description
Sheet | None

The Sheet entity, or None if not found.

Source code in src/marianne/daemon/baton/adapter.py
def get_sheet(self, job_id: str, sheet_num: int) -> Sheet | None:
    """Get a Sheet entity for a registered job.

    Args:
        job_id: The job identifier.
        sheet_num: The sheet number.

    Returns:
        The Sheet entity, or None if not found.
    """
    job_sheets = self._job_sheets.get(job_id)
    if job_sheets is None:
        return None
    return job_sheets.get(sheet_num)
wait_for_completion async
wait_for_completion(job_id)

Wait until a job reaches terminal state.

Blocks until all sheets in the job are completed, failed, skipped, or cancelled. Used by the manager's _run_job_task to await baton execution.

Parameters:

Name Type Description Default
job_id str

The job to wait for.

required

Returns:

Type Description
bool

True if all sheets completed successfully, False if any failed.

Raises:

Type Description
KeyError

If the job is not registered.

Source code in src/marianne/daemon/baton/adapter.py
async def wait_for_completion(self, job_id: str) -> bool:
    """Wait until a job reaches terminal state.

    Blocks until all sheets in the job are completed, failed, skipped,
    or cancelled. Used by the manager's _run_job_task to await baton
    execution.

    Args:
        job_id: The job to wait for.

    Returns:
        True if all sheets completed successfully, False if any failed.

    Raises:
        KeyError: If the job is not registered.
    """
    event = self._completion_events.get(job_id)
    if event is None:
        raise KeyError(f"Job '{job_id}' is not registered with the adapter")

    # Shutdown-responsive wait (#309): block on the completion event OR the
    # adapter shutdown, whichever happens first. NO total timeout — a job
    # may legitimately run for hours; per-sheet StaleCheck handles stuck
    # sheets, and the manager applies a 24h job ceiling. If shutdown wins
    # while the job is still in-flight we RAISE rather than return False:
    # returning False would record a healthy interrupted job as failed.
    completion_task = asyncio.ensure_future(event.wait())
    shutdown_task = asyncio.ensure_future(self._shutdown_event.wait())
    try:
        await asyncio.wait(
            {completion_task, shutdown_task},
            return_when=asyncio.FIRST_COMPLETED,
        )
        if self._shutdown_event.is_set() and not event.is_set():
            raise asyncio.CancelledError(
                f"baton adapter shutting down while waiting for job '{job_id}'"
            )
        return self._completion_results.get(job_id, False)
    finally:
        for task in (completion_task, shutdown_task):
            if not task.done():
                task.cancel()
has_job
has_job(job_id)

Whether the baton is currently tracking this job.

Delegates to the baton's presence predicate. Used by the manager to cancel auto-recovered baton jobs that have no wrapper task (#162).

Source code in src/marianne/daemon/baton/adapter.py
def has_job(self, job_id: str) -> bool:
    """Whether the baton is currently tracking this job.

    Delegates to the baton's presence predicate. Used by the manager to
    cancel auto-recovered baton jobs that have no wrapper task (#162).
    """
    return self._baton.has_job(job_id)
has_completed_sheets
has_completed_sheets(job_id)

Check if any sheet in the job reached COMPLETED status.

F-145: Used by the manager to set completed_new_work after baton execution. The zero-work guard for concert chaining needs to know whether any sheet completed new work — not just whether all sheets succeeded.

Parameters:

Name Type Description Default
job_id str

The job to check.

required

Returns:

Type Description
bool

True if at least one sheet completed, False otherwise.

Source code in src/marianne/daemon/baton/adapter.py
def has_completed_sheets(self, job_id: str) -> bool:
    """Check if any sheet in the job reached COMPLETED status.

    F-145: Used by the manager to set completed_new_work after baton
    execution. The zero-work guard for concert chaining needs to know
    whether any sheet completed new work — not just whether all
    sheets succeeded.

    Args:
        job_id: The job to check.

    Returns:
        True if at least one sheet completed, False otherwise.
    """
    job = self._baton._jobs.get(job_id)
    if job is None:
        return False
    return any(
        s.status == BatonSheetStatus.COMPLETED
        for s in job.sheets.values()
    )
clear_instrument_rate_limit
clear_instrument_rate_limit(instrument=None)

Clear instrument rate limit state in the baton core.

Delegates to BatonCore.clear_instrument_rate_limit(). Also moves WAITING sheets back to PENDING so they can be re-dispatched.

Parameters:

Name Type Description Default
instrument str | None

Instrument name to clear, or None for all.

None

Returns:

Type Description
int

Number of instruments whose rate limit was cleared.

Source code in src/marianne/daemon/baton/adapter.py
def clear_instrument_rate_limit(
    self,
    instrument: str | None = None,
) -> int:
    """Clear instrument rate limit state in the baton core.

    Delegates to ``BatonCore.clear_instrument_rate_limit()``.  Also
    moves WAITING sheets back to PENDING so they can be re-dispatched.

    Args:
        instrument: Instrument name to clear, or ``None`` for all.

    Returns:
        Number of instruments whose rate limit was cleared.
    """
    return self._baton.clear_instrument_rate_limit(instrument)
publish_sheet_skipped async
publish_sheet_skipped(event)

Publish a sheet skip event to the EventBus.

Parameters:

Name Type Description Default
event SheetSkipped

The sheet skip event.

required
Source code in src/marianne/daemon/baton/adapter.py
async def publish_sheet_skipped(self, event: SheetSkipped) -> None:
    """Publish a sheet skip event to the EventBus.

    Args:
        event: The sheet skip event.
    """
    if self._event_bus is None:
        return

    obs_event = skipped_to_observer_event(event)
    try:
        await self._event_bus.publish(obs_event)
    except Exception:  # noqa: BLE001 — structured logger reports adapter.event_publish_failed
        _logger.warning(
            "adapter.event_publish_failed",
            extra={
                "job_id": event.job_id,
                "sheet_num": event.sheet_num,
            },
            exc_info=True,
        )
publish_job_event async
publish_job_event(job_id, event_name, data=None)

Publish a job-level event to the EventBus.

Parameters:

Name Type Description Default
job_id str

The job identifier.

required
event_name str

Event name (e.g., "job.started", "job.completed").

required
data dict[str, Any] | None

Optional event data.

None
Source code in src/marianne/daemon/baton/adapter.py
async def publish_job_event(
    self,
    job_id: str,
    event_name: str,
    data: dict[str, Any] | None = None,
) -> None:
    """Publish a job-level event to the EventBus.

    Args:
        job_id: The job identifier.
        event_name: Event name (e.g., "job.started", "job.completed").
        data: Optional event data.
    """
    if self._event_bus is None:
        return

    event: ObserverEvent = {
        "job_id": job_id,
        "sheet_num": 0,
        "event": event_name,
        "data": data or {},
        "timestamp": time.time(),
    }
    try:
        await self._event_bus.publish(event)
    except Exception:  # noqa: BLE001 — structured logger reports adapter.job_event_publish_failed
        _logger.warning(
            "adapter.job_event_publish_failed",
            extra={"job_id": job_id, "event": event_name},
            exc_info=True,
        )
active_musicians
active_musicians()

Every musician still in flight: job, sheet, instrument, model, elapsed.

The rows a graceful drain is waiting on (GH #476). Task authority is what counts — a sheet relabelled WAITING on the baton side is still in flight while its task runs.

Source code in src/marianne/daemon/baton/adapter.py
def active_musicians(self) -> list[dict[str, Any]]:
    """Every musician still in flight: job, sheet, instrument, model, elapsed.

    The rows a graceful drain is waiting on (GH #476). Task authority is
    what counts — a sheet relabelled WAITING on the baton side is still
    in flight while its task runs.
    """
    now = time.monotonic()
    rows: list[dict[str, Any]] = []
    for key, task in self._active_tasks.items():
        if task.done():
            continue
        job_id, sheet_num = key
        details = self._active_execution_details.get(key)
        started = self._active_started_at.get(key)
        rows.append({
            "job_id": job_id,
            "sheet_num": sheet_num,
            "instrument": details[0] if details else "",
            "model": details[1] if details else None,
            "elapsed_seconds": round(now - started, 1) if started else None,
        })
    rows.sort(key=lambda r: (r["job_id"], r["sheet_num"]))
    return rows
set_max_concurrent_sheets
set_max_concurrent_sheets(limit)

Live-resize the global sheet-dispatch ceiling (#408, #231 pattern).

The run loop rebuilds DispatchConfig from this attribute every cycle, so an in-place update takes effect on the next dispatch pass — no object replacement, no baton restart. Lowering never cancels in-flight sheets: running executions drain, new dispatch waits until the global running count drops below the new limit. Raising enqueues a coalesced DispatchRetry so waiting sheets dispatch immediately instead of idling until an unrelated event.

Source code in src/marianne/daemon/baton/adapter.py
def set_max_concurrent_sheets(self, limit: int) -> None:
    """Live-resize the global sheet-dispatch ceiling (#408, #231 pattern).

    The run loop rebuilds ``DispatchConfig`` from this attribute every
    cycle, so an in-place update takes effect on the next dispatch pass —
    no object replacement, no baton restart. Lowering never cancels
    in-flight sheets: running executions drain, new dispatch waits until
    the global running count drops below the new limit. Raising enqueues a
    coalesced ``DispatchRetry`` so waiting sheets dispatch immediately
    instead of idling until an unrelated event.
    """
    self._max_concurrent_sheets = limit
    self._baton.enqueue_dispatch_retry()
sync_model_concurrency
sync_model_concurrency(caps)

Replace the live per-model cap map from fresh profiles (#408).

Delegates to BatonCore.sync_model_concurrency (atomic swap with removal) and wakes the dispatch loop so a raised cap releases waiting sheets without waiting for an unrelated event.

Source code in src/marianne/daemon/baton/adapter.py
def sync_model_concurrency(self, caps: dict[str, int]) -> dict[str, list[str]]:
    """Replace the live per-model cap map from fresh profiles (#408).

    Delegates to ``BatonCore.sync_model_concurrency`` (atomic swap with
    removal) and wakes the dispatch loop so a raised cap releases
    waiting sheets without waiting for an unrelated event.
    """
    diff = self._baton.sync_model_concurrency(caps)
    if diff["added"] or diff["changed"] or diff["removed"]:
        self._baton.enqueue_dispatch_retry()
    return diff
model_concurrency_snapshot
model_concurrency_snapshot()

Live per-model cap map copy (for status exposure, #408).

Source code in src/marianne/daemon/baton/adapter.py
def model_concurrency_snapshot(self) -> dict[str, int]:
    """Live per-model cap map copy (for status exposure, #408)."""
    return self._baton.model_concurrency_snapshot()
resolve_fermata
resolve_fermata(job_id, sheet_num, decision)

Resolve a FERMATA sheet on the composer's behalf (#361).

Backs mzt resolve via the job.resolve_escalation IPC method. Writes the SAME decision marker a composer would create by hand, then enqueues an immediate FermataCheck so the existing poll handler consumes it — one consumption path, restart-safe (the marker survives a crash between write and consumption), and the consumed/ audit trail is preserved.

Returns:

Type Description
bool

(ok, message) — ok False with a diagnostic message when

str

the decision is invalid or the sheet is not in FERMATA.

Source code in src/marianne/daemon/baton/adapter.py
def resolve_fermata(
    self, job_id: str, sheet_num: int, decision: str
) -> tuple[bool, str]:
    """Resolve a FERMATA sheet on the composer's behalf (#361).

    Backs ``mzt resolve`` via the ``job.resolve_escalation`` IPC method.
    Writes the SAME decision marker a composer would create by hand,
    then enqueues an immediate ``FermataCheck`` so the existing poll
    handler consumes it — one consumption path, restart-safe (the
    marker survives a crash between write and consumption), and the
    ``consumed/`` audit trail is preserved.

    Returns:
        ``(ok, message)`` — ``ok`` False with a diagnostic message when
        the decision is invalid or the sheet is not in FERMATA.
    """
    if decision not in self._FERMATA_DECISIONS:
        valid = ", ".join(sorted(self._FERMATA_DECISIONS))
        return False, f"Invalid decision '{decision}' — expected one of: {valid}"

    state = self._baton.get_sheet_state(job_id, sheet_num)
    if state is None:
        return False, f"Unknown sheet {sheet_num} for job '{job_id}'"
    if state.status != BatonSheetStatus.FERMATA:
        return False, (
            f"Sheet {sheet_num} is {state.status.value}, not FERMATA — "
            "only FERMATA sheets await a resolution"
        )

    marker_dir = self._fermata_marker_dir(job_id, sheet_num)
    if marker_dir is None:
        return False, f"No workspace known for job '{job_id}' sheet {sheet_num}"
    try:
        marker_dir.mkdir(parents=True, exist_ok=True)
        (marker_dir / f"sheet-{sheet_num}.{decision}").touch()
    except OSError as exc:
        return False, f"Failed to write resolution marker: {exc}"

    self._baton.inbox.put_nowait(
        FermataCheck(
            job_id=job_id,
            sheet_num=sheet_num,
            event_generation=self._baton.get_job_generation(job_id),
        )
    )
    _logger.info(
        "adapter.fermata.resolved_via_ipc",
        extra={
            "job_id": job_id,
            "sheet_num": sheet_num,
            "decision": decision,
        },
    )
    return True, f"Resolution '{decision}' recorded for sheet {sheet_num}"
run async
run()

Run the baton's event loop with dispatch integration.

Processes events from the inbox, updates state, dispatches ready sheets, and publishes events to the EventBus.

Runs until the baton receives a ShutdownRequested event.

Source code in src/marianne/daemon/baton/adapter.py
async def run(self) -> None:
    """Run the baton's event loop with dispatch integration.

    Processes events from the inbox, updates state, dispatches
    ready sheets, and publishes events to the EventBus.

    Runs until the baton receives a ShutdownRequested event.
    """
    from marianne.daemon.baton.dispatch import dispatch_ready

    self._running = True
    _logger.info("adapter.started")

    # Start the timer wheel drain task — fires scheduled events
    # (rate limit expiry, retry delays) into the baton's inbox.
    # Wrapped in a restart loop so a crash doesn't silently kill
    # all timer-based recovery (rate limit expiry, retry backoff).
    async def _timer_with_restart() -> None:
        while not self._baton._shutting_down:
            try:
                await self._timer_wheel.run()
            except asyncio.CancelledError:
                raise
            except Exception:
                _logger.error(
                    "adapter.timer_wheel_crashed",
                    exc_info=True,
                )
                await asyncio.sleep(1.0)  # Brief pause before restart

    timer_task = asyncio.create_task(
        _timer_with_restart(), name="baton-timer-wheel"
    )

    try:
        # Initial dispatch cycle — pick up PENDING sheets from resume/restart
        # without waiting for the first event. Without this, sheets mapped
        # from WAITING→PENDING on restart sit idle until an unrelated event
        # (e.g., a completion from another job) triggers dispatch.
        config = self._build_dispatch_config()
        initial_result = await dispatch_ready(
            self._baton, config, self._dispatch_callback
        )
        if initial_result.dispatched_sheets:
            _logger.info(
                "adapter.initial_dispatch",
                extra={
                    "count": len(initial_result.dispatched_sheets),
                    "sheets": [
                        f"{jid}:{sn}"
                        for jid, sn in initial_result.dispatched_sheets
                    ],
                },
            )
            for d_job_id, _d_sheet_num in initial_result.dispatched_sheets:
                if self._persist_callback:
                    self._persist_callback(d_job_id)
        for b_job_id, _b_sheet_num in initial_result.blocked_sheets:
            if self._persist_callback:
                self._persist_callback(b_job_id)
        await self._publish_skip_events()
        self._start_flow_fact_tasks()
        self._start_flow_action_tasks()

        while not self._baton._shutting_down:
            event = await self._baton.inbox.get()

            qsize = self._baton.inbox.qsize()
            self._baton.observe_inbox_depth(qsize)
            _logger.debug(
                "adapter.event_loop.received",
                event_type=type(event).__name__,
                queue_size=qsize,
            )
            self._maybe_warn_inbox_depth(qsize, type(event).__name__)

            # StaleCheck has its own handler: dead-task → synthetic STALE;
            # alive-but-idle → cancel (idle detection, #349/#350); alive +
            # busy/disabled → reschedule.
            if isinstance(event, StaleCheck):
                await self._handle_stale_check(event)
            elif isinstance(event, FermataCheck):
                # #361: poll for a composer's resolution marker on a paused
                # (FERMATA) sheet — its own handler, not the baton's.
                await self._handle_fermata_check(event)
            else:
                if (
                    isinstance(event, SheetAttemptResult)
                    and self._baton._event_generation_is_current(
                        event.job_id,
                        event.event_generation,
                        event_type=type(event).__name__,
                    )
                ):
                    await self._route_a2a_requests(event)
                await self._baton.handle_event(event)
                await self._record_pass_on_event(event)

            # #206: mirror instrument rate limits to the daemon-level
            # coordinator AFTER the baton has applied its own state
            # (WAITING transitions, expiry timer). The baton remains the
            # sole dispatch authority; this is observability write-through.
            if isinstance(event, RateLimitHit):
                await self._report_rate_limit_cross_job(event)

            # #361: start/stop FERMATA marker polling to match status —
            # arms newly-FERMATA sheets (fresh exhaustion OR restart-recovered)
            # and drops resolved/timed-out ones.
            await self._reconcile_fermata_polling()

            # Phase 2: persist to registry if state changed.
            # The baton writes directly to SheetState objects in
            # _live_states — no sync needed. Just persist.
            if self._baton._state_dirty and self._persist_callback:
                self._persist_dirty_jobs()
                self._baton._state_dirty = False
            self._cancel_flow_reset_tasks()
            await self._announce_flow_pauses()
            self._start_flow_fact_tasks()
            self._start_flow_action_tasks()
            await self._publish_flow_events()

            # Dispatch ready sheets after every event
            config = self._build_dispatch_config()
            dispatch_result = await dispatch_ready(
                self._baton, config, self._dispatch_callback
            )

            # Sync dispatched sheets so status display shows in_progress
            if dispatch_result.dispatched_sheets:
                _logger.info(
                    "adapter.dispatch_sync",
                    extra={
                        "count": len(dispatch_result.dispatched_sheets),
                        "sheets": [
                            f"{jid}:{sn}"
                            for jid, sn in dispatch_result.dispatched_sheets
                        ],
                    },
                )
            for d_job_id, d_sheet_num in dispatch_result.dispatched_sheets:
                # Persist dispatch state (sheet moved to DISPATCHED)
                if self._persist_callback:
                    self._persist_callback(d_job_id)
                # Schedule the timeout safety net and (when enabled) the
                # idle-detection cadence for this freshly-dispatched sheet.
                self._schedule_stale_detection(d_job_id, d_sheet_num)
            for b_job_id, _b_sheet_num in dispatch_result.blocked_sheets:
                if self._persist_callback:
                    self._persist_callback(b_job_id)

            # Publish scheduler side-effect events to EventBus.
            await self._publish_skip_events()
            await self._publish_fallback_events()
            await self._publish_flow_events()

            # Check for job completions after dispatch
            self._check_completions()

    except asyncio.CancelledError:
        _logger.info("adapter.cancelled")
        raise
    finally:
        for task in self._flow_action_tasks.values():
            task.cancel()
        if self._flow_action_tasks:
            await asyncio.gather(*self._flow_action_tasks.values(), return_exceptions=True)
        self._flow_action_tasks.clear()
        for task in self._flow_fact_tasks.values():
            task.cancel()
        if self._flow_fact_tasks:
            await asyncio.gather(*self._flow_fact_tasks.values(), return_exceptions=True)
        self._flow_fact_tasks.clear()
        timer_task.cancel()
        await self._timer_wheel.shutdown()
        self._running = False
        # Release any wait_for_completion() waiters — the loop is gone, so
        # their completion events would otherwise never fire (#309).
        self._shutdown_event.set()
        _logger.info("adapter.stopped")
shutdown async
shutdown()

Gracefully shut down the adapter.

Cancels all active musician tasks and closes the backend pool.

Source code in src/marianne/daemon/baton/adapter.py
async def shutdown(self) -> None:
    """Gracefully shut down the adapter.

    Cancels all active musician tasks and closes the backend pool.
    """
    # Release wait_for_completion() waiters first (#309) so a caller blocked
    # on an in-flight job unblocks as the engine tears down.
    self._shutdown_event.set()

    # Cancel all active tasks
    if self._active_tasks:
        affected = [
            {"job_id": k[0], "sheet_num": k[1]}
            for k in self._active_tasks
        ]
        _logger.warning(
            "adapter.shutdown.cancelling_tasks",
            extra={"tasks": affected, "count": len(affected)},
        )
    for key, task in self._active_tasks.items():
        task.cancel(msg=f"adapter shutdown (job={key[0]}, sheet={key[1]})")
    self._active_tasks.clear()
    self._active_execution_details.clear()
    self._active_started_at.clear()

    # Close backend pool
    if self._backend_pool is not None:
        try:
            await self._backend_pool.close_all()
        except Exception:  # noqa: BLE001 — structured logger reports adapter.pool_close_failed
            _logger.warning("adapter.pool_close_failed", exc_info=True)

    _logger.info("adapter.shutdown_complete")

BackendPool

BackendPool(registry, pgroup=None, keyring=None)

Manages Backend instances for per-sheet execution.

The baton acquires a backend before dispatching a sheet and releases it after the sheet completes (or fails). The pool enforces per-instrument concurrency by tracking in-flight instances.

Usage::

pool = BackendPool(registry)

# Dispatch a sheet
backend = await pool.acquire("claude-code", working_directory=ws)
try:
    result = await backend.execute(prompt)
finally:
    await pool.release("claude-code", backend)

# Job done
await pool.close_all()
Source code in src/marianne/daemon/baton/backend_pool.py
def __init__(
    self,
    registry: InstrumentRegistry,
    pgroup: ProcessGroupManager | None = None,
    keyring: ApiKeyKeyring | None = None,
) -> None:
    self._registry = registry
    self._pgroup = pgroup
    self._keyring = keyring

    # CLI instruments: free list per instrument name
    self._cli_free: dict[str, list[Backend]] = {}

    # HTTP instruments: singleton per instrument name
    self._http_singletons: dict[str, Backend] = {}

    # Tracking: how many backends are currently in-flight (acquired
    # but not yet released) per instrument.
    self._in_flight: dict[str, int] = {}

    # All backends ever created (for close_all cleanup)
    self._all_backends: list[Backend] = []

    # #171 hot-reload generation. invalidate() bumps it and clears the
    # free lists; backends are tagged with the generation they were
    # built in, so an in-flight backend built before a reload is
    # dropped (not reused stale) when released.
    self._generation: int = 0

    # Protect concurrent acquire/release to avoid race conditions
    # on the free lists
    self._lock = asyncio.Lock()

    self._closed = False
Methods:
acquire async
acquire(instrument_name, *, model=None, working_directory=None, interactive=None)

Acquire a Backend instance for an instrument.

For CLI instruments: returns a free instance if available, otherwise creates a new one. For HTTP instruments: returns the shared singleton (creating it on first call).

Parameters:

Name Type Description Default
instrument_name str

Name of the instrument (from registry).

required
model str | None

Optional model override for this execution.

None
working_directory Path | None

Working directory for the backend.

None
interactive bool | None

Tri-state execution-mode request. None (default) = use the profile's default — interactive when the profile carries verified interactive support, headless otherwise. True = force interactive (error if unsupported). False = force headless. Interactive instances live in their own free list — they never cross-pollinate with headless ones.

None

Returns:

Type Description
Backend

A Backend instance ready for execution.

Raises:

Type Description
ValueError

If the instrument is not registered, or interactive was explicitly requested for an instrument without verified interactive support.

RuntimeError

If the pool has been closed.

Source code in src/marianne/daemon/baton/backend_pool.py
async def acquire(
    self,
    instrument_name: str,
    *,
    model: str | None = None,
    working_directory: Path | None = None,
    interactive: bool | None = None,
) -> Backend:
    """Acquire a Backend instance for an instrument.

    For CLI instruments: returns a free instance if available,
    otherwise creates a new one. For HTTP instruments: returns
    the shared singleton (creating it on first call).

    Args:
        instrument_name: Name of the instrument (from registry).
        model: Optional model override for this execution.
        working_directory: Working directory for the backend.
        interactive: Tri-state execution-mode request. None (default)
            = use the profile's default — interactive when the profile
            carries verified interactive support, headless otherwise.
            True = force interactive (error if unsupported). False =
            force headless. Interactive instances live in their own
            free list — they never cross-pollinate with headless ones.

    Returns:
        A Backend instance ready for execution.

    Raises:
        ValueError: If the instrument is not registered, or interactive
            was explicitly requested for an instrument without verified
            interactive support.
        RuntimeError: If the pool has been closed.
    """
    if self._closed:
        msg = "BackendPool is closed — cannot acquire new backends"
        raise RuntimeError(msg)

    profile = self._registry.get(instrument_name)
    if profile is None:
        msg = (
            f"Instrument '{instrument_name}' not found in registry. "
            f"Available: {', '.join(p.name for p in self._registry.list_all())}"
        )
        raise InstrumentNotRegisteredError(msg)

    # Resolve API key from keyring for HTTP instruments before acquiring lock.
    # Key is loaded from disk, used to configure the backend, then not stored.
    api_key: str | None = None
    if profile.kind == "http" and self._keyring is not None:
        if self._keyring.has_keys(instrument_name):
            try:
                api_key = await self._keyring.select_key(instrument_name)
            except (KeyError, FileNotFoundError, ValueError):
                _logger.warning(
                    "backend_pool.keyring_select_failed",
                    extra={"instrument": instrument_name},
                    exc_info=True,
                )

    # Resolve the tri-state: score silence → the profile's default.
    resolved_interactive = (
        self._profile_default_interactive(profile)
        if interactive is None
        else interactive
    )

    async with self._lock:
        backend = self._acquire_locked(
            profile,
            model=model,
            working_directory=working_directory,
            api_key=api_key,
            interactive=resolved_interactive,
        )

    _logger.debug(
        "backend_pool.acquired",
        extra={
            "instrument": instrument_name,
            "in_flight": self._in_flight.get(instrument_name, 0),
            "model": model,
            "interactive": resolved_interactive,
            "interactive_requested": interactive,
        },
    )
    return backend
release async
release(instrument_name, backend)

Release a Backend instance back to the pool.

For CLI instruments: the backend goes back to the free list for reuse. For HTTP instruments: no-op (the singleton stays active).

Parameters:

Name Type Description Default
instrument_name str

The instrument name used in acquire().

required
backend Backend

The Backend instance to release.

required
Source code in src/marianne/daemon/baton/backend_pool.py
async def release(
    self,
    instrument_name: str,
    backend: Backend,
) -> None:
    """Release a Backend instance back to the pool.

    For CLI instruments: the backend goes back to the free list for
    reuse. For HTTP instruments: no-op (the singleton stays active).

    Args:
        instrument_name: The instrument name used in ``acquire()``.
        backend: The Backend instance to release.
    """
    # Clear any per-sheet overrides (model, etc.) before returning
    # the backend to the free list. Without this, a model override from
    # sheet N would silently carry over to sheet N+1 that reuses the
    # same backend instance. This was F-150's secondary bug.
    # For interactive backends this also resets the per-sheet driver
    # knobs and the attempt identity, so free-list reuse is clean.
    backend.clear_overrides()

    async with self._lock:
        count = self._in_flight.get(instrument_name, 0)
        self._in_flight[instrument_name] = max(0, count - 1)

        profile = self._registry.get(instrument_name)
        stale = (
            getattr(backend, "_pool_generation", self._generation)
            != self._generation
        )
        if profile is not None and profile.kind == "cli" and not stale:
            # Return CLI backend to free list for reuse. Interactive
            # instances live under their own key — a headless acquire
            # must never receive a session-driving backend or vice versa.
            free_key = self._free_list_key(instrument_name, backend)
            if free_key not in self._cli_free:
                self._cli_free[free_key] = []
            self._cli_free[free_key].append(backend)
        # A stale (pre-reload) backend is dropped, not re-listed (#171);
        # it remains in _all_backends for close_all on shutdown.

        # HTTP singletons are never "released" — they stay active

    _logger.debug(
        "backend_pool.released",
        extra={
            "instrument": instrument_name,
            "in_flight": self._in_flight.get(instrument_name, 0),
        },
    )
invalidate
invalidate()

Drop cached backends so the next acquire rebuilds from the current registry profiles (#171 hot-reload).

Idle backends (free lists, HTTP singletons) are dropped now; in-flight backends finish on their loaded profile and are dropped on release via the generation check. Synchronous + lock-free: it only bumps a counter and clears dicts, so it is safe to call from the SIGHUP handler.

Source code in src/marianne/daemon/baton/backend_pool.py
def invalidate(self) -> None:
    """Drop cached backends so the next acquire rebuilds from the
    current registry profiles (#171 hot-reload).

    Idle backends (free lists, HTTP singletons) are dropped now;
    in-flight backends finish on their loaded profile and are dropped
    on release via the generation check. Synchronous + lock-free: it
    only bumps a counter and clears dicts, so it is safe to call from
    the SIGHUP handler.
    """
    self._generation += 1
    self._cli_free.clear()
    self._http_singletons.clear()
    _logger.info(
        "backend_pool.invalidated",
        extra={"generation": self._generation},
    )
in_flight_count
in_flight_count(instrument_name)

How many backends are currently acquired for this instrument.

Used by the baton's dispatch logic to enforce per-instrument concurrency limits.

Source code in src/marianne/daemon/baton/backend_pool.py
def in_flight_count(self, instrument_name: str) -> int:
    """How many backends are currently acquired for this instrument.

    Used by the baton's dispatch logic to enforce per-instrument
    concurrency limits.
    """
    return self._in_flight.get(instrument_name, 0)
total_in_flight
total_in_flight()

Total backends in-flight across all instruments.

Source code in src/marianne/daemon/baton/backend_pool.py
def total_in_flight(self) -> int:
    """Total backends in-flight across all instruments."""
    return sum(self._in_flight.values())
create_one_off
create_one_off(instrument_name, *, model=None, working_directory=None)

Create a one-off Backend outside the dispatch-pool lifecycle.

Public seam for daemon-side services (interactive model nudges) that need an LLM backend without acquiring a dispatch slot. Delegates to create_backend_for_instrument — the single creation path — so service backends and musician backends can never drift. The caller owns closing the returned backend.

Source code in src/marianne/daemon/baton/backend_pool.py
def create_one_off(
    self,
    instrument_name: str,
    *,
    model: str | None = None,
    working_directory: Path | None = None,
) -> Backend:
    """Create a one-off Backend outside the dispatch-pool lifecycle.

    Public seam for daemon-side services (interactive model nudges)
    that need an LLM backend without acquiring a dispatch slot.
    Delegates to ``create_backend_for_instrument`` — the single
    creation path — so service backends and musician backends can
    never drift. The caller owns closing the returned backend.
    """
    return create_backend_for_instrument(
        self._registry,
        instrument_name,
        model=model,
        working_directory=working_directory,
    )
close_all async
close_all()

Close all Backend instances and mark the pool as closed.

Called at job completion, cancellation, or conductor shutdown. After this call, acquire() raises RuntimeError.

Source code in src/marianne/daemon/baton/backend_pool.py
async def close_all(self) -> None:
    """Close all Backend instances and mark the pool as closed.

    Called at job completion, cancellation, or conductor shutdown.
    After this call, ``acquire()`` raises RuntimeError.
    """
    self._closed = True

    async with self._lock:
        for backend in self._all_backends:
            try:
                await backend.close()
            except Exception:  # noqa: BLE001 — structured logger reports backend_pool.close_failed
                _logger.warning(
                    "backend_pool.close_failed",
                    extra={"backend": backend.name},
                    exc_info=True,
                )

        self._cli_free.clear()
        self._http_singletons.clear()
        self._in_flight.clear()

    _logger.debug(
        "backend_pool.closed",
        extra={"total_backends": len(self._all_backends)},
    )

BatonCore

BatonCore(*, timer=None, inbox=None, cron_handler=None)

The baton's event-driven execution core.

Manages the event inbox, processes events, tracks sheet state across all jobs, resolves ready sheets, and coordinates dispatch.

The baton does NOT own backend execution — it decides WHEN to dispatch, not HOW. Sheet execution is delegated to the musician (via dispatch callbacks registered by the conductor).

Usage::

baton = BatonCore()
baton.register_job("j1", sheets, deps)

# Run the main loop (blocks until shutdown)
await baton.run()

# Or process events manually (for testing)
await baton.handle_event(some_event)

Initialize the baton core.

Parameters:

Name Type Description Default
timer Any | None

Optional TimerWheel for scheduling retry delays. When None, retries are set to RETRY_SCHEDULED without actual timer events (tests or manual event injection).

None
inbox Queue[BatonEvent] | None

Optional pre-created event queue. When provided, allows the caller to share the queue with other components (e.g., TimerWheel) before BatonCore is constructed. When None, a new queue is created.

None
Source code in src/marianne/daemon/baton/core.py
def __init__(
    self,
    *,
    timer: Any | None = None,
    inbox: asyncio.Queue[BatonEvent] | None = None,
    cron_handler: CronHandler | None = None,
) -> None:
    """Initialize the baton core.

    Args:
        timer: Optional TimerWheel for scheduling retry delays.
            When None, retries are set to RETRY_SCHEDULED without
            actual timer events (tests or manual event injection).
        inbox: Optional pre-created event queue. When provided, allows
            the caller to share the queue with other components (e.g.,
            TimerWheel) before BatonCore is constructed. When None,
            a new queue is created.
    """
    self._inbox: asyncio.Queue[BatonEvent] = inbox or asyncio.Queue()
    self._jobs: dict[str, _JobRecord] = {}
    self._registration_token_counter: int = 0
    # Adapter-owned physical task authority. The core keeps this as an
    # injected probe so logical state transitions (notably fallback to
    # PENDING) cannot make a still-running musician look unstarted.
    self._active_execution_probe: Callable[[str, int], bool] | None = None
    self._instruments: dict[str, InstrumentState] = {}
    self._job_cost_limits: dict[str, float] = {}
    self._sheet_cost_limits: dict[tuple[str, int], float] = {}
    self._shutting_down = False
    self._running = False
    self._state_dirty = False
    self._timer = timer
    self._cron_handler = cron_handler

    # Active rate-limit timer handles per instrument. When a new
    # RateLimitHit arrives for an instrument that already has a pending
    # timer, the old timer is cancelled before scheduling the new one.
    # Without this, stale timers fire prematurely and cause wasted
    # dispatch→rate_limit→WAITING cycles.
    self._rate_limit_timers: dict[str, Any] = {}

    # Active circuit breaker recovery timer handles per instrument.
    # When a circuit breaker trips OPEN, a recovery timer is scheduled.
    # On fire, the instrument transitions OPEN→HALF_OPEN for a probe.
    # GH#169: Without this, sheets blocked by all-OPEN fallback chains
    # stay PENDING forever.
    self._circuit_breaker_timers: dict[str, Any] = {}

    # Fallback event collection — side effects of event processing.
    # The adapter drains these after each event cycle and publishes
    # them to the EventBus for observability (dashboard, learning hub).
    self._fallback_events: list[InstrumentFallback] = []
    # Canonical skip transitions use the same drain-and-publish pattern,
    # including scheduler-created dependency/fail-fast skips.
    self._skip_events: list[SheetSkipped] = []

    # Per-model concurrency limits from instrument profiles.
    # Keys: "instrument:model", values: max_concurrent.
    # Populated by set_model_concurrency() from instrument profiles.
    self._model_concurrency: dict[str, int] = {}

    # #201: shared self-healing remedy registry, created lazily on the first
    # healing attempt (cheap, but only needed when self_healing is enabled).
    self._healing_registry: Any = None

    # Retry backoff configuration. These match RetryConfig's field defaults;
    # the manager overrides them via configure_retry() once per job/recovery
    # so score-level `retry:` settings are honored (#196). Jitter defaults
    # OFF here (= the historical no-jitter behavior, so bare-BatonCore tests
    # stay deterministic); production turns it ON by threading
    # RetryConfig.jitter (default True). _jitter_fn is injectable for
    # deterministic boundary tests.
    self._base_retry_delay: float = 10.0
    self._retry_exponential_base: float = 2.0
    self._max_retry_delay: float = 3600.0
    self._jitter: bool = False
    self._jitter_fn: Callable[[float, float], float] = random.uniform
    # Startup-failure floor (GH #470): a fast non-zero exit did no work.
    self._startup_failure_floor: float = 120.0
    self._startup_failure_window: float = 60.0

    # DispatchRetry coalescing (#222). DispatchRetry is a pure wake signal:
    # the loop runs dispatch_ready + completion checks after EVERY event, so
    # multiple queued copies are redundant. A failure cascade that wants to
    # wake the loop N times only needs one. This flag keeps at most one
    # DispatchRetry pending; it is cleared when the loop handles it.
    self._dispatch_retry_pending: bool = False

    # #340: one owned TimerHandle per job (plus the legacy scalar key).
    # Handles are cancelled on deregistration and guarded by registration
    # generation so stale timer events cannot affect a reused job ID.
    self._stagger_wake_handles: dict[str, Any] = {}
    # Per-job stagger custody. A shared InstrumentState timestamp would let
    # one score delay another score using the same provider.
    self._job_last_dispatch_at: dict[tuple[str, str], float] = {}

    # Inbox-depth observability (#222). The inbox is intentionally UNBOUNDED
    # — dropping a baton event (a completion, rate-limit hit, retry-due,
    # control command, ...) would strand a sheet or corrupt state, and the
    # self-enqueue sites run on the consumer task so a blocking bounded put
    # would deadlock. Instead of a hard cap we track the high-water mark so
    # a consumer stall (the only way the queue grows without bound) is
    # diagnosable before it can trend toward OOM.
    self._inbox_high_water: int = 0
Attributes
inbox property
inbox

The event inbox — put events here for the baton to process.

is_running property
is_running

Whether the main loop is currently running.

job_count property
job_count

Number of registered jobs.

running_sheet_count property
running_sheet_count

Number of sheets currently in 'dispatched' status.

Methods:
set_cron_handler
set_cron_handler(handler)

Configure the async callback that receives recurring score ticks.

Source code in src/marianne/daemon/baton/core.py
def set_cron_handler(self, handler: CronHandler) -> None:
    """Configure the async callback that receives recurring score ticks."""
    self._cron_handler = handler
enqueue_dispatch_retry
enqueue_dispatch_retry()

Wake the event loop to run a dispatch / completion cycle.

Coalesced (#222): at most one DispatchRetry is ever pending. When the loop is idle (blocked on inbox.get()) the flag is clear, so this enqueues a fresh wake; while one is already queued, additional calls are no-ops because the pending wake already triggers a full dispatch + completion pass. Bounds cascade-driven wake accumulation to O(1).

Source code in src/marianne/daemon/baton/core.py
def enqueue_dispatch_retry(self) -> None:
    """Wake the event loop to run a dispatch / completion cycle.

    Coalesced (#222): at most one ``DispatchRetry`` is ever pending. When
    the loop is idle (blocked on ``inbox.get()``) the flag is clear, so this
    enqueues a fresh wake; while one is already queued, additional calls are
    no-ops because the pending wake already triggers a full dispatch +
    completion pass. Bounds cascade-driven wake accumulation to O(1).
    """
    if self._dispatch_retry_pending:
        return
    self._dispatch_retry_pending = True
    self._inbox.put_nowait(DispatchRetry())
observe_inbox_depth
observe_inbox_depth(depth)

Record the inbox depth seen by the consumer (#222 high-water mark).

Source code in src/marianne/daemon/baton/core.py
def observe_inbox_depth(self, depth: int) -> None:
    """Record the inbox depth seen by the consumer (#222 high-water mark)."""
    if depth > self._inbox_high_water:
        self._inbox_high_water = depth
drain_fallback_events
drain_fallback_events()

Return and clear collected InstrumentFallback events.

Called by the adapter after each event cycle to publish fallback events to the EventBus for observability.

Source code in src/marianne/daemon/baton/core.py
def drain_fallback_events(self) -> list[InstrumentFallback]:
    """Return and clear collected InstrumentFallback events.

    Called by the adapter after each event cycle to publish
    fallback events to the EventBus for observability.
    """
    events = list(self._fallback_events)
    self._fallback_events.clear()
    return events
drain_skip_events
drain_skip_events()

Return and clear canonical sheet-skip observer events.

Source code in src/marianne/daemon/baton/core.py
def drain_skip_events(self) -> list[SheetSkipped]:
    """Return and clear canonical sheet-skip observer events."""
    events = list(self._skip_events)
    self._skip_events.clear()
    return events
drain_flow_events
drain_flow_events()

Drain flow transitions after checkpoint persistence.

Source code in src/marianne/daemon/baton/core.py
def drain_flow_events(self) -> list[BatonEvent]:
    """Drain flow transitions after checkpoint persistence."""
    events: list[BatonEvent] = []
    for job in self._jobs.values():
        if job.flow is not None:
            events.extend(job.flow.drain_events())
    return events
register_instrument
register_instrument(name, *, max_concurrent=4)

Register an instrument for tracking.

If already registered, returns the existing state (idempotent).

Parameters:

Name Type Description Default
name str

Instrument name (matches InstrumentProfile.name).

required
max_concurrent int

Maximum concurrent sheets on this instrument.

4

Returns:

Type Description
InstrumentState

The InstrumentState for the instrument.

Source code in src/marianne/daemon/baton/core.py
def register_instrument(self, name: str, *, max_concurrent: int = 4) -> InstrumentState:
    """Register an instrument for tracking.

    If already registered, returns the existing state (idempotent).

    Args:
        name: Instrument name (matches InstrumentProfile.name).
        max_concurrent: Maximum concurrent sheets on this instrument.

    Returns:
        The InstrumentState for the instrument.
    """
    if name in self._instruments:
        return self._instruments[name]

    state = InstrumentState(name=name, max_concurrent=max_concurrent)
    self._instruments[name] = state
    _logger.debug(
        "baton.instrument_registered",
        extra={"instrument": name, "max_concurrent": max_concurrent},
    )
    return state
set_model_concurrency
set_model_concurrency(instrument, model, max_concurrent)

Set per-model concurrency limit from instrument profile data.

Called during adapter initialization from loaded InstrumentProfiles.

Source code in src/marianne/daemon/baton/core.py
def set_model_concurrency(
    self,
    instrument: str,
    model: str,
    max_concurrent: int,
) -> None:
    """Set per-model concurrency limit from instrument profile data.

    Called during adapter initialization from loaded InstrumentProfiles.
    """
    key = f"{instrument}:{model}"
    self._model_concurrency[key] = max_concurrent
sync_model_concurrency
sync_model_concurrency(caps)

Atomically replace the whole per-model cap map (#408).

Boot-time population used per-key set_model_concurrency; a config reload needs the full lifecycle: changed caps updated AND entries for profiles that disappeared REMOVED. The new map is built fully and the reference swapped in one step — dispatch reads a per-cycle snapshot copy (build_dispatch_config), so it never iterates a dict that is mutating under it.

Parameters:

Name Type Description Default
caps dict[str, int]

Complete desired map {"instrument:model": max_concurrent} from the fresh profile set. Empty dict removes all caps.

required

Returns:

Type Description
dict[str, list[str]]

Diff actually applied: ``{"added": [...], "changed": [...],

dict[str, list[str]]

"removed": [...]}`` of "instrument:model" keys.

Source code in src/marianne/daemon/baton/core.py
def sync_model_concurrency(self, caps: dict[str, int]) -> dict[str, list[str]]:
    """Atomically replace the whole per-model cap map (#408).

    Boot-time population used per-key ``set_model_concurrency``; a config
    reload needs the full lifecycle: changed caps updated AND entries for
    profiles that disappeared REMOVED. The new map is built fully and the
    reference swapped in one step — dispatch reads a per-cycle snapshot
    copy (``build_dispatch_config``), so it never iterates a dict that is
    mutating under it.

    Args:
        caps: Complete desired map ``{"instrument:model": max_concurrent}``
            from the fresh profile set. Empty dict removes all caps.

    Returns:
        Diff actually applied: ``{"added": [...], "changed": [...],
        "removed": [...]}`` of "instrument:model" keys.
    """
    added = [k for k in caps if k not in self._model_concurrency]
    changed = [
        k
        for k, v in caps.items()
        if k in self._model_concurrency and self._model_concurrency[k] != v
    ]
    removed = [k for k in self._model_concurrency if k not in caps]
    self._model_concurrency = dict(caps)
    return {"added": added, "changed": changed, "removed": removed}
model_concurrency_snapshot
model_concurrency_snapshot()

Copy of the live per-model cap map (for status exposure, #408).

Source code in src/marianne/daemon/baton/core.py
def model_concurrency_snapshot(self) -> dict[str, int]:
    """Copy of the live per-model cap map (for status exposure, #408)."""
    return dict(self._model_concurrency)
get_instrument_state
get_instrument_state(name)

Get the tracking state for a specific instrument.

Source code in src/marianne/daemon/baton/core.py
def get_instrument_state(self, name: str) -> InstrumentState | None:
    """Get the tracking state for a specific instrument."""
    return self._instruments.get(name)
set_active_execution_probe
set_active_execution_probe(probe)

Set the physical musician-liveness authority used by transitions.

Source code in src/marianne/daemon/baton/core.py
def set_active_execution_probe(
    self,
    probe: Callable[[str, int], bool] | None,
) -> None:
    """Set the physical musician-liveness authority used by transitions."""
    self._active_execution_probe = probe
get_job_generation
get_job_generation(job_id)

Return the public event generation for a live managed job.

Source code in src/marianne/daemon/baton/core.py
def get_job_generation(self, job_id: str) -> int | None:
    """Return the public event generation for a live managed job."""
    job = self._jobs.get(job_id)
    return job.event_generation if job is not None else None
get_job_registration_token
get_job_registration_token(job_id)

Return the always-unique private identity of a live registration.

Source code in src/marianne/daemon/baton/core.py
def get_job_registration_token(self, job_id: str) -> int | None:
    """Return the always-unique private identity of a live registration."""
    job = self._jobs.get(job_id)
    return job.registration_token if job is not None else None
is_job_registration_current
is_job_registration_current(job_id, token)

Whether job_id still denotes the captured private identity.

Source code in src/marianne/daemon/baton/core.py
def is_job_registration_current(self, job_id: str, token: int) -> bool:
    """Whether ``job_id`` still denotes the captured private identity."""
    job = self._jobs.get(job_id)
    return job is not None and job.registration_token == token
build_dispatch_config
build_dispatch_config(*, max_concurrent_sheets=10, stagger_delay_ms=0, active_executions=None)

Build a DispatchConfig from the current instrument state.

This bridges the gap between the baton's instrument tracking and the dispatch logic's configuration needs. Called before each dispatch cycle.

Parameters:

Name Type Description Default
max_concurrent_sheets int

Global concurrency ceiling.

10

Returns:

Type Description
DispatchConfig

DispatchConfig with rate-limited instruments, open circuit

DispatchConfig

breakers, and per-instrument concurrency limits derived

DispatchConfig

from the current InstrumentState.

Source code in src/marianne/daemon/baton/core.py
def build_dispatch_config(
    self,
    *,
    max_concurrent_sheets: int = 10,
    stagger_delay_ms: int = 0,
    active_executions: dict[tuple[str, int], tuple[str, str | None]] | None = None,
) -> DispatchConfig:
    """Build a DispatchConfig from the current instrument state.

    This bridges the gap between the baton's instrument tracking
    and the dispatch logic's configuration needs. Called before
    each dispatch cycle.

    Args:
        max_concurrent_sheets: Global concurrency ceiling.

    Returns:
        DispatchConfig with rate-limited instruments, open circuit
        breakers, and per-instrument concurrency limits derived
        from the current InstrumentState.
    """
    # Deferred import to break circular dependency
    # (dispatch.py imports BatonCore at runtime)
    from marianne.daemon.baton.dispatch import DispatchConfig  # noqa: N814

    rate_limited: set[str] = set()
    open_breakers: set[str] = set()
    concurrency: dict[str, int] = {}

    for name, inst in self._instruments.items():
        if inst.rate_limited:
            rate_limited.add(name)
        if inst.circuit_breaker == CircuitBreakerState.OPEN:
            open_breakers.add(name)
        concurrency[name] = inst.max_concurrent

    return DispatchConfig(
        max_concurrent_sheets=max_concurrent_sheets,
        instrument_concurrency=concurrency,
        model_concurrency=dict(self._model_concurrency),
        rate_limited_instruments=rate_limited,
        open_circuit_breakers=open_breakers,
        stagger_delay_ms=stagger_delay_ms,
        active_executions=active_executions,
        job_max_concurrent={
            job_id: job.max_concurrent
            for job_id, job in self._jobs.items()
            if job.max_concurrent is not None
        },
        job_stagger_delay_ms={
            job_id: job.stagger_delay_ms
            for job_id, job in self._jobs.items()
            if job.stagger_delay_ms > 0
        },
    )
set_job_cost_limit
set_job_cost_limit(job_id, max_cost_usd)

Set a per-job cost limit. The baton pauses the job when exceeded.

Parameters:

Name Type Description Default
job_id str

The job to set the limit for.

required
max_cost_usd float

Maximum total cost in USD.

required
Source code in src/marianne/daemon/baton/core.py
def set_job_cost_limit(self, job_id: str, max_cost_usd: float) -> None:
    """Set a per-job cost limit. The baton pauses the job when exceeded.

    Args:
        job_id: The job to set the limit for.
        max_cost_usd: Maximum total cost in USD.
    """
    self._job_cost_limits[job_id] = max_cost_usd
get_job_pause_reason
get_job_pause_reason(job_id)

Return a human-readable reason why a job is paused.

Returns "not_paused" if the job isn't paused or isn't registered.

Source code in src/marianne/daemon/baton/core.py
def get_job_pause_reason(self, job_id: str) -> str:
    """Return a human-readable reason why a job is paused.

    Returns "not_paused" if the job isn't paused or isn't registered.
    """
    job = self._jobs.get(job_id)
    if job is None or not job.paused:
        return "not_paused"
    if job.user_paused:
        return "user_initiated"
    limit = self._job_cost_limits.get(job_id)
    if limit is not None:
        total_cost = sum(s.total_cost_usd for s in job.sheets.values())
        if total_cost >= limit:
            return "cost_limit_exceeded"
    if any(s.status == BatonSheetStatus.FERMATA for s in job.sheets.values()):
        return "escalation_needed"
    return "internal"
get_rate_limited_instruments
get_rate_limited_instruments()

Get the set of currently rate-limited instrument names.

Used by dispatch logic to skip rate-limited instruments.

Source code in src/marianne/daemon/baton/core.py
def get_rate_limited_instruments(self) -> set[str]:
    """Get the set of currently rate-limited instrument names.

    Used by dispatch logic to skip rate-limited instruments.
    """
    return {name for name, inst in self._instruments.items() if inst.rate_limited}
clear_instrument_rate_limit
clear_instrument_rate_limit(instrument=None)

Clear rate limit state on one or all instruments.

Resets rate_limited to False and rate_limit_expires_at to None. Also moves any WAITING sheets on the cleared instrument(s) back to PENDING so they can be re-dispatched.

Parameters:

Name Type Description Default
instrument str | None

Instrument name to clear, or None for all.

None

Returns:

Type Description
int

Number of instruments whose rate limit was cleared.

Source code in src/marianne/daemon/baton/core.py
def clear_instrument_rate_limit(
    self,
    instrument: str | None = None,
) -> int:
    """Clear rate limit state on one or all instruments.

    Resets ``rate_limited`` to ``False`` and ``rate_limit_expires_at``
    to ``None``.  Also moves any WAITING sheets on the cleared
    instrument(s) back to PENDING so they can be re-dispatched.

    Args:
        instrument: Instrument name to clear, or ``None`` for all.

    Returns:
        Number of instruments whose rate limit was cleared.
    """
    cleared = 0
    if instrument is not None:
        # Specific instrument — look it up. If not found, targets is
        # empty (return 0). Previously, missing instruments fell through
        # to clear-all — F-200 bug found by Breakpoint M3.
        # Uses `is not None` (not truthiness) to prevent empty string
        # from falling through to clear-all — F-201 (same bug class).
        inst = self._instruments.get(instrument)
        targets = [inst] if inst is not None else []
    else:
        # None → clear all instruments
        targets = list(self._instruments.values())
    for inst in targets:
        if inst.rate_limited:
            inst.rate_limited = False
            inst.rate_limit_expires_at = None
            cleared += 1
            # Move WAITING sheets on this instrument back to PENDING
            for job in self._jobs.values():
                for sheet in job.sheets.values():
                    if (
                        sheet.status == BatonSheetStatus.WAITING
                        and sheet.instrument_name == inst.name
                    ):
                        sheet.status = BatonSheetStatus.PENDING
    if cleared > 0:
        self._state_dirty = True
    # An operator clearing ALL limits expects every rate-limit WAITING
    # sheet to move, including one stranded on a never-limited instrument
    # by an older conductor's fallback race.
    if instrument is None:
        self._release_stranded_waiting_sheets()
    return cleared
get_open_circuit_breakers
get_open_circuit_breakers()

Get the set of instruments with open circuit breakers.

Used by dispatch logic to skip unhealthy instruments.

Source code in src/marianne/daemon/baton/core.py
def get_open_circuit_breakers(self) -> set[str]:
    """Get the set of instruments with open circuit breakers.

    Used by dispatch logic to skip unhealthy instruments.
    """
    return {
        name
        for name, inst in self._instruments.items()
        if inst.circuit_breaker == CircuitBreakerState.OPEN
    }
set_sheet_cost_limit
set_sheet_cost_limit(job_id, sheet_num, max_cost_usd)

Set a per-sheet cost limit. The baton fails the sheet when exceeded.

Parameters:

Name Type Description Default
job_id str

The job containing the sheet.

required
sheet_num int

The sheet number.

required
max_cost_usd float

Maximum cost in USD for this sheet.

required
Source code in src/marianne/daemon/baton/core.py
def set_sheet_cost_limit(self, job_id: str, sheet_num: int, max_cost_usd: float) -> None:
    """Set a per-sheet cost limit. The baton fails the sheet when exceeded.

    Args:
        job_id: The job containing the sheet.
        sheet_num: The sheet number.
        max_cost_usd: Maximum cost in USD for this sheet.
    """
    self._sheet_cost_limits[(job_id, sheet_num)] = max_cost_usd
configure_retry
configure_retry(*, base_delay=None, exponential_base=None, max_delay=None, jitter=None, jitter_fn=None, startup_failure_floor=None, startup_failure_window=None)

Configure per-job retry backoff (#196).

Threaded once from the manager out of the score's RetryConfig (at registration and recovery) so score-level retry: settings reach the scheduler instead of the hardcoded defaults. Backoff params are BatonCore-level (one set per active job) — distinct from the per-sheet max_retries. Only non-None args override, so partial reconfiguration and the constructor defaults both work. jitter_fn is injectable for deterministic boundary tests; production uses random.uniform.

Source code in src/marianne/daemon/baton/core.py
def configure_retry(
    self,
    *,
    base_delay: float | None = None,
    exponential_base: float | None = None,
    max_delay: float | None = None,
    jitter: bool | None = None,
    jitter_fn: Callable[[float, float], float] | None = None,
    startup_failure_floor: float | None = None,
    startup_failure_window: float | None = None,
) -> None:
    """Configure per-job retry backoff (#196).

    Threaded once from the manager out of the score's ``RetryConfig`` (at
    registration and recovery) so score-level ``retry:`` settings reach the
    scheduler instead of the hardcoded defaults. Backoff params are
    BatonCore-level (one set per active job) — distinct from the per-sheet
    ``max_retries``. Only non-None args override, so partial reconfiguration
    and the constructor defaults both work. ``jitter_fn`` is injectable for
    deterministic boundary tests; production uses ``random.uniform``.
    """
    if base_delay is not None:
        self._base_retry_delay = base_delay
    if exponential_base is not None:
        self._retry_exponential_base = exponential_base
    if max_delay is not None:
        self._max_retry_delay = max_delay
    if jitter is not None:
        self._jitter = jitter
    if jitter_fn is not None:
        self._jitter_fn = jitter_fn
    if startup_failure_floor is not None:
        self._startup_failure_floor = startup_failure_floor
    if startup_failure_window is not None:
        self._startup_failure_window = startup_failure_window
calculate_retry_delay
calculate_retry_delay(attempt)

Calculate retry delay using exponential backoff (#196: optional jitter).

Parameters:

Name Type Description Default
attempt int

0-based attempt index (0 = first retry).

required

Returns:

Type Description
float

Delay in seconds, clamped to _max_retry_delay. When jitter is

float

enabled, EQUAL jitter is applied: raw/2 + U(0, raw/2) — the floor

float

of raw/2 preserves at least half the exponential backoff (unlike

float

full jitter, which can collapse to ~0 and hammer a recovering API),

float

while the spread across [raw/2, raw] desynchronizes a thundering

float

herd of simultaneously-failing fan-out sheets. This is the ONLY

float

backoff path; authoritative rate-limit waits are scheduled

float

separately and never jittered.

Source code in src/marianne/daemon/baton/core.py
def calculate_retry_delay(self, attempt: int) -> float:
    """Calculate retry delay using exponential backoff (#196: optional jitter).

    Args:
        attempt: 0-based attempt index (0 = first retry).

    Returns:
        Delay in seconds, clamped to ``_max_retry_delay``. When jitter is
        enabled, EQUAL jitter is applied: ``raw/2 + U(0, raw/2)`` — the floor
        of ``raw/2`` preserves at least half the exponential backoff (unlike
        full jitter, which can collapse to ~0 and hammer a recovering API),
        while the spread across ``[raw/2, raw]`` desynchronizes a thundering
        herd of simultaneously-failing fan-out sheets. This is the ONLY
        backoff path; authoritative rate-limit waits are scheduled
        separately and never jittered.
    """
    delay = self._base_retry_delay * (self._retry_exponential_base**attempt)
    delay = min(delay, self._max_retry_delay)
    if self._jitter:
        half = delay / 2
        delay = half + self._jitter_fn(0, half)
    return delay
register_job
register_job(job_id, sheets, dependencies, *, escalation_enabled=False, self_healing_enabled=False, pacing_seconds=0.0, max_concurrent=None, fail_fast=False, stagger_delay_ms=0, completion_threshold_percent=0.0, event_generation=None, workspace=None, config_path=None, loops=None, triggers=None, flow_state=None, flow_variables=None)

Register a job's sheets with the baton for scheduling.

Parameters:

Name Type Description Default
job_id str

Unique job identifier.

required
sheets dict[int, SheetExecutionState]

Map of sheet_num → SheetExecutionState.

required
dependencies dict[int, list[int]]

Map of sheet_num → list of dependency sheet_nums. Sheets not in this map have no dependencies.

required
escalation_enabled bool

Whether to enter fermata on exhaustion.

False
self_healing_enabled bool

Whether to try healing on exhaustion.

False
pacing_seconds float

Inter-sheet delay after each completion (from pause_between_sheets_seconds). 0 = no delay.

0.0
max_concurrent int | None

Per-job ceiling, or None for serial/legacy jobs.

None
fail_fast bool

Terminalize unstarted work after the first failure.

False
stagger_delay_ms int

Per-job spacing between same-instrument launches.

0
event_generation int | None

Public custody identity for adapter-managed jobs. Direct low-level callers omit it for legacy events.

None
Source code in src/marianne/daemon/baton/core.py
def register_job(
    self,
    job_id: str,
    sheets: dict[int, SheetExecutionState],
    dependencies: dict[int, list[int]],
    *,
    escalation_enabled: bool = False,
    self_healing_enabled: bool = False,
    pacing_seconds: float = 0.0,
    max_concurrent: int | None = None,
    fail_fast: bool = False,
    stagger_delay_ms: int = 0,
    completion_threshold_percent: float = 0.0,
    event_generation: int | None = None,
    workspace: Path | None = None,
    config_path: Path | None = None,
    loops: dict[str, LoopConfig] | None = None,
    triggers: dict[str, SheetTriggerConfig] | None = None,
    flow_state: FlowState | None = None,
    flow_variables: dict[str, Any] | None = None,
) -> None:
    """Register a job's sheets with the baton for scheduling.

    Args:
        job_id: Unique job identifier.
        sheets: Map of sheet_num → SheetExecutionState.
        dependencies: Map of sheet_num → list of dependency sheet_nums.
            Sheets not in this map have no dependencies.
        escalation_enabled: Whether to enter fermata on exhaustion.
        self_healing_enabled: Whether to try healing on exhaustion.
        pacing_seconds: Inter-sheet delay after each completion (from
            ``pause_between_sheets_seconds``). 0 = no delay.
        max_concurrent: Per-job ceiling, or None for serial/legacy jobs.
        fail_fast: Terminalize unstarted work after the first failure.
        stagger_delay_ms: Per-job spacing between same-instrument launches.
        event_generation: Public custody identity for adapter-managed jobs.
            Direct low-level callers omit it for legacy events.
    """
    if job_id in self._jobs:
        _logger.warning(
            "baton.register_job.duplicate",
            extra={"job_id": job_id},
        )
        return

    # Auto-register any instruments used by the job's sheets
    self._auto_register_instruments(sheets)

    self._registration_token_counter = getattr(self, "_registration_token_counter", 0) + 1
    flow = (
        FlowEngine(
            job_id,
            FlowPlan(loops or {}, triggers or {}, flow_variables or {}),
            flow_state if flow_state is not None else FlowState(),
            event_generation=event_generation,
        )
        if loops or triggers
        else None
    )
    if flow is not None and flow.state.pause_reason and not flow.state.escalation_pause_owners:
        # A checkpoint from before escalation ownership was persisted still
        # carries FERMATA sheets and a flow pause reason.
        flow.state.escalation_pause_owners.update(
            num
            for num, sheet in sheets.items()
            if sheet.status == BatonSheetStatus.FERMATA and sheet.fermata_reason
        )
        if (
            not flow.state.escalation_pause_owners
            and flow.state.trigger_pause_reason is None
        ):
            # No FERMATA sheet owns it: the pre-field checkpoint's pause
            # was a trigger `pause`. Re-own it so a later escalation
            # release cannot clear it.
            flow.state.trigger_pause_reason = flow.state.pause_reason
    self._jobs[job_id] = _JobRecord(
        job_id=job_id,
        sheets=sheets,
        dependencies=dependencies,
        escalation_enabled=escalation_enabled,
        self_healing_enabled=self_healing_enabled,
        workspace=workspace,
        config_path=config_path,
        pacing_seconds=pacing_seconds,
        max_concurrent=max_concurrent,
        fail_fast=fail_fast,
        stagger_delay_ms=stagger_delay_ms,
        completion_threshold_percent=completion_threshold_percent,
        registration_token=self._registration_token_counter,
        event_generation=event_generation,
        flow=flow,
    )
    if flow is not None and flow.state.pause_reason is not None:
        self._jobs[job_id].paused = True
    self._state_dirty = True

    # F-440: Re-propagate failure for any sheet that's already FAILED.
    # During normal execution, _propagate_failure_to_dependents() cascades
    # failure to downstream sheets. But _sync_sheet_status() only fires
    # for SheetAttemptResult/SheetSkipped events, so cascaded failures
    # are NOT synced to the checkpoint. On restart recovery, dependents
    # revert to PENDING while their upstream is FAILED → zombie job.
    # Re-running propagation here is idempotent (only touches non-terminal
    # sheets) and fixes the sync gap for both fresh registration and
    # recovery.
    for sheet_num, sheet in sheets.items():
        if sheet.status == BatonSheetStatus.FAILED and not (flow and flow.state.chains):
            self._propagate_failure_to_dependents(job_id, sheet_num)

    if flow is not None and flow.settle(sheets):
        self._state_dirty = True

    _logger.info(
        "baton.job_registered",
        extra={
            "job_id": job_id,
            "sheet_count": len(sheets),
            "dependency_count": len(dependencies),
        },
    )
deregister_job
deregister_job(job_id)

Remove a job from the baton's tracking.

Cleans up all per-job state including cost limit entries to prevent memory leaks in long-running conductors (F-062).

Source code in src/marianne/daemon/baton/core.py
def deregister_job(self, job_id: str) -> None:
    """Remove a job from the baton's tracking.

    Cleans up all per-job state including cost limit entries to
    prevent memory leaks in long-running conductors (F-062).
    """
    if job_id in self._jobs:
        del self._jobs[job_id]
        # F-062: Clean up cost limit dicts to prevent memory leaks
        self._job_cost_limits.pop(job_id, None)
        # Remove sheet cost limits for this job
        sheet_keys_to_remove = [key for key in self._sheet_cost_limits if key[0] == job_id]
        for key in sheet_keys_to_remove:
            del self._sheet_cost_limits[key]
        for dispatch_key in [key for key in self._job_last_dispatch_at if key[0] == job_id]:
            del self._job_last_dispatch_at[dispatch_key]
        stagger_handle = self._stagger_wake_handles.pop(job_id, None)
        if stagger_handle is not None and self._timer is not None:
            self._timer.cancel(stagger_handle)
        self._skip_events = [event for event in self._skip_events if event.job_id != job_id]
        self._state_dirty = True
        _logger.info("baton.job_deregistered", extra={"job_id": job_id})
get_sheet_state
get_sheet_state(job_id, sheet_num)

Get the scheduling state for a specific sheet.

Source code in src/marianne/daemon/baton/core.py
def get_sheet_state(self, job_id: str, sheet_num: int) -> SheetExecutionState | None:
    """Get the scheduling state for a specific sheet."""
    job = self._jobs.get(job_id)
    if job is None:
        return None
    return job.sheets.get(sheet_num)
is_job_paused
is_job_paused(job_id)

Check if a job's dispatch is paused.

Source code in src/marianne/daemon/baton/core.py
def is_job_paused(self, job_id: str) -> bool:
    """Check if a job's dispatch is paused."""
    job = self._jobs.get(job_id)
    return job.paused if job is not None else False
is_job_complete
is_job_complete(job_id)

Check if all sheets in a job are in terminal state.

Source code in src/marianne/daemon/baton/core.py
def is_job_complete(self, job_id: str) -> bool:
    """Check if all sheets in a job are in terminal state."""
    job = self._jobs.get(job_id)
    if job is None:
        return False
    if job.user_paused:
        return False
    if job.flow is not None and (
        job.flow.busy()
        or job.flow.boundary_pending(job.sheets)
        or job.flow.state.pause_reason is not None
    ):
        return False
    return all(sheet.status in _TERMINAL_BATON_STATUSES for sheet in job.sheets.values())
has_job
has_job(job_id)

Whether the baton is currently tracking this job.

The presence predicate for jobs running in the baton event loop, including auto-recovered jobs that have no manager wrapper task. Used by cancel/pause to tell a genuinely-stale "running" status (no live work anywhere) from a live baton job.

Source code in src/marianne/daemon/baton/core.py
def has_job(self, job_id: str) -> bool:
    """Whether the baton is currently tracking this job.

    The presence predicate for jobs running in the baton event loop,
    including auto-recovered jobs that have no manager wrapper task. Used
    by cancel/pause to tell a genuinely-stale "running" status (no live
    work anywhere) from a live baton job.
    """
    return job_id in self._jobs
get_ready_sheets
get_ready_sheets(job_id)

Find sheets that are ready to dispatch.

A sheet is ready when: 1. Status is 'pending' or 'ready' 2. All dependencies are satisfied (completed or skipped) 3. The job is not paused

Source code in src/marianne/daemon/baton/core.py
def get_ready_sheets(self, job_id: str) -> list[SheetExecutionState]:
    """Find sheets that are ready to dispatch.

    A sheet is ready when:
    1. Status is 'pending' or 'ready'
    2. All dependencies are satisfied (completed or skipped)
    3. The job is not paused
    """
    job = self._jobs.get(job_id)
    if job is None or job.paused or job.pacing_active:
        return []
    if job.flow is not None and job.flow.busy():
        return []

    ready: list[SheetExecutionState] = []
    for sheet_num, sheet in job.sheets.items():
        if sheet.status not in _DISPATCHABLE_BATON_STATUSES:
            continue

        # Check dependencies
        deps = job.dependencies.get(sheet_num, [])
        deps_satisfied = (
            job.flow is not None and sheet_num in job.flow.state.goto_bypass
        ) or all(self._is_dependency_satisfied(job, dep) for dep in deps)
        if deps_satisfied:
            ready.append(sheet)

    return ready
handle_event async
handle_event(event)

Process a single event. Updates state but does NOT dispatch.

This is the core decision-making method. Each event type has a specific handler that updates sheet state.

Per the baton spec: handler exceptions are logged, not re-raised. The baton continues processing subsequent events.

Source code in src/marianne/daemon/baton/core.py
async def handle_event(self, event: BatonEvent) -> None:
    """Process a single event. Updates state but does NOT dispatch.

    This is the core decision-making method. Each event type has
    a specific handler that updates sheet state.

    Per the baton spec: handler exceptions are logged, not re-raised.
    The baton continues processing subsequent events.
    """
    try:
        # Per-job async mutators bind the public generation of their
        # intended managed registration. Direct-core legacy records use
        # None and continue accepting generation-less events while live.
        if hasattr(event, "event_generation"):
            event_job_id = getattr(event, "job_id", None)
            if event_job_id is None or not self._event_generation_is_current(
                event_job_id,
                event.event_generation,
                event_type=type(event).__name__,
            ):
                return
        match event:
            # === Musician events ===
            case SheetAttemptResult():
                await self._handle_attempt_result(event)

            case SheetSkipped():
                self._handle_sheet_skipped(event)

            case SheetDispatched():
                self._handle_sheet_dispatched(event)

            # === Rate limit events ===
            case RateLimitHit():
                self._handle_rate_limit_hit(event)

            case RateLimitExpired():
                self._handle_rate_limit_expired(event)

            # === Timer events ===
            case RetryDue():
                self._handle_retry_due(event)

            case StaleCheck():
                self._handle_stale_check(event)

            case LoopFactsReady():
                job = self._jobs.get(event.job_id)
                if job is not None and job.flow is not None:
                    if job.flow.facts_ready(
                        job.sheets,
                        event.span,
                        event.request_id,
                        event.files,
                        event.error,
                    ):
                        self._state_dirty = True

            case FlowRunFinished():
                job = self._jobs.get(event.job_id)
                if job is not None and job.flow is not None:
                    if job.flow.action_finished(
                        job.sheets,
                        event.chain_id,
                        event.cursor,
                        {
                            "exit_code": event.exit_code,
                            "timed_out": event.timed_out,
                            "log_path": event.log_path,
                            "error": event.error,
                        },
                    ):
                        if event.supervisor_pid is not None:
                            job.flow.state.run_cleanup.append({
                                "supervisor_pid": event.supervisor_pid,
                                "reparented_orphans": event.reparented_orphans,
                            })
                        self._state_dirty = True

            case FlowConcertSubmitted():
                job = self._jobs.get(event.job_id)
                if job is not None and job.flow is not None:
                    if job.flow.action_finished(
                        job.sheets,
                        event.chain_id,
                        event.cursor,
                        {
                            "accepted": event.accepted,
                            "child_job_id": event.child_job_id,
                            "message": event.message,
                        },
                    ):
                        self._state_dirty = True

            case CronTick():
                if self._cron_handler is None:
                    _logger.error(
                        "baton.cron_handler_missing",
                        extra={
                            "entry_name": event.entry_name,
                            "score_path": event.score_path,
                            "due_at": event.due_at,
                        },
                    )
                else:
                    await self._cron_handler(event)

            case JobTimeout():
                self._handle_job_timeout(event)

            case PacingComplete():
                self._handle_pacing_complete(event)

            # === Escalation events ===
            case EscalationNeeded():
                self._handle_escalation_needed(event)

            case EscalationResolved():
                self._handle_escalation_resolved(event)

            case EscalationTimeout():
                self._handle_escalation_timeout(event)

            # === External command events ===
            case PauseJob():
                self._handle_pause_job(event)

            case ResumeJob():
                self._handle_resume_job(event)

            case CancelJob():
                self._handle_cancel_job(event)

            case ConfigReloaded():
                _logger.warning(
                    "baton.event.unimplemented",
                    extra={"event_type": "ConfigReloaded"},
                )

            case ShutdownRequested():
                self._handle_shutdown(event)

            # === Observer events ===
            case ProcessExited():
                await self._handle_process_exited(event)

            case ResourceAnomaly():
                self._handle_resource_anomaly(event)

            # === Instrument fallback events ===
            case InstrumentFallback():
                # InstrumentFallback events are emitted by the baton
                # itself, not received from external sources. They pass
                # through the event bus for observability (dashboard,
                # learning hub, notifications). No handler needed.
                pass

            # === Internal events ===
            case DispatchRetry():
                # Wake signal consumed — clear the coalescing flag so the
                # next cascade can enqueue a fresh wake (#222). Dispatch and
                # completion checks run in the adapter loop after this.
                self._dispatch_retry_pending = False
                # #340: release only the handle belonging to the same job
                # registration. Stale events from a cancelled/replaced
                # timer cannot clear a reused job ID's live handle.
                if event.stagger_job_id is not None:
                    job = self._jobs.get(event.stagger_job_id)
                    if job is not None and event.stagger_generation == job.registration_token:
                        self._stagger_wake_handles.pop(event.stagger_job_id, None)
                elif event.stagger_generation == 0:
                    self._stagger_wake_handles.pop("__legacy__", None)

            case CircuitBreakerRecovery():
                self._handle_circuit_breaker_recovery(event)

            case _:
                _logger.warning(
                    "baton.unknown_event",
                    extra={"event_type": type(event).__name__},
                )

        event_job_id = getattr(event, "job_id", None)
        if isinstance(event_job_id, str):
            self._settle_flow(event_job_id)

    except Exception:
        # #317: include the job/sheet context (when the event carries it)
        # so a handler traceback can be correlated to a specific job in a
        # multi-job conductor without timestamp-based log grepping.
        _logger.error(
            "baton.event_handler_failed",
            extra={
                "event_type": type(event).__name__,
                "job_id": getattr(event, "job_id", None),
                "sheet_num": getattr(event, "sheet_num", None),
            },
            exc_info=True,
        )
request_pause
request_pause(job_id)

Eagerly close the dispatch gate for a job, synchronously (#184).

Called from the producer side (JobManager.pause_job) BEFORE the PauseJob event is enqueued. dispatch_ready gates on job.paused, but that flag was previously set only when the PauseJob event was processed — so a sheet completion queued ahead of the pause would dispatch the next sheet before the pause was seen. Setting the gate here, synchronously, closes the race: on the single-threaded event loop no dispatch can run between this call and the caller's next await.

Sets user_paused too (not just paused): otherwise an escalation timeout — which clears paused only if not user_paused — could unpause a user-paused job in the window before the PauseJob event lands (#326). _handle_pause_job then becomes an idempotent re-set.

Returns True if the job exists in the baton, False otherwise.

Source code in src/marianne/daemon/baton/core.py
def request_pause(self, job_id: str) -> bool:
    """Eagerly close the dispatch gate for a job, synchronously (#184).

    Called from the producer side (``JobManager.pause_job``) BEFORE the
    ``PauseJob`` event is enqueued. ``dispatch_ready`` gates on ``job.paused``,
    but that flag was previously set only when the ``PauseJob`` event was
    *processed* — so a sheet completion queued ahead of the pause would
    dispatch the next sheet before the pause was seen. Setting the gate here,
    synchronously, closes the race: on the single-threaded event loop no
    dispatch can run between this call and the caller's next ``await``.

    Sets ``user_paused`` too (not just ``paused``): otherwise an escalation
    timeout — which clears ``paused`` only ``if not user_paused`` — could
    unpause a user-paused job in the window before the ``PauseJob`` event
    lands (#326). ``_handle_pause_job`` then becomes an idempotent re-set.

    Returns True if the job exists in the baton, False otherwise.
    """
    job = self._jobs.get(job_id)
    if job is None:
        return False
    job.paused = True
    job.user_paused = True
    self._state_dirty = True
    return True
run async
run()

The baton's main event loop.

Processes events from the inbox, updates state, and dispatches ready sheets. Runs until a ShutdownRequested event is received.

Source code in src/marianne/daemon/baton/core.py
async def run(self) -> None:
    """The baton's main event loop.

    Processes events from the inbox, updates state, and dispatches
    ready sheets. Runs until a ShutdownRequested event is received.
    """
    self._running = True
    _logger.info("baton.started")

    try:
        while not self._shutting_down:
            event = await self._inbox.get()
            await self.handle_event(event)
            # dispatch_ready() would be called here when wired to
            # conductor
    except asyncio.CancelledError:
        _logger.info("baton.cancelled")
        raise
    finally:
        self._running = False
        _logger.info("baton.stopped")
get_diagnostics
get_diagnostics(job_id)

Get diagnostic information for a job.

Returns a dict with sheet counts by status, instrument state, and other debugging information. Returns None if job not found.

Source code in src/marianne/daemon/baton/core.py
def get_diagnostics(self, job_id: str) -> dict[str, Any] | None:
    """Get diagnostic information for a job.

    Returns a dict with sheet counts by status, instrument state,
    and other debugging information. Returns None if job not found.
    """
    job = self._jobs.get(job_id)
    if job is None:
        return None

    status_counts: dict[str, int] = {}
    instruments_used: set[str] = set()
    for sheet in job.sheets.values():
        status_key = sheet.status.value
        status_counts[status_key] = status_counts.get(status_key, 0) + 1
        if sheet.instrument_name:
            instruments_used.add(sheet.instrument_name)

    return {
        "job_id": job_id,
        "paused": job.paused,
        "sheets": {
            "total": len(job.sheets),
            **status_counts,
        },
        "instruments_used": sorted(instruments_used),
        "parallel_policy": {
            "max_concurrent": job.max_concurrent,
            "fail_fast": job.fail_fast,
            "stagger_delay_ms": job.stagger_delay_ms,
        },
        # Inbox depth observability (#222) — the inbox is process-wide, not
        # per-job, but surfacing it here makes a consumer stall visible via
        # `mzt diagnose` without a log grep.
        "inbox_depth": self._inbox.qsize(),
        "inbox_high_water": self._inbox_high_water,
    }

CancelJob dataclass

CancelJob(job_id, timestamp=time(), *, event_generation=None)

Cancel all sheets for a job and deregister it from the baton.

In-flight sheet tasks are cancelled. The job is marked as cancelled in CheckpointState.

CircuitBreakerRecovery dataclass

CircuitBreakerRecovery(instrument, timestamp=time())

Timer fired — check if a circuit-broken instrument can accept a probe.

When a circuit breaker trips OPEN, the baton schedules this event via the timer wheel. On fire, the instrument transitions from OPEN to HALF_OPEN, allowing one probe request through. The next dispatch cycle picks up any PENDING sheets blocked by the dead-ended fallback chain.

If the probe succeeds, the breaker closes. If it fails, the breaker reopens and a new recovery timer is scheduled with increased backoff.

GH#169: Without this, sheets whose entire fallback chain is circuit-broken stay PENDING forever — the score appears RUNNING but is dead.

ConfigReloaded dataclass

ConfigReloaded(job_id, new_config, timestamp=time(), *, event_generation=None)

Config has changed for a job (SIGHUP, mzt modify, resume -c).

The baton rebuilds pending sheets from the new config. Completed sheets are preserved. Cost limits may be reset if they changed.

CronTick dataclass

CronTick(entry_name, score_path, due_at=None, timestamp=time())

Timer fired — a cron-scheduled job should be submitted.

The baton submits the configured score as a new job and schedules the next tick. If a previous run is still active, this tick is skipped.

DispatchRetry dataclass

DispatchRetry(stagger_job_id=None, stagger_generation=None, timestamp=time())

Internal signal to retry dispatch after a backpressure delay.

When the baton encounters backpressure during dispatch, it schedules this event via the timer wheel rather than blocking.

EscalationNeeded dataclass

EscalationNeeded(job_id, sheet_num, reason, options=list(), timestamp=time(), *, event_generation=None)

A sheet execution requires composer judgment — enter fermata.

The baton pauses the job's dispatch and notifies the composer (human or AI) via configured channels. A timeout timer is scheduled.

EscalationResolved dataclass

EscalationResolved(job_id, sheet_num, decision, timestamp=time(), *, event_generation=None)

The composer has made a decision on a fermata.

The baton applies the decision and resumes dispatching for the job. Arrives via IPC (job.resolve_escalation method).

EscalationTimeout dataclass

EscalationTimeout(job_id, sheet_num, timestamp=time(), *, event_generation=None)

Timer fired — no escalation response received within the deadline.

The baton defaults to the safe action: fail the sheet (not the job) and resume dispatching for other sheets.

FermataCheck dataclass

FermataCheck(job_id, sheet_num, timestamp=time(), *, event_generation=None)

Timer fired — poll for a composer's resolution marker on a FERMATA sheet (#361).

A sheet in FERMATA is paused awaiting a composer decision. The adapter polls {workspace}/markers/fermata/{job_id}/sheet-{N}.{decision} and, on a valid marker, emits the existing EscalationResolved event. The poll reschedules itself only while the sheet remains FERMATA.

JobTimeout dataclass

JobTimeout(job_id, timestamp=time(), *, event_generation=None)

Timer fired — a job has exceeded its wall-clock time limit.

The baton cancels all remaining sheets for this job.

PacingComplete dataclass

PacingComplete(job_id, timestamp=time(), *, event_generation=None)

Timer fired — the inter-sheet pacing delay for a job has elapsed.

The baton clears the pacing flag, allowing the next sheet to dispatch. Implements pause_between_sheets_seconds from score config.

PauseJob dataclass

PauseJob(job_id, timestamp=time(), *, event_generation=None)

Pause dispatching for a job. In-flight sheets continue to completion.

No new sheets are dispatched until ResumeJob is received. Retry timers are preserved — when resumed, scheduled retries fire normally.

ProcessExited dataclass

ProcessExited(job_id, sheet_num, pid, exit_code=None, timestamp=time(), *, event_generation=None)

Observer detected that a backend process died unexpectedly.

The baton checks if this was a sheet's backend process and, if so, marks the sheet as crashed — faster than waiting for timeout.

RateLimitExpired dataclass

RateLimitExpired(instrument, timestamp=time())

Timer fired — check if the rate-limited instrument is available again.

If the instrument is still unavailable, the baton schedules another timer. If available, sheets waiting on this instrument become ready.

RateLimitHit dataclass

RateLimitHit(instrument, wait_seconds, job_id, sheet_num, model=None, timestamp=time())

An instrument hit a rate limit. NOT a failure — a tempo change.

The baton marks the instrument as rate-limited and schedules a timer for recovery. Sheets targeting this instrument move to waiting state. Other instruments are completely unaffected.

ResourceAnomaly dataclass

ResourceAnomaly(severity, metric, value, timestamp=time())

Observer/monitor detected a resource pressure event.

Critical severity triggers backpressure — the baton stops dispatching new sheets and lets running sheets drain.

ResumeJob dataclass

ResumeJob(job_id, new_config=None, timestamp=time(), *, event_generation=None)

Resume dispatching for a paused job, optionally with new config.

When new_config is provided, pending sheets are rebuilt from the new config. Completed sheets are preserved. Failed sheets being retried use the new config for the retry.

RetryDue dataclass

RetryDue(job_id, sheet_num, timestamp=time(), *, event_generation=None, dispatch_epoch=None)

Timer fired — a previously failed sheet is ready for retry.

The baton moves the sheet from retry-scheduled to ready state. The next dispatch cycle will pick it up.

SheetAttemptResult dataclass

SheetAttemptResult(job_id, sheet_num, instrument_name, attempt, execution_success=True, exit_code=None, duration_seconds=0.0, validations_passed=0, validations_total=0, validation_pass_rate=0.0, validation_details=None, error_classification=None, error_message=None, error_code=None, exit_reason=None, rate_limited=False, rate_limit_wait_seconds=None, cost_usd=0.0, input_tokens=0, output_tokens=0, cache_read_tokens=0, cache_write_tokens=0, cost_uncertain=False, preflight_warnings=list(), prompt_receipt=None, model_used=None, stdout_tail='', stderr_tail='', structured_output=None, structured_output_omitted=False, output_kind=None, tool_calls=list(), a2a_requests=list(), timestamp=time(), model_echo_status=None, model_observed=None, model_requested=None, *, event_generation=None, dispatch_epoch=None)

A musician reports the result of a single sheet attempt.

This is the central event in the baton's event loop. The musician plays once and reports in full detail. The conductor (baton) decides what happens next — retry, completion mode, healing, escalation, or accept.

Rate limits are NOT failures. When rate_limited is True, the baton re-queues the sheet for when the instrument recovers. No retry budget is consumed.

Attributes
validation_pass_rate class-attribute instance-attribute
validation_pass_rate = 0.0

Percentage of validations that passed (0.0-100.0).

CRITICAL CONTRACT (F-018): Set to 100.0 when execution succeeds with no validation rules OR when all validations pass. The baton treats the default (0.0) as "all validations failed" and will retry.

A musician that reports execution_success=True with validations_total=0 but leaves this at 0.0 will trigger unnecessary retries until max_retries is exhausted.

rate_limit_wait_seconds class-attribute instance-attribute
rate_limit_wait_seconds = None

Parsed wait duration from the API's rate limit error message.

When set, the baton uses this instead of the default 60s for scheduling the recovery timer. This is the actual duration the API told us to wait.

SheetSkipped dataclass

SheetSkipped(job_id, sheet_num, reason, timestamp=time(), *, event_generation=None, dispatch_epoch=None)

A sheet was skipped due to skip_when condition or start_sheet override.

The baton propagates skip state to dependents — downstream sheets that depend on a skipped sheet receive a skip sentinel, not empty string.

ShutdownRequested dataclass

ShutdownRequested(graceful=True, timestamp=time())

The conductor is shutting down (SIGTERM, mzt stop).

When graceful is True, the baton waits for in-flight sheets to complete (up to the configured drain timeout) before stopping. When False, sheets are cancelled immediately.

StaleCheck dataclass

StaleCheck(job_id, sheet_num, timestamp=time(), *, event_generation=None, dispatch_epoch=None)

Timer fired — check if a running sheet has gone stale.

If no output progress has been received within the configured idle timeout, the baton kills the stale sheet and reschedules or fails it.

PromptRenderer

PromptRenderer(prompt_config, total_sheets, total_stages, parallel_enabled, *, job_id=None, schedule_id=None, scheduled_due_at=None)

Renders full prompts for baton musicians.

Bridges the PromptBuilder pipeline with the baton's Sheet-based execution model. Handles template rendering, injection resolution, preamble assembly, and validation requirements — everything the old runner's context mixin did, but without the runner dependency.

Create one per job (or share across jobs with the same config). Call render() per sheet dispatch.

Parameters:

Name Type Description Default
prompt_config PromptConfig

The job's PromptConfig (template, variables, etc.).

required
total_sheets int

Total sheets in the job (for preamble).

required
total_stages int

Total stages before fan-out expansion (for template aliases).

required
parallel_enabled bool

Whether parallel execution is enabled (for preamble).

required
Source code in src/marianne/daemon/baton/prompt.py
def __init__(
    self,
    prompt_config: PromptConfig,
    total_sheets: int,
    total_stages: int,
    parallel_enabled: bool,
    *,
    job_id: str | None = None,
    schedule_id: str | None = None,
    scheduled_due_at: float | None = None,
) -> None:
    self._prompt_config = prompt_config
    self._total_sheets = total_sheets
    self._total_stages = total_stages
    self._parallel_enabled = parallel_enabled
    self._native_execution = (
        {"job_id": job_id, "schedule_id": schedule_id, "scheduled_due_at": scheduled_due_at}
        if job_id is not None else None
    )
Methods:
render
render(sheet, attempt_context, *, patterns=None, failure_history=None, spec_fragments=None, technique_manifest=None, technique_skill_docs=None, raw_prompt=False, memory_manifest=None)

Render a full prompt for a sheet execution.

Performs the complete 9-layer prompt assembly: template rendering -> injection resolution -> optional layers -> validation requirements -> completion suffix.

Parameters:

Name Type Description Default
sheet Sheet

The Sheet entity to render for.

required
attempt_context AttemptContext

Context from the baton (attempt number, mode).

required
patterns list[str] | None

Optional learned pattern descriptions to inject.

None
failure_history list[HistoricalFailure] | None

Optional historical failures from previous sheets.

None
spec_fragments list[SpecFragment] | None

Optional spec corpus fragments to inject.

None
technique_manifest str | None

Optional technique manifest text to inject as a skill-category item. Generated by the technique resolver from the job's technique declarations filtered by phase.

None
technique_skill_docs Mapping[str, str] | Sequence[str] | None

Optional list of technique document contents discovered by the technique resolver. Each entry is the full text of a skill-kind technique document, injected as a skill-category item alongside the manifest.

None
memory_manifest str | None

The memory block for this sheet. Its own channel, never part of the technique manifest, so a template that already lists techniques cannot suppress it. Injected once, as memory:manifest.

None
raw_prompt bool

When True (driven by the instrument profile's raw_prompt field), verify required attachments but do not deliver their bytes, then skip technique injection, completion suffix, and the preamble. The resulting RenderedPrompt carries the rendered Jinja template only, with an empty preamble. Used for instruments like the bash cli profile whose input must remain a literal command.

False

Returns:

Type Description
RenderedPrompt

RenderedPrompt with fully rendered prompt and preamble.

Source code in src/marianne/daemon/baton/prompt.py
def render(
    self,
    sheet: Sheet,
    attempt_context: AttemptContext,
    *,
    patterns: list[str] | None = None,
    failure_history: list[HistoricalFailure] | None = None,
    spec_fragments: list[SpecFragment] | None = None,
    technique_manifest: str | None = None,
    technique_skill_docs: Mapping[str, str] | Sequence[str] | None = None,
    raw_prompt: bool = False,
    memory_manifest: str | None = None,
) -> RenderedPrompt:
    """Render a full prompt for a sheet execution.

    Performs the complete 9-layer prompt assembly:
    template rendering -> injection resolution -> optional layers ->
    validation requirements -> completion suffix.

    Args:
        sheet: The Sheet entity to render for.
        attempt_context: Context from the baton (attempt number, mode).
        patterns: Optional learned pattern descriptions to inject.
        failure_history: Optional historical failures from previous sheets.
        spec_fragments: Optional spec corpus fragments to inject.
        technique_manifest: Optional technique manifest text to inject
            as a skill-category item. Generated by the technique resolver
            from the job's technique declarations filtered by phase.
        technique_skill_docs: Optional list of technique document contents
            discovered by the technique resolver. Each entry is the full
            text of a skill-kind technique document, injected as a
            skill-category item alongside the manifest.
        memory_manifest: The memory block for this sheet. Its own channel, never
            part of the technique manifest, so a template that already lists
            techniques cannot suppress it. Injected once, as ``memory:manifest``.
        raw_prompt: When True (driven by the instrument profile's
            ``raw_prompt`` field), verify required attachments but do not
            deliver their bytes, then skip technique injection, completion
            suffix, and the preamble. The resulting RenderedPrompt carries
            the rendered Jinja template only, with an empty preamble. Used
            for instruments like the bash ``cli`` profile whose input must
            remain a literal command.

    Returns:
        RenderedPrompt with fully rendered prompt and preamble.
    """
    # Layer 1: Build SheetContext from Sheet entity (F-210: includes cross-sheet)
    context = self._build_context(sheet, attempt_context)

    # Layer 2-3: Resolve prelude/cadenza injections into the context.  Raw
    # command profiles do not receive these bytes, but ``required`` still
    # means required: resolve first so a missing/invalid attachment fails
    # closed instead of being silently bypassed.
    self._resolve_injections(context, sheet)

    if not raw_prompt:
        # Layer 2.5: Inject technique manifest and skill documents.
        # Skill docs go FIRST (they're the actual knowledge the musician
        # needs), then the manifest (lists what's available). Both are
        # injected as skill-category items so they appear before the
        # template in the assembled prompt.
        if technique_skill_docs:
            named_docs = (
                technique_skill_docs.items()
                if isinstance(technique_skill_docs, Mapping)
                else (
                    (f"document-{index}", doc)
                    for index, doc in enumerate(technique_skill_docs, 1)
                )
            )
            for name, doc in named_docs:
                context.injected_skills.append(doc)
                self._record_delivery(
                    context,
                    source=f"technique:{name}",
                    category=InjectionCategory.SKILL,
                    delivered_content=doc,
                    delivery_kind="inline-technique",
                )
        if technique_manifest and self._template_contains_technique_manifest(sheet):
            self._note_dropped(
                context, "technique", "technique-manifest",
                "template_already_lists_techniques",
            )
        if technique_manifest and not self._template_contains_technique_manifest(
            sheet
        ):
            context.injected_skills.append(technique_manifest)
            self._record_delivery(
                context,
                source="technique-manifest",
                category=InjectionCategory.SKILL,
                delivered_content=technique_manifest,
                delivery_kind="inline-technique-manifest",
            )
        if memory_manifest:
            context.injected_skills.append(memory_manifest)
            self._record_delivery(
                context,
                source="memory:manifest",
                category=InjectionCategory.SKILL,
                delivered_content=memory_manifest,
                delivery_kind="inline-memory-manifest",
            )

    # Layer 4-8: Build prompt through PromptBuilder (raw_prompt short-circuits inside)
    prompt = self._build_prompt(
        sheet, context, patterns, failure_history, spec_fragments,
        flow_vars=attempt_context.flow_vars,
        raw_prompt=raw_prompt,
    )

    if raw_prompt:
        # No completion suffix, no preamble — the instrument receives
        # the rendered template verbatim. Empty preamble is the
        # "no preamble" sentinel.
        return RenderedPrompt(
            prompt=prompt, preamble="", context_manifest=(),
            prompt_receipt=self._receipt(sheet, context, prompt, "", raw_prompt=True),
        )

    # Layer 9: Completion mode suffix
    if attempt_context.completion_prompt_suffix:
        prompt = f"{prompt}\n\n{attempt_context.completion_prompt_suffix}"

    # Preamble: positional identity + retry status
    retry_count = max(0, attempt_context.attempt_number - 1)
    preamble = build_preamble(
        sheet_num=sheet.num,
        total_sheets=self._total_sheets,
        workspace=sheet.workspace,
        retry_count=retry_count,
        is_parallel=self._parallel_enabled,
        healing_context=attempt_context.healing_context,
    )

    return RenderedPrompt(
        prompt=prompt,
        preamble=preamble,
        prompt_extensions=tuple(sheet.prompt_extensions),
        context_manifest=tuple(context.delivery_manifest),
        prompt_receipt=self._receipt(sheet, context, prompt, preamble),
    )

RenderedPrompt dataclass

RenderedPrompt(prompt, preamble, prompt_extensions=(), context_manifest=(), prompt_receipt=None)

Output of the prompt rendering pipeline.

Contains both the rendered prompt (for backend execution) and the preamble (set on the backend before execution). Separating them allows the musician to configure the backend correctly.

Attributes
prompt instance-attribute
prompt

Fully rendered prompt with all injections and context layers.

preamble instance-attribute
preamble

Dynamic preamble with positional identity and retry status.

prompt_extensions class-attribute instance-attribute
prompt_extensions = ()

Request-local additional directives appended by the backend.

context_manifest class-attribute instance-attribute
context_manifest = ()

Hash-only manifest of context and technique bytes in prompt.

prompt_receipt class-attribute instance-attribute
prompt_receipt = None

Per-source sizes, hashes and drop reasons for this prompt (GH #546).

AttemptContext dataclass

AttemptContext(attempt_number, mode, dispatch_epoch=None, flow_vars=dict(), completion_prompt_suffix=None, healing_context=None, previous_results=None, learned_patterns=None, total_sheets=1, total_movements=1, previous_outputs=dict(), previous_files=dict(), response_format=RESPONSE_FORMAT_UNSET, model=None, max_tokens=None, temperature=None, http_timeout_seconds=None, expected_route=None, route_model_override=None, route_provider_override=None, first_output_timeout_seconds=FIRST_OUTPUT_TIMEOUT_UNSET, effort=None, tools=None)

Context provided by the conductor to the musician for a single attempt.

Each dispatch carries this context so the musician knows: - Which attempt this is (1 = first try, 2+ = retry) - What mode to operate in (normal/completion/healing) - Any extra context for non-normal modes - Learned patterns from the learning store (instrument-scoped) - Previous attempt results (for failure history injection)

Attributes
attempt_number instance-attribute
attempt_number

1-based attempt number. First try = 1, first retry = 2, etc.

flow_vars class-attribute instance-attribute
flow_vars = field(default_factory=dict)

The execution mode for this attempt.

completion_prompt_suffix class-attribute instance-attribute
completion_prompt_suffix = None

For completion mode: appended to the prompt to fix partial failures.

healing_context class-attribute instance-attribute
healing_context = None

For healing mode: diagnostic context from self-healing analysis.

previous_results class-attribute instance-attribute
previous_results = None

Previous attempt results for failure history injection into prompts.

learned_patterns class-attribute instance-attribute
learned_patterns = None

Patterns from the learning store, scoped to this instrument.

total_sheets class-attribute instance-attribute
total_sheets = 1

Total concrete sheet count in the job (for preamble and template vars).

total_movements class-attribute instance-attribute
total_movements = 1

Total movement count in the job (for template vars).

previous_outputs class-attribute instance-attribute
previous_outputs = field(default_factory=dict)

Stdout outputs from completed sheets. Keys are sheet numbers (1-indexed). Populated by the adapter from completed sheet attempt results.

previous_files class-attribute instance-attribute
previous_files = field(default_factory=dict)

File contents captured via capture_files patterns. Keys are file paths. Populated by the adapter from workspace files matching CrossSheetConfig patterns.

response_format class-attribute instance-attribute
response_format = RESPONSE_FORMAT_UNSET

Per-sheet structured-output resolution for this attempt (W-F1/W-F2).

Tri-state: RESPONSE_FORMAT_UNSET (the sheet did not configure one — the backend applies its profile default at execute), None (explicit opt-out of a profile default), or a validated mapping forwarded to the OpenAI-compatible wire contract. Resolved ONCE at dispatch (adapter, validated by the shared wire-contract validator) and consumed request-locally by the musician via SheetRequestState — it never rides the shared pooled backend as mutable attribute state.

first_output_timeout_seconds class-attribute instance-attribute
first_output_timeout_seconds = FIRST_OUTPUT_TIMEOUT_UNSET

CLI first-output bound: unset inherits the profile, None disables it, and a positive number overrides it request-locally for this attempt.

effort class-attribute instance-attribute
effort = None

Reasoning-effort level from this attempt's chain entry (instrument_config.effort, GH #535); None keeps the profile default. Checked against the profile at dispatch, consumed request-locally.

tools class-attribute instance-attribute
tools = None

Harness tool names from this attempt's chain entry (instrument_config.tools, GH #534); None keeps the harness default and () means no tools. Checked against the profile at dispatch, consumed request-locally.

AttemptMode

Bases: str, Enum

The mode a sheet attempt runs in.

  • NORMAL — standard execution (first try or retry)
  • COMPLETION — partial validation passed, trying to complete
  • HEALING — self-healing after retry exhaustion

BatonJobState dataclass

BatonJobState(job_id, total_sheets, paused=False, pacing_active=False, sheets=dict())

The baton's per-job tracking during a performance.

Contains all sheet states for a job, plus job-level flags (paused, pacing, cost tracking).

Attributes
job_id instance-attribute
job_id

The unique job identifier.

total_sheets instance-attribute
total_sheets

Total number of sheets in this job.

paused class-attribute instance-attribute
paused = False

Whether dispatching is paused for this job.

pacing_active class-attribute instance-attribute
pacing_active = False

Whether inter-sheet pacing delay is currently active.

sheets class-attribute instance-attribute
sheets = field(default_factory=dict)

Map of sheet_num → SheetExecutionState.

total_cost_usd property
total_cost_usd

Total cost across all sheets in this job.

completed_count property
completed_count

Number of sheets in COMPLETED status.

terminal_count property
terminal_count

Number of sheets in a terminal status (completed, failed, skipped).

is_complete property
is_complete

Whether all registered sheets have reached a terminal status.

running_sheets property
running_sheets

Sheets currently in RUNNING status.

has_any_failed property
has_any_failed

Whether any sheet has reached FAILED status.

Methods:
register_sheet
register_sheet(sheet)

Register a sheet's execution state with this job.

Source code in src/marianne/daemon/baton/state.py
def register_sheet(self, sheet: SheetExecutionState) -> None:
    """Register a sheet's execution state with this job."""
    self.sheets[sheet.sheet_num] = sheet
get_sheet
get_sheet(sheet_num)

Get a sheet's execution state, or None if not registered.

Source code in src/marianne/daemon/baton/state.py
def get_sheet(self, sheet_num: int) -> SheetExecutionState | None:
    """Get a sheet's execution state, or None if not registered."""
    return self.sheets.get(sheet_num)

CircuitBreakerState

Bases: str, Enum

Three-state circuit breaker for per-instrument health tracking.

  • CLOSED — healthy, accepting requests
  • OPEN — unhealthy, rejecting requests, waiting for recovery timer
  • HALF_OPEN — probing, allowing one request to test recovery

InstrumentState dataclass

InstrumentState(name, max_concurrent, running_count=0, last_dispatch_at=0.0, rate_limited=False, rate_limit_expires_at=None, circuit_breaker=CLOSED, consecutive_failures=0, circuit_breaker_threshold=5, circuit_breaker_recovery_at=None)

Per-instrument state tracking for rate limits, circuit breakers, and concurrency.

The baton tracks each instrument's health independently. Rate limits on claude-code don't affect gemini-cli. Circuit breaker thresholds are per-instrument. Concurrency limits come from the InstrumentProfile.

Attributes
name instance-attribute
name

Instrument name (matches InstrumentProfile.name).

max_concurrent instance-attribute
max_concurrent

Maximum concurrent sheets on this instrument (from InstrumentProfile).

running_count class-attribute instance-attribute
running_count = 0

Number of currently running sheets on this instrument.

last_dispatch_at class-attribute instance-attribute
last_dispatch_at = 0.0

Monotonic time of the most recent dispatch on this instrument (#340).

The dispatch stagger gate skips a same-instrument sheet when now - last_dispatch_at < stagger_delay_ms, spreading a burst of simultaneously-ready same-instrument sheets to avoid a same-provider API burst. Default 0.0 means "never dispatched" (gate passes immediately).

rate_limited class-attribute instance-attribute
rate_limited = False

Whether this instrument is currently rate-limited.

rate_limit_expires_at class-attribute instance-attribute
rate_limit_expires_at = None

Monotonic time when the rate limit is expected to clear.

circuit_breaker class-attribute instance-attribute
circuit_breaker = CircuitBreakerState.CLOSED

Current circuit breaker state.

consecutive_failures class-attribute instance-attribute
consecutive_failures = 0

Consecutive failures across all jobs for this instrument.

circuit_breaker_threshold class-attribute instance-attribute
circuit_breaker_threshold = 5

Number of consecutive failures to trip the circuit breaker.

circuit_breaker_recovery_at class-attribute instance-attribute
circuit_breaker_recovery_at = None

Monotonic time for circuit breaker recovery check.

is_available property
is_available

Whether this instrument can accept new sheets.

Available when not rate-limited and circuit breaker is not open. Half-open allows one probe request through.

at_capacity property
at_capacity

Whether all concurrent slots are in use.

Methods:
record_success
record_success()

Record a successful execution on this instrument.

Resets consecutive failures. If circuit breaker is half-open, closes it (the probe succeeded).

Source code in src/marianne/daemon/baton/state.py
def record_success(self) -> None:
    """Record a successful execution on this instrument.

    Resets consecutive failures. If circuit breaker is half-open,
    closes it (the probe succeeded).
    """
    self.consecutive_failures = 0
    if self.circuit_breaker == CircuitBreakerState.HALF_OPEN:
        self.circuit_breaker = CircuitBreakerState.CLOSED
record_failure
record_failure()

Record a failed execution on this instrument.

Increments consecutive failures. If threshold reached, opens the circuit breaker. If already half-open, reopens it.

Source code in src/marianne/daemon/baton/state.py
def record_failure(self) -> None:
    """Record a failed execution on this instrument.

    Increments consecutive failures. If threshold reached, opens
    the circuit breaker. If already half-open, reopens it.
    """
    self.consecutive_failures += 1

    if self.circuit_breaker == CircuitBreakerState.HALF_OPEN:
        # Probe failed — back to open
        self.circuit_breaker = CircuitBreakerState.OPEN
    elif self.consecutive_failures >= self.circuit_breaker_threshold:
        self.circuit_breaker = CircuitBreakerState.OPEN
to_dict
to_dict()

Serialize to a dict for SQLite persistence.

Source code in src/marianne/daemon/baton/state.py
def to_dict(self) -> dict[str, Any]:
    """Serialize to a dict for SQLite persistence."""
    return {
        "name": self.name,
        "max_concurrent": self.max_concurrent,
        "rate_limited": self.rate_limited,
        "rate_limit_expires_at": self.rate_limit_expires_at,
        "circuit_breaker": self.circuit_breaker.value,
        "consecutive_failures": self.consecutive_failures,
        "circuit_breaker_threshold": self.circuit_breaker_threshold,
        "circuit_breaker_recovery_at": self.circuit_breaker_recovery_at,
    }
from_dict classmethod
from_dict(data)

Restore from a serialized dict.

Source code in src/marianne/daemon/baton/state.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> InstrumentState:
    """Restore from a serialized dict."""
    state = cls(
        name=data["name"],
        max_concurrent=data.get("max_concurrent", 4),
    )
    state.rate_limited = data.get("rate_limited", False)
    state.rate_limit_expires_at = data.get("rate_limit_expires_at")
    state.circuit_breaker = CircuitBreakerState(
        data.get("circuit_breaker", "closed")
    )
    state.consecutive_failures = data.get("consecutive_failures", 0)
    state.circuit_breaker_threshold = data.get("circuit_breaker_threshold", 5)
    state.circuit_breaker_recovery_at = data.get("circuit_breaker_recovery_at")
    return state

TimerHandle dataclass

TimerHandle(fire_at, event, _seq=_next_seq())

Opaque handle returned by schedule(). Used for cancellation.

Attributes:

Name Type Description
fire_at float

Monotonic time when the event should fire.

event BatonEvent

The BatonEvent to deliver to the inbox.

TimerWheel

TimerWheel(inbox)

Priority queue of future events with a background drain task.

Usage::

inbox = asyncio.Queue()
wheel = TimerWheel(inbox)

# Schedule a retry in 30 seconds
handle = wheel.schedule(
    30.0,
    RetryDue(job_id="j1", sheet_num=5, event_generation=1),
)

# Cancel if no longer needed
wheel.cancel(handle)

# Run the drain task (usually as asyncio.create_task(wheel.run()))
await wheel.run()  # blocks forever, fires events into inbox

Parameters:

Name Type Description Default
inbox Queue[Any]

The asyncio.Queue that receives fired events. This is the baton's event inbox — the same queue that receives musician results, external commands, etc.

required
Source code in src/marianne/daemon/baton/timer.py
def __init__(self, inbox: asyncio.Queue[Any]) -> None:
    self._inbox = inbox
    self._heap: list[_TimerEntry] = []
    self._cancelled: set[int] = set()  # set of cancelled _seq values
    self._wake = asyncio.Event()
    self._shutting_down = False
Attributes
pending_count property
pending_count

Number of non-cancelled timers in the wheel.

Methods:
schedule
schedule(delay_seconds, event)

Schedule an event to fire after delay_seconds.

Parameters:

Name Type Description Default
delay_seconds float

Seconds from now. Clamped to >= 0.

required
event BatonEvent

The BatonEvent to deliver when the timer fires.

required

Returns:

Type Description
TimerHandle

A TimerHandle that can be passed to cancel().

Source code in src/marianne/daemon/baton/timer.py
def schedule(self, delay_seconds: float, event: BatonEvent) -> TimerHandle:
    """Schedule an event to fire after ``delay_seconds``.

    Args:
        delay_seconds: Seconds from now. Clamped to >= 0.
        event: The BatonEvent to deliver when the timer fires.

    Returns:
        A TimerHandle that can be passed to ``cancel()``.
    """
    delay = max(0.0, delay_seconds)
    fire_at = time.monotonic() + delay
    handle = TimerHandle(fire_at=fire_at, event=event)
    entry = _TimerEntry(fire_at=fire_at, seq=handle._seq, handle=handle)
    heapq.heappush(self._heap, entry)

    _logger.debug(
        "timer.scheduled",
        extra={
            "event_type": type(event).__name__,
            "delay_seconds": delay,
            "fire_at": fire_at,
            "pending": self.pending_count,
        },
    )

    # Wake the drain task — it may need to recalculate its sleep
    self._wake.set()
    return handle
cancel
cancel(handle)

Cancel a scheduled timer.

Parameters:

Name Type Description Default
handle TimerHandle

The handle returned by schedule().

required

Returns:

Type Description
bool

True if the timer was pending and is now cancelled.

bool

False if it was already cancelled or already fired.

Source code in src/marianne/daemon/baton/timer.py
def cancel(self, handle: TimerHandle) -> bool:
    """Cancel a scheduled timer.

    Args:
        handle: The handle returned by ``schedule()``.

    Returns:
        True if the timer was pending and is now cancelled.
        False if it was already cancelled or already fired.
    """
    seq = handle._seq
    if seq in self._cancelled:
        return False

    # Check if it's still in the heap (not yet fired)
    for entry in self._heap:
        if entry.handle._seq == seq and not entry.cancelled:
            entry.cancelled = True
            self._cancelled.add(seq)
            _logger.debug(
                "timer.cancelled",
                extra={
                    "event_type": type(handle.event).__name__,
                    "fire_at": handle.fire_at,
                },
            )
            return True

    return False
snapshot
snapshot()

Export pending (non-cancelled) timers for persistence.

Returns a list of (fire_at, event) tuples — the data needed to reconstruct the timer wheel after a restart.

Source code in src/marianne/daemon/baton/timer.py
def snapshot(self) -> list[tuple[float, BatonEvent]]:
    """Export pending (non-cancelled) timers for persistence.

    Returns a list of (fire_at, event) tuples — the data needed to
    reconstruct the timer wheel after a restart.
    """
    return [
        (entry.fire_at, entry.handle.event)
        for entry in self._heap
        if entry.handle._seq not in self._cancelled
    ]
run async
run()

Background drain task — fire timers into the inbox.

This coroutine runs indefinitely. Cancel the task to stop it. It sleeps until the next timer is due (or a wake signal arrives), fires all due timers, and repeats.

Source code in src/marianne/daemon/baton/timer.py
async def run(self) -> None:
    """Background drain task — fire timers into the inbox.

    This coroutine runs indefinitely. Cancel the task to stop it.
    It sleeps until the next timer is due (or a wake signal arrives),
    fires all due timers, and repeats.
    """
    while True:
        # Skip cancelled entries at the front of the heap
        while self._heap and self._heap[0].handle._seq in self._cancelled:
            heapq.heappop(self._heap)

        if not self._heap:
            # No timers — sleep until a timer is added
            self._wake.clear()
            await self._wake.wait()
            continue

        next_fire = self._heap[0].fire_at
        now = time.monotonic()

        if next_fire <= now:
            # Timer is due — pop and fire
            entry = heapq.heappop(self._heap)
            if entry.handle._seq in self._cancelled:
                # Was cancelled between check and pop — skip
                self._cancelled.discard(entry.handle._seq)
                continue

            self._cancelled.discard(entry.handle._seq)
            await self._inbox.put(entry.handle.event)

            _logger.debug(
                "timer.fired",
                extra={
                    "event_type": type(entry.handle.event).__name__,
                    "fire_at": entry.fire_at,
                    "latency_ms": (time.monotonic() - entry.fire_at) * 1000,
                },
            )
        else:
            # Sleep until next timer or wake signal
            sleep_for = next_fire - now
            self._wake.clear()
            try:
                await asyncio.wait_for(self._wake.wait(), timeout=sleep_for)
            except TimeoutError:
                pass  # Timer is due, loop will fire it
shutdown async
shutdown()

Fire all pending timers immediately and stop.

Used during graceful shutdown — ensures no events are lost. Events are placed into the inbox in fire_at order.

Source code in src/marianne/daemon/baton/timer.py
async def shutdown(self) -> None:
    """Fire all pending timers immediately and stop.

    Used during graceful shutdown — ensures no events are lost.
    Events are placed into the inbox in fire_at order.
    """
    self._shutting_down = True

    # Drain heap in order, skipping cancelled
    while self._heap:
        entry = heapq.heappop(self._heap)
        if entry.handle._seq not in self._cancelled:
            await self._inbox.put(entry.handle.event)

    _logger.debug("timer.shutdown_complete")

Functions:

sheet_task async

sheet_task(*, job_id, sheet, backend, attempt_context, inbox, total_sheets=1, total_movements=1, rendered_prompt=None, preamble=None, memory_manifest=None, cost_per_1k_input=None, cost_per_1k_output=None, cost_per_1k_cache_read=None, cost_per_1k_cache_write=None, instrument_override=None, technique_router=None, code_executor=None, context_delivery=None, event_generation=None)

Execute a single sheet attempt and report the result.

This is the musician's entire job. Play once, report in full detail. The conductor (baton) decides what happens next.

Parameters:

Name Type Description Default
job_id str

The job this sheet belongs to.

required
sheet Sheet

The sheet to execute (prompt, validations, timeout, etc.).

required
backend Backend

The backend to execute through.

required
attempt_context AttemptContext

Context from the conductor (attempt number, mode, etc.).

required
inbox Queue[SheetAttemptResult]

The baton's event inbox to report results to.

required
total_sheets int

Total concrete sheets in the job (for template variables).

1
total_movements int

Total movements in the job (for template variables).

1
rendered_prompt str | None

Optional pre-rendered prompt from PromptRenderer. When provided, the musician uses this directly instead of calling _build_prompt(). This enables the full 9-layer prompt assembly pipeline including spec fragments, learned patterns, and failure history.

None
preamble str | None

Optional pre-built preamble. Passed to the backend request-locally at execution (SheetRequestState — W-F3), never via the mutable set_preamble() slot. Only used when rendered_prompt is also provided (the PromptRenderer separates them).

None
cost_per_1k_input float | None

Cost per 1000 input tokens (USD) from the instrument profile's ModelCapacity. None uses hardcoded fallback.

None
cost_per_1k_output float | None

Cost per 1000 output tokens (USD) from the instrument profile's ModelCapacity. None uses hardcoded fallback.

None
instrument_override str | None

When set, used as the instrument_name in the SheetAttemptResult instead of sheet.instrument_name. Required after instrument fallback — the Sheet entity keeps the original instrument but the baton's SheetExecutionState tracks the fallback instrument. Without this, attempt results credit the wrong instrument for success/failure tracking.

None

Never raises — all exceptions are caught and reported via the inbox.

Source code in src/marianne/daemon/baton/musician.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
async def sheet_task(
    *,
    job_id: str,
    sheet: Sheet,
    backend: Backend,
    attempt_context: AttemptContext,
    inbox: asyncio.Queue[SheetAttemptResult],
    total_sheets: int = 1,
    total_movements: int = 1,
    rendered_prompt: str | None = None,
    preamble: str | None = None,
    memory_manifest: str | None = None,
    cost_per_1k_input: float | None = None,
    cost_per_1k_output: float | None = None,
    cost_per_1k_cache_read: float | None = None,
    cost_per_1k_cache_write: float | None = None,
    instrument_override: str | None = None,
    technique_router: TechniqueRouter | None = None,
    code_executor: CodeModeExecutor | None = None,
    context_delivery: RenderedPrompt | None = None,
    event_generation: int | None = None,
) -> None:
    """Execute a single sheet attempt and report the result.

    This is the musician's entire job. Play once, report in full detail.
    The conductor (baton) decides what happens next.

    Args:
        job_id: The job this sheet belongs to.
        sheet: The sheet to execute (prompt, validations, timeout, etc.).
        backend: The backend to execute through.
        attempt_context: Context from the conductor (attempt number, mode, etc.).
        inbox: The baton's event inbox to report results to.
        total_sheets: Total concrete sheets in the job (for template variables).
        total_movements: Total movements in the job (for template variables).
        rendered_prompt: Optional pre-rendered prompt from PromptRenderer.
            When provided, the musician uses this directly instead of
            calling _build_prompt(). This enables the full 9-layer
            prompt assembly pipeline including spec fragments, learned
            patterns, and failure history.
        preamble: Optional pre-built preamble. Passed to the backend
            request-locally at execution (SheetRequestState — W-F3), never
            via the mutable set_preamble() slot. Only used when
            rendered_prompt is also provided (the PromptRenderer separates
            them).
        cost_per_1k_input: Cost per 1000 input tokens (USD) from the
            instrument profile's ModelCapacity. None uses hardcoded fallback.
        cost_per_1k_output: Cost per 1000 output tokens (USD) from the
            instrument profile's ModelCapacity. None uses hardcoded fallback.
        instrument_override: When set, used as the instrument_name in the
            SheetAttemptResult instead of sheet.instrument_name. Required
            after instrument fallback — the Sheet entity keeps the original
            instrument but the baton's SheetExecutionState tracks the
            fallback instrument. Without this, attempt results credit
            the wrong instrument for success/failure tracking.

    Never raises — all exceptions are caught and reported via the inbox.
    """
    start_time = time.monotonic()
    # Resolve the effective instrument name — fallback may have changed it
    effective_instrument = instrument_override or sheet.instrument_name
    # #202: warn-only preflight notes, computed once the prompt is rendered.
    preflight_warnings: list[str] = []
    # GH #546: what the assembled prompt was made of (hashes and sizes only).
    prompt_receipt: PromptReceipt | None = None

    try:
        # This is the first executable line inside ``sheet_task``.  A receipt
        # written here proves the rendered bytes crossed the call boundary;
        # setup failures before this function is invoked produce no receipt.
        if context_delivery is not None:
            from marianne.daemon.baton.prompt import write_context_delivery_receipt

            write_context_delivery_receipt(
                workspace=sheet.workspace,
                job_id=job_id,
                sheet_num=sheet.num,
                attempt=attempt_context.attempt_number,
                instrument=effective_instrument,
                rendered=context_delivery,
                instrument_class=(
                    sheet.instrument_resolution.requested
                    if sheet.instrument_resolution is not None else None
                ),
                class_snapshot_sha256=(
                    sheet.instrument_resolution.snapshot_digest
                    if sheet.instrument_resolution is not None else None
                ),
            )

        # Step 1: Build prompt
        if rendered_prompt is not None:
            # F-104 via PromptRenderer — pre-rendered with all 9 layers.
            # The preamble is separated by the renderer but travels
            # REQUEST-LOCALLY (W-F3): a pooled backend shared across
            # sheets/jobs must never hold another sheet's prompt bytes in
            # a mutable slot, so it is passed to execute() below instead
            # of set_preamble().
            prompt = rendered_prompt
        else:
            # Fallback: inline rendering (covers basic cases)
            prompt = _build_prompt(
                sheet, attempt_context,
                total_sheets=total_sheets,
                total_movements=total_movements,
                memory_manifest=memory_manifest,
            )

        # GH #546: the receipt travels on every result from here on, success or
        # failure. The renderer built it with per-source detail; the inline
        # fallback has only the finished prompt, so its receipt lists no sources.
        prompt_receipt = (
            context_delivery.prompt_receipt
            if context_delivery is not None and context_delivery.prompt_receipt is not None
            else build_receipt(
                prompt=prompt,
                preamble=preamble or "",
                sources=[],
            )
        )

        # #202: warn-only token preflight on the rendered prompt (advisory —
        # never blocks). Computed before execution so it reflects what will run.
        preflight_warnings = _preflight_token_warnings(
            prompt, effective_instrument, sheet.instrument_config.get("model")
        )

        # Step 2-3: Execute through backend. The per-sheet request state
        # (W-F1/W-F2/W-F3) is dispatch-resolved and immutable: the pooled
        # HTTP singleton is shared by concurrent sheets across jobs, so
        # this attempt's response_format/preamble must reach the payload
        # build through the request, never through mutable backend
        # attributes another dispatch may have written or may write.
        request_state = SheetRequestState(
            job_id=job_id,
            sheet_num=sheet.num,
            response_format=attempt_context.response_format,
            model=attempt_context.model,
            max_tokens=attempt_context.max_tokens,
            temperature=attempt_context.temperature,
            http_timeout_seconds=attempt_context.http_timeout_seconds,
            first_output_timeout_seconds=attempt_context.first_output_timeout_seconds,
            effort=attempt_context.effort,
            tools=attempt_context.tools,
            http_timeout_resolved=True,
            expected_route=attempt_context.expected_route,
            route_model_override=attempt_context.route_model_override,
            route_provider_override=attempt_context.route_provider_override,
            preamble=preamble,
            prompt_extensions=(
                context_delivery.prompt_extensions
                if context_delivery is not None
                else tuple(sheet.prompt_extensions)
            ),
        )
        # #386: note which other-sheet artifacts exist now, so a write by
        # this attempt is attributable to it and not to a prior sheet.
        artifact_paths = _expand_artifact_paths(
            sheet, total_sheets=total_sheets, total_movements=total_movements,
        )
        artifacts_before = _snapshot_artifacts(artifact_paths)
        exec_result = await _execute(
            backend, prompt, sheet.timeout_seconds, request_state
        )
        quarantine = (
            _quarantine_dir(sheet) if sheet.foreign_artifact_policy == "quarantine" else None
        )
        preflight_warnings.extend(
            _foreign_artifact_warnings(artifact_paths, artifacts_before, quarantine=quarantine)
        )

        # Step 3a: Classify output via TechniqueRouter (Stage 2a).
        # Only runs when a router is provided AND execution succeeded —
        # classification of a failed run's output is not informative, and
        # the field stays None to signal "no classification performed".
        # Downstream stages (Stage 3 code-mode executor, Stage 5 A2A
        # routing) consume classified.kind to decide further action.
        classified = _classify_output(
            technique_router, exec_result, job_id=job_id, sheet_num=sheet.num,
        )
        output_kind_value = classified.kind.value if classified is not None else None
        tool_call_payloads: list[dict[str, Any]] = []
        a2a_request_payloads: list[dict[str, Any]] = []
        if classified is not None:
            tool_call_payloads = [
                {
                    "server": call.server,
                    "method": call.method,
                    "arguments": dict(call.arguments),
                }
                for call in classified.tool_calls
            ]
            a2a_request_payloads = [
                {
                    "target_agent": request.target_agent,
                    "task_description": request.task_description,
                    "context": dict(request.context),
                }
                for request in classified.a2a_requests
            ]

        # Step 3b: Code mode execution (Stage 3).
        # When the classified output contains code blocks AND a code
        # executor is wired into this sheet, run each block in the
        # sandbox. The sandbox output (stdout, stderr, exit code,
        # artifacts summary) is appended to exec_result.stdout so
        # validations can see both the agent's reasoning and the
        # real execution result. On failure, a diagnostic block is
        # appended — the baton's normal retry logic handles the
        # retry path via the standard validation/error flow.
        if (
            code_executor is not None
            and classified is not None
            and classified.kind == OutputKind.CODE_BLOCK
            and classified.code_blocks
            and exec_result.success
        ):
            sandbox_section = await _execute_code_blocks(
                classified.code_blocks,
                code_executor,
                job_id=job_id,
                sheet_num=sheet.num,
            )
            # Append sandbox output to stdout so validations and
            # capture_output see it. ExecutionResult is a mutable
            # dataclass — append in place.
            separator = "" if exec_result.stdout.endswith("\n") else "\n"
            exec_result.stdout = (
                f"{exec_result.stdout}{separator}\n{sandbox_section}"
            )

        # Step 3c: the reply as a file (sheet.stdout_to, GH #494). An http
        # instrument has no filesystem; the only way its answer can meet a
        # file validation or reach a later sheet whole is for the musician
        # to write it. Written before validations so they can read it.
        stdout_to_warning = _write_stdout_to(sheet, exec_result)
        if stdout_to_warning:
            preflight_warnings.append(stdout_to_warning)

        # Step 4: Run validations (only if execution succeeded)
        # F-118: pass total_sheets/total_movements for rich context
        val_passed, val_total, val_rate, val_details = await _validate(
            sheet, exec_result,
            total_sheets=total_sheets,
            total_movements=total_movements,
            flow_vars=attempt_context.flow_vars,
        )

        # #344 obs1: rescue a plain non-zero exit whose work passed every
        # validation. The acceptance criteria are met, so report success —
        # the baton's normal success path completes the sheet, no core
        # change. exit_code stays on the result as the recorded truth.
        if (
            _is_nonzero_exit_rescuable(
                exec_result, has_validations=bool(sheet.validations)
            )
            and val_total > 0
            and val_rate >= 100.0
        ):
            _logger.info(
                "musician.nonzero_exit_rescued",
                extra={
                    "job_id": job_id,
                    SHEET_NUM_KEY: sheet.num,
                    "exit_code": exec_result.exit_code,
                    "validations": val_total,
                },
            )
            exec_result.success = True

        # Step 5: Record output with credential redaction
        stdout_tail, stderr_tail = _capture_output(exec_result)
        structured_output, structured_omitted = _capture_structured_output(
            exec_result
        )

        # Step 6: Classify errors (redact credentials from error messages —
        # backend error_message can contain API keys from auth failures,
        # config errors, or URL parameters)
        classification = _classify_error(exec_result)
        error_class = classification.classification
        raw_error_msg = classification.message
        error_msg = redact_credentials(raw_error_msg) if raw_error_msg else raw_error_msg

        # Build and report result
        duration = exec_result.duration_seconds
        result = SheetAttemptResult(
            job_id=job_id,
            sheet_num=sheet.num,
            instrument_name=effective_instrument,
            attempt=attempt_context.attempt_number,
            event_generation=event_generation,
            dispatch_epoch=attempt_context.dispatch_epoch,
            execution_success=exec_result.success,
            exit_code=exec_result.exit_code,
            duration_seconds=duration,
            validations_passed=val_passed,
            validations_total=val_total,
            validation_pass_rate=val_rate,
            validation_details=val_details,
            error_classification=error_class,
            error_message=error_msg,
            exit_reason=exec_result.exit_reason,
            error_code=classification.error_code,
            rate_limited=exec_result.rate_limited,
            rate_limit_wait_seconds=exec_result.rate_limit_wait_seconds,
            cost_usd=_estimate_cost(
                exec_result,
                cost_per_1k_input=cost_per_1k_input,
                cost_per_1k_output=cost_per_1k_output,
                instrument_name=effective_instrument,
                cost_per_1k_cache_read=cost_per_1k_cache_read,
                cost_per_1k_cache_write=cost_per_1k_cache_write,
            ),
            cost_uncertain=_attempt_cost_uncertain(
                exec_result, cost_per_1k_input, cost_per_1k_output,
            ),
            input_tokens=exec_result.input_tokens or 0,
            output_tokens=exec_result.output_tokens or 0,
            cache_read_tokens=exec_result.cache_read_tokens or 0,
            cache_write_tokens=exec_result.cache_write_tokens or 0,
            model_used=exec_result.model,
            model_echo_status=exec_result.model_echo_status,
            model_observed=exec_result.model_observed,
            model_requested=exec_result.model_requested,
            stdout_tail=stdout_tail,
            stderr_tail=stderr_tail,
            structured_output=structured_output,
            structured_output_omitted=structured_omitted,
            output_kind=output_kind_value,
            tool_calls=tool_call_payloads,
            a2a_requests=a2a_request_payloads,
            preflight_warnings=preflight_warnings,
            prompt_receipt=prompt_receipt,
        )

    except Exception as exc:
        # Step 6 (exception path): Never crash the baton
        duration = time.monotonic() - start_time
        raw_error_msg = f"{type(exc).__name__}: {exc}"
        # Redact credentials from exception messages before logging/storing.
        # Exception text can contain API keys (e.g., auth failures that echo
        # the key, config loading errors with key values in paths). Without
        # redaction, credentials propagate to logs, state DB, dashboard,
        # learning store, and diagnostic output — 6+ storage locations.
        error_msg = redact_credentials(raw_error_msg) or raw_error_msg
        _logger.error(
            "musician.sheet_task.exception",
            extra={
                "job_id": job_id,
                SHEET_NUM_KEY: sheet.num,
                "error": error_msg,
            },
            exc_info=True,
        )

        result = SheetAttemptResult(
            job_id=job_id,
            sheet_num=sheet.num,
            instrument_name=effective_instrument,
            attempt=attempt_context.attempt_number,
            event_generation=event_generation,
            dispatch_epoch=attempt_context.dispatch_epoch,
            execution_success=False,
            exit_code=None,
            duration_seconds=duration,
            error_classification="TRANSIENT",
            error_message=error_msg,
            exit_reason="error",
            rate_limited=False,
            preflight_warnings=preflight_warnings,
            prompt_receipt=prompt_receipt,
        )

    # Always report — the baton must know what happened
    await inbox.put(result)
    _logger.info(
        "musician.sheet_task.reported",
        extra={
            "job_id": job_id,
            SHEET_NUM_KEY: sheet.num,
            "success": result.execution_success,
            "pass_rate": result.validation_pass_rate,
            "duration": result.duration_seconds,
        },
    )