Skip to content

Agents

robotsix_mill.agents.base

pydantic-ai agent factory over OpenRouter.

pydantic_ai is imported lazily inside :func:build_agent so the core imports without the heavy LLM stack and runs offline. The main agent's model is ALWAYS the plain (non-:online) model — web search would otherwise bill a per-request surcharge on this expensive model. web=True instead exposes a single web_research tool that delegates to a cheap, bounded sub-agent (see :mod:.web_research) and returns only its conclusion. Skills are always injected into the prompt. _model_name and skill assembly are factored out so they're unit-testable without a key or pydantic_ai.

AgentHandle

Wraps a pydantic-ai Agent with its httpx client so callers can deterministically close the client after use.

Delegates attribute access to the underlying agent so existing code (including test mocks) works unchanged.

close

close()

Close the HTTP client. Idempotent; safe to call multiple times.

level_uses_claude

level_uses_claude(level)

Whether level currently routes to the Claude SDK provider.

Reflects the ACTIVE provider slot: llmio's for_level resolves the slot the failover tracker designates, so this flips to False for every level while provider failover is running on the OpenRouter slot.

new_openrouter_model

new_openrouter_model(model_name, level, *, slot=None)

Build a direct (model, http_client) for level via llmio.

llmio's get_provider_for_level resolves the provider for the given provider slot (None follows the failover tracker's active slot — default slot → keyless Claude SDK; fallback slot → keyed OpenRouter). Cost recording, the provider pin, and the per-level reasoning policy (level 1 → reasoning off, else xhigh) are all baked into the provider. The caller owns closing the returned client (pair with :func:_aclose_async_client).

build_openrouter_model

build_openrouter_model(level=1, *, online=False)

(model, http_client) for a direct (non-build_agent) model (web_research, web_knowledge, trace_inspector, consult_expert).

When level is an int, resolves the concrete model via llmio's tier defaults. When level is a str, it is used as the model name directly (with reasoning policy set to level 1). Appends :online when online (web search). Caller owns closing the client (pair with :func:_aclose_async_client).

build_subagent

build_subagent(
    settings,
    *,
    level,
    system_prompt,
    tools,
    name,
    max_tokens=None,
    workspace_root=None,
)

(agent, http_client) for a tool-bearing, text-output sub-agent (the explore scout) at capability level, bypassing :func:build_agent's mill-tool injection and prompt composition.

A raw pydantic_ai.Agent on a Claude tier cannot carry function tools (ClaudeSDKModel rejects them — the SDK runs its own tool loop), so Claude levels go through the llmio provider's build_agent exactly like :func:build_agent does: tools become injected MCP tools, the SDK's built-in Bash/Read/Edit/… are denied (builtin_tools=False) so the sub-agent stays as read-only as its tool list. max_tokens rides on the provider constructor there. The returned client is None on Claude tiers (the CLI is the transport); OpenRouter tiers return the httpx client the caller must close (pair with :func:_aclose_async_client).

build_agent_from_definition

build_agent_from_definition(
    settings,
    definition,
    *,
    tools=None,
    repo_dir=None,
    current_ticket_id="",
    web_knowledge_block_reason=None,
    **overrides,
)

Build an agent from an :class:AgentDefinition, bridging the YAML loader and the agent runtime.

Any keyword in **overrides that matches a :func:build_agent parameter name (system_prompt, model_name, output_type, web, report_issue, retries, name) replaces the value extracted from definition.

If repo_dir is provided and definition.inject_agent_md is True, the contents of AGENT.md (if it exists at the repo root) are injected into the system prompt as a <repo_conventions> block, placed after the role preamble but before the procedure steps.

compose_prompt

compose_prompt(
    settings,
    system_prompt,
    skills=None,
    modules=False,
    workflows=False,
    repo_dir=None,
)

Compose the final system prompt: the YAML system_prompt plus any skills sections.

Tool descriptions are NOT appended here. pydantic-ai already forwards each tool's signature + docstring to the model as a structured tools array on every API call, so a prose copy in the system prompt is pure duplication — same surface, twice the tokens, on every coordinator iteration.

build_agent

build_agent(
    settings,
    *,
    system_prompt,
    output_type=str,
    tools=None,
    web_knowledge=False,
    report_issue=True,
    read_ticket=False,
    list_epic_children=False,
    current_ticket_id="",
    reply_to_thread=True,
    close_thread=True,
    list_threads=True,
    ask_user=True,
    level=2,
    model=None,
    name=None,
    retries=2,
    max_tokens=None,
    skills=None,
    modules=False,
    workflows=False,
    board_id="",
    repo_dir=None,
    web_knowledge_block_reason=None,
    images=None,
    vision_api_key=None,
    slot=None,
)

Construct a pydantic-ai Agent for a capability level (1/2/3).

The level resolves to (transport, model) via llmio's baked tier defaults for the requested provider slot — None follows the slot the failover tracker designates as active, so this flips to the OpenRouter (fallback) slot automatically while provider failover is running. llmio's call_with_failover loop hands mill an explicit slot for each of its attempts; everything else resolves the active slot. The transport is what selects the backend — there is no separate toggle.

Set report_issue=False for agents that already emit draft tickets through their structured output (audit, retrospect).

images ((media_type, bytes) pairs) and vision_api_key are forwarded to the provider's build_agent: Claude SDK reads images natively; OpenRouter (DeepSeek) gets llmio's ask_image tool answered by the TierConfig.vision binding. The caller's prompt stays text-only — never embed BinaryContent when passing images=.

Note: for a structured output_type on a model whose provider rejects forced tool_choice, wrap it in PromptedOutput at the call site (the default ToolOutput mode 404s there).

Role agents

robotsix_mill.agents.auditing

The audit agent: meta-audit to identify gaps in quality/security tooling coverage.

Seam: tests monkeypatch run_audit_agent. Structured output so the runner has a clear result to work with.

robotsix_mill.agents.coding

Implement seam.

run_implement_agent is the single seam the implement stage drives (tests monkeypatch it). It runs ONE coordinator pass (see :mod:.coordinating): a capable model that explores via cheap sub-agents and edits the repo itself. The deterministic test→retry→escalate loop lives in the implement stage, which re-invokes this seam with a distilled feedback diagnosis after a failed test gate.

Budget/agent failures raise :class:AgentBudgetError / :class:AgentRunError so the stage blocks-as-resumable (a resume just re-runs the coordinator fresh — it re-explores, no transcript needed).

AgentBudgetError

Bases: RuntimeError

Usage/budget cap hit — operationally retryable.

conversation_state carries the serialized message history (all_messages_json() bytes) when available so the stage can persist it for a budget-exhaustion resume. It is None when the primary model raised UsageLimitExceeded mid-run (pydantic-ai does not expose partial state in the installed version).

AgentRunError

Bases: RuntimeError

Agent raised / could not converge — block-as-resumable.

cause carries the original exception so the implement stage can classify it (e.g. via transient_errors.classify_stage_exc) and route transient infra failures — OpenRouter timeouts, 5xx, 429 — to a retry-with-backoff instead of hard-BLOCK. Without the typed cause, the str-coerced wrap loses the exception's identity and every failure looks the same.

run_implement_agent

run_implement_agent(
    *,
    settings,
    repo_dir,
    spec,
    feedback=None,
    reference_files=None,
    message_history=None,
    memory="",
    epic_context="",
    previous_attempt_summary=None,
    board_id="",
    current_ticket_id="",
    language_instructions="",
    extra_roots=None,
    level=None,
    sandbox_image=None,
    stage_name="implement",
    target_branch="main",
    ci_log_fetch_fn=None,
    checkpoint=None,
)

Run ONE coordinator pass for this ticket. Returns (summary, reference_files, updated_memory, conversation_state, new_messages, no_change_needed, no_change_rationale, deferred_spec_items, deferred_verification_items). conversation_state is the full transcript (for resume); new_messages is only what this run added (for pause detection). The last two fields let implement signal "no edits needed, ticket is already satisfied" — see :class:ImplementResult for the routing contract.

feedback — set by the implement stage when it re-invokes after a failed test gate — is a distilled diagnosis of that failure, forwarded to the coordinator so the next pass fixes exactly it. reference_files — pre-loaded file content from the refine stage (reference_files.json), injected as synthetic read_file messages on the first coordinator pass so the model starts with those files already "read." message_history — advanced/test use: pre-built pydantic-ai message history passed through to the coordinator unchanged. previous_attempt_summary — the coordinator's summary from a prior pass, injected as a <previous_attempt> block on retries so the model doesn't undo its prior correct work. extra_roots — additional repo roots forwarded to the coordinator so the agent can read/write across multiple cloned repos (meta-board tickets). ci_log_fetch_fn — host-side forge probe that returns the job logs for a workflow run id (and full_log flag). When provided, the coordinator gets the fetch_ci_logs tool so it can autonomously pull a failing CI run's logs — e.g. to extract an OSV advisory id from a security-audit failure the sandbox cannot reproduce (api.osv.dev is not reachable from the agent's network). None (the default) still wires the tool, but every call reports the capability is unavailable. The implement agent is always the primary worker and can delegate to per-domain expert sub-agents via its consult_expert tool, with each expert keeping its own memory ledger.

robotsix_mill.agents.coordinating

The implement agent.

A capable model that reads and edits the repo ITSELF to satisfy ONE ticket. Each invocation is a single explore→read→edit pass — the implement stage owns the deterministic test→retry→escalate loop and re-invokes this agent with a distilled failure diagnosis when the suite fails. No separate implement sub-agent — that layer just re-explored everything and never converged.

run_coordinator is the seam coding.run_implement_agent drives (name kept for the stage/tests).

ImplementResult

Bases: BaseModel

Structured output from the implement (coordinator) agent.

ValidationResult

Bases: BaseModel

Deterministic routing decision for one implement iteration.

Produced by the implement stage after each test-gate run (NOT by the model). It is the single routing authority — it decides whether to deliver (proceed), re-invoke the coordinator (retry), or block the ticket (escalate).

decide classmethod

decide(*, passed, iterations, max_iters, feedback='')

Route deterministically from a test-gate outcome.

passed → proceed; a failure with attempts remaining → retry; a failure on the last allowed attempt → escalate. No LLM is involved — for any (passed, iterations, max_iters) triple the result is fixed.

run_coordinator

run_coordinator(
    *,
    settings,
    repo_dir,
    spec,
    memory="",
    level=None,
    feedback=None,
    epic_context="",
    reference_files=None,
    message_history=None,
    previous_attempt_summary=None,
    board_id="",
    current_ticket_id="",
    language_instructions="",
    extra_roots=None,
    sandbox_image=None,
    stage_name="implement",
    target_branch="main",
    ci_log_fetch_fn=None,
    checkpoint=None,
)

Run ONE explore→read→edit pass for the ticket and return the structured result.

The implement stage owns the deterministic test→retry→escalate loop; when it re-invokes after a failed test gate it passes feedback — a distilled diagnosis of the previous run's failure — which is appended to the prompt as a <test_failure> block. The partial edits from earlier passes persist on disk in repo_dir, so a retry continues from the current working tree. The seam tests monkeypatch this.

robotsix_mill.agents.testing

The test sub-agent.

Runs the project's test command in the isolated sandbox (mechanical, deterministic), then — on failure — a CHEAP model distills the raw output into a short, actionable diagnosis the coordinator can turn into the next precise implement instruction. The coordinator never sees the full log; its history stays short.

run_test_agent is the mockable seam.

diag_is_transient

diag_is_transient(diag)

Return True when a test/smoke diagnosis string signals a transient / environmental failure rather than a spec-determined one.

Covers the deterministic ENV-ERROR: diagnoses (missing binary, sandbox timeout, noexec tmpfs — see :func:_env_error_diag) and the sandbox/docker infrastructure signatures that can surface as a gate diagnosis. Callers that finalize a BLOCKED attempt use this to decide whether to persist a spec fingerprint: a transient terminal diagnosis means "did not run to a spec result", so no fingerprint is recorded and the next resume re-implements normally.

Conservative by construction: git failures from workspace setup and other typed exceptions are classified upstream by :func:robotsix_mill.runtime.transient_errors.classify_stage_error; this string matcher only fires on the infrastructure phrases that reach the coordinator as a diagnosis, never on a genuine assertion failure.

is_network_dependent_failure

is_network_dependent_failure(out)

Return True when out (raw test log or diag) shows a sandbox-hostile network signature — no real assertion failure.

Matches: connection refused/reset, DNS/name-resolution failures, and the empty-response JSONDecodeError (char 0 form only).

Conservative: a normal AssertionError or a JSONDecodeError on malformed (non-empty) data never matches.

is_resource_exhaustion_failure

is_resource_exhaustion_failure(out)

Return True when out (raw test log or diag) shows the sandbox memory cap killing the run — exit code 137 / SIGKILL / OOM — rather than a test assertion failing.

The implement sandbox runs with sandbox_memory (1g in prod) and a large suite can exceed it regardless of the code under test; live 2026-09-08 the mill repo's own pytest -q on main died at ~970 MB anon-rss (dmesg Memory cgroup out of memory: Killed process … pytest), the baseline gate read the exit code 137 diag as "pre-existing test failures on main", blocked the ticket and spawned a bogus baseline-fix ticket (fe7b → PR #3188 "moved an import to prevent rc=137").

Conservative: a plain AssertionError/FAILED line never matches; Killed is matched only at line start or as the kernel's Killed process N form so a test named test_killed does not.

run_test_agent

run_test_agent(
    *,
    settings,
    repo_dir,
    repo_config=None,
    retry_on_failure=False,
    file_map=None,
)

Run the test command in the sandbox. Return (passed, feedback). On pass, feedback is a short confirmation; on fail it is a cheap-model distilled, actionable diagnosis (NOT the raw log). Sandbox infra failure -> (False, "<reason>") so the coordinator can react.

retry_on_failure: re-run the suite ONCE before distilling a failure; a green re-run is reported as passing (flaky first run). The baseline gate sets this — one flaky test on main otherwise fabricates "pre-existing test failures on main", blocks the ticket AND spawns a bogus dependency-fix ticket (live case: a74b blocked on a test that passed when the distill agent re-ran it minutes later). The implement fix loop leaves it off: there the suite re-runs next iteration anyway, and doubling every red gate run would be pure cost.

file_map: an optional list of file paths the implement agent is permitted to change. When None, auto-discovered from repo_dir.parent / "artifacts" / "file_map.json" (the sibling convention of :class:~robotsix_mill.core.workspace.Workspace). Injected into the distill sub-agent's user message as a soft scope hint so the cheap model prefers fixes within declared scope — avoiding wasted implement iterations that the scope guardrail would REJECT. No effect when the test passes or when the failure is an ENV-ERROR (handled deterministically without the distill LLM).

