Skip to content

adapter

adapter

BatonAdapter — wires the baton into the conductor.

Step 28: Replace monolithic execution with the baton's event-driven model.

The adapter is the bridge between the conductor (JobManager) and the baton (BatonCore). It handles:

  1. Job submission → baton registration (Surface 1) JobConfig → Sheet[] → SheetExecutionState[] → BatonCore.register_job()

  2. Dispatch callback → backend acquisition (Surface 2) BatonCore dispatches → adapter acquires backend → spawns musician task

  3. Prompt assembly (Surface 3) Creates SheetContext, calls PromptBuilder.build_sheet_prompt()

  4. State synchronization (Surface 4) BatonSheetStatus ↔ CheckpointState.SheetStatus mapping

  5. EventBus integration (Surface 5) Baton events → ObserverEvent format → EventBus.publish()

  6. Rate limit callback bridge (Surface 6) Musician extracts wait time → SheetAttemptResult → baton handles

  7. Lifecycle (Surface 8) The adapter is always initialized by the conductor at startup

Design decisions: - Checkpoint is source of truth. Baton rebuilds from checkpoint on restart. - Save checkpoint FIRST, then update baton state (prevents re-execution). - The adapter does NOT own the baton's main loop — the manager runs it. - Concert support: sequential score submission (option 1 from wiring analysis).

