Skip to content

Core

robotsix_mill.core.service

TicketService — the management-plane API surface over the DB.

All state mutation goes through here so the API, the worker, and tests share one set of invariants (transition validation, history events, workspace pointer upkeep). DB access is synchronous; the worker calls it from its coroutine (never from the stage threadpool).

The implementation is split across responsibility mixins for navigability (this package was previously a single service.py module): read/query access (:mod:._queries), ticket creation (:mod:._create_mixin), state transitions (:mod:._transition_mixin), cross-board migration (:mod:._migrate_mixin), delete/redraft (:mod:._delete_mixin), DB maintenance (:mod:._maintenance_mixin), single-column metadata setters (:mod:._metadata), and comment/thread handling (:mod:._comments). The module-level helpers and :class:TransitionError live in :mod:._helpers. The concrete :class:TicketService is assembled here by multiple inheritance; the public import path robotsix_mill.core.service is unchanged.

AmbiguousTicketId

Bases: Exception

Multiple tickets matched the given short-ID suffix.

TransitionError

Bases: RuntimeError

Requested state transition is not allowed by the state machine.

TicketService

Bases: _CreateMixin, _TransitionMixin, _MigrateMixin, _DeleteMixin, _MaintenanceMixin, _QueryMixin, _MetadataMixin, _CommentMixin

Manage the ticket lifecycle over per-repo SQLite databases.

Central service for creating tickets, moving them through the state machine (raising :class:TransitionError on illegal transitions), persisting them to per-repo SQLite DBs, and keeping each ticket's :class:Workspace in sync. It is constructed from :class:Settings (which supplies the database path and the workspace root) and a board_id identifying the repository this instance is bound to; workspaces live under <data_dir>/<board_id>/workspaces/<ticket_id>/, routed via :meth:workspace.

Key method groups:

  • Reads — :meth:get (ID lookup with cross-repo fanout when board_id is empty), :meth:list, :meth:history, :meth:list_children, :meth:list_comments.
  • Lifecycle / writes — :meth:create, :meth:transition, :meth:delete, :meth:add_comment, :meth:add_history_note, :meth:redraft, :meth:request_changes, :meth:mark_done, :meth:close_thread, :meth:reopen_thread.
  • Relationships / metadata — :meth:set_parent, :meth:set_unblocks, :meth:set_depends_on, :meth:promote_to_epic, :meth:set_priority, :meth:set_title.

workspace

workspace(ticket)

Return the :class:Workspace for ticket.

Routed via :meth:Settings.workspaces_dir_for using the ticket's board_id (falling back to this service's board_id), so workspaces live under the per-repo subtree <data_dir>/<board_id>/workspaces/<ticket_id>/.

robotsix_mill.core.models

Management-plane data model (SQLModel / SQLite).

The DB is authoritative for management — state, history, queueing, relationships — and is what the API (and a future web frontend) read. The ticket body is not stored here: it lives in the filesystem workspace (description.md); the row keeps only workspace_path and content_hash as the pointer. SQLModel classes double as API schemas.

SourceKind

Bases: StrEnum

Enumeration of ticket origin sources (user, retrospect, audit, etc.).

TicketKind

Bases: StrEnum

Enumeration of ticket kinds — canonical source of truth for kind values.

Persisted as the canonical UPPERCASE member name via CaseTolerantEnum (below). State is the other name-mapped StrEnum and is intentionally left with its auto-generated Enum column — not in scope for this ticket.

CaseTolerantEnum

Bases: TypeDecorator[str]

Stores a StrEnum by its canonical UPPERCASE member name and tolerates any-case DB strings on read (legacy lowercase rows resolve cleanly).

WRITE Accept a TicketKind member or a str of any case → store the canonical uppercase member name. READ Upper-case the DB string before the enum NAME lookup so a legacy lowercase 'task' resolves to TicketKind.TASK.

process_bind_param

process_bind_param(value, dialect)

Convert value to its canonical uppercase member name for DB storage.

Accepts None (pass-through), an existing StrEnum member (stores its .name), or a str of any case (resolved to the canonical member name via uppercase lookup). Raises ValueError when the string does not match any member of the enum class.

process_result_value

process_result_value(value, dialect)

Restore a DB string to the corresponding StrEnum member.

Accepts None (pass-through) or a str — uppercased and resolved against self.enum_cls. Raises ValueError when the string does not match any member name.

Ticket

Bases: SQLModel

Database row for a ticket — tracks state, branch, cost, retries, and parent/child relationships.

TicketEvent

Bases: SQLModel