Test command resolution (highest precedence first): the per-repo .robotsix-mill/config.yaml test_command committed in the clone wins when set (a managed repo owns its command), else settings.test_command (the fleet-wide global fallback). When both are empty the gate short-circuits to PASS — repos without a test suite (doc-only, etc.) need no opt-out flag. (repo_config no longer carries a per-repo test_command; it moved to the repo's own .robotsix-mill/config.yaml.)

smoke_paths_match

smoke_paths_match(changed_files, smoke_paths)

Return True when the smoke gate should run for changed_files.

Pure and side-effect-free (no sandbox / git) so it is unit-testable in isolation. An empty smoke_paths means "run unconditionally" (the gate is path-scoped only when globs are declared). Otherwise the gate runs when ANY changed file matches ANY glob.

Matching uses both :func:fnmatch.fnmatch and :meth:pathlib.PurePath.match against POSIX-style relative paths (as returned by git_ops.introduced_files) so directory-recursive patterns like src/robotsix_mill/runtime/** and shallow patterns like src/robotsix_mill/runtime/static/*.css both work.

run_smoke_agent

run_smoke_agent(
    *,
    settings,
    repo_dir,
    repo_config=None,
    retry_on_failure=False,
    file_map=None,
)

Run the smoke command in the sandbox. Return (passed, feedback). Closely mirrors :func:run_test_agent: on pass the feedback is a short confirmation; on fail it is a cheap-model distilled, actionable diagnosis (NOT the raw log). Sandbox infra failure -> (False, "<reason>") so the coordinator can react.

Smoke command resolution (highest precedence first): the per-repo .robotsix-mill/config.yaml smoke_command committed in the clone wins when set, else settings.smoke_command (the fleet-wide global fallback). When both are empty the gate short-circuits to PASS — the smoke gate is strictly opt-in, so a repo without a smoke command no-ops.

retry_on_failure: re-run the smoke command ONCE before distilling a failure (mirrors the test-gate flake guard).

file_map: mirrors :func:run_test_agent — auto-discovered from the sibling artifacts/file_map.json when None.

robotsix_mill.agents.documenting

Documentation agent: classifies diff impact and updates docs.

The agent reads the ticket spec + git diff, classifies the change as user-facing or internal-only, and — for user-facing changes — surveys the repo's existing docs and applies targeted surgical edits.

Returns a structured DocResult with user_facing and summary.

DocClassifierResult

Bases: BaseModel

Structured output from the cheap doc-classifier gate.

This is a separate type from DocResult — the classifier only classifies; it never edits docs.

DocResult

Bases: BaseModel

Structured output from the documentation agent.

run_doc_classifier

run_doc_classifier(*, settings, diff, spec)

Run the cheap doc-classifier gate.

Loads agent_definitions/doc_classifier.yaml, builds a zero-tool agent, and returns a DocClassifierResult classifying the change as user-facing or internal-only. The classifier is purely diff-and-spec-driven — it receives no tools.

Conservative bias: when uncertain, classifies as user-facing (the only real risk is a wrong "internal-only" that skips needed docs).

run_doc_agent

run_doc_agent(
    *,
    settings,
    repo_dir,
    diff,
    spec,
    level=None,
    extra_roots=None,
    board_id="",
    reference_files=None,
)

Build a documentation agent, classify diff + spec, and update docs for user-facing changes.

The agent receives the ticket spec and git diff. It surveys the repo's docs (README.md, docs/*, AGENT.md) and applies targeted edits for user-facing changes. Internal-only changes are a no-op.

When reference_files is provided, those repo-relative paths are pre-loaded into the agent's context via the same parallel-read_file preseed used by implement/review — the documenter usually has to read README.md and every changed source file to decide what to update, so handing those over up front skips one read_file round-trip per file.

A persistent memory ledger (settings.memory_file_for("doc", board_id)) records the repo's doc layout across runs so subsequent passes don't have to re-explore the structure from scratch.

robotsix_mill.agents.reviewing

Dual-model review agent: audits a git diff blind.

A second model (defaults to a different model than the implement agent) reviews the implementation diff with no access to the implement agent's context — only the diff and ticket spec. Returns a structured verdict: APPROVE / REQUEST_CHANGES / NEEDS_DISCUSSION.

ReviewAsk

Bases: BaseModel

One actionable change request, classified against ticket scope.

The review stage uses files_touched to split asks into in-scope vs out-of-scope (against the ticket's file_map.json) and routes them differently: in-scope asks become a single review comment and bounce the ticket to READY for another implement pass; each out-of-scope ask is materialised as a fresh dependency ticket and the current ticket is parked on those deps. This prevents the loop where scope-triage rejects edits that review legitimately demands.

ReviewVerdict

Bases: BaseModel

Structured output from the blind review agent.

changed_line_ranges_from_diff

changed_line_ranges_from_diff(diff)

Extract per-file changed line ranges from a unified diff.

Returns {path: [(start, end), …]} with 1-indexed inclusive ranges taken from each hunk's new-side @@ -a,b +c,d @@ header. Only genuinely MODIFIED files are included — a new file (old side -0,0) already has its entire content in the diff, and a deletion (new side +0,0) has no content left to excerpt, so both are skipped. Paths map to an empty list never appear.

run_review_agent

run_review_agent(
    *,
    settings,
    diff,
    spec,
    level=None,
    prior_context=None,
    repo_dir=None,
    reference_files=None,
    changed_line_ranges=None,
    screenshot_path=None,
    extra_roots=None,
    ticket_id="",
)

Run a blind review of diff against spec.

The agent receives ONLY the diff and spec — no implementation context, no memory, no history. Uses level if given, otherwise the level declared in review.yaml.

When prior_context is provided (prior review comments and the implement agent's rebuttal from the last round), it is injected before the ticket spec so the reviewer can avoid re-raising resolved issues.

When repo_dir is provided, the agent receives read-only filesystem tools (read_file and list_dir) sandboxed to that directory, allowing it to verify claims before raising them. run_command is deliberately excluded — even sandboxed, executing shell is not read-only.

When reference_files is provided (paths relative to repo_dir), each file's contents are preloaded as a synthetic read_file ToolCall / ToolReturn pair in the agent's message_history. The reviewer "wakes up" with those files already in context — saving one LLM round-trip per file (the "decide to call read_file → consume the result" cycle). Pass the union of the implement stage's ImplementResult.reference_files and paths parsed from the diff so the common case (reviewer wants every modified file) skips all its read_file round-trips.

When extra_roots is provided, those directories are added as secondary sandbox roots so the agent can also read_file and list_dir inside cloned sibling repositories (e.g. to verify reusable-workflow interfaces referenced in the diff). Paths outside repo_dir and outside every extra_roots entry are still rejected.

When screenshot_path is provided AND the file exists, its PNG bytes are passed to build_agent(images=[("image/png", bytes)], ...) with vision_api_key set to the OpenRouter key, so the model sees the rendered board alongside the diff. llmio delivers the image natively to the Claude SDK and answers via the TierConfig.vision binding for OpenRouter — the prompt itself stays text-only. A missing/unreadable screenshot degrades silently to the text-only path; it never alters routing or crashes review.

robotsix_mill.agents.refining

The refine agent: a capable model that authors the spec, grounded in the ACTUAL repo when a local clone is available.

When the refine stage has cloned the target repo it passes repo_dir; the agent then gets the cheap explore scout + read-only read_file/list_dir/run_command to ground the spec in real code (instead of web-fetching the project's own files — slow & indirect). run_command runs sandboxed, read-only commands (e.g. re-run failing tests when error output is truncated). web_research stays for genuinely external lookups only. With no repo (no forge configured) it falls back to draft-only as before. run_refine_agent is the seam tests monkeypatch.

ChildSpec

Bases: BaseModel

A split child.

FileMapEntry

Bases: BaseModel

A file relevant to the ticket, with a one-line note on its role.

RefineResult

Bases: BaseModel

Refine agent output.

is_internal_toolchain_failure

is_internal_toolchain_failure(draft)

Return True when draft text carries concrete internal CI/type/lint/test failure signals.

Designed as a refine-stage gate: when True the draft describes a local code fix scoped from the repo and logs, NOT an external knowledge gap. The caller uses this to disable ask_web_knowledge (web-search) and/or to short-circuit to a minimal spec.

The predicate is conservative — it requires at least one FAILURE-OUTPUT signature (traceback, pytest FAILED/summary, mypy error codes, lint codes, exit codes; see _INTERNAL_FAILURE_MARKERS). It deliberately does NOT match bare tool names (pytest/mypy/ruff/…): a normal feature spec routinely mentions those (e.g. "ship pytest tests"), and matching them mis-fired the refine short-circuit, replacing the real spec with a generic "fix the failing check" template.

run_refine_agent

run_refine_agent(
    *,
    settings,
    title,
    draft,
    repo_dir=None,
    repo_config=None,
    reviewer_comments=None,
    memory="",
    epic_context="",
    extra_roots=None,
    message_history=None,
    board_id="",
    current_ticket_id="",
    language_instructions="",
    deployed_log_summary="",
    deployed_log_dir=None,
    screenshot_paths=None,
    include_explore=True,
    include_parallel_explore=True,
    refine_level=None,
    refine_model=None,
    request_limit_override=None,
    triage_findings=None,
    standards_context="",
)

Return a structured RefineResult. When repo_dir is given the agent grounds the spec in that local clone via explore/ read_file/list_dir/run_command; otherwise it works draft-only. When reviewer_comments is given the agent incorporates the feedback into the refined spec.

message_history — when non-None, passed directly to agent.run_sync(…) so the agent continues from a prior paused conversation (the resume path after ask_user).

screenshot_paths — user-supplied image files attached to the ticket. Each readable image is passed to build_agent as native images=[(media_type, bytes), ...] with the OpenRouter key as vision_api_key so the model can see it on any transport (llmio delivers images natively to the Claude SDK and answers image questions via the injected ask_image tool on the OpenRouter vision binding). The prompt stays text-only. When screenshots are supplied but none can be read, a short text note tells the agent they exist instead.

standards_context — pre-fetched robotsix-standards content injected as read-only context so the agent can cross-check its spec against fleet-wide conventions (versioning/release, repo lifecycle, API patterns). When empty (fetch failure) the agent is told to note "standards context unavailable" in the spec.

Raises RuntimeError if no OpenRouter key is configured.

The returned RefineResult.conversation_state is the raw JSON bytes from all_messages_json() — None when the agent call didn't produce a message history. The stage runner uses it to detect ask_user pauses and persist the conversation for resume.

Return fields
  • split: whether the draft was split into children
  • spec_markdown: single-scope spec (when split=False)
  • children: list of ChildSpec (when split=True)
  • updated_memory: updated memory ledger
  • epic_body: revised epic description when <epic_context> was provided, otherwise None
  • conversation_state: raw conversation JSON for pause/resume

Sub-agents & utilities

robotsix_mill.agents.explore

The exploration sub-agent.

The cheap driver model has a LIMITED context window, so it must never read the repository directly. Instead it asks this sub-agent specific questions. The sub-agent gets its OWN fresh, bounded context plus read-only repo tools, does the navigating/reading, and returns only a concise answer (or the specific file contents the driver requested) — keeping the driver's context small.

run_explore is the mockable seam — tests monkeypatch it (no key / network), like the other agent seams.

is_explore_budget_exhausted

is_explore_budget_exhausted()

Return whether the explore-budget-exhausted sentinel is set.

mark_explore_budget_exhausted

mark_explore_budget_exhausted()

Set the explore-budget-exhausted sentinel.

Called by the explore sub-agent retry path when it exceeds UsageLimits.request_limit even after a bounded retry. coding.py checks this after the coordinator run.

reset_explore_budget_exhausted

reset_explore_budget_exhausted()

Reset the explore-budget-exhausted sentinel for the next coordinator run.

run_explore async

run_explore(
    *,
    settings,
    repo_dir,
    question,
    known_context=None,
    pre_seeded_paths=None,
    extra_roots=None,
)

Run the read-only exploration sub-agent against repo_dir and return its concise findings. Degrades to a short message instead of raising so the driver can react.

Async so it composes with whichever event loop is driving the parent coordinator: under the Claude SDK backend the explore tool callback fires inside the SDK's already-running loop, so the sub-agent is awaited via pydantic-ai's async agent.run rather than run_sync (which would call asyncio.run and raise "event loop is already running").

make_explore_tool

make_explore_tool(
    settings,
    repo_dir,
    extra_roots=None,
    pre_seeded_paths=None,
    explore_served_files=None,
)

Return the explore(question) closure.

Factory that creates a per-coordinator explore function wired to the given settings, repo directory, and extra roots, and registers itself in ToolRegistry so agents can discover it.

pre_seeded_paths lists reference-file paths the calling agent has already loaded into its own context; the factory forwards them to :func:run_explore so the scout is told NOT to re-read them. It is injected by the factory, not a parameter the LLM supplies.

explore_served_files is a shared mutable set of resolved file path strings. After each explore call, paths mentioned in the scout's response are added to this set so the coordinator's read_file can refuse redundant re-reads of the same content.

make_repo_scoped_explore_tool

make_repo_scoped_explore_tool(settings, repo_clones)

Return an explore(repo, question) closure for multi-repo agents.

The plain :func:make_explore_tool binds a single repo_dir (in a multi-repo workspace, the first clone), so every relative path the scout uses resolves against that one repo — it then reports the other repos as "empty". This variant takes the target repo as an explicit argument and scopes the scout to THAT repo's clone, so a cross-repo agent (e.g. meta) can reliably survey any selected repository.

make_parallel_explore_tool

make_parallel_explore_tool(
    settings,
    repo_dir,
    extra_roots=None,
    explore_served_files=None,
)

Return a parallel_explore(questions) closure that batches questions into a single scout call.

Before delegating to the full scout, each question is tested against a lightweight git grep pre-filter — if grep finds a small set of matching lines the result is returned directly, avoiding the scout's system-prompt token cost entirely.

Instead of spawning one independent :func:run_explore scout per question (each re-sending the ~68k-char system prompt), all remaining questions are batched into a single explore call so the system prompt is sent only once. The scout answers every question in one response, labeled by number. This cuts the input-token cost by a factor of N for N questions.

At most _PARALLEL_EXPLORE_BATCH_CAP questions are accepted per call (default 5) to bound the worst-case input context.

robotsix_mill.agents.web_research

Web research sub-agent.

The main (expensive) implement/refine agent must NOT run with OpenRouter's :online suffix — that bills a web-search surcharge on every request of a pricey model (a ~$3 ticket was traced to it). It also bloats the main context with raw pages.

Instead the main agent gets a single web_research(query) tool. Its body runs THIS small, cheap, bounded sub-agent — the only place :online + web_fetch live — and returns just a tight factual conclusion. Raw search results / pages never reach the main agent.

run_web_research is the single mockable seam: tests monkeypatch it (no real LLM/network), exactly like the other agent seams.

run_web_research async

run_web_research(*, settings, query)

Run the cheap research sub-agent for query and return only its conclusion string. Bounded by web_research_request_limit and a per-invocation web_research_fetch_max_calls cap. Never raises out — research failure degrades to a short message so the main agent can carry on.

robotsix_mill.agents.report_issue

A report_issue tool injected into every agent by build_agent.

Any agent (coordinator, rebase, ci-fix, audit, refine, explore, …) can file a draft ticket when it hits something that blocks or degrades it: a missing tool, an unrecoverable error, a workflow improvement, missing detail in its inputs, etc. The ticket is a normal source="agent" DRAFT, so it flows through refine (which dedups against existing work) and the human approval gate like any other draft.

Hard requirement: this must never spam. An agent stuck in a loop (the rebase ping-pong we just bounded is the cautionary tale) would otherwise file the same ticket hundreds of times. So the tool refuses to create a second ticket while a non-terminal one with the same title already exists — it reports back that the issue is already filed. It also suppresses a second ticket that references the same #<n> external PR/issue as a non-terminal ticket, so several isolated agent runs cannot each file a differently-worded review-disposition ticket about the same PR (see the three PR robotsix-mill#3150 tickets filed in ~2 minutes on 2026-09-11).

make_report_issue_tool

make_report_issue_tool(
    settings, *, agent_name=None, board_id=""
)

Return the report_issue closure bound to settings.

Lazily constructs a TicketService per call so this stays cheap to attach to every agent and hermetic for tests.

Parameters:

Name Type Description Default
settings Settings

The application settings instance.

required
agent_name str | None

If provided, stamped into the ticket body so the originating agent is identifiable at a glance (e.g. "run_tests"). When None or empty, the generic wording is used.

None
board_id str

The board the host agent is running for. Threaded through to the TicketService so issues filed from inside an auto-mail run land on the auto-mail board, not on the default DB. Empty string preserves the legacy single-repo behaviour.

''

robotsix_mill.agents.dedup

Pre-refine dedup / already-done check.

A single cheap LLM call that inspects a draft against existing tickets to decide whether it's a duplicate or already implemented. The refiner would be wasted on such drafts — this guard short-circuits them straight to CLOSED before the expensive agent runs.

run_dedup_check is the mockable seam — tests monkeypatch it just like run_refine_agent.

DedupResult

Bases: BaseModel

Structured output from the dedup check agent.

tokenize

tokenize(text)

Tokenize text for Jaccard similarity: lowercase, split on non-alphanumeric characters, keep tokens longer than 2 chars.

any_candidate_overlap

any_candidate_overlap(
    *, draft_title, draft_body, candidates_texts
)

True iff the draft shares at least one meaningful token with any candidate's title or body. Used to skip the LLM dedup call when no candidate could plausibly be a duplicate.

candidates_texts are the caller-assembled title+body strings for each candidate (kept as plain strings so this helper stays pure and unit-testable). Returns False for an empty candidate list or an empty draft token set; returns True on the first non-empty token intersection.

rank_candidates_by_similarity

rank_candidates_by_similarity(
    *, draft_title, draft_body, candidates, max_candidates
)

Return the top-max_candidates tickets ranked by Jaccard similarity to the draft.

When len(candidates) <= max_candidates, returns the list unchanged (no-op for small repos). Otherwise tokenizes the draft and each candidate's title, computes the Jaccard coefficient, sorts descending, and returns the top max_candidates.

run_dedup_check

run_dedup_check(
    *,
    settings,
    draft_title,
    draft_body,
    candidates_json,
    repo_dir=None,
)

Return {"duplicate_of": ..., "already_done": ..., "reason": ...}.

Degrades gracefully: on any exception, returns nulls with a failure reason — the guard is best-effort and never blocks the pipeline.

robotsix_mill.agents.fs_tools

Filesystem + shell tools for the implement agent, sandboxed to one repo directory.

Every path is resolved and checked to stay inside root so the agent cannot read or write outside the ticket's clone. run_command executes with cwd=root and a hard timeout. Tools are plain closures with type hints + docstrings — pydantic-ai derives the schema from those.

build_preseed_history

build_preseed_history(
    repo_dir,
    paths,
    *,
    user_prompt=None,
    max_files=20,
    max_total_bytes=200000,
    line_ranges=None,
    context_lines=0,
)

Build a synthetic message_history that pre-loads paths under repo_dir into the agent's context.

All paths share a single turn: one ModelResponse carrying N ToolCallParts for read_file and one matching ModelRequest carrying N ToolReturnParts with the contents. This is the parallel-tool-call shape every modern provider supports — the agent sees "I made N read_file calls in parallel and got N results in one batch" rather than N sequential one-call turns.

When user_prompt is provided, a leading ModelRequest carrying the prompt as a UserPromptPart is prepended to the history. The caller must then invoke agent.run_sync(None, message_history=...) (or with a different continuation prompt). The resulting conversation reads cleanly:

system → user (real prompt) → assistant (preload tool_calls)
→ user (tool returns) → assistant (model's actual response)

Without this restructuring pydantic-ai bundles the new user_prompt as a trailing TextPart inside the same ModelRequest as the tool returns, so the Langfuse "Formatted" view hides it and the model sees its own request only AFTER the tool-call exchange.

When line_ranges is provided (mapping repo-relative path → list of 1-indexed inclusive (start, end) changed ranges), each file is preloaded as EXCERPTS instead of its whole contents: every changed range is expanded by context_lines on each side, clamped to the file's extent, and merged, then emitted as one read_file call/return per merged range. Paths absent from line_ranges are skipped (the caller knows their content is already represented — e.g. a new file whose full body sits in the diff). This is the review-stage shape: bounded excerpts plus on-demand read_file replace the old whole-file preload.

Returns an empty list when paths is empty AND user_prompt is None.

Defensive checks: - Files that don't exist on disk are skipped (with a warning) so a deleted-file entry in the caller's list doesn't abort the run. - The combined payload is capped at max_files / max_total_bytes; paths past the cap are dropped (with a warning) so a huge diff can't blow the context window.

Used by: - implement (coordinating.py) — preloads reference_files the refine agent curated. - review (reviewing.py) — preloads excerpts around each file's changed regions instead of the whole modified file.

full_suite_pytest_segment

full_suite_pytest_segment(command)

Return the shell segment of command that runs pytest over the WHOLE suite, or None when every pytest invocation is targeted.

"Targeted" means at least one positional that is not a suite root (tests, ., …) — a file, a directory below the root, a node id — or a selection flag (-k, -m, --lf, --deselect, --collect-only…). Recognised launchers: pytest, py.test, python -m pytest, uv run [--frozen|--with X] pytest, .venv/bin/pytest. Segments are split on &&, ||, ; and | so uv run ruff check . && uv run pytest tests/x passes.

missing_lint_tool_result

missing_lint_tool_result(rc, out)

Return the structured skipped result when a linter binary is missing.

The shell exits 127 when a command is not found. If any missing command is a known lint tool, the lint did NOT run. The returned text starts with skipped: missing tool <name>, a fixed marker the review prompt treats as a blocking gap for .github/workflows/** changes. Returns None when no known lint tool is missing.

build_fs_tools

build_fs_tools(
    root,
    settings,
    *,
    pre_seeded=None,
    extra_roots=None,
    sandbox_image=None,
    read_file_max_calls=None,
    write_blocked_prefixes=None,
    explore_served_files=None,
)

Build the filesystem + shell tool closures sandboxed to root.

Returns the read_file, write_file, edit_file, delete_file, list_dir, and run_command tools as plain closures (pydantic-ai derives each tool's schema from its type hints + docstring). Every path is resolved and confined to root (or an entry in extra_roots) so the agent cannot read or write outside the ticket's clone, and the tools share an in-memory file-content cache for the lifetime of this call. Each tool is also registered in the :class:~.tool_registry.ToolRegistry catalog.

Parameters:

Name Type Description Default
root Path

The repository directory the tools are confined to.

required
settings Settings

Application configuration (controls e.g. lint_on_edit syntax checking and the run_command sandbox).

required
pre_seeded dict[Path, str] | None

Optional mapping of resolved Path to file content used to warm the shared read cache (e.g. the implement coordinator's reference files).

None
extra_roots list[Path] | None

Optional additional directories that resolved paths are also allowed to fall inside.

None
sandbox_image str | None

Optional per-repo sandbox image override forwarded to sandbox.run for the run_command tool. None → falls back to settings.sandbox_image.

None
read_file_max_calls int | None

Optional per-run hard cap on read_file calls. When set, the 1+read_file_max_calls th call returns an error string instead of reading the file. Default None (unbounded). The counter is per build_fs_tools invocation.

None
write_blocked_prefixes list[str] | None

Optional list of path prefixes that the write_file, edit_file, and delete_file tools are forbidden from touching. When a write/delete targets a path starting with any of these prefixes, the tool returns an error string instead of mutating the file. Default None (all writes allowed). Used by the document agent to block writes under www/, src/, and tests/ so that a document pass cannot overwrite source-code changes from implement.

None
explore_served_files set[str] | None

Optional set of resolved file path strings that the explore sub-agent has already loaded into the coordinator's context. When a read_file call targets a path present in this set (and the request covers the explored range), the tool returns a short "already in context" marker instead of re-reading the file from disk. Entries are invalidated on write_file / edit_file / delete_file so stale markers don't mask mutations. Shared across the coordinator and all explore sub-agents within one run_coordinator invocation.

None

Returns:

Type Description
list[Any]

A list of the seven tool closures, in the order read_file,

list[Any]

write_file, edit_file, delete_file, list_dir,

list[Any]

run_command, parallel_commands.

robotsix_mill.agents.web_tools

web_fetch tool: GET a URL via the dedicated network-enabled fetch sandbox (see sandbox.fetch — no repo/data mount, fixed curl).

Per-tool layering on top of the raw sandbox fetch:

  1. Per-run URL dedupe — fetches whose canonical URL (scheme + netloc
  2. path + query, fragment stripped) match a prior call return the cached response instantly. The trace that motivated this layer (d40e3c9d4fa5add80b2fe313c1d821f2) hit the same Python docs page twice in one refine pass, differing only in #fragment.

  3. HTML → text extraction — when the body looks like HTML the markup is stripped to whitespace-collapsed prose. A 315 KB docs page shrinks to ~80 KB of usable text. The agent gets the same information; the context costs ~1/4 as many tokens.

  4. Post-extraction cap — separate from the curl --max-filesize network cap, this bounds what the agent's context actually sees.

Operator can disable layers 1-2 by setting web.fetch_raw: true in the mill YAML config.

reset_web_fetch_budget

reset_web_fetch_budget()

Zero the per-consult web_fetch budget counters. Called at the start of each web-knowledge consult so the budget scopes to one ask_web_knowledge call across every web_research sub-agent it spawns.

reset_trace_web_fetch_budget

reset_trace_web_fetch_budget(max_calls, max_bytes)

Zero the per-survey-run web_fetch budget counters and store new caps.

Call with max_calls=0 AND max_bytes=0 to deactivate the trace budget (return to per-consult-only gating). The per-consult budget (reset_web_fetch_budget) is NOT affected by this call.

web_fetch_budget

web_fetch_budget()

Return the current (calls, bytes) consumed against the budget. Exposed for tests.

make_web_fetch

make_web_fetch(settings, *, max_calls=None, max_bytes=None)

Build the web_fetch tool exposed to web-knowledge agents.

The returned callable performs an http(s) GET via the dedicated network-enabled fetch sandbox (:func:sandbox.fetch) and layers per-run URL deduplication, HTML→text extraction, a post-extraction size cap, and a per-consult fetch budget on top of the raw fetch. Setting web.fetch_raw: true in the YAML config disables the dedup/extraction layers and returns the verbatim curl body.

Parameters:

Name Type Description Default
settings Settings

Application configuration — controls web_fetch_raw, the byte/call budgets (web_fetch_max_calls, web_fetch_max_total_bytes), and the text cap (web_fetch_max_text_bytes).

required
max_calls int | None

Optional override for web_fetch_max_calls (e.g. a tighter per-invocation cap from web_research).

None
max_bytes int | None

Optional override for web_fetch_max_total_bytes.

None

Returns:

Type Description
Callable[[str], str]

A web_fetch(url) closure returning the (possibly

Callable[[str], str]

extracted, capped, or cached) text content, or an error /

Callable[[str], str]

budget-exhausted sentinel string.

robotsix_mill.agents.bespoke

Generic LLM runner for bespoke per-repo periodic agents.

A bespoke agent is operator-authored YAML committed to a managed repo's source tree at <repo>/.robotsix-mill/agents/<name>.yaml. The YAML carries the entire prompt; everything else (tool palette, output shape, retry/usage limits, memory plumbing) is fixed in code so a managed repo can not turn arbitrary execution loose on mill.

Tool palette: explore, read_file, list_dir, and web_research (when web=true on the YAML). No write/edit/run tools. Drafts are emitted via structured output, not by a separate ticket-emission tool — keeps the agent loop short and the contract inspectable from outside.

BespokeResult

Bases: BaseModel

Structured output from one bespoke pass.

Shape intentionally mirrors :class:~.auditing.AuditResult so the shared :func:~..pass_runner.run_agent_pass boilerplate (memory persist + draft-ticket creation + dedup) accepts it without branching.

Prompt contract: draft_titles / draft_bodies are parallel lists, one entry per draft. By default every draft lands on the host repo's board. An audit that inspects other fleet repos must also set draft_repo_ids (parallel list, one registered repo_id per draft, "" for the host board) so each draft is filed on the audited repo's board; the runner stamps such drafts with Audited from: <host repo> / <agent name>.

run_bespoke_agent

run_bespoke_agent(
    *,
    settings,
    definition,
    memory="",
    recent_proposals="",
    verified_proposals="",
    repo_dir=None,
)

Execute one bespoke-agent pass.

Builds a pydantic-ai agent with:

  • the operator-authored definition.system_prompt as the entire system prompt (no shipped YAML merged in);
  • a read-only tool palette derived from repo_dir — explore, read_file, list_dir, and (when definition.web is True) web_research;
  • structured output of type :class:BespokeResult.

Bespoke agents never get write_file, edit_file, or run_command — those would let any managed-repo committer turn mill into a mutation engine. Drafts are emitted via the structured output and surfaced to the operator as DRAFT tickets on the repo's board.

robotsix_mill.agents.bespoke_loader

Loader for bespoke per-repo periodic-agent definitions.

A managed repo can carry repo-specific periodic agents in its own source tree at:

<repo_root>/.robotsix-mill/agents/<name>.yaml

Each YAML defines a single agent that mill schedules independently. The schema is intentionally smaller than AgentDefinition — bespoke agents don't need to wire output types, modules, or arbitrary tools; they share a single generic runner with a read-only tool palette plus draft emission via structured output.

Malformed YAMLs are skipped with a log warning (not raised). A managed repo MUST NOT be able to crash mill by committing a broken agent definition.

BespokeAgentDefinition

Bases: BaseModel

One bespoke per-repo periodic agent loaded from .robotsix-mill/agents/<name>.yaml.

load_bespoke_definitions

load_bespoke_definitions(repo_dir)

Return every well-formed bespoke definition found under <repo_dir>/.robotsix-mill/agents/*.yaml.

Returns an empty list when repo_dir is None, the agents directory does not exist, or every YAML is malformed. Each malformed file is skipped with a log.warning — the bespoke discovery surface MUST be no-op-safe for new managed repos and MUST NOT be able to take mill down with a typo.

robotsix_mill.agents.periodic_base

Shared pipeline for periodic agents.

Every periodic agent — audit, health, survey, bc_check, completeness_check, test_gap, copy_paste, agent_check — follows the same 7-step pipeline. This module provides the single :func:run_periodic_agent entry point that the eight thin wrappers delegate to.

PeriodicAgentResult

Bases: BaseModel

Shared structured-output model for the periodic gap-finding agents.

Agents whose result shape matches these six fields alias this class directly (e.g. AuditResult = PeriodicAgentResult); agents that add fields subclass it (e.g. AgentCheckResult adds findings).

load_periodic_system_prompt

load_periodic_system_prompt(name)

Load a periodic agent's static system prompt from its YAML definition without env-var resolution.

Resolves agent_definitions/periodic/<name>.yaml (relative to the package root) and returns its system_prompt value. Periodic agent modules re-export the result as a module-level SYSTEM_PROMPT for their test seams.

run_periodic_agent

run_periodic_agent(
    *,
    settings,
    definition_name,
    max_gaps,
    repo_dir,
    memory,
    recent_proposals,
    verified_proposals="",
    prompt_tail,
    include_forge_url=False,
    include_jscpd=False,
    include_workflow_caller_audit=False,
    include_run_command=False,
    include_parallel_commands=False,
    include_write_file=False,
    extra_roots=None,
    usage_limits=None,
    definition_override=None,
    max_errors=0,
    board_id="",
)

Run a periodic agent through the standard 7-step pipeline.

Parameters

settings: Application configuration. definition_name: Stem for the YAML path and overlay key. Must match a file in agent_definitions/periodic/<name>.yaml. max_gaps: Clipping constant for draft_titles, draft_bodies, and gap_ids on the final result. repo_dir: Optional path to the local repository clone. When not None, fs tools + explore (and optionally jscpd) are injected. memory: The agent's memory ledger as a Markdown string. recent_proposals: Prior proposals string from the pass runner. verified_proposals: Ephemeral verified-state table (rendered Markdown) recomputed from the ticket DB every pass and injected into the prompt between recent_proposals and memory. Passed separately — not concatenated onto memory — so it does not round-trip through the agent's updated_memory field into the persisted ledger. Empty string means no prior proposals to verify. prompt_tail: Agent-specific final sentence of the prompt. include_forge_url: When True, prepends a section("forge-remote-url", …) block after recent_proposals and before memory. include_jscpd: When True, appends make_jscpd_tool(repo_dir) to the tool list. include_workflow_caller_audit: When True, appends make_workflow_caller_audit_tool(repo_dir) — a deterministic detector for broken reusable-workflow callers (wrong org / missing permissions) — to the tool list. include_run_command: When True, adds "run_command" to the fs-tool name filter (default filter is {"read_file", "list_dir"}). include_write_file: When True, adds "write_file" to the fs-tool name filter (default filter is {"read_file", "list_dir"}). extra_roots: Forwarded to build_fs_tools(…, extra_roots=extra_roots). usage_limits: When not None, passed as usage_limits=… to agent.run_sync(prompt, …). max_errors: When > 0, tools are wrapped with a shared error counter that raises UsageLimitExceeded after max_errors tool-call errors — terminating runaway agent loops. Defaults to 0 (no error limit). board_id: The board the pass runs for. Threaded into the agent's read_ticket / list_recent_tickets / report_issue tools; without it they fail at call time with db._db_path: board_id is required (2026-10-22: every list_recent_tickets call of a triage_boilerplate pass).

Returns:

Any The output attribute of the run result — typically a Pydantic model with draft_titles, draft_bodies, gap_ids, and updated_memory fields, each clipped to max_gaps.

make_agent_runner

make_agent_runner(
    *,
    definition_name,
    prompt_tail,
    max_gaps=5,
    include_forge_url=False,
    include_jscpd=False,
    include_workflow_caller_audit=False,
    include_run_command=False,
    include_parallel_commands=False,
    include_write_file=False,
    dynamic_kwargs_fn=None,
    extra_kwargs=None,
)

Create a run_*_agent function with the standard periodic-agent signature.

The returned callable accepts (*, settings, memory, recent_proposals, verified_proposals, repo_dir=None, definition_override=None, board_id="") and delegates to :func:run_periodic_agent with the parameters captured at factory time. The model is resolved from the definition's level.

dynamic_kwargs_fn is called with settings at invocation time to produce extra keyword arguments for :func:run_periodic_agent — use it for settings-dependent parameters such as usage_limits and max_errors.

The returned function looks up run_periodic_agent at call time (module-level name lookup) so that monkeypatching periodic_base.run_periodic_agent in tests is honoured.

robotsix_mill.agents.periodic_loader

Per-repo periodic-workflow discovery + override resolution.

A managed repo declares which periodic workflows run against it by committing files into its own source tree at:

<repo_root>/.robotsix-mill/periodic/<name>.yaml

The PRESENCE of a file enables that workflow for the repo — there is no separate enable flag. A "periodic workflow" is the umbrella; an LLM agent is one kind of workflow (see WorkflowKind). "Agent" is reserved for the llm_agent kind.

Resolution by name
  • The name matches a built-in workflow → the file PARTIAL-MERGES over the built-in: only the fields present override; absent fields inherit. A name-only file just enables the built-in with its shipped parameters. The prompt overlay is handled in-file: prompt_overlay: appends to the built-in system prompt, system_prompt: fully replaces it (the two are mutually exclusive).
  • The name matches NO built-in → it defines a brand-new repo-specific agent (bespoke kind); it must carry a system_prompt.

Malformed files are skipped with a log.warning (never raised): a managed repo MUST NOT be able to crash mill by committing a broken file.

PeriodicWorkflowFile

Bases: BaseModel

A per-repo .robotsix-mill/periodic/<name>.yaml file.

Only name is required; every other field is optional and, when present, overrides the built-in of the same name (partial merge). For a brand-new (bespoke) workflow whose name matches no built-in, system_prompt is required (validated in :func:resolve_periodic_workflow, not here, so discovery can report a clear per-file reason).

ResolvedPeriodicWorkflow dataclass

One discovered + resolved per-repo periodic workflow.

PeriodicResolutionFailure dataclass

One per-repo periodic file that failed to resolve this cycle.

PeriodicResolutionFailureTracker

Cross-cycle state for per-repo periodic-config resolution failures.

The periodic supervisor owns one tracker per repo and calls :meth:observe once per discovery cycle with the failures seen this cycle. The tracker:

  • counts consecutive failures per file path;
  • self-moots — the instant a file resolves again or disappears, its count is dropped and it is un-reported, so a fixed or deleted file stops counting and never files (another) ticket;
  • rate-limits the warning log — WARNING on the first failure and again on the cycle a ticket is filed, DEBUG on the quiet cycles in between, replacing the every-cycle log.warning spam that previously required a human to notice;
  • returns the failures that have just crossed :data:RESOLUTION_FAILURE_TICKET_THRESHOLD so the caller can file a deduplicated board ticket (once per file).

observe

observe(failures)

Fold this cycle's failures into the tracker.

Returns the subset that just crossed the ticket threshold (empty on most cycles). Emits the rate-limited warning/debug log as a side effect.

validate_periodic_file_content

validate_periodic_file_content(name, system_prompt)

Return a list of human-readable error strings for a proposed presence file.

Empty list → valid. Callers MUST NOT write the file when errors are returned.

resolve_periodic_workflow

resolve_periodic_workflow(path)

Parse + resolve a single .robotsix-mill/periodic/<name>.yaml file.

Returns a :class:ResolvedPeriodicWorkflow, or None when the file is malformed / unsupported (a global_only name). Never raises — a bad file is logged and skipped so a managed repo can't take mill down.

discover_periodic_workflows

discover_periodic_workflows(repo_dir, *, failures=None)

Return every well-formed workflow under <repo_dir>/.robotsix-mill/periodic/.

Empty list when repo_dir is None or the directory is absent. Duplicate names: first file (alphabetical) wins.

Malformed / unresolvable files are skipped. When failures is provided, each dead-config file is appended to it (as a :class:PeriodicResolutionFailure) and NOT logged here — the caller (the periodic supervisor) owns rate-limited logging and deduplicated ticket-filing via :class:PeriodicResolutionFailureTracker. When failures is None (the read-only API routes), the legacy per-call log.warning is emitted instead.

Remaining agent modules

robotsix_mill.agents.agent_check

The agent-check agent: inspects agent definitions for internal coherence — tool–prompt mismatches, skill drift, metadata correctness, registration completeness, and prompt self-consistency.

Seam: tests monkeypatch run_agent_check_agent. Structured output so the runner has a clear result to work with.

AgentCheckResult

Bases: PeriodicAgentResult

Structured result of an agent-definition coherence pass.

Extends :class:~.periodic_base.PeriodicAgentResult (which carries the updated memory ledger and the parallel draft-ticket lists) with a findings field holding the human-readable narrative of the coherence issues the agent surfaced.

run_agent_check_agent

run_agent_check_agent(
    *,
    settings,
    repo_dir=None,
    definition_override=None,
    memory_dir=None,
    memory="",
    recent_proposals="",
    verified_proposals="",
)

Run the agent-definition coherence inspection pass.

Inspects agent definitions for internal coherence — tool–prompt mismatches, skill drift, metadata correctness, registration completeness, and prompt self-consistency — and returns a structured AgentCheckResult with draft tickets.

The agent is constructed via :func:~.periodic_base.run_periodic_agent.

Parameters:

Name Type Description Default
settings Settings

Application configuration.

required
repo_dir Path | None

Optional path to the local repository clone.

None
definition_override Any

Optional per-repo merged agent definition (resolved from .robotsix-mill/periodic/<name>.yaml) to pass through to the agent callable.

None
memory_dir Path | None

Optional extra root passed to build_fs_tools.

None
memory str

The agent's memory ledger.

''
recent_proposals str

Prior proposals from the pass runner.

''
verified_proposals str

Ephemeral verified-state table (rendered Markdown) recomputed from the ticket DB every pass and injected into the prompt. Empty string means no prior proposals to verify.

''

Returns:

Type Description
AgentCheckResult

An AgentCheckResult with findings, draft titles, bodies,

AgentCheckResult

and gap IDs clipped to MAX_GAPS (10) entries.

robotsix_mill.agents.answering

The answering agent: an investigative analyst that answers questions using all available tools — repo exploration, web research, and Langfuse trace data — and returns a free-form Markdown answer.

run_answer_agent is the mockable seam — tests monkeypatch it.

run_answer_agent

run_answer_agent(
    *,
    settings,
    title,
    question,
    repo_dir=None,
    repo_config=None,
)

Return a free-form Markdown answer string. When repo_dir is given the agent grounds its answer in that local clone via explore/read_file/list_dir/run_command. Always has web access (via web_knowledge flag) and Langfuse tools. Raises RuntimeError if no OpenRouter key is configured.

When repo_config is provided, its Langfuse credentials are forwarded to the Langfuse tools so the agent queries the repo's own Langfuse project instead of the global one.

robotsix_mill.agents.ask_user

A ask_user tool for agents to pause a ticket and ask the operator a clarifying question.

The refine and implement agents can call this tool when they hit ambiguity instead of guessing or declaring BLOCKED. It writes a structured comment with a [ASK_USER] marker, returns a sentinel string (__ASK_USER_PAUSE__) that the stage runner detects to transition the ticket into AWAITING_USER_REPLY, and is idempotent so a retrying agent can't spam duplicate comments.

make_ask_user_tool

make_ask_user_tool(settings, agent_name)

Return the ask_user closure bound to settings.

Parameters:

Name Type Description Default
settings Settings

The application settings instance.

required
agent_name str

Stamped as the comment author so the originating agent is identifiable (e.g. "implement").

required

robotsix_mill.agents.bc_check

The bc-check agent: scans the repository for backward-compatibility shims, no-op compat entry points, legacy property accessors, alias assignments, default-arg compat branches, and legacy shape fallbacks — then files draft tickets proposing cleanup for those that are ripe for removal.

Seam: tests monkeypatch run_bc_check_agent. Structured output so the runner has a clear result to work with.

BcCheckCoverage

Bases: BaseModel

What the scan actually reached, so a 0-draft run is verifiable.

BcCheckResult

Bases: PeriodicAgentResult

PeriodicAgentResult plus a coverage report of the scan.

robotsix_mill.agents.candidates

Parse and mutate AGENT_CANDIDATES.md — the per-board append-only queue retrospect writes to.

Each ### Proposed addition to <section> block becomes a structured Candidate so the board UI can list pending entries and act on them. validate(...) rewrites the block in place with a **Status:** validated → <ticket_id> line so the entry is recorded as acted-on; reject(...) does the same with rejected.

The file is the single source of truth: no sidecar JSON, no DB row. Keeping state inline preserves the human-readable format retrospect writes and means an operator can still hand-edit if needed.

candidate_id is a content hash (rule + proposed_at), not the file offset. That keeps IDs stable if retrospect prepends a fresh entry between a UI list-fetch and a UI button click.

Candidate dataclass

One ### Proposed addition block from AGENT_CANDIDATES.md.

candidates_path

candidates_path(data_dir, board_id)

Mirror retrospect.py's filename rule so a single source of truth backs both the writer and the UI reader.

load_candidates

load_candidates(path)

Parse every block in path. Returns [] when the file doesn't exist or is empty — the UI just shows an empty list.

update_status

update_status(
    path, candidate_id, new_status, filed_ticket=None
)

Rewrite the matching block's Status line in place.

Atomic: writes to a sibling .tmp then renames so a crash during write can't truncate the file. Returns the updated Candidate on success, None when no block with candidate_id exists.

prune_candidates

prune_candidates(path, max_entries)

Bounded-retention sweep for AGENT_CANDIDATES.md.

Drops resolved (validated/rejected) blocks oldest-first so the total kept block count is ≤ max_entries, while ALWAYS keeping every pending block (actionable entries must never be silently dropped). Resolved blocks carry their provenance on the **Status:** … → <ticket_id> line, so retaining the full block forever is pure bloat.

No-op (returns 0) when max_entries <= 0 (disabled) or the file does not exist. Returns the number of blocks dropped.

Kept blocks preserve their exact raw text (no re-serialization from the Candidate dataclass) so hand-edits/formatting survive. Rewrites atomically (tmp + rename), mirroring update_status; only rewrites when at least one block is dropped.

to_ticket_payload

to_ticket_payload(c)

Render the audited-repo ticket title + body for a validated candidate. Title stays short (~80 chars); body restates the rule, rationale, target section, and provenance so refine has full context when it runs.

robotsix_mill.agents.ci_fixing

CI-fix agent: auto-fixes failing remote CI checks on a PR branch.

Reads the failing check-run summary/details from the forge, inspects the affected files in the ticket's workspace clone, makes the minimal code change to fix the failure, runs the project's local tests, and commits.

The agent now DRIVES the full push flow via bridged git tools (git_fetch, git_remote_sha, git_push_with_lease, git_branch_ancestry) that the mill executes host-side with the per-repo token — the agent stays network-isolated and never sees credentials. On a lease rejection the agent inspects the remote ancestry and auto-recovers when the remote only carries its own prior push (no foreign commits).

CiFixResult

Bases: BaseModel

Structured output from the CI-fix agent.

run_ci_fix_agent

run_ci_fix_agent(
    *,
    settings,
    repo_dir,
    branch,
    failing_summary,
    memory="",
    previous_attempts="",
    ticket_id="",
    board_id="",
    target="main",
    remote_url=None,
    token=None,
    token_provider=None,
    token_cache_clear=None,
    ci_log_fetch_fn=None,
    sandbox_image=None,
    checkpoint=None,
    resume_history=None,
)

Run the CI-fix agent, which OWNS the fix→push→verify loop.

Uses the LLM (pydantic-ai agent) with sandboxed file + shell tools scoped to repo_dir, plus bridged git tools that execute host-side with remote_url and token so the agent can drive fetch + push.

The agent is ONE-SHOT: it fixes the failure, pushes, and reports DONE. It does NOT wait for CI verification — the orchestrator re-checks CI on the next poll cycle. If CI is still failing, the agent will be re-invoked with the new failure summary.

When ci_log_fetch_fn is provided, the agent also gets the fetch_ci_logs tool: it can fetch the logs for any workflow run by run id or URL, with an option for full (uncapped) logs. ci_log_fetch_fn is the host-side forge probe returning log text for a given run id and full_log flag.

Returns a CiFixResult with status, summary, and updated memory.

This is the mockable seam — tests monkeypatch it to avoid real LLM and Docker calls.

robotsix_mill.agents.ci_prevention_rules

CI prevention-rules reasoning core.

Turns a deterministic digest of a board's recent CI failures (grouped by semantic bucket, with root causes and how ci_fix resolved them) into a handful of short, imperative prevention rules for the implement agent.

The agent does NOT read the event store itself — the digest is built by runners.ci_prevention_rules_runner, which also owns writing the rules into the implement memory ledger. Built from the periodic YAML definition (agent_definitions/periodic/ci_prevention_rules.yaml) so a per-repo presence file can overlay the prompt; the YAML pins a small tier because the task is compression of an already-structured digest, not judgement.

CiPreventionRulesResult

Bases: BaseModel

Structured output from the ci_prevention_rules pass.

rules are short imperative sentences ("Run ruff format on changed files before stopping"), most impactful first. The runner clips the list to settings.ci_prevention_max_rules and drops blanks.

run_ci_prevention_rules_agent

run_ci_prevention_rules_agent(
    *, settings, digest, definition
)

Run the prevention-rules agent over a pre-built digest.

Parameters:

Name Type Description Default
settings Settings

Application configuration.

required
digest str

The deterministic per-bucket CI failure digest built by the runner.

required
definition Any

The (possibly overlaid) periodic agent definition.

required

Returns:

Type Description
CiPreventionRulesResult

A CiPreventionRulesResult; an infrastructure failure that yields

CiPreventionRulesResult

no output raises RuntimeError so the pass records an error run

CiPreventionRulesResult

instead of silently wiping the ledger section.

robotsix_mill.agents.ci_patterns

Structured CI pattern memory for the ci-fix agent.

Stores categorized fix attempts with success/failure stats in a JSON file, enabling the agent to look up proven approaches for recurring failure signatures without re-reading the entire Markdown ledger.

CiPatternEntry

Bases: BaseModel

A single CI-fix attempt, indexed by failure category and signature.

load_patterns

load_patterns(path)

Load pattern entries from path, returning [] on any error.

save_patterns

save_patterns(path, patterns)

Persist patterns to path, trimming to the most recent 50.

find_relevant_patterns

find_relevant_patterns(
    patterns, failing_summary, *, category=None, limit=3
)

Return recent patterns whose signature appears in failing_summary.

Matching is case-insensitive substring. When category is not None, only entries with a matching category are considered. Results are sorted by timestamp descending and capped at limit.

robotsix_mill.agents.close_thread

A close_thread tool for agents to close a comment thread.

The implement agent (and potentially others in the future) can use this to mark a top-level comment thread as resolved after addressing the feedback it contains.

make_close_thread_tool

make_close_thread_tool(settings, agent_name)

Return (close_thread, close_threads) closures bound to settings.

Parameters:

Name Type Description Default
settings Settings

The application settings instance.

required
agent_name str

Included for future per-agent authorisation or logging (currently unused).

required

robotsix_mill.agents.completeness_check

The completeness-check agent: inspects the repository for incomplete feature wiring — missing config mappings, missing defaults, routes with no button, runners with no CLI, and agent files with no caller — then files draft tickets proposing completion for each discovered gap.

Seam: tests monkeypatch run_completeness_check_agent. Structured output so the runner has a clear result to work with.

robotsix_mill.agents.config_syncing

The config-sync agent: config-drift detection across the JSON config layers.

The authoritative config source is the single committed template config/config.example.json (every non-secret knob with its default, plus a secrets: block of SECRET sentinels). The live file config/config.json (gitignored) is its real-valued counterpart. This agent cross-references the template against the src/robotsix_mill/config/ package (the Pydantic model that consumes it) and docs/config/configuration.md (when present) to catch drift: settings declared in code but missing from the JSON template, JSON keys with no matching field, documented defaults that disagree with the model defaults, etc.

Seam: tests monkeypatch run_config_sync_agent. Structured output so the runner has a clear result to work with.

ConfigSyncResult

Bases: BaseModel

Structured result of a config-sync drift inspection pass.

Carries the agent's updated_memory ledger plus three parallel lists describing newly-discovered config-drift gaps to file as draft tickets: draft_titles, draft_bodies, and the gap_ids used for dedup against the memory ledger.

run_config_sync_agent

run_config_sync_agent(
    *,
    settings,
    memory="",
    recent_proposals="",
    verified_proposals="",
    repo_dir=None,
)

Run the config-sync configuration drift inspection pass.

Inspects the config/ package, .env, and docs/config/configuration.md for missing, stale, and drifted settings and returns a structured ConfigSyncResult with draft tickets for newly-discovered gaps.

When repo_dir is provided, the agent gets filesystem tools (read_file, list_dir) and the explore scout tool so it can inspect the actual files. Without repo_dir the agent runs in a read-only reasoning mode (no repo access).

The agent is constructed via :func:~.base.build_agent with web=False (only reads local files), and level=1.

Execution is wrapped in :func:~.retry.call_with_retry, which handles transient network/model failures (exponential backoff: 2s base, 30s cap) and UsageLimitExceeded rate-limit errors (30s base, 120s cap with provider fallback after settings.rate_limit_fallback_retries consecutive failures).

Parameters:

Name Type Description Default
settings Settings

Application configuration — model names (config_sync_model), retry parameters, forge URL, and tool paths.

required
memory str

The agent's memory ledger as a Markdown string. Defaults to "" (the agent starts a fresh ledger).

''
recent_proposals str

Formatted block of recent proposals from the board, used for deduplication. Defaults to "".

''
verified_proposals str

Formatted block of verified (already-posted) proposals, used for deduplication. Defaults to "".

''
repo_dir Path | None

Optional path to the local repository clone. When not None, enables the explore, read_file, and list_dir tools.

None

Returns:

Type Description
ConfigSyncResult

A ConfigSyncResult with draft titles, bodies, and gap IDs

ConfigSyncResult

clipped to MAX_GAPS (5) entries, plus the updated memory

ConfigSyncResult

ledger.

robotsix_mill.agents.consult_expert

Domain expert consultation sub-agent.

The implement coordinator can call consult_expert(domain, question) to ask a domain expert a focused question. The expert is a read-only sub-agent with its own memory ledger — it answers the question and returns a concise string; it does NOT drive the ticket or touch the filesystem. The coordinator remains the sole author of every change.

The expert keeps its own per-domain, per-board memory ledger at <data_dir>/<board>/expert_<domain>_memory.md. The ledger is loaded into the expert's system prompt before each consultation and the expert may return an updated_memory field which the runner persists verbatim, so observations carry across consultations.

run_consult_expert is the single mockable seam: tests monkeypatch it (no real LLM), exactly like the other agent seams.

ExpertConsultResult

Bases: BaseModel

Structured output from a domain-expert consultation.

answer is the concise response handed back to the coordinator. updated_memory is the expert's revised memory ledger; the runner persists it verbatim when non-empty so future consultations of the same domain see the expert's accumulated knowledge.

run_consult_expert async

run_consult_expert(
    *, settings, repo_dir, domain, question, board_id=""
)

Run a read-only domain expert sub-agent for domain with question and return its answer string.

Bounded by consult_request_limit. Never raises out — failure degrades to a short message so the coordinator can carry on. Expert memory is loaded before the run and the expert's updated_memory (when non-empty) is persisted verbatim afterwards, so insights accumulate across consultations.

make_consult_expert_tool

make_consult_expert_tool(settings, repo_dir, board_id='')

Build the consult_expert tool exposed to the coordinator. It only ever returns the expert sub-agent's answer string.

robotsix_mill.agents.copy_pasting

The copy-paste agent: deterministic clone detection and triage.

Runs jscpd (via detect_duplication) to find copy-paste duplication, triages clone pairs by severity, cross-references against the memory ledger and recent-proposals, and files one draft ticket per high-severity clone pair.

Seam: tests monkeypatch run_copy_paste_agent. Structured output so the runner has a clear result to work with.

robotsix_mill.agents.epic_breakdown

Epic breakdown agent: reads an epic description and produces a list of well-scoped child tickets.

Seam: tests monkeypatch run_epic_breakdown_agent. The agent does NOT get filesystem access — it only sees the epic title + description.

EpicBreakdownResult

Bases: BaseModel

Structured result of breaking an epic into child tickets.

Holds parallel child_titles, child_bodies, and child_repo_ids lists (one entry per proposed child ticket) plus an optional epic_body carrying a revised epic description when the agent reworked it.

PromptedOutput describes the schema in the prompt but does not enforce it, and models (haiku AND opus alike, observed live) reliably emit the children under the natural keys titles / bodies rather than child_titles / child_bodies — which silently parsed to empty lists, so the epic spawned zero children. The validation_alias AliasChoices accept BOTH the canonical and the natural keys so the parse succeeds regardless of which the model emits; populate_by_name keeps construction by the field name working (tests, internal callers).

plan_child_dependencies

plan_child_dependencies(
    children,
    *,
    predecessor_id=None,
    child_board_id=None,
    create_child=None,
)

Compute depends_on edges for freshly-created epic children.

children is an ordered list of (child_id, title, body) tuples, one per newly-created child in agent order. predecessor_id, when given, is an existing sibling the new batch is appended after (the worker re-process path chains the batch onto the last existing child).

Default behaviour is the existing linear chain C0 → C1 → C2 … (each child depends on the previous), anchored to predecessor_id when supplied.

When the batch contains an init-repo child (a create/initialize- repository action that registers a brand-new repo in config/repos.yaml), the wiring changes: every OTHER child depends on that init-repo child instead, so the repo-populating siblings stay blocked (unmet_deps) until the init-repo child closes and the repo is registered. This stops a populating child from running — and misrouting its output to the wrong repo — before its target repo exists.

When child_board_id and create_child are both provided, the function also detects cross-repo producer→consumer dependencies among the children: if a consumer child (target repo B) imports symbols from a producer sibling repo (target repo A, A != B) that the consumer git-rev-pins, a synthetic bump-child ticket is created that bumps B's pin of A to include those symbols. The consumer depends on the bump child, and the bump child depends on the producer children, so the consumer stays blocked (unmet_deps) until the pin is bumped.

Returns a {child_id: [dep_id, …]} map covering only the children that gain an edge; callers apply it via set_depends_on.

run_epic_breakdown_agent

run_epic_breakdown_agent(
    *,
    settings,
    epic_title,
    epic_description,
    comments="",
    available_repos=None,
    epic_repo_id="",
)

Break an epic into well-scoped child tickets.

The agent receives only the epic title + description — no filesystem access. Returns a structured EpicBreakdownResult with parallel child_titles, child_bodies, and child_repo_ids lists, and an optional epic_body field with a revised epic description.

When comments is non-empty, the operator's comment history is appended to the prompt in an <operator_comments> block so the agent can follow the operator's explicit direction.

When available_repos is provided (a list of (repo_id, board_id) tuples), a section listing valid repo IDs is injected into the prompt so the agent can assign each child to the correct repo. epic_repo_id names the epic's own repo (the safe default for any child whose repo is unspecified).

The agent is constructed via :func:~.base.build_agent with PromptedOutput(EpicBreakdownResult), web=False, report_issue=False, and the epic_breakdown definition's level: 3 (Claude fable-5). Decomposition emits a structured PromptedOutput whose field names a cheap model (e.g. the audit_model tier — haiku under the Claude SDK backend) fails to honor: it returns the children under titles/bodies rather than child_titles/child_bodies, so the parser silently yields zero children. The default model is reliable here.

Execution is wrapped in :func:~.retry.call_with_retry for transient/rate-limit resilience, and in llmio's provider-failover loop for an unavailable provider. :func:_require_children is passed as the run's validator: a childless result is surfaced as a real error rather than an empty success.

robotsix_mill.agents.epic_status

Epic status agent: re-evaluates whether an epic's goal has been achieved given the current state of all its child tickets.

Seam: tests monkeypatch run_epic_status_agent. The agent does NOT get filesystem access — it only sees the structured data passed in by the caller.

EpicStatusResult

Bases: BaseModel

Structured verdict on whether an epic's goal has been achieved.

decision is the action to take on the epic (close, keep_open, update_description, or update_deps) and note is a human-readable rationale. The remaining optional fields carry the concrete mutations a decision may imply: dep_updates (per-child dependency rewrites), new_children (additional child tickets to file), child_rescopes (per-child title/body rewrites), and child_closures (a map of child ID -> the merged covering sibling whose delivered scope obsoletes it).

child_closures is a dict[child_id -> covering_sibling_id]. A legacy bare list[str] (child IDs with no named covering sibling) is still accepted for robustness and normalized by the worker — but such entries carry no covering sibling and are refused by the delivery-evidence gate.

run_epic_status_agent

run_epic_status_agent(
    *, settings, epic_title, epic_description, children
)

Evaluate whether an epic's goal has been achieved.

The agent receives the epic title + description and a list of child ticket summaries (each with id, title, state, and description). Returns a structured EpicStatusResult with a decision and a human-readable note.

The agent is constructed via :func:~.base.build_agent with PromptedOutput(EpicStatusResult), web=False, report_issue=False, and the epic_status definition's level: 1.

Execution is wrapped in :func:~.retry.call_with_retry for transient/rate-limit resilience.

robotsix_mill.agents.expert_loader

YAML loader for expert domain definitions.

Parses expert_definitions/<domain>.yaml, validates the result against the ExpertDefinition Pydantic model, and returns a structured object. Each definition declares a capability level (1/2/3) resolved by build_agent via llmio's tier defaults.

This module is independent of the agent runtime (build_agent, Settings, pydantic_ai) — it only depends on pydantic (already in the tree via pydantic-settings), PyYAML, and stdlib.

This is purely declarative: zero runtime integration. The ExpertManager that instantiates experts from these definitions is a separate future ticket.

ExpertMemoryConfig

Bases: BaseModel

Memory/retrieval tuning for an expert.

These parameters control how much context the expert loads and how the repo_map retriever splits/returns results. All fields are optional with sensible defaults — omit the memory key in YAML to get the defaults.

ExpertDefinition

Bases: BaseModel

A validated expert domain definition loaded from a YAML file.

Describes an expert's domain identity, module scope (via module_paths globs), custom instructions, model override, memory/retrieval tuning, tool allow-list, skills, and an extras dict for future extension.

All fields are validated at parse time. Unknown top-level keys are rejected (extra="forbid") — use extras for deliberate passthrough.

load_expert_definition

load_expert_definition(path)

Parse and validate an expert YAML definition.

path must point to a YAML file whose top-level keys map to ExpertDefinition fields.

Returns a validated ExpertDefinition instance.

Raises:

Type Description
FileNotFoundError

path does not exist (from Path.read_text()).

YAMLError

the file is not valid YAML.

ValidationError

a required field is missing, a value has the wrong type, or an unknown key is present.

robotsix_mill.agents.expert_manager

Expert lifecycle manager.

ExpertManager is the single runtime owner for expert agent instances. It loads declarative ExpertDefinition objects from YAML files in expert_definitions/ and instantiates, caches, retrieves, and cleans up the corresponding pydantic-ai agents.

Usage::

from robotsix_mill.agents.expert_manager import ExpertManager

mgr = ExpertManager(settings, repo_dir)
defs = mgr.load_definitions()          # {domain: ExpertDefinition}
py_agent = mgr.create_expert(defs["python-backend"])
# ... later ...
mgr.close_all()

ExpertManager

Single lifecycle owner for expert agent instances.

Loads ExpertDefinition objects from YAML files and lazily builds cached pydantic-ai agents on demand. Each domain maps to exactly one AgentHandle — repeated calls to create_expert for the same domain return the identical cached instance.

load_definitions

load_definitions(definitions_dir=None)

Scan definitions_dir for *.yaml files and return a dict of {domain: ExpertDefinition}.

definitions_dir defaults to the repo-root expert_definitions/ directory. Raises FileNotFoundError if the directory does not exist or contains no .yaml files (fail-fast at startup).

create_expert

create_expert(
    definition, *, output_type=None, memory_text=""
)

Build (or retrieve a cached) pydantic-ai agent for definition.

On first call per domain the agent is constructed via build_agent and cached; subsequent calls return the same AgentHandle object. The cache key is the domain alone — so if you pass a different output_type or memory_text to the second call, you'll still get the first call's cached agent. Callers that need a non-cached behaviour (e.g. a fresh memory block) should call :meth:remove_expert first.

Tool resolution maps the string names in definition.tools to actual pydantic-ai callables: - fs_tools (read_file, write_file, edit_file, delete_file, list_dir, run_command) are filtered from build_fs_tools. - explore is added via make_explore_tool when present.

The report_issue tool is always injected by build_agent (default report_issue=True).

Model: resolved from definition.level (default level 2).

output_type — when non-None, forwarded to build_agent so the expert returns structured output (e.g. PromptedOutput (ImplementResult)). When None (default), preserves the existing str-output behaviour for back-compat with callers that don't expect structured output.

memory_text — when non-empty, appended to the system prompt inside a <memory>…</memory> block so the expert can read its own ledger. When empty (default), no memory block is injected.

match_module_paths staticmethod

match_module_paths(module_paths, file_path)

Return True when file_path matches ANY pattern in module_paths.

file_path is expected to be a POSIX-style relative path (e.g. "src/robotsix_mill/agents/coordinating.py"). Empty module_paths returns False.

get_expert

get_expert(domain)

Return the cached agent for domain, or None.

Never triggers creation — use create_expert for that.

remove_expert

remove_expert(domain)

Close and discard the cached agent for domain.

Idempotent — a no-op when domain is not cached.

close_all

close_all()

Close every cached agent and clear the cache.

robotsix_mill.agents.freshness

Pre-refine freshness gate.

Verifies that file paths and line ranges cited in a ticket draft still exist on the current HEAD of the working branch. When the cited evidence has gone stale — upstream rewrite, sibling commit, or hallucinated finding — the ticket is short-circuited to DONE before the expensive refine agent runs.

The gate is deterministic (no LLM call): it extracts file paths from the draft text with regex and checks their existence on disk. A ticket is flagged stale only when it cites multiple file paths and the majority cannot be verified — a single missing path (possible typo) does not trigger the gate.

extract_cited_paths

extract_cited_paths(draft)

Extract cited file-like paths from draft.

Returns a de-duplicated list of raw path strings (which may include trailing :NN or :NN-NN line-range suffixes). When both a bare path and a line-range citation refer to the same file, only the more specific form (with line range) is kept.

run_freshness_check

run_freshness_check(*, draft, repo_dir)

Verify that cited file paths exist on HEAD.

Returns a dict with keys stale (bool) and reason (str). When stale is True the ticket should be short-circuited to DONE — the cited evidence no longer matches HEAD.

Degrades gracefully: on any error returns stale=False so the pipeline is never blocked by the freshness gate itself.

robotsix_mill.agents.health

The health agent: codebase-health inspection for module size, function length, documentation coverage, test gaps, complexity hotspots, and dead code.

Seam: tests monkeypatch run_health_agent. Structured output so the runner has a clear result to work with.

robotsix_mill.agents.jscpd_tool

detect_duplication agent tool — deterministic copy-paste detection via jscpd (AST/token-based clone detection).

Provides a reproducible, non-LLM detector to replace visual inspection for the audit agent. The tool scans the entire repo with jscpd and returns structured clone-pair data suitable for LLM consumption.

run_jscpd

run_jscpd(repo_dir)

Run jscpd and return a structured summary of clone pairs.

Returns a human-readable string with, for each clone pair: both file paths, line ranges (start–end), duplicated line count, and token count. If jscpd is unavailable or fails, returns a descriptive error string instead of raising.

make_jscpd_tool

make_jscpd_tool(repo_dir)

Create the detect_duplication tool closure.

Follows the same factory pattern as make_explore_tool: wraps run_jscpd in a closure and self-registers into ToolRegistry.

robotsix_mill.agents.langfuse_tools

Shared Langfuse tool factories for agents that need read-only access to Langfuse trace data.

Used by both the answer agent and the refine agent. The four simple tools (langfuse_session_summary, langfuse_list_traces, langfuse_trace_detail, langfuse_session_cost) do a single Langfuse API call each. The heavier langfuse_inspect_trace tool delegates to the trace-inspector sub-agent for deep analysis.

make_cost_inspect_tool

make_cost_inspect_tool(
    settings, repo_dir=None, repo_config=None
)

Build the inspect_cost tool closure.

When repo_dir is provided the tool is registered (repo-scoped, same gate as langfuse_inspect_trace). When repo_config is not None its Langfuse credentials are used for the read calls; otherwise the global :class:Secrets fallback applies. The tool returns a compact per-trace cost breakdown with provider attribution so the refine agent can surface discrepancies like "openrouter traces show $0 while the session total is non-zero" without guessing from source code alone.

render_trace_findings

render_trace_findings(findings, trace_id, error=None)

Render a list of TraceFinding objects as a Markdown inspection report.

make_langfuse_inspect_tool

make_langfuse_inspect_tool(
    settings, repo_dir=None, repo_config=None
)

Build the langfuse_inspect_trace tool closure.

When repo_dir is provided, the trace-inspector sub-agent gets read-only repo tools (read_file, list_dir, run_command, explore) so its findings can be grounded in the actual code. When None, the sub-agent runs tool-less (same as the existing retrospect trace_inspect path).

When repo_config is not None its Langfuse credentials are used to fetch the trace and resolve the inspector's read client; otherwise the global :class:Secrets fallback applies.

robotsix_mill.agents.list_threads

A list_threads tool for agents to discover top-level comment threads on the current ticket.

Without read_ticket access, agents that need to reply to threads (reply_to_thread) have no way to discover valid thread_id values. This lightweight tool fills that gap.

make_list_threads_tool

make_list_threads_tool(settings, agent_name)

Return the list_threads closure bound to settings.

Parameters:

Name Type Description Default
settings Settings

The application settings instance.

required
agent_name str

Included for future per-agent authorisation or logging (currently unused).

required

robotsix_mill.agents.module_curator

The module-curator agent: codebase-organization oversight.

Compares the live directory tree against docs/modules.yaml and emits draft tickets for detected drift — unclassified files, stale paths, and new-module proposals — including reorganization opportunities toward the per-module layout (src/<module>, docs/<module>, tests/<module>). System prompt and schema are loaded from agent_definitions/periodic/module_curator.yaml.

Seam: tests monkeypatch run_module_curator_agent. Structured output (ModuleCuratorResult) so the runner has a clear result to work with; draft lists are clipped to MAX_DRAFTS (20).

run_module_curator_agent

run_module_curator_agent(
    *,
    settings,
    memory="",
    recent_proposals="",
    verified_proposals="",
    repo_dir=None,
    definition_override=None,
)

Run the module-curator pass.

Compares the live directory tree against docs/modules.yaml, identifies drift (unclassified files, stale paths, new-module proposals), and returns a structured ModuleCuratorResult with draft tickets.

When repo_dir is provided, the agent gets filesystem tools (read_file, list_dir) and the explore scout tool so it can inspect the actual codebase. Without repo_dir the agent runs in a read-only reasoning mode (no repo access).

Parameters:

Name Type Description Default
settings Settings

Application configuration — model names (module_curator_model), retry parameters, and tool paths.

required
memory str

The agent's memory ledger as a Markdown string. Defaults to "" (the agent starts a fresh ledger).

''
recent_proposals str

Prior proposals from the pass runner.

''
verified_proposals str

Ephemeral verified-state table (rendered Markdown) recomputed from the ticket DB every pass and injected into the prompt. Empty string means no prior proposals to verify.

''
repo_dir Path | None

Optional path to the local repository clone.

None
definition_override Any

Optional per-repo merged agent definition (resolved from .robotsix-mill/periodic/<name>.yaml) to pass through to the agent callable.

None

Returns:

Type Description
ModuleCuratorResult

A ModuleCuratorResult with draft titles, bodies, and gap IDs

ModuleCuratorResult

clipped to MAX_DRAFTS (20) entries, plus the updated memory

ModuleCuratorResult

ledger.

robotsix_mill.agents.obsolescence

Pre-refine obsolescence gate.

A single cheap LLM call that re-evaluates whether a spawned follow-up or corrective draft's cited gap still exists on HEAD. When a draft is spawned from a prior-stage recommendation (doc-agent note, code-review suggestion) or a parent ticket's review, the cited gap (a missing doc section, a still-listed dependency, a grep that should return nothing) may already have been filled in place by a parallel/parent ticket before the draft reaches refine. This gate reads the cited files at HEAD and, when the gap is clearly already resolved, short-circuits the draft straight to DONE before the expensive refine agent runs.

run_obsolescence_check is the mockable seam — tests monkeypatch it just like run_dedup_check.

ObsolescenceResult

Bases: BaseModel

Structured output from the obsolescence check agent.

run_obsolescence_check

run_obsolescence_check(
    *, settings, draft_title, draft_body, repo_dir
)

Return {"obsolete": bool, "reason": str}.

Degrades gracefully: on any exception, returns obsolete=False with a failure reason — the gate is best-effort and never blocks the pipeline.

robotsix_mill.agents.overlays

Per-repo prompt overlays for generic periodic agents.

A managed repo can carry repo-specific prompt guidance for any of mill's generic periodic agents in its own source tree, under:

<repo_root>/.robotsix-mill/agent_overlays/<agent_name>.md

When mill clones the repo for a periodic pass, the overlay file (if present) is appended to the agent's shipped system prompt. The managed repo therefore owns its specialisation: clones, forks, and fresh mill deployments pick it up automatically.

Mill itself is one of the managed repos and ships its own overlays git-tracked at the same path in its source tree.

load_overlay

load_overlay(repo_dir, agent_name)

Return the per-repo overlay Markdown for agent_name, or "".

Looks at <repo_dir>/.robotsix-mill/agent_overlays/<agent_name>.md. Returns the file's contents stripped of surrounding whitespace. Returns "" when repo_dir is None (no clone available), the directory does not exist, or the file is absent — every branch must be a silent no-op so a repo with no .robotsix-mill/ folder behaves exactly as before.

apply_overlay

apply_overlay(system_prompt, overlay)

Append overlay to system_prompt with one blank line separator.

Empty overlay → system_prompt unchanged. Keeps the caller from having to know the formatting convention.

robotsix_mill.agents.post_comment

A post_comment tool for agents to post a top-level comment on the current ticket — no thread_id required.

Use case: a ticket whose deliverable is information rather than code. The implement agent reaches this when a spec says "post a comment summarising the findings" and the agent has nothing to edit. Without this tool the only comment-shaped surfaces are reply_to_thread (needs a parent thread) and close_thread (needs a comment id) — both useless for a fresh top-level comment. That mismatch produced ticket d129's bogus "what's the thread_id?" ASK_USER question.

The tool is idempotent on (ticket, author, body) so a retrying agent doesn't spam duplicates — the guard checks against every comment this agent has already posted on the ticket (surviving tool-closure rebuilds within a run), not just the most recent one. The author is stamped with the agent name (e.g. "implement") so the comment is traceable to the originating agent's run.

The tool is for substance only — never for progress/completion announcements. Post the deliverable summary exactly once; never post self-referential meta-comments ("Done.", "Delivered — see diff/summary thread X", "Ignore my previous comment", "(Stop-noise marker)"), and never append a "correction" of a comment already posted (there is no edit-in-place API — corrected content belongs in the agent's final structured summary, not a follow-up comment).

Prompt/docstring guidance proved unenforceable (ticket 20261121T042200Z: the implement agent still posted a deliverable summary plus 5-6 noise comments despite the written rules), so the tool enforces both constraints deterministically:

  • Per-(ticket, author) comment cap — the tool refuses to post once this agent has already posted max_comments comments on the ticket in the run (default 1; multi-finding info tickets pass 2-3). The count is taken from the persisted comments (author == agent_name), so the cap survives tool-closure rebuilds and retried passes, not just the in-memory seen-set.
  • Content guard — bodies that are pure self-referential meta-noise (bare "Done.", "Stand down — no further action.", "(no further replies)", "Delivered — see diff and summary thread X", "Ignore my previous comment", ...) are refused regardless of how the wording is varied, because the dedupe's byte-identical check cannot catch semantically-similar but textually-distinct noise.

A refusal is logged as a warning and recorded as a step event (history, never a comment) so the recurring violation stays observable; the refused content belongs in the agent's final structured summary — there is no edit-in-place API.

make_post_comment_tool

make_post_comment_tool(
    settings, agent_name, max_comments=1
)

Return the post_comment closure bound to settings.

Parameters:

Name Type Description Default
settings Settings

The application settings instance.

required
agent_name str

Stamped as the comment author so the originating agent is identifiable (e.g. "implement").

required
max_comments int

Per-(ticket, author) comment cap — the tool refuses to post once this agent has already posted this many comments on the ticket in the current run. Counted against the PERSISTED comments so the cap survives tool-closure rebuilds and retried passes. Default 1; multi-finding info tickets pass 2-3.

1

robotsix_mill.agents.prerequisite

Pre-implement prerequisite gate.

Verifies that external symbol/import prerequisites declared in a ticket spec are satisfiable in the cloned repo's environment BEFORE the expensive implement coordinator agent runs. When a spec depends on a symbol that must exist in an installed external dependency (e.g. an unmerged robotsix_llmio port) and that symbol is not yet importable, the ticket is short-circuited to BLOCKED — the work is still required once the upstream symbol lands.

The gate is deterministic (no LLM call): it parses a machine-readable ## Prerequisites / prereq block from the spec with regex and runs a bounded subprocess check per directive in the repo's Python environment. Two directive forms are supported — the grammar is kept small and conservative, like _SOURCE_EXTENSIONS in freshness.py:

  • import <module.dotted.path> — passes iff the module is importable.
  • symbol <Name> from <module.dotted.path> — passes iff from <module> import <Name> succeeds.

Lines that don't match either form are ignored (forward-compatible).

Directives whose module top-level package matches the target repo's own package name are skipped (treated as met, with a log line) — same-repo symbols are deliverables, not prerequisites.

parse_prerequisites

parse_prerequisites(spec)

Extract prerequisite directives from spec.

Returns a list of {"directive": <normalized str>, "code": <python -c snippet>} dicts — one per recognized directive line inside the prereq block under the ## Prerequisites heading. Returns [] when the section or block is absent / empty, or when no line matches a known directive form (prose and other code fences are ignored).

run_prerequisite_check

run_prerequisite_check(
    spec,
    repo_dir,
    *,
    runner=_default_runner,
    settings=None,
    sandbox_image=None,
)

Verify external symbol/import prerequisites declared in spec.

Returns {"unmet": [<directive strings>], "reason": <summary>}. An empty unmet list means the gate passed (proceed). Returns early (no unmet) when the ## Prerequisites section is absent or empty — most specs declare no prerequisites.

Degrades gracefully: on ANY error the gate returns an empty unmet so a checker fault never blocks a ticket — exactly as freshness.run_freshness_check does.

robotsix_mill.agents.prompt_blocks

Markdown-friendly section wrapper for user prompts.

Replaces the prior <ticket_spec>...</ticket_spec> XML-tag scaffolding that rendered as escaped text in Langfuse's Formatted view (and added zero structural value for human auditors). Sections are now framed by a 4-backtick fenced code block with a language hint matching the section name; a trailing HTML comment makes the close unambiguous to the model and stays invisible in any Markdown viewer::

````ticket-spec
## Problem
...
````
<!-- /ticket-spec -->

The 4-backtick outer fence is deliberate: the content (specs, diffs, reviewer feedback) routinely embeds triple-backtick code blocks, so a 3-backtick wrapper would close on the first inner fence and corrupt the block.

Convention: section names use kebab-case (a-z, hyphens) so the language hint reads naturally as ticket-spec / git-diff / reviewer-feedback.

section

section(name, content)

Wrap content in a 4-backtick fence with a closing comment marker.

See module docstring for layout and rationale.

robotsix_mill.agents.prompt_tool_consistency

Deterministic (no-LLM) guard: a prompt must not tell an agent to call a tool the agent's resolved tool set doesn't include.

Two prompt/tool mismatches shipped and were point-fixed (PR #755, the refine sendback override; PR #780, the implement review-feedback injection). In each the agent's prompt instructed the LLM to call a tool that the agent's resolved tool set never included, and nothing at build time asserted that the two stayed in sync — so the divergence surfaced only at runtime (a missing-tool error or a wasted operator round-trip). This module is that missing assertion.

The check is intentionally narrow to avoid false positives. It flags only an imperative call directive — a backtick-quoted tool name immediately followed by a parenthesised call, e.g. call `close_thread(comment_id)```. A bare backtick-quoted mention that is *not* a call — e.g. the disclaimer "you do not have a `close_thread` tool" — is deliberately NOT flagged. The trailing(`` is what distinguishes the two.

call_directive_tools

call_directive_tools(prompt)

Return the tool names that appear as `call(...)``` directives in prompt.

A bare backtick-quoted name with no following ( (e.g. a disclaimer) is not a call directive and is not returned.

unregistered_call_directives

unregistered_call_directives(
    prompt, resolved_tools, known_tools=None
)

Return the tools a prompt tells the agent to call that are absent from its resolved tool set.

resolved_tools — names of the tools actually wired into the agent (e.g. [t.__name__ for t in handle's tools]).

known_tools — optional catalog of real mill tool names. When given, only call directives naming a known mill tool are considered, so an unrelated parenthesised backtick span (example code, cast(...), section(...)) can't produce a false positive. When None every call directive is considered (the backtick-plus-parens pattern is the only guard).

strip_disabled_tool_directives

strip_disabled_tool_directives(prompt, disabled_tools)

Remove prompt lines that issue a \`tool(...)\ call directive for any tool in disabled_tools.

Companion to :func:unregistered_call_directives: when a tool is deliberately dropped from an agent's resolved tool set (refine's cost-gated explore sub-agents, the dedup check without a repo checkout) but the static prompt still tells the agent to call it, the build-time consistency guard raises ValueError. Stripping the offending lines keeps the guard satisfied and stops the agent being told to call a tool it no longer has.

A markdown bullet item whose block contains such a directive is removed wholesale (so a stripped bullet doesn't leave a dangling continuation); any other line containing a directive is removed too. A bare backtick mention (no trailing () is left intact — only call directives matter.

robotsix_mill.agents.read_ticket

A read_ticket tool injected into periodic agents via build_agent.

Periodic agents (audit, health, survey, test-gap, bc-check, agent-check, config-sync, retrospect) receive a <recent_proposals> block listing their past proposals with one-line summaries. When an agent needs the full context of a past proposal — its description, history, and comments — this tool provides it. It is the read-only counterpart to report_issue.

Hard requirement: read-only. The tool closure never calls create, transition, add_comment, set_branch, redraft, or any other mutating TicketService method. This is structurally enforced — the closure has no access to write methods.

make_read_ticket_tool

make_read_ticket_tool(settings, board_id='')

Return the read_ticket closure bound to settings.

Lazily constructs a TicketService per call so this stays cheap to attach to every agent and hermetic for tests.

Parameters:

Name Type Description Default
settings Settings

The application settings instance.

required
board_id str

The board (repo) whose ticket DB to read from. When empty the service fans out across every configured board, matching the <recent_proposals> block's cross-repo view.

''

make_list_recent_tickets_tool

make_list_recent_tickets_tool(settings, board_id='')

Return the list_recent_tickets closure bound to settings.

Lazily constructs a TicketService per call. Returns the same [STATE] id | title format as the prompt-injected <recent_proposals> block so agents have a programmatic enumeration path when that block is empty or stale.

Parameters:

Name Type Description Default
settings Settings

The application settings instance.

required
board_id str

The board (repo) whose ticket DB to enumerate. When empty the service falls back to the default repo, matching the <recent_proposals> block's cross-repo view.

''

robotsix_mill.agents.rebasing

Rebase agent: resolves merge conflicts on a stale PR branch.

Runs git rebase origin/<target> inside the ticket's existing workspace clone. On conflict it reads the conflicted files, edits them in place, and continues the rebase.

The agent now DRIVES the full push flow via bridged git tools (git_fetch, git_remote_sha, git_push_with_lease, git_branch_ancestry) that the mill executes host-side with the per-repo token — the agent stays network-isolated and never sees credentials. On a lease rejection the agent inspects the remote ancestry and auto-recovers when the remote only carries its own prior rebase push (no foreign commits).

Also hosts the rebase-supersede judge (:func:run_supersede_check): when the post-rebase integrity check reports implement-stage files absent from the diff, this LLM compares the ticket spec against the target's actual content to separate genuine drops from changes the target already satisfies.

RebaseResult

Bases: BaseModel

Structured output from the rebase agent.

SupersedeVerdict

Bases: BaseModel

Whether origin/ already satisfies the spec for one file.

SupersedeResult

Bases: BaseModel

Structured output from the rebase-supersede judge.

run_supersede_check

run_supersede_check(
    *,
    settings,
    repo_dir,
    target,
    spec,
    dropped_files,
    target_contents,
)

Decide which of dropped_files origin/ already satisfies.

The deterministic post-rebase integrity check compares bytes, not meaning: it reports an implement-stage file as dropped whenever the target lacks the branch's exact blob, even when the target already implements the spec's requirement for that file through different content (e.g. a CI job that migrated into a shared reusable workflow). This LLM judgement compares the ticket spec against the target's actual content (captured host-side with git show origin/<target>:<path>) and returns a per-file verdict.

This is the mockable seam — tests monkeypatch it to avoid real LLM calls.

run_rebase_agent

run_rebase_agent(
    *,
    settings,
    repo_dir,
    branch,
    target,
    memory="",
    remote_url=None,
    token=None,
    token_provider=None,
    token_cache_clear=None,
    pre_rebase_files=None,
    previously_dropped_files=None,
)

Run one rebase attempt of branch onto origin/<target>.

Uses the LLM (pydantic-ai agent) with sandboxed file + shell tools scoped to repo_dir, plus bridged git tools that execute host-side with remote_url and token so the agent can drive fetch + push.

The agent loops internally to resolve every conflict the rebase encounters; it returns a RebaseResult with status, summary, and updated memory.

This is the mockable seam — tests monkeypatch it to avoid real LLM and Docker calls.

robotsix_mill.agents.reply_thread

A reply_to_thread tool for agents to reply to a comment thread.

The implement agent (and potentially others in the future) can use this to answer questions, acknowledge feedback, or provide status updates directly on the ticket's comment thread.

make_reply_to_thread_tool

make_reply_to_thread_tool(settings, agent_name)

Return the reply_to_thread closure bound to settings.

Parameters:

Name Type Description Default
settings Settings

The application settings instance.

required
agent_name str

Stamped as the comment author so the originating agent is identifiable (e.g. "implement").

required

robotsix_mill.agents.retrospecting

The retrospect agent: analyse a finished ticket's workflow + its Langfuse session and propose a concrete improvement as a draft.

Seam: tests monkeypatch run_retrospect_agent. Structured output so the stage has a clear spawn decision.

MemoryEdit

Bases: BaseModel

A single targeted edit to the retrospect memory ledger.

Expresses one change without re-emitting the whole ledger. op selects the operation (append, replace, or remove); find is the exact existing ledger block to locate (required for replace/remove, matched verbatim including the ## heading); and text is the new content (the section to add for append or the replacement for replace; ignored for remove).

RetrospectResult

Bases: BaseModel

Structured outcome of a retrospect pass over a finished ticket.

findings and conclusion are the agent's analysis of the ticket's workflow and Langfuse session. The propose_draft / draft_title / draft_body / draft_gap_id fields describe an optional improvement ticket to file, and follow_up_title / follow_up_body an optional continuation ticket; draft_target and follow_up_target route each to the current repo's board or the mill maintenance board. Memory updates flow through exactly one of updated_memory (full re-emit), memory_edits (targeted :class:MemoryEdit operations, preferred for modifications), or memory_delta — in that precedence order. agented_md_proposals carries any proposed AGENT.md changes.

run_retrospect_agent

run_retrospect_agent(
    *,
    settings,
    ticket_summary,
    history_text,
    langfuse_summary,
    memory="",
    comments_text="",
    recent_proposals="",
    verified_proposals="",
    epic_context="",
    sibling_context="",
    repo_dir=None,
)

Analyse a finished ticket and propose a concrete improvement.

Builds the retrospect agent from its YAML definition and runs it over the ticket's workflow history plus its Langfuse session summary, returning a structured :class:RetrospectResult. When a repository clone is available the agent gets read-only filesystem tools (read_file, list_dir, run_command) so it can verify gap claims before filing follow-ups. A pre-parse repair hook salvages output whose updated_memory JSON contains unescaped characters, and non-structured output is degraded safely via :func:_coerce_result.

Parameters:

Name Type Description Default
settings Settings

Application configuration — model name (retrospect_model) and retry parameters.

required
ticket_summary str

Summary of the finished ticket under review.

required
history_text str

The ticket's rendered workflow history.

required
langfuse_summary str | None

Pre-computed Langfuse session summary, or None for a workflow-only review.

required
memory str

The agent's memory ledger as a Markdown string.

''
comments_text str

The ticket's operator/agent comment history.

''
recent_proposals str

Recent prior proposals prepended to the prompt for dedup awareness.

''
verified_proposals str

Verified-state table of prior proposals for ledger reconciliation.

''
epic_context str

Optional epic context block appended to the prompt.

''
sibling_context str

Optional sibling-ticket context block appended to the prompt.

''
repo_dir Path | None

Optional path to the local repository clone; when set and present, enables the read-only filesystem tools.

None

Returns:

Name Type Description
A RetrospectResult

class:RetrospectResult with findings, conclusion, optional

RetrospectResult

draft/follow-up proposals, and memory updates. Degrades to an

RetrospectResult

empty result when the agent returns unparseable output.

robotsix_mill.agents.retry

Compatibility shim — retry/backoff now lives in the robotsix-llmio library.

call_with_retry + the transient/rate-limit classifiers were extracted into robotsix-llmio (core + the provider layers). This module preserves the historical mill API: the retry/backoff constants are baked in the library (which equal mill's former defaults), and the public classifier names are re-exported.

The call-level retry predicate is the OpenRouter transient set (429/5xx/timeout/ malformed-JSON/upstream-error) — deliberately NOT provider-specific reasoning-400, which surfaces to the worker's stage-retry (a fresh re-run) rather than being retried in the same conversation. classify_stage_error picks up the reasoning-400 via the re-exported detector.

is_transient

is_transient(exc)

Transient if EITHER backend's classifier says so.

mill runs both the OpenRouter and Claude SDK transports, so a single retry predicate must recognise both families: OpenRouter 429/5xx/upstream on the OpenRouter path, and Claude SDK subprocess/connection/ query-timeout failures on the Claude path. The two sets don't overlap in practice, so OR-ing them keeps local retries correct for whichever backend actually ran — previously only OpenRouter errors were retried, so a Claude CLI hiccup or query timeout skipped local retry entirely.

An API 400 (request validation — every retry re-sends the identical rejected payload) needs no guard here: is_claude_sdk_transient already excludes it, ahead of the degenerate-success signature the SDK collapses it into. That ordering lives in the library, so this function inherits it.

The degenerate Claude SDK success result (is_error=True with subtype='success') is excluded — it is deterministic for a given input. The refine runner catches it at the agent-output level and treats it as a successful empty result.

Also recognises sqlite3.OperationalError containing "database or disk is full" — a host-level disk-full condition that cannot be resolved by retrying, so this classifier lets the worker's stage-level park mechanism kick in sooner instead of burning internal retries.

closing_scratch_loop

closing_scratch_loop()

Close the event loop pydantic_ai leaves installed on this thread.

Agent.run_sync funnels through pydantic_ai._utils.get_event_loop, which does asyncio.new_event_loop() + asyncio.set_event_loop() and never closes the loop. BaseEventLoop.close() is what shuts a loop's default executor down, so an unclosed loop strands that executor's asyncio_N threads in futex_wait for the life of the process — each one costing an 8 MB stack reservation and its own glibc malloc arena. On a long-lived worker thread (mill runs stages via asyncio.to_thread) the loops accumulate until the container hits its memory cap and is OOM-killed, which kills in-flight sandboxes and silently burns implement spawn attempts.

Only a loop this block is responsible for is closed: if a loop was already installed on the thread on entry it is left exactly as found, and a running loop is never touched. Agents are built and closed per call (see agents.base), so nothing loop-affine outlives the block.

call_with_retry

call_with_retry(
    fn, *, what="model call", sleep=sleep, fallback_fn=None
)

Run fn with bounded transient/rate-limit retry.

When called from within a running event loop (e.g. worker processing on Python >=3.14), the library's call_with_retry cannot use asyncio.run() (RuntimeError). In that case the call is delegated to a thread so the library can create its own event loop safely.

acall_with_retry async

acall_with_retry(
    fn, *, what="model call", sleep=sleep, fallback_fn=None
)

Async sibling of :func:call_with_retry.

Mirrors the library's retry schedule (the baked TRANSIENT_* constants + the OpenRouter transient classifier and rate-limit fallback semantics), but awaits an async fn and uses asyncio.sleep for backoff. This lets a nested sub-agent tool retry await agent.run(...) on the coordinator's own running event loop, rather than calling asyncio.run (illegal inside the Claude SDK's already-running loop).

When fallback_fn is provided, the primary is retried locally first. Only when local retries are exhausted does the fallback run, itself through a fresh retry session. This guards against persistent provider-side outages (e.g. provider 503 on OpenRouter) by falling back to a different model.

After a successful run, per-step usage data is recorded on the current OTel span (same contract as :func:run_agent).

run_agent

run_agent(
    agent,
    make_run,
    *,
    fallback_fn=None,
    what="model call",
    sleep=sleep,
    tier_fallback=True,
)

Run agent with bounded local retry.

make_run takes a handle and performs the actual run, e.g. lambda h: h.run_sync(prompt, message_history=hist, usage_limits=limits). The transport is fixed by the agent's level; transient errors retry on the same handle.

When fallback_fn is provided, the primary agent is retried locally first (same transient/backoff schedule). Only when local retries are exhausted does the fallback run, itself through a fresh retry session. This guards against persistent provider-side outages (e.g. provider 503 on OpenRouter) by falling back to a different model.

When tier_fallback is True (the default), a tier-unavailable failure (Claude subscription exhausted / dead OAuth credential) rebuilds the agent on the fallback provider slot via the _failover_rebuild hook and reruns there. Pass tier_fallback=False when a higher layer (llmio's call_with_failover loop) already owns provider failover — e.g. load_and_run_agent's slot factory — so the exhaustion propagates up and the loop (not the nested fallback) records the slot and the armed window.

After a successful run, per-step usage data (token counts, model name, request count, tool calls, and retry info) is recorded as a span attribute on the current OTel span so the trace inspector and cost-analyst can attribute spend without fetching every Langfuse observation.

When called from within a running event loop (e.g. worker processing on Python >=3.14, or a tool on the Claude SDK's loop), make_run typically ends in run_sync → asyncio.run(), which raises RuntimeError. As in :func:call_with_retry, the whole retry session is then delegated to a thread so a fresh event loop can be created safely.

is_tier_unavailable

is_tier_unavailable(exc)

Whether exc means the agent's whole tier is out of service.

Usage exhaustion (the subscription's session/weekly cap) and a dead OAuth credential are per-provider, not per-request: re-running at the same tier cannot help, and llmio deliberately never retries them (see ClaudeSDKUsageExhaustedError / ClaudeSDKAuthError). They are the cases where the run should move to a different tier instead of failing.

robotsix_mill.agents.review_revision

Review-revision agent: implements human-requested changes on a PR branch.

Reads the review comments + current file contents from the ticket's workspace clone, makes the requested changes, runs local tests, and commits. Returns DONE iff changes were applied successfully.

This agent operates only on the local clone — it never pushes, opens PRs, or interacts with the forge. The caller (merge stage) decides whether to force-push the result.

ReviewRevisionResult

Bases: BaseModel

Structured output from the review-revision agent.

run_review_revision_agent

run_review_revision_agent(
    *,
    settings,
    repo_dir,
    branch,
    review_comments,
    pr_files,
    memory="",
)

Run one review-revision attempt.

Uses the LLM (pydantic-ai agent) with sandboxed file + shell tools scoped to repo_dir. The agent reads the review comments, inspects the relevant files, makes minimal edits to address the reviewer's feedback, runs local tests, and commits. Returns a ReviewRevisionResult with status, summary, and updated memory.

This is the mockable seam — tests monkeypatch it to avoid real LLM and Docker calls.

robotsix_mill.agents.run_health

Run-health reasoning core.

Reasons over a deterministically pre-built RUN-HEALTH DIGEST (failed and degraded runs grouped by (kind, normalized signature) across every board's run registry) and emits high-confidence draft proposals for the genuine failures, separating them from legitimate empty/no-op runs.

The agent does NOT read the registries itself — the digest is injected by runners.run_health_runner. Built directly via build_agent (not build_agent_from_definition) on the default/normal model: telling a real failure apart from a benign empty run needs judgement, and the bounded digest keeps the input small.

RunHealthResult

Bases: BaseModel

Structured output from the run-health pass.

draft_titles / draft_bodies / gap_ids are parallel lists (one entry per proposal) clipped to MAX_PROPOSALS by the runner.

run_run_health_agent

run_run_health_agent(
    *,
    settings,
    memory="",
    recent_proposals="",
    digest,
    board_id="",
)

Run the run-health reasoning pass over a pre-built digest.

Parameters:

Name Type Description Default
settings Settings

Application configuration.

required
memory str

The agent's memory ledger (Markdown).

''
recent_proposals str

Prior run-health proposals block.

''
digest str

The deterministic run-health digest (grouped failed/degraded run candidates), built by the runner.

required
board_id str

Board the drafts are filed to; scopes the read_ticket / list_recent_tickets tools (without it list_recent_tickets fails with "board_id is required").

''

Returns:

Type Description
RunHealthResult

A RunHealthResult with parallel draft lists (clipped to

RunHealthResult

MAX_PROPOSALS) plus the updated memory ledger.

robotsix_mill.agents.scope_triage

Scope-violation triage agent: a cheap classifier that decides whether changed files outside the ticket's declared scope are legitimate expansions or scope creep.

This follows the same pattern as triage_refine and triage_auto_approve in :mod:refining: load the YAML definition, build a no-tools agent, call with retry, and return a structured Pydantic output.

ScopeTriageVerdict

Bases: BaseModel

Classifier verdict on out-of-scope file changes.

action is the triage decision — EXPAND (accept the changes as a legitimate scope expansion), REJECT (scope creep to revert), or ESCALATE (defer to a human). justification is the rationale, and expand_files lists the out-of-scope paths approved when action is EXPAND.

run_scope_triage_agent

run_scope_triage_agent(
    *,
    settings,
    ticket_spec,
    file_map,
    out_of_scope_files,
    diff_summaries,
    operator_resolution="",
    full_diffs=False,
)

Triage whether out-of-scope file changes are legitimate.

Builds a cheap no-tools classifier from the scope_triage YAML definition and runs it (with retry) over the ticket spec, declared file map, the offending out-of-scope files, and their diff summaries, returning a structured :class:ScopeTriageVerdict.

Parameters:

Name Type Description Default
settings Settings

Application configuration — model name (scope_triage_model) and retry parameters.

required
ticket_spec str

The ticket specification text.

required
file_map list[str]

The files the ticket declared in scope.

required
out_of_scope_files list[str]

Changed files not covered by file_map.

required
diff_summaries dict[str, str]

Mapping of file path to a summary of its diff.

required
operator_resolution str

The operator's resume note(s) answering a previous ESCALATE on this ticket; empty when there is none.

''
full_diffs bool

diff_summaries hold each file's FULL diff (the re-ask after an ESCALATE that blamed a truncated summary); rendered as a full-diffs section instead.

False

Returns:

Name Type Description
A ScopeTriageVerdict

class:ScopeTriageVerdict with the action, justification,

ScopeTriageVerdict

and any approved expansion files.

robotsix_mill.agents.spawn_subtask

The spawn_subtask tool for the implement coordinator.

When a ticket decomposes into many atomic, independent edits — the canonical case is a per-file or per-module batch — the coordinator can delegate one chunk at a time to a sub-agent with its own request budget. This lets the parent stay lean (one outer plan + N sub-agent calls) and keeps each subtask's context bounded to its own files.

Design pins:

  • Same tool palette as the parent (read/write/edit/list/explore/ run_command). The sub-agent runs on the same workspace clone, so edits land on the parent's branch directly.
  • No consult_expert, no spawn_subtask (no recursion). One level of delegation; the parent owns orchestration.
  • Per-subtask request budget set by settings.subtask_request_limit (default 30). The parent's overall coordinator_request_limit is the outer cap, so a runaway sub-agent can't starve the parent past it.
  • Plain-string output. The sub-agent returns a short summary of what it did; the parent uses that to decide on the next subtask.

run_spawn_subtask async

run_spawn_subtask(
    *,
    settings,
    repo_dir,
    name,
    prompt,
    files_in_scope=None,
    level=None,
)

Run one sub-agent pass to completion. Returns its summary.

Parameters:

Name Type Description Default
settings Settings

Mill settings — drives model + budget.

required
repo_dir Path

Workspace clone the sub-agent edits.

required
name str

Short kebab-case label for the subtask (lands in logs + tracing). The parent picks the name so its plan stays traceable.

required
prompt str

The operator-authored subtask spec the parent built. The sub-agent sees this as its entire system+user prompt payload; treat it as a self-contained mini-spec.

required
files_in_scope list[str] | None

Optional list of paths the parent expects the sub-agent to touch. Injected into the prompt as a scope hint. The sub-agent still has full read/write fs tools — this is guidance, not enforcement.

None
level int | None

Optional capability-level override; defaults to level 2 (the workhorse/implement tier).

None

Returns:

Name Type Description
str

The sub-agent's final string output (its summary). On budget

str

cap or other failure, returns a structured "subtask

incomplete str

…" string so the parent can decide what to do

str

instead of raising into the parent's loop.

make_spawn_subtask_tool

make_spawn_subtask_tool(settings, repo_dir)

Build the spawn_subtask tool exposed to the implement coordinator. Returns a callable the agent invokes by name.

robotsix_mill.agents.structured_output_guard

Post-hoc structured-output guard shared by the implement / review / retrospect agents.

When a structured-output agent's final message fails to parse as the expected pydantic model, pydantic-ai's transport returns the raw text unchanged. The downstream stage then crashes ('str' has no attribute 'verdict' / 'updated_memory') or blocks the ticket. The implement stage originally inlined a "re-prompt once with a focused reminder before degrading" guard in coordinating.py; this module extracts that block so the same recovery can be wired into the other two structured-output agents.

The helper performs exactly ONE additional run via :func:robotsix_mill.agents.retry.run_agent. Caller-side terminal coercion (_coerce_verdict / _coerce_result / the implement stage's ImplementResult(summary=...) fallback) remains the final safety net when the re-prompt also fails.

reprompt_if_unstructured

reprompt_if_unstructured(
    *,
    result,
    agent,
    expected_type,
    reprompt_message,
    settings,
    what,
    run_kwargs=None,
    require_no_tool_calls=False,
    char_threshold=10000,
    workspace_has_changes=None,
)

Re-prompt agent once when result.output is unstructured, OR when require_no_tool_calls is True and the pass produced zero tool calls.

The zero-tool-call gate runs BEFORE the structured-output check so that a structured ImplementResult the model produced without ever calling a tool does not slip through — that is the exact zero-tool-call pass this guard exists to catch.

Returns result unchanged when:

  • require_no_tool_calls is True, zero tool calls were made, BUT the output is a structured result with no_change_needed=True (a deliberate signal the spec is already satisfied); OR
  • result.output is already an instance of expected_type (and the zero-tool-call gate above did not fire); OR
  • len(str(result.output)) < char_threshold (too short to act on); OR
  • the re-prompt itself raises (original result returned so the caller's terminal coercion still runs).

Detection rule:

  • Zero-tool-call gate (when require_no_tool_calls is True): no tool-call or tool-return part present AND output is NOT a structured no_change_needed=True pass → re-prompt.
  • Structured-output gate: isinstance(result.output, expected_type) is False, AND len(str(result.output)) >= char_threshold, AND (when require_no_tool_calls is True) tool calls ARE present (the zero-tool-call gate above would have caught a no-tool-call case) → re-prompt.

run_kwargs is forwarded to agent.run_sync on the re-prompt (e.g. {"usage_limits": limits}); message_history is owned by the guard and must NOT appear in run_kwargs.

workspace_has_changes is an optional probe consulted only when the zero-tool-call gate would fire. When it returns True the edits are already on disk (e.g. tool calls ran inside a backend that does not surface them in the message history), so the re-prompt is skipped and the pass is treated as having used tools.

robotsix_mill.agents.surveying

The survey agent: discovers and learns from similar open-source projects, proposing concrete improvements for the current repo.

Seam: tests monkeypatch run_survey_agent. Structured output so the runner has a clear result to work with.

robotsix_mill.agents.test_gap

The test-gap agent: dedicated test-coverage oversight.

Identifies modules with zero dedicated test coverage, prioritizes by complexity, I/O surface, and state-transition logic, and proposes draft tickets for the highest-priority gaps.

Seam: tests monkeypatch run_test_gap_agent. Structured output so the runner has a clear result to work with.

robotsix_mill.agents.tool_registry

A system-wide, programmatically-queryable catalog of tool capabilities.

pydantic-ai auto-generates per-agent tool schemas at inference time from each callable's signature + docstring. That tells each agent what it can call. This registry fills the gap: it tells planning/refine agents what could exist system-wide so they don't hallucinate tools that don't exist or miss ones they should plan for.

ToolInfo

Bases: BaseModel

Describes one tool registered in the system.

ToolRegistry

Class-level singleton catalog of all tool capabilities.

Tools are registered explicitly at their construction site (not via decorators or AST inspection) so the codebase stays grep-friendly.

register classmethod

register(tool)

Insert tool by name. Overwrites on duplicate name (last registration wins).

list_tools classmethod

list_tools()

Return every registered tool, sorted by category then name.

robotsix_mill.agents.trace_inspector

Trace inspector sub-agent.

The retrospect agent's deep-analysis mode spawns this cheap sub-agent per trace to inspect the full observation tree — raw model calls, tool invocations, and their outcomes. It surfaces systematic tool errors, agent behavioural patterns (e.g. fix loops that never converge), and cost/latency optimisation opportunities that the pre-computed summary misses.

run_trace_inspector is the single mockable seam — tests monkeypatch it to inject synthetic results without a real LLM or Langfuse.

TraceFinding

Bases: BaseModel

One actionable finding from a deep-review pass.

Solution-bearing by design — proposed_solution is mandatory so the + Ticket flow can file drafts whose body is something an implement agent can act on directly, not just a symptom string.

TraceInspectResult

Bases: BaseModel

Structured result of a single trace deep-inspection pass.

findings is the list of solution-bearing :class:TraceFinding items the inspector surfaced (empty for a clean trace), updated_memory is the agent's refreshed pattern ledger, and error is non-empty only when the analysis itself failed (e.g. the trace was too large for the model context) — which distinguishes a genuine no-findings run from one that never ran.

run_trace_inspector

run_trace_inspector(
    *,
    settings,
    trace_data,
    repo_dir=None,
    repo_config=None,
    memory="",
    started_at=None,
    classifier_flags=None,
    request_limit_override=None,
)

Analyse a single trace's full observation tree and return structured findings with proposed solutions.

Two operating modes:

  • Tool-less (repo_dir is None): no code access, no tools, tight request_limit from trace_review_inspector_toolless_requests (default 3). Used by the retrospect agent's trace_inspect tool path — retrospect already runs in a tools-rich agent of its own, and the tool's contract is a quick text summary, not a deep dive.

  • Tools-on (repo_dir provided): the inspector gets read_file, list_dir, run_command, explore, and parallel_explore — everything it needs to confirm a hypothesis in the code before writing a proposed_solution. request_limit scales dynamically with the observation count: max(min_requests, min(max_requests, int(obs_count * requests_per_obs))), defaulting to 20–80 range at 0.1 requests/obs. When obs_count exceeds trace_review_inspector_max_obs_for_tools (default 200) the inspector falls back to the tool-less path even though repo_dir is supplied — a trace that large cannot be deep-verified in a bounded run.

The optional memory is rendered into the prompt as <memory>...</memory> so the agent can avoid re-proposing what it already addressed, strengthen confidence on recurring patterns, and emit an updated ledger via result.updated_memory.

The optional started_at is the process start time — passed through from the trace-review runner so the LLM can reason about restart correlation when incomplete_trace + restart_correlated flags are present.

The optional classifier_flags are the deterministic Phase-1 flags that surfaced the trace — when non-empty they are rendered into the prompt as a classifier_flags section so the inspector knows why the trace was flagged and can apply the statistical-signal verification gate. None/empty omits the section (the periodic retrospect tool-less call site leaves it unset).

The optional repo_config carries the target repo's Langfuse read credentials so callers that fetch additional trace data on behalf of this sub-agent resolve the per-repo project rather than mill's global one. The inspector itself analyses the supplied trace_data and makes no further Langfuse calls, so this is threaded for credential-resolution consistency; the OpenRouter key (get_secrets()) stays global.

request_limit_override (int | None, default None) caps the tools-on request_limit from above — when set the effective limit is min(dynamic_limit, request_limit_override). The tool-less path is unaffected. Intended for interactive tool call-sites (e.g. langfuse_inspect_trace) that should do a quick, bounded confirmation rather than an unbounded deep audit.

On error, the result's error field is populated rather than returning a silent empty findings list — the previous behaviour made model-context-overflow indistinguishable from a clean no-findings run.

robotsix_mill.agents.web_knowledge

Web-knowledge sub-agent — the single gateway to the internet.

A multi-turn flash agent that answers focused library / API / framework questions. It owns a small mill-global knowledge base on disk:

  • <data_dir>/web_knowledge/<lib>.md — one Markdown file per library, frontmatter-stamped with last_updated:.
  • <data_dir>/web_knowledge/_general.md — cross-library memory for cross-cutting notes that don't fit a single library (e.g. "OpenRouter caches prompts with N-minute TTL").

The cache is centralized (NOT per-board): library facts like "imaplib.login raises this exception on Gmail" don't change between repos, and partitioning them per-board fragmented identical knowledge across every repo that asked the same question.

The agent is autonomous. It receives the caller's question, sees an index of every existing knowledge file in its system prompt, and decides for itself whether the cached files cover the question or whether to web_search for fresh information. After answering it typically updates its own knowledge file so future consults can answer from cache.

This module replaces the deterministic consult_library+web_research split: the previous design forced refreshes purely on mtime, which couldn't tell the difference between "fresh file that covers the question" and "fresh file that covers a different question on the same library." With a multi-turn agent that owns its memory, that judgment lives in the model. The trade-off is real — even the happy path costs 3-4 flash turns instead of one — but the alternative (the cache returning "I don't know" until the 30-day TTL expires) is worse.

All other agents lose direct web_research access; their only route to the internet is the ask_web_knowledge tool this module exposes. That makes the trace cost-attribution cleaner (every web hit shows up under one agent name) and means the operator can audit web traffic by reading exactly one place.

run_web_knowledge is the single mockable seam for tests — same pattern every other agent in this tree follows.

reset_trace_web_search_budget

reset_trace_web_search_budget(max_calls)

Zero the per-survey-run web_search counter and set a new cap.

Call with max_calls=0 to deactivate the trace budget (return to unlimited searches across consults). The per-consult web_fetch budget is NOT affected by this call.

run_web_knowledge async

run_web_knowledge(*, settings, question)

Run one multi-turn consult and return the agent's answer.

Degrades to a short error string on any failure — never raises; the calling coordinator can carry on.

make_ask_web_knowledge_tool

make_ask_web_knowledge_tool(settings, *, block_reason=None)

Build the ask_web_knowledge tool that calling agents use as their single gateway to the internet. Other agents do NOT receive a direct web_search tool — only this gateway.

When block_reason is set the tool returns it immediately (no run_web_knowledge call, no web budget spent) — the caller uses this to disable web consultation for drafts that are internal toolchain failures (CI/type/lint/test), where web-searching wastes turns on irrelevant results. The tool is still registered in ToolRegistry so the prompt-tool- consistency guard is not tripped.

robotsix_mill.agents.yaml_loader

YAML loader for agent definitions.

Parses agent_definitions/<name>.yaml, validates the result against the AgentDefinition Pydantic model, and returns a structured object. Each definition declares a capability level (1/2/3) that build_agent resolves to a (transport, model) via llmio's tier defaults.

This module is independent of the agent runtime (build_agent, Settings, pydantic_ai) — it only depends on pydantic (already in the tree via pydantic-settings), PyYAML, stdlib, and the stdlib-only core.duration helper for the human-readable interval form.

AgentDefinition

Bases: BaseModel

A validated agent definition loaded from a YAML file.

All fields map 1:1 to the keys demonstrated in agent_definitions/refine.yaml. No fields beyond that set are introduced.

resolve_agent_level

resolve_agent_level(settings, definition)

Return the capability level a stage should run at.

settings.agent_levels[definition.name] wins when set (the operator's per-stage L1..L4 choice); otherwise the level declared in the YAML definition is the default. Call sites that pick a cheaper level for a specific ticket (config-only implement/review, the refine trivial route) apply their choice on top of this resolution.

load_agent_definition

load_agent_definition(path)

Parse and validate an agent YAML definition.

path must point to a YAML file whose top-level keys map to AgentDefinition fields.

Returns a validated AgentDefinition instance.

Raises:

Type Description
FileNotFoundError

path does not exist (from Path.read_text()).

YAMLError

the file is not valid YAML.

ValidationError

a required field is missing, a value has the wrong type, or an unknown key is present.

load_periodic_agent_definition

load_periodic_agent_definition(name, repo_dir=None)

Load a periodic agent's definition with per-repo override support.

Lookup order
  1. <repo_dir>/.robotsix-mill/agents/<name>.yaml — if present, it fully replaces the built-in definition (same schema). This is the per-repo override path; a repo can ship a different prompt, model, interval, or enabled flag without touching the mill image.
  2. agent_definitions/periodic/<name>.yaml — the built-in.

Raises FileNotFoundError when neither file exists.

load_and_run_agent

load_and_run_agent(
    *,
    settings,
    definition_name,
    tools=None,
    level=None,
    prompt,
    what,
    repo_dir=None,
    run_kwargs=None,
    system_prompt_format_kwargs=None,
    validate=None,
    **build_overrides,
)

Load a YAML agent definition, build the agent, run it, and return output.

This is the single shared helper for the canonical pattern repeated across ~11+ non-periodic agent files:

  1. load_agent_definition from agent_definitions/<definition_name>.yaml
  2. build_agent_from_definition with tools, model_name, repo_dir, and any **build_overrides
  3. run_agent with prompt and any **run_kwargs
  4. _safe_close in a finally block

Steps 2-4 run inside llmio's provider-failover loop: the capability level NEVER changes, but a provider-shaped failure (outage, rate limit, exhausted subscription credits) on the active provider slot retries the same level on the other slot — rebuilding the agent, since the slot selects the provider. Local retry of transient errors still happens inside run_agent; only what survives that escalates. Failover is OFF unless settings.provider_failover_enabled is on — the fallback slot is paid OpenRouter, and with it off the worker parks the ticket until the quota resets.

Parameters:

Name Type Description Default
settings Settings

Application configuration.

required
definition_name str

YAML file name under agent_definitions/, e.g. "scope_triage" or "periodic/module_curator".

required
tools list[Any] | None

Tool list for the agent (default []).

None
level int | None

Override capability level (default: settings.agent_levels for this definition's name, else definition.level).

None
prompt str

The user prompt passed to h.run_sync(prompt, **run_kwargs).

required
what str

Human-readable label for retry log messages.

required
repo_dir Path | None

Optional repo clone directory (passed through to build_agent_from_definition).

None
run_kwargs dict[str, Any] | None

Extra keyword arguments forwarded to h.run_sync(prompt, **run_kwargs) (e.g. usage_limits, message_history).

None
validate Callable[[Any], None] | None

Optional check run on the agent's result inside the failover loop. It should raise when the result is unusable, so a hollow success surfaces as a real error instead of being returned (a task-shaped failure is never retried on the other provider — re-running a doomed task would just spend twice).

None
system_prompt_format_kwargs dict[str, Any] | None

When set, definition.system_prompt is formatted with these kwargs (via str.format(**kwargs)) and passed as system_prompt to build_agent_from_definition. Ignored when system_prompt is already in **build_overrides.

None
**build_overrides Any

Extra keyword arguments forwarded to build_agent_from_definition (e.g. system_prompt, board_id).

{}