Wiring analysis: step-28-wiring-analysis.md from the v1-beta-v3 movement-2 workspace (preserved in the project's private history archive).

Attributes

Classes

ProcessGroupCleanupResult dataclass

ProcessGroupCleanupResult(cleanup_generation='unbound', tracked_process_groups=0, sigterm_attempted=0, sigterm_succeeded=0, sigterm_failed=0, sigterm_skipped=0, escalation_state='not_needed', sigkill_attempted=0, sigkill_succeeded=0, sigkill_failed=0, residual_check_state='unverified', residual_process_groups=None)

Observable process-group effects of one Baton deregistration.

Methods:
to_dict
to_dict()

Return identifier-free cleanup evidence for status and logs.

Source code in src/marianne/daemon/baton/adapter.py
def to_dict(self) -> dict[str, int | str | None]:
    """Return identifier-free cleanup evidence for status and logs."""
    return asdict(self)

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")

Functions:

baton_to_checkpoint_status

baton_to_checkpoint_status(status)

Identity mapping — Phase 2 unified the enums.

Kept for backward compatibility with tests that import this function. Since BatonSheetStatus IS SheetStatus, this is just status.value.

Source code in src/marianne/daemon/baton/adapter.py
def baton_to_checkpoint_status(status: BatonSheetStatus) -> str:
    """Identity mapping — Phase 2 unified the enums.

    Kept for backward compatibility with tests that import this function.
    Since BatonSheetStatus IS SheetStatus, this is just status.value.
    """
    return status.value

checkpoint_to_baton_status

checkpoint_to_baton_status(status)

Reconstruct SheetStatus from string — Phase 2 unified the enums.

Kept for backward compatibility with tests that import this function.

Source code in src/marianne/daemon/baton/adapter.py
def checkpoint_to_baton_status(status: str) -> BatonSheetStatus:
    """Reconstruct SheetStatus from string — Phase 2 unified the enums.

    Kept for backward compatibility with tests that import this function.
    """
    return BatonSheetStatus(status)

attempt_result_to_observer_event

attempt_result_to_observer_event(result)

Convert a SheetAttemptResult to the ObserverEvent format.

Maps baton musician results to the event names the EventBus subscribers expect (dashboard, learning hub, notifications).

Parameters:

Name Type Description Default
result SheetAttemptResult

The musician's execution report.

required

Returns:

Type Description
ObserverEvent

Dict matching the ObserverEvent TypedDict shape.

Source code in src/marianne/daemon/baton/adapter.py
def attempt_result_to_observer_event(
    result: SheetAttemptResult,
) -> ObserverEvent:
    """Convert a SheetAttemptResult to the ObserverEvent format.

    Maps baton musician results to the event names the EventBus
    subscribers expect (dashboard, learning hub, notifications).

    Args:
        result: The musician's execution report.

    Returns:
        Dict matching the ObserverEvent TypedDict shape.
    """
    if result.rate_limited:
        event_name = "rate_limit.active"
    elif result.execution_success and result.validation_pass_rate >= 100.0:
        event_name = "sheet.completed"
    elif result.execution_success:
        event_name = "sheet.partial"
    else:
        event_name = "sheet.failed"

    return {
        "job_id": result.job_id,
        "sheet_num": result.sheet_num,
        "event": event_name,
        "data": {
            "instrument": result.instrument_name,
            "attempt": result.attempt,
            "success": result.execution_success,
            VALIDATION_PASS_RATE_KEY: result.validation_pass_rate,
            "cost_usd": result.cost_usd,
            "duration_seconds": result.duration_seconds,
            "rate_limited": result.rate_limited,
            "error_classification": result.error_classification,
            "model_used": result.model_used,
        },
        "timestamp": result.timestamp,
    }

skipped_to_observer_event

skipped_to_observer_event(event)

Convert a SheetSkipped event to ObserverEvent format.

Parameters:

Name Type Description Default
event SheetSkipped

The sheet skip event.

required

Returns:

Type Description
ObserverEvent

Dict matching the ObserverEvent TypedDict shape.

Source code in src/marianne/daemon/baton/adapter.py
def skipped_to_observer_event(event: SheetSkipped) -> ObserverEvent:
    """Convert a SheetSkipped event to ObserverEvent format.

    Args:
        event: The sheet skip event.

    Returns:
        Dict matching the ObserverEvent TypedDict shape.
    """
    return {
        "job_id": event.job_id,
        "sheet_num": event.sheet_num,
        "event": "sheet.skipped",
        "data": {"reason": event.reason},
        "timestamp": event.timestamp,
    }

sheets_to_execution_states

sheets_to_execution_states(sheets, *, max_retries=3, max_completion=5)

Convert Sheet entities to SheetExecutionState dict for baton registration.

Each Sheet becomes a SheetExecutionState with the baton's extended tracking fields. The sheet_num is the dict key.

Parameters:

Name Type Description Default
sheets list[Sheet]

List of Sheet entities from build_sheets().

required
max_retries int

Maximum normal retry attempts per sheet.

3
max_completion int

Maximum completion mode attempts per sheet.

5

Returns:

Type Description
dict[int, SheetExecutionState]

Dict of sheet_num → SheetExecutionState.

Source code in src/marianne/daemon/baton/adapter.py
def sheets_to_execution_states(
    sheets: list[Sheet],
    *,
    max_retries: int = 3,
    max_completion: int = 5,
) -> dict[int, SheetExecutionState]:
    """Convert Sheet entities to SheetExecutionState dict for baton registration.

    Each Sheet becomes a SheetExecutionState with the baton's extended
    tracking fields. The sheet_num is the dict key.

    Args:
        sheets: List of Sheet entities from build_sheets().
        max_retries: Maximum normal retry attempts per sheet.
        max_completion: Maximum completion mode attempts per sheet.

    Returns:
        Dict of sheet_num → SheetExecutionState.
    """
    states: dict[int, SheetExecutionState] = {}
    for sheet in sheets:
        raw_model = sheet.instrument_config.get("model")
        states[sheet.num] = SheetExecutionState(
            sheet_num=sheet.num,
            instrument_name=sheet.instrument_name,
            instrument_resolution=(
                sheet.instrument_resolution
                if isinstance(sheet.instrument_resolution, InstrumentResolution)
                else None
            ),
            model=str(raw_model) if raw_model is not None else None,
            max_retries=max_retries,
            max_completion=max_completion,
            fallback_chain=list(sheet.instrument_fallbacks),
            fallback_configs=[dict(c) for c in sheet.instrument_fallback_configs],
            balance_chain=bool(getattr(sheet, "balance_chain", False)),
            primary_config=dict(sheet.instrument_config),
            sheet_timeout_seconds=sheet.timeout_seconds,
        )
        states[sheet.num].remember_primary_identity()
    return states

extract_dependencies

extract_dependencies(config)

Extract baton-compatible dependency graph from a JobConfig.

The baton expects: {sheet_num: [dep_sheet_num, ...]}

When config.sheet.dependencies is set (non-empty), it is used as the authoritative DAG. Stage-level dependencies are expanded to sheet-level: if stage S has a fan-out of 3 (sheets 4,5,6) and depends on stage T (sheets 1,2,3), each of 4/5/6 depends on all of 1/2/3. Stages not listed in the dependencies map are treated as having no dependencies (independent).

When config.sheet.dependencies is empty or absent, falls back to the legacy linear chain: all sheets in stage N+1 depend on all sheets in stage N.

Parameters:

Name Type Description Default
config Any

Parsed JobConfig with sheet.get_fan_out_metadata().

required

Returns:

Type Description
dict[int, list[int]]

Dict of sheet_num → list of dependency sheet_nums.

Source code in src/marianne/daemon/baton/adapter.py
def extract_dependencies(config: Any) -> dict[int, list[int]]:
    """Extract baton-compatible dependency graph from a JobConfig.

    The baton expects: ``{sheet_num: [dep_sheet_num, ...]}``

    When ``config.sheet.dependencies`` is set (non-empty), it is used
    as the authoritative DAG.  Stage-level dependencies are expanded to
    sheet-level: if stage S has a fan-out of 3 (sheets 4,5,6) and
    depends on stage T (sheets 1,2,3), each of 4/5/6 depends on all of
    1/2/3.  Stages not listed in the dependencies map are treated as
    having no dependencies (independent).

    When ``config.sheet.dependencies`` is empty or absent, falls back to
    the legacy linear chain: all sheets in stage N+1 depend on all sheets
    in stage N.

    Args:
        config: Parsed JobConfig with sheet.get_fan_out_metadata().

    Returns:
        Dict of sheet_num → list of dependency sheet_nums.
    """
    total = config.sheet.total_sheets

    # Group sheets by stage
    stage_sheets: dict[int, list[int]] = {}
    for num in range(1, total + 1):
        meta = config.sheet.get_fan_out_metadata(num)
        stage = meta.stage
        stage_sheets.setdefault(stage, []).append(num)

    raw_deps = getattr(config.sheet, "dependencies", None)
    yaml_deps: dict[int, list[int]] = (
        raw_deps if isinstance(raw_deps, dict) else {}
    )

    if yaml_deps:
        # Check if dependencies are already expanded to sheet-level.
        # The config model expands stage-level deps to sheet-level at parse
        # time (SheetConfig._expand_fan_out) and clears fan_out={} to prevent
        # re-expansion.  When that has happened, the dep keys are sheet nums
        # (potentially > total_stages) and the values reference sheet nums.
        # We must NOT re-expand already-expanded deps — that produces wrong
        # results (GH#167 variant: double expansion).
        fan_out = getattr(config.sheet, "fan_out", None)
        already_expanded = not fan_out  # fan_out cleared → deps are sheet-level

        if already_expanded:
            _logger.debug(
                "extract_dependencies.using_pre_expanded",
                extra={
                    "sheet_count": total,
                    "dep_entries": len(yaml_deps),
                },
            )
            # Deps are already sheet-level.  Ensure every sheet has an entry
            # (sheets not in the map have no dependencies).
            deps: dict[int, list[int]] = {}
            for num in range(1, total + 1):
                deps[num] = list(yaml_deps.get(num, []))
            return deps

        # Dependencies are still stage-level (fan_out not yet applied, or
        # no fan-out declared).  Expand each stage-level dep to sheet level.
        _logger.debug(
            "extract_dependencies.expanding_stage_deps",
            extra={"stage_count": len(stage_sheets), "dep_edges": len(yaml_deps)},
        )
        deps = {}
        for stage, sheet_nums in stage_sheets.items():
            stage_deps: list[int] = yaml_deps.get(stage, [])
            # Expand: replace each dep-stage with ALL sheets in that stage
            expanded: list[int] = []
            for dep_stage in stage_deps:
                expanded.extend(stage_sheets.get(dep_stage, [dep_stage]))
            for sn in sheet_nums:
                deps[sn] = list(expanded)
        return deps

    # Fallback: linear chain (legacy behavior for scores without
    # explicit dependencies).
    _logger.debug(
        "extract_dependencies.linear_fallback",
        extra={"stage_count": len(stage_sheets)},
    )
    sorted_stages = sorted(stage_sheets.keys())
    deps = {}

    for i, stage in enumerate(sorted_stages):
        if i == 0:
            for num in stage_sheets[stage]:
                deps[num] = []
        else:
            prev_stage = sorted_stages[i - 1]
            prev_sheets = stage_sheets[prev_stage]
            for num in stage_sheets[stage]:
                deps[num] = list(prev_sheets)

    return deps