Append-only state-transition history with hash-chain integrity.

Comment

Bases: SQLModel

Reviewer comment on a ticket — supports threading via parent_id and open/closed tracking on top-level threads via closed_at.

TicketCreate

Bases: SQLModel

API request shape for creating a new ticket.

TicketTransition

Bases: SQLModel

API request shape for transitioning a ticket to a new state.

TicketMigrate

Bases: SQLModel

API request shape for migrating a ticket to another board.

TicketDescriptionUpdate

Bases: SQLModel

API request shape for updating a ticket's spec description.

TicketRead

Bases: SQLModel

API response shape for reading a ticket, including computed fields like unmet_deps and PR URL.

CommentCreate

Bases: SQLModel

API request shape for creating a comment (optionally threaded via parent_id).

CommentRead

Bases: SQLModel

API response shape for reading a comment.

Memory

Bases: SQLModel

Per-board, per-agent memory ledger row.

Replaces the file-based Markdown ledger with a DB-backed table so retention is enforced and the full file is never injected unbounded into agent prompts. Each row is one agent's ledger for one board.

robotsix_mill.core.states

The pipeline state machine.

Each active state is owned by exactly one stage, which consumes tickets in that state and transitions them onward. ERRORED and BLOCKED are side states reachable from any active state when a stage errors or escalates; they require human attention before re-entering the pipeline. HUMAN_ISSUE_APPROVAL is a human-wait state between refine and implement — it has no stage owner and pauses the chain until a human approves. IMPLEMENT_COMPLETE is an active state between DELIVERABLE and HUMAN_MR_APPROVAL: the PR exists but CI and mergeability gates have not been verified yet. The merge stage polls it and promotes the ticket to HUMAN_MR_APPROVAL (notifying the human) only when both CI is green and the PR is mergeable. If either gate degrades while the ticket is in HUMAN_MR_APPROVAL, the merge stage silently falls back to IMPLEMENT_COMPLETE so the robot can auto-fix before re-notifying. WAITING_AUTO_MERGE is an active state between HUMAN_MR_APPROVAL and DONE: the merge stage detects a mergeable PR whose CI is pending and auto-merge is eligible, then on each poll re-checks CI; when CI goes green it auto-merges to DONE, on CI failure or conflict it falls back to IMPLEMENT_COMPLETE, and on eligibility changes it returns to HUMAN_MR_APPROVAL. REBASING is an active state between IMPLEMENT_COMPLETE and IMPLEMENT_COMPLETE: the merge stage detects a conflicting PR — or a green-CI PR whose branch is behind the target under a strict up-to-date branch policy — and transitions to REBASING, then on the next poll runs the rebase agent and force-pushes the ticket branch. On success it returns to IMPLEMENT_COMPLETE for gate re-verification; on temporary failure it stays in REBASING for a retry; on exhaustion it escalates to BLOCKED. When the rebase succeeds but every implement-stage file's required change is already satisfied by origin/main (all files absent from the post-rebase diff are superseded), it closes the ticket as no-change (CLOSED) instead of blocking for a human decision. FIXING_CI is an active state between IMPLEMENT_COMPLETE and IMPLEMENT_COMPLETE: the merge stage detects a mergeable PR with failing CI and transitions to FIXING_CI, then on the next poll runs the CI-fix agent. On success it returns to IMPLEMENT_COMPLETE for gate re-verification; on failure it escalates to BLOCKED. ADDRESSING_REVIEW is an active state between HUMAN_MR_APPROVAL and HUMAN_MR_APPROVAL: the merge stage detects a PR with a human reviewer's "request changes" review and transitions to ADDRESSING_REVIEW, then on the next poll runs the review-revision agent. On success it returns to HUMAN_MR_APPROVAL for re-review; on failure with retries remaining it stays in ADDRESSING_REVIEW; on exhaustion it escalates to BLOCKED.

When a ticket is blocked, the state it was blocked from is recorded (Ticket.blocked_from). A human can resume the blocked ticket straight back to that originating state to re-run only the failed stage (no need to replay earlier stages). The existing BLOCKED → READY and BLOCKED → DRAFT transitions remain available as explicit human overrides that re-run the full downstream chain.

State

Bases: StrEnum

Ticket states in the pipeline lifecycle.

can_transition

can_transition(
    src, dst, blocked_from=None, paused_from=None
)

Return True if src → dst is a legal transition.

When src is BLOCKED, dst is also allowed when it matches the recorded blocked_from state (the resume path). The existing BLOCKED → READY and BLOCKED → DRAFT overrides are always available regardless of blocked_from. Additionally, BLOCKED → ASKED is allowed when resuming a blocked inquiry.

