Skip to content

Runtime

robotsix_mill.runtime.api

FastAPI app = the management-plane service.

It owns the DB, the in-process worker, and the HTTP surface the CLI (and a future web frontend) use. Emitting a ticket enqueues it; the worker picks it up immediately and chains it through the pipeline.

build_secure_headers

build_secure_headers()

Return the OWASP security-header set (robotsix-standards http-security-headers.md): Preset.BALANCED plus no-store.

CSP relaxations — all here, at the single registration site: the board HTML uses inline onclick= handlers and an inline module script, and loads marked (and FastAPI's /docs Swagger UI) from cdn.jsdelivr.net.

create_app

create_app(repos, settings=None, single_repo_id=None)

Build and return a fully-wired FastAPI application.

repos is the :class:ReposRegistry holding all configured repos. settings may be None, in which case Settings() (from env) is used. single_repo_id scopes the process to one repo (optional; when None the process serves all repos). The returned app has all routes registered and the lifespan configured.

robotsix_mill.runtime.worker

Event-driven worker. No scheduler.

A ticket is enqueued the moment it is emitted (or transitions into an actionable state). A consumer pulls it and chains stages — draft → … → done — until it hits a terminal state, a stub, or an error. A bounded pool of consumers (MILL_MAX_CONCURRENCY) runs distinct tickets in parallel; a dedupe set guarantees one ticket is never processed by two consumers at once (one ticket's stages still run sequentially within its own consumer).

This package was split from a single worker.py module into focused submodules organized by responsibility. This __init__ re-exports the full public + internal symbol surface so existing import sites keep resolving unchanged.

Worker

Bases: PeriodicPassesMixin, PollLoopsMixin

In-process queue + consumer task, owned by the API service.

queue_size

queue_size()

Aggregate ticket count across all per-repo queues.

queue_join async

queue_join()

Wait for every per-repo queue to drain.

set_drain

set_drain(ttl_seconds=DEFAULT_DRAIN_TTL_SECONDS)

Arm drain mode: stop starting NEW heavy stages until ttl_seconds from now, while letting in-flight ones finish.

The caretaker calls this when it sees a pending image update, then deploys at the first drained tick and clears the flag via restart (in-memory state — a restart naturally clears it).

clear_drain

clear_drain()

Clear drain mode immediately (fail-open fast-path).

drain_active

drain_active()

Return True while drain mode is armed and not yet expired.

Expiry is checked and enforced lazily here (and in the dequeue loop) so a stale flag whose caretaker has vanished resumes normal intake after the TTL.

drain_status

drain_status()

Read-only drain snapshot for /system/drain and /health.

active — drain is armed and unexpired. drained — no heavy stage is currently in flight (the mill is at a deployable quiet point). active_stages — current stage names in flight, useful for the caretaker to see what remains.

enqueue

enqueue(ticket_id)

Enqueue ticket_id on its repo's queue with CURRENT priority AND stage rank.

Queue items are (priority_rank, stage_rank, seq, ticket_id). Sort order: priority tickets (rank 0) first; within priority class, later-pipeline tickets (lower stage_rank) first; FIFO within a (priority, stage) pair. The stage tie-break drains in-flight tickets through to terminal before starting fresh refines — keeps the board from piling up with intermediate states.

Priority AND stage are captured at enqueue time and the _pending set de-duplicates concurrent enqueues. If the ticket's priority or stage changes after enqueue, the pop-time sanity check in :meth:_run re-enqueues at the correct rank. Operators can also call :meth:requeue_with_current_priority to force a refresh explicitly.

requeue_with_current_priority

requeue_with_current_priority(ticket_id)

Force a re-enqueue that picks up the ticket's current priority from the DB.

Use this from callers that mutate Ticket.priority after the initial enqueue (the POST /tickets/{id}/priority route, any future stage transition that changes priority). Without it the stale enqueue entry stays at the OLD priority rank in the heap.

The OLD heap entry is NOT removed (Python's PriorityQueue doesn't support removal). When it eventually pops, the consumer's pop-time priority re-check (see _run) either accepts it at the current priority or re-enqueues it again — so duplicates are tolerated, not double-processed.

start

start()

Start all worker tasks: per-repo consumer pools, health monitoring, and periodic poll loops.

Idempotent — safe to call multiple times. On first call, spawns a global-semaphore-gated pool of _run consumer tasks per board (keyed by repos.yaml concurrency settings), the main _poll_loop, and a suite of periodic background tasks: trace-health, Langfuse cleanup, timeout escalation, meta-agent, run-health, diagnostic, stale-branch cleanup, orphaned-PR check, DB maintenance, sandbox reaper, CI-debt recheck, Dependabot ingest, credit-balance poll, CI monitor, and one periodic-supervisor task per repo.

reconcile_consumers async

reconcile_consumers()

Spawn consumer tasks for newly registered repos and cancel consumers for deregistered ones.

Called from POST /repos and DELETE /repos/{repo_id} so that runtime-registered boards are picked up immediately — without this a board registered after start() gets a queue (via the reconcile sweep's lazy _queue_for) but no consumer tasks, and tickets sit in DRAFT forever.

stop async

stop()

Stop all worker tasks: cancel consumers, periodic supervisors, and mid-flight periodic passes.

Waits for in-progress periodic passes (survey, audit, health, …) to finish within shutdown_grace_seconds before cancelling them. Then cancels every per-board consumer task and all periodic-supervisor tasks, awaiting their CancelledError completion.

requeue_unfinished

requeue_unfinished()

On startup, re-enqueue any ticket left mid-pipeline so a restart resumes work (idempotent: stages are re-entrant).

Spawns a background drip-feed task that enqueues matching tickets in batches (with a pause between batches) to avoid saturating the freshly-booted event loop. Returns immediately so lifespan startup is not blocked.

process_ticket async

process_ticket(
    ticket_id, ctx, active_map=None, allowed_states=None
)

Drive one ticket through as many stages as possible, in order, until it reaches a terminal/waiting state or a stub stops the chain.

When allowed_states is given, the chain also stops as soon as the ticket leaves those states (the caller re-enqueues it so the next stage goes through normal admission).

robotsix_mill.runtime.deps

FastAPI Depends callables and standalone utilities for route handlers.

Replaces the closure helpers (_svc, _maybe_enqueue, _with_cost) that were previously defined inside create_app().

get_service

get_service(request)

Return the TicketService stored on app state during lifespan startup.

resolve_ticket_id

resolve_ticket_id(ticket_id, svc)

Resolve ticket_id — try exact match first, then suffix resolution.

Returns the full ticket ID on success. Raises HTTPException(404) when no ticket matches, and lets :class:AmbiguousTicketId propagate (caught by the registered exception handler → 409) when the suffix is ambiguous.

get_worker

get_worker(request)

Return the Worker stored on app state during lifespan startup.

get_settings

get_settings(request)

Return the Settings stored on app state during lifespan startup.

get_broadcaster

get_broadcaster(request)

Return the BoardBroadcaster stored on app state during lifespan startup.

get_run_registry

get_run_registry(request, repo_id=Query(None))

Return the per-repo RunRegistry (lifespan creates one per board). Routes that pass ?repo_id=X get X's registry; routes without that query fall back to app.state.run_registry — today the lead repo's, so legacy callers still record somewhere.

get_repos_registry

get_repos_registry(request)

Return the ReposRegistry stored on app state during lifespan startup.

maybe_enqueue

maybe_enqueue(ticket, worker)

Enqueue ticket on the worker if its state has a pipeline stage.

with_cost

with_cost(
    ticket, settings, *, blocking=True, repo_config=None
)

Populate cost_usd on ticket (in-place) from the Langfuse session.

Cost is NOT persisted — it lives in Langfuse; this is read-time only. Mutates and returns the same object.

When blocking=False the lookup is cache-only — returns the cached value if present, else 0.0, and never hits the network. Use this for list endpoints like /tickets which the board polls every 1s; otherwise N cold-cache tickets would issue N serial Langfuse HTTP calls and the response would take seconds.

When repo_config is provided, its Langfuse credentials are used for the cost lookup (per-repo isolation).

enrich_ticket_read

enrich_ticket_read(
    ticket,
    settings,
    service,
    *,
    blocking_cost=True,
    fetch_pr_url=True,
    repo_config=None,
)

Convert a :class:Ticket into a :class:TicketRead, populating cost_usd from Langfuse, computing origin_session_url, and resolving unmet dependencies.

blocking_cost=False makes the cost lookup cache-only — used by the polled /tickets list endpoint to avoid N serial Langfuse calls on a cold cache stalling the response past the next poll tick.

fetch_pr_url=False skips the per-ticket forge pr_status call entirely. Same problem class: with N review-state tickets in the list, N serial GitHub API calls would stall the response. The drawer (per-ticket GET) keeps the full lookup so the PR link is authoritative when the user actually opens a ticket.

repo_config is passed through to Langfuse lookups and the origin-session URL builder so per-repo project data is used. When None the global Secrets singleton is consulted.

robotsix_mill.runtime.lifespan

FastAPI lifespan management for robotsix-mill.

Provides setup_logging() (called once at import time) and create_lifespan(settings) which returns an async context manager suitable for FastAPI(lifespan=...).

setup_logging

setup_logging()

Surface robotsix_mill.* logs on stdout.

Without this, app logs (worker/audit/stages/notify) propagate to a root logger that uvicorn leaves handler-less, so they vanish from docker logs — masking failures (e.g. a silently-crashing /audit background thread). Idempotent.

create_lifespan

create_lifespan(settings, repos, single_repo_id=None)

Build a FastAPI lifespan callable that performs the same startup and shutdown steps as the original inline @asynccontextmanager:

  • Initialise the DB and tracing.
  • Construct TicketService, StageContext, and Worker.
  • Store them on app.state for route handlers.
  • Start the worker and requeue unfinished tickets.
  • On shutdown, gracefully stop the worker.

robotsix_mill.runtime.board_adapter

BoardAdapter implementation for robotsix-mill's Ticket model.

Implements the robotsix_board.BoardAdapter Protocol so that robotsix-board's render_board() and render_config_script() can drive the mill kanban board.

MillBoardAdapter

BoardAdapter for mill's TicketRead objects.

Implements the robotsix_board.BoardAdapter Protocol.

columns

columns()

Return the ordered (status_key, label) pairs for the board.

card_id

card_id(card)

Return the ticket id.

card_title

card_title(card)

Return the ticket title.

card_badges

card_badges(card)

Return badge labels: priority, kind, and blocked status.

Source is NOT included here — it is rendered separately as source_badge in the card payload to avoid duplication.

card_timestamps

card_timestamps(card)

Return created / updated timestamps.

render_mode

render_mode()

Mill uses JSON_HYDRATION (FastAPI + board.js).

robotsix_mill.runtime.broadcaster

BoardBroadcaster — pushes ticket state changes to connected WebSocket clients so the board UI can update in real time without polling.

BoardBroadcaster

Manages connected WebSocket clients and broadcasts ticket updates.

Each connected client gets an asyncio.Queue. The synchronous broadcast_sync method is safe to call from any thread — it schedules the async broadcast on the event loop.

broadcast_sync

broadcast_sync(ticket, old_state='')

Schedule a broadcast of ticket to all connected clients.

Thread-safe: may be called from the worker threadpool as well as the main event-loop thread.

subscribe async

subscribe(initial_tickets)

Register a new WebSocket client.

Returns an asyncio.Queue that the client can iterate to receive broadcast messages. initial_tickets is sent as the first message (a ticket_list event) so the client doesn't need a separate HTTP fetch on connect.

unsubscribe

unsubscribe(q)

Remove a client queue (called on disconnect).

Routes

robotsix_mill.runtime.routes._agents

GET /agents — per-repo enabled on-demand agent names.

The board's "🤖 Agents ▾" dropdown lists the periodic agents a human can run on demand. On a repo-specific board the menu must show only the agents actually enabled for that repo, which mirrors the worker's _periodic_supervisor resolution: a periodic workflow runs for a repo iff the repo ships .robotsix-mill/periodic/<name>.yaml (presence = enabled, unless the YAML sets enabled: false) AND the fleet-wide Settings.<name>_interval_seconds is > 0 (0 = disabled).

This route is read-only and side-effect free — it never starts an agent.

list_enabled_agents

list_enabled_agents(
    request,
    repo_id=Query(None),
    repos=Depends(get_repos_registry),
)

Return the periodic-agent names enabled for repo_id.

When repo_id is missing, "all", or unknown, an empty list is returned — the per-repo agent run endpoints each target a single repo, so the aggregate board has nothing meaningful to offer (the frontend hides the dropdown there anyway).

robotsix_mill.runtime.routes._board

Board-specific HTTP endpoints for the robotsix-board integration.

Provides /board/cards (card list for JSON hydration).

There is deliberately no column-move route: the board chrome renders no move control, and all 22 mill columns are automated pipeline stages owned by the agent workflow / TicketService. A state change goes through POST /tickets/{id}/transition, which is the path the pipeline itself uses.

board_cards

board_cards(
    request,
    svc=Depends(get_service),
    settings=Depends(get_settings),
    include_closed=False,
)

Return all tickets as card objects for the board JS hydration.

Mirrors GET /tickets but returns the flat card shape expected by robotsix-board's board.js instead of the full TicketRead model.

include_closed defaults to False — terminal states (CLOSED, EPIC_CLOSED, ANSWERED) are excluded. Pass include_closed=true to retrieve them.

Closed and epic-closed cards are sorted by updated_at descending (most recent first); all other cards remain sorted by created_at ascending.

board_move

board_move(
    card_id,
    target_status,
    request,
    svc=Depends(get_service),
    worker=Depends(get_worker),
    settings=Depends(get_settings),
)

Move a card to a new column (robotsix-board move action).

Receives the POST from robotsix-board's board-card-move form (JSON_HYDRATION mode). Translates to a ticket state transition.

robotsix_mill.runtime.routes._candidates

AGENT.md candidate routes — list, validate, reject.

These endpoints expose the per-board AGENT_CANDIDATES.md file (written by the retrospect stage) to the board UI. Validating an entry files an audited-repo draft ticket whose body proposes the AGENT.md edit, then stamps the candidate's Status line so it's not surfaced again.

CandidateRead

Bases: BaseModel

JSON shape returned to the board UI.

list_candidates

list_candidates(
    request,
    repo_id="",
    include_acted=False,
    settings=Depends(get_settings),
)

List AGENT.md candidates for a repo.

By default returns only pending entries — validated and rejected candidates are kept in the file as an audit trail but the UI shouldn't re-surface them. Pass include_acted=true to fetch everything.

When repo_id is "all" (or empty) the candidates from every repo are aggregated into a single flat list, each tagged with its owning repo_id so the UI can target validate/reject at the correct per-board file. The synthetic "meta" board is skipped — it has no candidates file.

validate_candidate

validate_candidate(
    candidate_id,
    repo_id,
    request,
    settings=Depends(get_settings),
    worker=Depends(get_worker),
)

File the audited-repo draft ticket and stamp the candidate.

The ticket lands on the repo whose board owns the candidates file — same repo that retrospect was reviewing when it proposed the rule — so refine + implement clone the right tree and edit the right AGENT.md.

reject_candidate

reject_candidate(
    candidate_id,
    repo_id,
    request,
    settings=Depends(get_settings),
)

Mark the candidate rejected — no ticket is filed. The entry stays in the file as audit trail but the UI hides it on the next refresh.

robotsix_mill.runtime.routes._comments

Comment CRUD + thread management routes.

add_comment

add_comment(
    ticket_id,
    body,
    svc=Depends(get_service),
    settings=Depends(get_settings),
)

Add a comment to a ticket (any state).

Set parent_id to reply to an existing comment, forming a threaded discussion. Omit it (or pass null) to start a new top-level thread.

For epic tickets, the comment triggers a background re-processing: the epic is re-broken-down by the breakdown agent with the full comment history as operator direction, and net-new children are created. Non-epic tickets are unaffected — the comment is simply persisted.

list_comments

list_comments(ticket_id, svc=Depends(get_service))

List all comments for a ticket, ordered oldest-first.

close_thread

close_thread(
    comment_id, ticket_id=None, svc=Depends(get_service)
)

Close a top-level comment thread to mark it as resolved.

Pass ticket_id so the service resolves the correct per-board DB — Comment.id is per-board (not globally unique), so a bare comment_id lookup is ambiguous across repos.

close_thread_for_ticket

close_thread_for_ticket(
    ticket_id, comment_id, svc=Depends(get_service)
)

Close a comment thread that is scoped to a specific ticket.

Safety-gated for chat-agent use: only allows closing threads when the ticket is not in awaiting_user_reply. When the ticket IS in that state the thread represents a live question the state machine still depends on — closing it would silently discard a pending question and break the pipeline.

After closing the last open [ASK_USER] thread on a ticket that has already advanced past awaiting_user_reply, this also unblocks the merge path (POST /tickets/{id}/merge-now will no longer 409 on open threads).

reopen_thread

reopen_thread(
    comment_id, ticket_id=None, svc=Depends(get_service)
)

Reopen a previously-closed comment thread.

Pass ticket_id so the service resolves the correct per-board DB — Comment.id is per-board (not globally unique).

robotsix_mill.runtime.routes._epics

Epic creation and child-generation routes.

create_epic

create_epic(
    body,
    request,
    svc=Depends(get_service),
    settings=Depends(get_settings),
)

Create a new epic — accepts {"title": str, "description": str}.

An optional repo_id field scopes the epic to a specific repo's board. When omitted in single-repo mode the sole repo is used; in multi-repo mode repo_id is required and a 400 is returned if it is missing.

abandon_epic

abandon_epic(
    ticket_id,
    body,
    request,
    svc=Depends(get_service),
    settings=Depends(get_settings),
)

Abandon an EPIC_OPEN epic by transitioning it to EPIC_CLOSED.

The epic stops spawning children once abandoned (the re-eval worker skips EPIC_CLOSED epics). Accepts an optional actor field in the JSON body (defaults to "operator").

Returns 422 when the ticket is not in EPIC_OPEN state.

list_children

list_children(
    ticket_id,
    request,
    svc=Depends(get_service),
    settings=Depends(get_settings),
)

Return all tickets whose parent_id equals ticket_id.

generate_children

generate_children(
    ticket_id,
    request,
    svc=Depends(get_service),
    settings=Depends(get_settings),
    registry=Depends(get_run_registry),
)

Generate child tickets from an epic description using the LLM epic-breakdown agent. Returns 202 Accepted immediately — the agent runs in a background thread.

Returns 400 if the ticket is not an epic. Returns 404 if the ticket does not exist.

robotsix_mill.runtime.routes._health

Health, Langfuse status, repos, gates, board UI routes.

health async

health(request)

Liveness probe — deliberately async def.

A plain def route is dispatched through Starlette's shared thread pool, which mill's agent pipeline saturates with long-running asyncio.to_thread LLM calls under load. That starved this zero-I/O handler for up to 25s, intermittently failing Docker's own healthcheck and central-deploy's chat-skill probe.

health_ready async

health_ready(request, settings=Depends(get_settings))

Health-check endpoint that probes database connectivity, Langfuse observability status, and sandbox git-push bridge credential validity, returning a structured readiness response.

Parameters:

Name Type Description Default
request Request

The incoming FastAPI request, used to resolve the board_id from the repos registry.

required
settings Settings

Application settings injected via Depends(get_settings).

Depends(get_settings)

Returns:

Type Description
JSONResponse | dict[str, Any]

A dict with keys "status" ("ready" or "not_ready")

JSONResponse | dict[str, Any]

and "checks" (a list of per-component result dicts, each with

JSONResponse | dict[str, Any]

"name", "status" and "latency_ms"). When any check

JSONResponse | dict[str, Any]

reports "error" or "timeout" the endpoint returns a

JSONResponse | dict[str, Any]

JSONResponse with HTTP 503.

langfuse_status

langfuse_status()

Return recent Langfuse export failures so the UI can surface "tracing broken" without the operator having to grep worker logs.

Empty failures list means everything is shipping fine.

credit_status

credit_status()

Return the current low-OpenRouter-credit warning state.

Polled by the board UI's fetchCreditStatus() every refresh cycle. low is true when the balance is below the configured threshold OR a 402 insufficient-credit error was seen.

provider_status

provider_status()

Return llmio's provider-failover state for the board UI banner.

Polled by the board UI's fetchProviderStatus(). While failover_active is true, agent calls run on the fallback provider slot (paid OpenRouter) and return to the default (Anthropic) when the window expires — the banner makes that visible to the operator.

credential_status

credential_status(settings=Depends(get_settings))

Return which required credentials are missing from the live config.

Polled by the board UI's fetchCredentialStatus() every refresh cycle and rendered as a board-wide banner. ok is false when mill is missing a credential without which no ticket can advance — the fleet-wide cause behind what otherwise just looks like every ticket blocking on its own.

Deliberately not dismissible: unlike low credit, this is not a warning the operator can ride out.

credit_status_clear

credit_status_clear()

Dismiss the low-credit warning after the operator acknowledges it.

worker_status

worker_status(worker=Depends(get_worker))

Live worker introspection for diagnosing stuck tickets.

Reports per-board queue depth, the in-flight _pending set, and consumer-task health (incl. the exception of any task that died — a dead per-board consumer is why a ready ticket on that board would never be popped). Read-only.

langfuse_status_clear

langfuse_status_clear()

Drop the failure log after the operator acknowledges.

list_repos

list_repos(request, repos=Depends(get_repos_registry))

Return the registered repos for the UI repo selector.

No secrets (Langfuse keys) are included — repo_id, board_id and a credential-stripped forge_remote_url (so agent consumers like robotsix-chat can locate the code). In single-repo mode (--repo-id passed) only that repo is returned.

gates

gates(settings=Depends(get_settings))

Return the four pipeline gate flags from the live configuration.

Same open access model as /health — no auth. The board polls these every refresh cycle and renders them as header pills so the operator always sees which behavioural gates are active.

board

board()

Render the Mill board HTML page with card data and live-refresh configuration.

Returns a server-rendered HTML page: column skeletons are built server-side via build_board_skeleton, while individual ticket cards are hydrated client-side by board.js (JSON_HYDRATION) polling /board/cards every 5 seconds.

ws_board async

ws_board(websocket)

WebSocket endpoint for real-time board updates (live auto-refresh).

On connect, sends the full ticket list as the first message; subsequent messages are ticket_update events pushed by the broadcaster on each ticket transition.

Deps are read straight off websocket.app.state rather than via Depends(...): FastAPI cannot resolve HTTP Request-based dependencies for a WebSocket scope, so declaring them made the handshake fail with 403 before accept(). (This route also previously lived only in the unincluded legacy _misc.py, so it was never registered — which silently disabled the board's live auto-refresh.)

robotsix_mill.runtime.routes._passes

Background agent pass routes.

list_passes

list_passes(
    request, repo_id=None, repos=Depends(get_repos_registry)
)

Return all known periodic passes with their kind, label, and per-repo enabled status.

When repo_id is given and resolves to a known repo, each entry carries an enabled bool derived from the repo's presence files (same resolution as the worker's periodic supervisor). When repo_id is missing or "all", enabled is always False.

run_pass

run_pass(
    pass_id,
    repo_id=None,
    request=None,
    registry=Depends(get_run_registry),
)

Kick off a periodic pass in the BACKGROUND and return at once.

Looks up pass_id in the pass registry, imports its runner lazily, and launches it in a daemon thread. Works for both llm_agent and schedule_only passes.

robotsix_mill.runtime.routes._repo_helpers

Shared helpers for repo_id → board_id resolution.

robotsix_mill.runtime.routes._tickets

Core ticket lifecycle routes.

create_ticket

create_ticket(
    body,
    request,
    svc=Depends(get_service),
    worker=Depends(get_worker),
    settings=Depends(get_settings),
)

Create a new ticket (POST /tickets).

Resolves the board from body.repo_id, creates the ticket row plus workspace, enqueues it for the pipeline, and returns the enriched TicketRead. Returns 400 when the board cannot be resolved or the ticket data is invalid.

list_tickets

list_tickets(
    state=None,
    include_closed=False,
    repo_id=None,
    offset=0,
    limit=None,
    sort_by="created_at",
    created_after=None,
    updated_after=None,
    request=None,
    svc=Depends(get_service),
    settings=Depends(get_settings),
)

List tickets (GET /tickets).

Returns the active tickets, optionally filtered by state and repo_id. include_closed defaults to False — terminal states (CLOSED, EPIC_CLOSED, ANSWERED) are hidden; DONE stays visible (the transient retrospect window). Closed/terminal tickets are the overwhelming majority of rows (>90 % on a mature board) and are not useful for board operation, so loading + enriching them on every poll is the dominant cost behind an unresponsive board; callers that genuinely need them must opt in with include_closed=true. Enrichment is downgraded for performance — cost is cache-only and PR URLs are skipped — because the board polls this every few seconds. The Langfuse cost cache is warmed inline (parallelized via ThreadPoolExecutor) before enrichment, so every response shows real cost_usd values — not the misleading 0.0 that a pure background-task approach would return on cold caches.

An explicit state filter (e.g. state=closed) takes precedence over the default exclusion — the terminal state is removed from the exclusion set so the explicit filter works as expected.

Pagination

offset — rows to skip (default 0). limit — max rows to return (None = unbounded / all rows).

Sorting

sort_by — one of created_at, updated_at, title, state, priority, kind (default created_at).

Filtering

created_after — ISO-8601 UTC datetime string; only tickets created strictly after this instant are returned. updated_after — ISO-8601 UTC datetime string; only tickets whose updated_at is strictly after this instant are returned. Useful as a reconciliation mechanism for event subscribers that may have missed a delivery.

get_ticket

get_ticket(
    ticket_id,
    request,
    svc=Depends(get_service),
    settings=Depends(get_settings),
)

Return a single ticket (GET /tickets/{ticket_id}).

Returns the fully enriched TicketRead (with cost and PR link). Raises 404 when the ticket does not exist.

get_history

get_history(
    ticket_id,
    limit=Query(None, ge=1),
    offset=Query(0, ge=0),
    order=Query("asc", pattern="^(asc|desc)$"),
    svc=Depends(get_service),
)

Return event history for a ticket (GET /tickets/{ticket_id}/history).

Returns TicketEvent rows ordered by at. Query params:

  • limit — max events to return (unbounded when omitted).
  • offset — events to skip before the first returned event.
  • order — asc (chronological, default) or desc (most-recent-first — useful for retrieving the final event). Raises 404 when the ticket does not exist.

get_description

get_description(ticket_id, svc=Depends(get_service))

Return the current description for a ticket (GET /tickets/{ticket_id}/description).

Reads the description from the ticket's workspace on disk. Returns {"description": "..."}. Raises 404 when the ticket does not exist.

update_description

update_description(
    ticket_id, body, svc=Depends(get_service)
)

Update a ticket's spec description (PUT /tickets/{ticket_id}/description).

Replaces the ticket's description.md, recomputes the spec fingerprint so the implement stage's stale-respawn guard allows a fresh attempt, and records a history event with old/new fingerprint and author.

Body: {"description": "<new spec>", "reset_fingerprint_guard": false, "author": "operator"}.

Raises 404 when the ticket does not exist, 409 when the ticket is in a terminal state (CLOSED, ANSWERED, EPIC_CLOSED, DONE).

upload_screenshot async

upload_screenshot(
    ticket_id, file=File(...), svc=Depends(get_service)
)

Attach an image screenshot to a ticket for the refine agent to view.

Stores the bytes under the ticket's screenshots/ directory (a sibling of artifacts/ so a refine reset does not wipe user input). Rejects non-image uploads with 400 and unknown tickets with 404. The filename is reduced to its basename to prevent traversal.

get_retrospect

get_retrospect(ticket_id, svc=Depends(get_service))

Return the retrospect.md artifact for a ticket, or empty if retrospect has not run yet (or the artifact was lost). Lets the board surface what retrospect actually wrote — without this the DONE -> CLOSED transition looks like it happened with no reflection, even when retrospect did run and write real analysis.

list_artifacts

list_artifacts(ticket_id, svc=Depends(get_service))

List artifact files in this ticket's workspace.

Returns {"artifacts": [{"name": str, "size": int, "mtime": str}, ...]} sorted by mtime ascending. Used by the board UI's drawer to surface each agent's output — pre-v1 the implement / refine / retrospect markdowns only existed on disk.

get_artifact

get_artifact(ticket_id, name, svc=Depends(get_service))

Return the text content of a single artifact file.

Refuses path-traversal (.., /) so the route only serves files directly under the ticket's artifacts_dir. Binary files return decoded-with-replace text since the drawer renders markdown / JSON; a hex viewer can be added later if needed.

delete_ticket

delete_ticket(ticket_id, svc=Depends(get_service))

Hard-delete a ticket (row + history + workspace). Irreversible. 404 if it doesn't exist.

transition

transition(
    ticket_id,
    body,
    request,
    svc=Depends(get_service),
    worker=Depends(get_worker),
    settings=Depends(get_settings),
)

Transition a ticket to a new state (POST /tickets/{ticket_id}/transition).

Body: {"state": "<state>", "note": "<optional note>"}. Enqueues the ticket after transition so the pipeline picks it up. Returns the enriched TicketRead. Raises 404 when the ticket does not exist.

migrate_ticket

migrate_ticket(
    ticket_id,
    body,
    request,
    svc=Depends(get_service),
    worker=Depends(get_worker),
    settings=Depends(get_settings),
)

Move a ticket to another board (row, history, comments, workspace).

For tickets filed on the wrong board (the fix belongs to a different repo). The migrated ticket lands in DRAFT on the target board so its refine stage re-triages it there.

set_unblocks

set_unblocks(
    ticket_id,
    body=Body(...),
    request=None,
    svc=Depends(get_service),
    settings=Depends(get_settings),
)

Set the list of ticket IDs that ticket_id auto-unblocks when it completes (DONE/CLOSED/EPIC_CLOSED). Body: {"ticket_ids": [...]}.

Each listed ticket that is BLOCKED at that point is transitioned BLOCKED -> DRAFT. Cross-board safe. Returns the updated solver ticket.

edit_dependencies

edit_dependencies(
    ticket_id,
    request,
    body=Body(...),
    svc=Depends(get_service),
    worker=Depends(get_worker),
    settings=Depends(get_settings),
)

Replace or clear a ticket's own depends_on edges.

Body: {"depends_on": [...], "reason": "..."}. Validates the resulting dependency graph is acyclic — rejecting with 400 and naming the offending IDs otherwise — records the justification in GET /tickets/{id}/history, and (when the ticket is BLOCKED and clearing the edges leaves no unmet dependencies) unparks it back to its originating state so a follow-up resume-blocked is unnecessary. Returns the updated ticket.

approve_ticket

approve_ticket(
    ticket_id,
    request,
    svc=Depends(get_service),
    worker=Depends(get_worker),
    settings=Depends(get_settings),
)

Human approval for a ticket (POST /tickets/{ticket_id}/approve).

Transitions the ticket to READY and enqueues it so implement picks it up. If the ticket has an epic parent and a proposed epic body artifact exists (epic-body-proposed.md), that body is applied to the epic as a best-effort side effect. Returns 404 when the ticket does not exist.

robotsix_mill.runtime.routes._traces

Operational monitoring + traces routes.

list_runs

list_runs(
    repo_id=None,
    request=None,
    registry=Depends(get_run_registry),
)

Return recent background-run entries (newest first).

?repo_id=X returns X's runs. Without it (or ?repo_id=all) the aggregate view UNIONS every per-repo registry. Periodic runs (audit, bc_check, health, …) are recorded into the per-repo registry, not the lead repo's, so reading only the default registry would hide them on the all-repos board even though they show on the per-repo board.

list_active

list_active(
    repo_id=None, request=None, worker=Depends(get_worker)
)

Return tickets currently being processed by a pipeline stage.

?repo_id=X filters to active tickets belonging to that repo. When omitted, returns all (current behaviour preserved).

list_recent_traces

list_recent_traces(
    limit=10,
    min_cost=None,
    max_cost=None,
    settings=Depends(get_settings),
)

Return recent Langfuse traces, filtered by cost and limited in count. limit is clamped to 1–50; min_cost and max_cost are inclusive USD filters on totalCost.

Each trace now includes an observationSummary with per-trace token counts, model, tool-call list, and error/warning counts so fleet-level cost analysis can attribute spend without fetching every trace individually.

get_trace_detail

get_trace_detail(trace_id, settings=Depends(get_settings))

Return full Langfuse trace detail including all observations.

Callers that need the complete prompt/completion bodies, per- observation token usage, or raw cost-details should use this endpoint (one call per trace) rather than /traces/recent, which only returns aggregated summaries.