When src is AWAITING_USER_REPLY, dst is also allowed when it matches the recorded paused_from state (the resume path).

robotsix_mill.core.db

SQLite engine + schema lifecycle.

Per-repo databases: each registered repo gets its own SQLite file at <data_dir>/<board_id>/mill.db; the default <data_dir>/mill.db holds anything without a board_id (legacy / unmapped). Engines are cached process-wide, one per board.

check_same_thread=False because stage work runs in a threadpool while the worker coroutine owns DB access; all writes for a given board are still serialized through that board's single worker, so SQLite's single-writer model is respected.

Schema migration

SQLModel.metadata.create_all() creates tables on fresh databases. Alembic (alembic/) handles all subsequent schema changes — column additions, renames, type changes, and table restructures. The previous hand-rolled additive-migration system (sqlite_utils.py) is retained temporarily for reference but is no longer called; it will be removed once all deployments have transitioned.

DiskFullError

Bases: RuntimeError

Raised when a DB operation fails with a disk-full condition even after an emergency VACUUM + retry pass.

retry_on_db_full

retry_on_db_full(settings, board_id)

Context manager yielding a session whose commit() and flush() are wrapped with disk-full retry + emergency VACUUM.

Use as a drop-in replacement for db.session() at sites that call commit() or flush()::

with retry_on_db_full(settings, board_id) as s:
    s.add(ticket)
    s.commit()  # auto-retried on disk-full

get_engine

get_engine(settings, board_id)

Return the per-board SQLite engine, creating it on first call.

board_id is required — raises ValueError (via :func:_db_path) when empty.

init_db

init_db(settings, board_id)

Create tables (if missing) on the per-board DB and apply any pending Alembic migrations.

session

session(settings, board_id)

Return a new SQLModel Session bound to the per-board engine.

Lazily initializes the per-board schema on first access — so a fresh repo's DB is created on its first session() call without requiring an explicit init_db() at startup.

reset_engine

reset_engine()

Test hook: drop the cached engines so fresh DB paths are picked up.

Dispose each engine before dropping it so its pooled SQLite connections (and their file descriptors) are released. Without this every test that swaps the cache leaks an undisposed engine; across a full suite run those leaked file descriptors accumulate and eventually trip an "unable to open database file" / too-many-open- files error on whichever later test happens to cross the limit.

load_memory_db

load_memory_db(settings, board_id, name, max_chars=None)

Read name's memory ledger for board_id from the DB.

When max_chars is set and the content exceeds that limit, the oldest entries are dropped — only the most recent content (by newline alignment) is kept, with a truncation note prepended. Returns "" when no row exists for this (board_id, name) pair.

persist_memory_db

persist_memory_db(
    settings, board_id, name, text, max_chars=None
)

Write text as name's memory ledger for board_id to the DB.

Upserts the (board_id, name) row. On first write for a given row (no existing row), attempts a one-time migration from the legacy Markdown file (at settings.memory_file_for(name, board_id)) and renames the migrated file to <name>_memory.md.migrated.

Strips ephemeral sections, applies max_chars truncation (same as the file-based persist_memory), and updates updated_at.

robotsix_mill.core.workspace

Per-ticket filesystem workspace (the work plane).

File-canonical: description.md is the source of truth for the ticket body — agents read and rewrite it directly. The DB only stores the path and a content hash so the management plane can detect external edits.

Workspace

Per-ticket directory layout providing access to description.md, artifacts/, and repo/.

description_path property

description_path

Path to description.md — the canonical ticket body.

artifacts_dir property

artifacts_dir

Path to the artifacts/ subdirectory, creating it lazily on first access.

screenshots_dir property

screenshots_dir

Path to the screenshots/ subdirectory, creating it lazily on first access.

Kept as a sibling of artifacts/ (not under it) so user-supplied screenshots survive a refine restart-from-scratch, which wipes artifacts/ but must preserve user input.

repo_dir property

repo_dir

Path to the repo/ subdirectory (no creation side-effect).

list_screenshots

list_screenshots()

Return stored screenshot image files, sorted by name for determinism.

Returns [] when the screenshots/ directory is absent. Only files with a supported image extension (.png, .jpg, .jpeg, .gif, .webp) are included.

write_description

write_description(text)

Write text to description.md and return the new content hash.

read_description

read_description()

Return the text of description.md, or an empty string if absent.

content_hash

content_hash()

Return the SHA-256 hex digest of description.md, or an empty string if absent.

read_counter

read_counter(path)

Read an integer from path, returning 0 when the file is missing or unparseable.

write_counter

write_counter(path, value)

Write value to path, creating parent directories as needed.

read_spawn_exhaustion_marker

read_spawn_exhaustion_marker(ws)

Return (spec_fp, count) from the spawn-exhaustion marker.

Returns None when the marker is absent, malformed, or carries an empty fingerprint / non-positive count.

record_spawn_exhaustion_marker

record_spawn_exhaustion_marker(ws, spec_fp, count)

Write the spawn-exhaustion marker with the given fingerprint and count.

Creates the artifacts dir as needed. An OSError propagates — callers treat marker writes as best-effort (the event emission is already fail-safe).

clear_spawn_exhaustion_marker

clear_spawn_exhaustion_marker(ws)

Delete the spawn-exhaustion marker; silent when absent.

prune_clone

prune_clone(workspace)

Delete the repo/ subdirectory of workspace.

Idempotent – silently succeeds when repo/ is absent. Best-effort – any OSError is logged and swallowed; the caller continues as if pruning succeeded.

robotsix_mill.core.datetime_utils

Timezone-safe datetime helpers.


Why this module exists

SQLite has no native datetime type. SQLModel / SQLAlchemy store Python datetime objects as ISO-8601 strings but strip tzinfo on read-back. This means::

# Write: fully aware
ticket.updated_at = datetime.now(timezone.utc)

# Round-trip through SQLite: tzinfo is None
assert ticket.updated_at.tzinfo is None  # naive UTC

Any comparison between a tz-naive DB value and a tz-aware value (e.g., a freshly-built lookback_cutoff) raises::

TypeError: can't compare offset-naive and offset-aware datetimes

The TZDateTime type decorator (below) is the model-level fix: it stores all timestamps as naive UTC in the database and re-attaches timezone.utc on read-back, so application code always sees aware datetimes. _as_utc() remains as a defense-in-depth helper for any value that bypasses the ORM type machinery.

TZDateTime

Bases: TypeDecorator[datetime]

A SQLAlchemy column type that stores aware UTC datetimes as naive UTC in the database (compatible with SQLite, which has no native timezone support) and re-attaches timezone.utc on read-back.

from datetime import datetime, timezone tz_dt = TZDateTime() stored = tz_dt.process_bind_param( ... datetime(2025, 1, 1, tzinfo=timezone.utc), dialect=None ... ) stored.tzinfo is None True restored = tz_dt.process_result_value(stored, dialect=None) restored.tzinfo == timezone.utc True

process_bind_param

process_bind_param(value, dialect)

Convert value to naive UTC for SQLite storage.

Raises:

Type Description
TypeError

If value is timezone-naive.

process_result_value

process_result_value(value, dialect)

Re-attach timezone.utc to value on read-back from SQLite.

Returns:

Type Description
datetime | None

value with tzinfo=UTC, or None if value was None.

robotsix_mill.core.delta_context

Trimming helpers for retry/audit/re-refine passes.

When a stage re-invokes an agent on the same ticket (test-failure retry, reviewer sendback, re-refine), the agent already knows the full context from the first pass. Re-sending the full accumulated lifecycle context — spec, epic context, memory ledger, reference files — inflates every call. This module provides helpers to trim the context down to the delta: the specific failing item plus a minimal spec reminder.

trim_spec_for_retry

trim_spec_for_retry(spec, *, max_chars=800)

Return a minimal version of spec suitable for a retry pass.

Keeps the first max_chars characters, advancing to the next paragraph boundary so the truncation is clean. On a retry pass the agent already saw the full spec on the first pass; this reminder is just enough to re-orient it.

trim_draft_for_re_refine

trim_draft_for_re_refine(draft, *, max_chars=800)

Return a minimal version of draft for a refine re-refine pass.

Keeps the first max_chars characters, advancing to the next paragraph boundary. On a re-refine pass the agent only needs the reviewer's delta comments + a brief reminder of the draft's topic.

compact_message_history

compact_message_history(
    message_history, *, max_turns=8, summary_max_chars=3000
)

Cap a pydantic-ai message_history to the last max_turns tool exchanges, replacing the dropped prefix with a short rolling summary.

The implement resume path replays the full prior transcript, so the history grows with every tool turn (file dumps, git-diff output) until it dominates the request. This helper keeps the most recent max_turns assistant tool-call rounds and summarises everything older.

Only WHOLE tool turns are dropped: a ModelResponse carrying ToolCallParts and the immediately following ModelRequest carrying their ToolReturnParts are always removed together, so no tool return is ever orphaned from its tool call (a 400 failure mode on the OpenRouter capable tier). Conversations with no tool exchanges are returned unchanged, and the kept suffix always begins at the start of an assistant tool-call message so its returns follow intact.

robotsix_mill.core.duration

Human-readable duration parsing/formatting — stdlib-only.

Periodic-agent run intervals are ultimately consumed downstream as an integer number of seconds, but a raw 86400 carries no obvious meaning to an operator editing a YAML file. This module lets intervals be expressed in a compact, descending-order duration form::

1w2d3h40m10s   →  790810 seconds
1d             →  86400
12h            →  43200
90m            →  5400

Unit map: w = 604800s (week), d = 86400s (day), h = 3600s (hour), m = 60s (minute), s = 1s (second). Each unit may appear at most once, in descending order, with at least one unit present. A bare integer (or integer-as-string) is accepted unchanged and interpreted as seconds, so legacy raw-seconds YAML keeps working.

This module depends only on the stdlib (re) so it is importable without pulling in the agent runtime, matching the core/ convention.

parse_duration

parse_duration(value)

Parse value into a total number of seconds.

An int passes through unchanged (interpreted as seconds); bool is rejected. A string in the canonical descending-order form 1w2d3h40m10s (any subset of units, each at most once) is parsed to total seconds; a bare integer string (e.g. "3600") is accepted and treated as seconds. Surrounding whitespace is stripped.

Raises ValueError for negative values or malformed input (empty string, unknown unit, duplicate unit, non-numeric magnitude, no units), with a message naming the offending value.

format_duration

format_duration(seconds)

Render seconds as a compact duration string (inverse of :func:parse_duration).

Emits only the largest-to-smallest non-zero units (86400 -> "1d", 9010 -> "2h30m10s"); 0 renders as "0s". Raises ValueError for negative input. The round-trip property parse_duration(format_duration(n)) == n holds for any n >= 0.

robotsix_mill.core.text_utils

Text utilities — smart truncation and other string helpers.

truncate_at_boundary

truncate_at_boundary(text, max_chars)

Truncate text at the last strong boundary before max_chars.

If len(text) <= max_chars the string is returned unchanged. Otherwise the function scans text[:max_chars] for the last occurrence of any of these boundaries:

  • sentence-ending punctuation followed by whitespace: . ! ?
  • sentence-ending punctuation at end of line: .\\n !\\n ?\\n
  • paragraph break: \\n\\n
  • Markdown code-fence close: ```

Truncation happens after the boundary (the boundary itself is kept). If no boundary is found the function falls back to a hard cut at max_chars. When truncation does occur a note like \\n\\n[... description truncated; N chars omitted] is appended.

Returns:

Type Description
str

The (possibly truncated) string.

tail_keep

tail_keep(text, max_chars, *, label='content')

Keep the most-recent tail of text, dropping the oldest content.

If len(text) <= max_chars the string is returned unchanged. Otherwise the last max_chars characters are kept, advanced forward to the next newline boundary so the first kept line is complete, and a [... <label> truncated: N chars omitted] note is prepended.

This is the correct primitive for chronological logs / append-only ledgers where the newest content matters most — unlike :func:truncate_at_boundary, which keeps the HEAD.

Returns:

Type Description
str

The (possibly tail-truncated) string.

limit_diff_context

limit_diff_context(diff, context_lines)

Thin long context runs in a unified diff to context_lines per side.

Change lines (+/-), hunk headers (@@), file headers (---/+++) and other structural lines are preserved verbatim. Context lines (a single leading space) are capped to context_lines before and after each change; when lines are dropped an explicit [... N context lines omitted ...] marker is inserted. Hunk @@ line numbers are left as-is — the result is LLM review context, not an applicable patch.

context_lines <= 0 returns diff unchanged.

head_tail_keep

head_tail_keep(text, max_chars, *, label='content')

Keep a head slice and a tail slice of text, dropping the middle.

If max_chars == 0 or len(text) <= max_chars the string is returned unchanged. Otherwise the budget is split ~60% head / 40% tail; each slice is advanced to a line boundary so kept lines are complete, and the two are joined by an explicit marker line [... <label> truncated: N chars omitted from the middle ...].

Head+tail (not pure head or tail) is the correct primitive for git diffs: both the early and late files in the diff get representation, unlike :func:tail_keep (keeps only the end) or :func:truncate_at_boundary (keeps only the start).

Returns:

Type Description
str

The (possibly middle-truncated) string.