Stages
robotsix_mill.stages.refine
Refine stage: raw DRAFT -> actionable READY ticket.
Rewrites the file-canonical description.md into a precise spec the
implement agent can act on unattended; the original draft is kept as an
artifact for traceability. Empty draft or missing OpenRouter key ->
BLOCKED with a clear note (not a crash).
When require_approval is true (the default), the refined ticket
enters human_issue_approval instead of ready — a human must approve
before the implement stage picks it up.
Before the expensive refine agent runs, a cheap dedup / already-done
check inspects the draft against existing tickets. If the draft is a
clear duplicate or the change is already covered by a recently-closed
ticket, the ticket is short-circuited to CLOSED — no refiner, no
human approval gate, no wasted cost.
This module is a thin façade (Pattern A) over the refine package:
helpers— module-level constants/regexes and pure functionsgates— :class:RefineGatesMixin(pre-refine guard phases)orchestration— :class:RefineAgentMixin(refine-agent pipeline)core— :class:RefineStage(the assembledStagesubclass)
The agent submodules are bound as package attributes (dedup,
freshness, obsolescence, refining) so the dotted-string
monkeypatch targets used by the tests (e.g.
robotsix_mill.stages.refine.dedup.run_dedup_check) resolve to the same
module objects the gate/orchestration code calls through.
RefineStage
Bases: RefineGatesMixin, RefineAgentMixin, Stage
Refine a draft ticket into a detailed, self-contained engineering specification.
run
run(ticket, ctx)
Process a DRAFT ticket: gate on dependencies, refine the draft into a self-contained engineering spec (or split into children / promote to epic) via the refining agent.
load_memory
load_memory(memory_file, max_chars=None)
Read a memory ledger file; returns "" if missing/unreadable.
When max_chars is set and the file exceeds that limit, the oldest
entries are dropped — only the last max_chars characters (most
recent) are kept, adjusted to a newline boundary so entries aren't
split mid-line. A [... memory truncated: N chars omitted] note
is prepended and a warning is logged.
persist_memory
persist_memory(memory_file, text, max_chars=None)
Write text to memory_file, creating parent dirs as needed.
Strips the ephemeral ## Prior proposals — verified state table an
agent may have copied back into its memory output — that block is
injected fresh each run from the DB and must never accrete in the
cross-run ledger.
When max_chars is set and len(text) > max_chars, the text is
tail-truncated via :func:tail_keep before writing — the same
primitive and label already used by :func:load_memory. Ephemeral
sections are stripped BEFORE the cap check so the budget isn't
wasted on content that would be stripped anyway.
verify_claim
verify_claim(claim_text, target_files, repo_dir)
Verify that a claim citing a PR or commit SHA actually touches target_files.
Best-effort: returns True when verification passes or when there
is nothing to verify (no PR/SHA reference, no target files, or no
repo_dir). Returns False only when a cited artifact is
confirmed NOT to touch any target file — i.e. when the stage can
prove the claim is wrong.
Verification rules:
- Extract PR numbers (
#NNN) and commit SHAs from claim_text. - For each PR reference, check
git log origin/main --grep '#NNN' -- <file>for each target file — any match confirms the claim. - For each commit SHA, check
git diff --stat <sha>~1..<sha> -- <file>for each target file — any match confirms the claim. - When no concrete reference (PR/SHA) is found but claim_text
contains an external-fix phrase (e.g. "already fixed"), check
git log -n 1 -- <file>for each target file — any recent commit touching the file counts as plausible confirmation.
robotsix_mill.stages.base
Stage contract.
A Stage consumes tickets in exactly one input_state, does its work
(reading/writing the ticket's filesystem workspace), and returns an
:class:Outcome naming the next state. The worker applies the
transition — a stage never writes the DB directly.
Stage.run is synchronous (LLM/tool calls). The worker runs it in a
threadpool so the API event loop stays responsive.
StageContext
dataclass
Dependency-injection context passed to every :meth:Stage.run.
Attributes:
| Name | Type | Description |
|---|---|---|
settings |
Settings
|
Mill runtime configuration (models, paths, limits). |
service |
TicketService
|
:class: |
repo_config |
RepoConfig | None
|
Per-repository configuration resolved from the
|
memory_board_id
memory_board_id(ticket)
Resolve the board_id for settings.memory_file_for(...).
repo_config is None for the synthetic meta board (not a
registered repo), so the old repo_config.board_id if repo_config
else "" crashed meta tickets with "memory_file_for: board_id is
required" once the board-less memory fallback was removed. Fall back
to the bound service board, then the ticket's own board (both are
"meta" for a meta ticket).
spawn_board_id
spawn_board_id(parent)
Resolve the board a follow-up spawned from parent lands on.
Children inherit the PARENT's repo board — never the synthetic,
forge-less "meta" board, which cannot implement anything
(a meta-sourced parent that was filed on a repo board must not
leak its children onto meta). Candidates in order: the
parent's board_id, the stage's repo_config board, then
the bound service board; the first non-meta one wins. Returns
the parent's board ("meta" included) or None when no
repo board is known, leaving the create-time guard to decide.
Outcome
dataclass
Result of processing one ticket.
Stage
Bases: ABC
One step in the ticket pipeline.
Implementors must set name and input_state, and implement
:meth:run. Set traced = False for poll-driven, no-LLM stages
(e.g. merge, deliver) to avoid spamming empty Langfuse traces.
preflight
preflight(ticket, ctx)
Lightweight pre-trace gate — run BEFORE any Langfuse trace is opened.
Return an :class:Outcome to short-circuit the stage dispatch
without opening a trace or incrementing the dispatch counter.
Return None to proceed normally (trace opens, :meth:run called).
The default implementation returns None (always proceed).
Stages that have cheap early-exit conditions should override.
run
abstractmethod
run(ticket, ctx)
Process one ticket. Raise to fail the ticket (worker -> FAILED); raise NotImplementedError for a stub (worker logs, stops the chain, leaves the ticket).
robotsix_mill.stages.implement
Implement stage: READY -> DELIVERABLE (or BLOCKED, resumable).
First run: clone the target repo into the ticket workspace, branch,
then run a deterministic, stage-owned fix loop: invoke the implement
agent for one edit pass, run the test gate, and — on failure — re-invoke
the agent with a distilled diagnosis. The routing (proceed / retry /
escalate) is decided in Python (see
:class:~..agents.coordinating.ValidationResult), bounded by
settings.max_fix_iterations. Pass -> DELIVERABLE.
Resume: if the ticket workspace already has the clone + its branch (a prior BLOCKED run), do NOT re-clone — check the branch out and continue from the committed WIP.
This module is a thin façade (Pattern A) over the implement package:
_shared— module-level constants/regexes, stateless helpers, the internal dataclasses, and the packagelog(the pure leaf).phase_coordinator— :class:PhaseCoordinatorMixin(run / loop / context load / finalize / pause).validation— :class:ValidationMixin(prerequisite gate, baseline check, scope guardrail).implementation_logic— :class:ImplementationLogicMixin(agent invocation, single pass, test/result evaluation).file_operations— :class:FileOperationsMixin(clone/branch, repo-change and gitignore checks).core— :class:ImplementStage(the assembledStagesubclass).
The patchable seams run_test_agent / run_smoke_agent /
load_repo_smoke_paths are bound as package attributes so the
existing test monkeypatches (robotsix_mill.stages.implement.run_test_agent
and setattr(impl_mod, "run_smoke_agent"/"load_repo_smoke_paths", ...))
intercept the real call sites, which reach them through a
from robotsix_mill.stages import implement as _facade indirection.
ImplementStage
Bases: PhaseCoordinatorMixin, ValidationMixin, ImplementationLogicMixin, FileOperationsMixin, Stage
Clone the repo, create a feature branch, and run the implementation agent loop to produce code changes.
run
run(ticket, ctx)
Run the mixin's implementation loop, then clear the in-flight spawn marker.
The marker is written at the end of preflight so the NEXT preflight can detect a process death / SIGTERM that killed the attempt mid-flight. Clearing it here — whether the run succeeds, blocks, or raises (the worker records raised errors durably, so they are never silent) — marks this attempt as having reached a recorded terminal state.
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.
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.)
load_repo_smoke_paths
load_repo_smoke_paths(repo_dir)
Return the per-repo smoke_paths glob list from
<repo_dir>/.robotsix-mill/config.yaml, or [].
Accepts smoke_paths: [src/runtime/**, src/x/*.css] (a list of
glob strings). Strips whitespace from each entry and filters out
empty/whitespace-only strings. Non-string items are coerced via
str(x).strip() (matching :func:load_repo_languages). Never
raises — a malformed value or missing file yields [].
The globs scope the path-scoped smoke gate: an empty/absent list means the smoke command runs unconditionally (when set), otherwise the gate runs only when a ticket's introduced files match a glob.
Important: smoke_paths is a smoke-test gating mechanism
ONLY — it does NOT restrict which paths agent-stage filesystem
tools (read_file, list_dir, run_command) can access. The agent
sandbox always mounts the full repo checkout; the globs here only
decide whether the post-implement smoke command fires.
robotsix_mill.stages.ci_fix
CI-fix stage: FIXING_CI -> IMPLEMENT_COMPLETE (fix succeeded) | BLOCKED.
When the merge stage detects a mergeable PR with failing remote CI checks, it transitions the ticket to FIXING_CI. This stage invokes the ci-fix agent to auto-resolve the failures, commits locally, and force-pushes only the ticket branch. On success the ticket goes back to IMPLEMENT_COMPLETE so the merge stage re-verifies both gates before promoting to HUMAN_MR_APPROVAL.
Failure after max attempts escalates to BLOCKED (resumable).
CIFixStage
Bases: Stage
Check forge CI status and run automated fix logic to resolve CI failures on the ticket branch.
run
run(ticket, ctx)
Process a FIXING_CI ticket: poll forge CI status on the ticket branch and, on failure, run the automated CI-fix agent to push corrective commits.
robotsix_mill.stages.merge
IMPLEMENT_COMPLETE -> HUMAN_MR_APPROVAL (gates passed)
-> DONE (merged) | BLOCKED (closed unmerged) -> FIXING_CI (failing CI, deferred) -> REBASING (conflicting, deferred)
HUMAN_MR_APPROVAL -> DONE (merged) | BLOCKED (closed unmerged) -> IMPLEMENT_COMPLETE (gate degradation — silent fallback) -> WAITING_AUTO_MERGE (eligible, CI pending)
REBASING -> IMPLEMENT_COMPLETE (rebase succeeded, re-verify gates) -> CLOSED (every implement-stage change superseded — no-change close)
FIXING_CI -> IMPLEMENT_COMPLETE (fix succeeded, re-verify gates)
The PR is the review. This stage is re-run by the worker's lightweight poll while the ticket sits in IMPLEMENT_COMPLETE, HUMAN_MR_APPROVAL, REBASING, FIXING_CI, or WAITING_AUTO_MERGE; it checks the forge:
IMPLEMENT_COMPLETE (gate-check): - merged -> DONE - closed, unmerged -> BLOCKED (resumable) - open, mergeable -> check CI status: - failing CI -> FIXING_CI (auto-fix agent) - green CI -> HUMAN_MR_APPROVAL (gates passed! notify human) - pending CI -> IMPLEMENT_COMPLETE (no-op; re-poll) - open, conflicting -> REBASING (defer rebase agent)
HUMAN_MR_APPROVAL: - merged -> DONE - closed, unmerged -> BLOCKED (resumable) - open, mergeable -> check CI status: - failing CI -> IMPLEMENT_COMPLETE (silent fallback) - green CI -> HUMAN_MR_APPROVAL (no-op; re-poll) - pending CI -> HUMAN_MR_APPROVAL (no-op; re-poll) - open, conflicting -> IMPLEMENT_COMPLETE (silent fallback)
Returning the same state is the worker's "leave it, re-poll" signal — no history spam, no busy loop.
This module is a thin façade (Pattern A) over the merge package:
_shared— module-level helpers, constants, and the packagelogcore— :class:MergeStage(run dispatch + shared class-level helpers)ci_fix_mixin— :class:MultiRepoCiFixMixin(inline CI-fix recovery)multi_repo— :class:MultiRepoMixinci_poll— :class:CIPollMixin(IMPLEMENT_COMPLETE poll path)human_approval— :class:HumanApprovalMixin(HUMAN_MR_APPROVAL poll path)pr_baseline— :class:PrBaselineMixin(shared PR preamble + eligibility)auto_merge_gate— :class:AutoMergeGateMixin(WAITING_AUTO_MERGE poll path)rebase— :class:RebaseMixinreview_revision— :class:ReviewRevisionMixin
The patchable seams (git_ops, tracing, run_rebase_agent,
run_supersede_check, run_ci_fix_agent,
run_review_revision_agent) are bound as
package attributes so the existing test monkeypatches
(robotsix_mill.stages.merge.git_ops, merge_mod.run_rebase_agent,
etc.) intercept the real call sites.
MergeStage
Bases: MultiRepoCiFixMixin, MultiRepoMixin, CIPollMixin, HumanApprovalMixin, PrBaselineMixin, AutoMergeGateMixin, RebaseMixin, ReviewRevisionMixin, Stage
Orchestrate the merge pipeline: poll CI, rebase, address review feedback, and auto-merge when green.
run
run(ticket, ctx)
Drive a ticket through the merge pipeline: poll CI / mergeability, dispatch to rebase or review-revision handlers based on the current state, and auto-merge when all gates are green.
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.
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.
run_supersede_check
run_supersede_check(
*,
settings,
repo_dir,
target,
spec,
dropped_files,
target_contents,
)
Decide which of dropped_files origin/
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_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.
load_memory
load_memory(memory_file, max_chars=None)
Read a memory ledger file; returns "" if missing/unreadable.
When max_chars is set and the file exceeds that limit, the oldest
entries are dropped — only the last max_chars characters (most
recent) are kept, adjusted to a newline boundary so entries aren't
split mid-line. A [... memory truncated: N chars omitted] note
is prepended and a warning is logged.
persist_memory
persist_memory(memory_file, text, max_chars=None)
Write text to memory_file, creating parent dirs as needed.
Strips the ephemeral ## Prior proposals — verified state table an
agent may have copied back into its memory output — that block is
injected fresh each run from the DB and must never accrete in the
cross-run ledger.
When max_chars is set and len(text) > max_chars, the text is
tail-truncated via :func:tail_keep before writing — the same
primitive and label already used by :func:load_memory. Ephemeral
sections are stripped BEFORE the cap check so the budget isn't
wasted on content that would be stripped anyway.
github_push_token
github_push_token(settings, repo_config=None)
Return a token scoped for git push operations.
Resolution order (PAT mode, forge_auth != "app"):
SANDBOX_PUSH_TOKENfrom secrets — a dedicated push-bridge credential, isolated from the general forge token. When set, a broken push token only blocks pushes, not PR creation or API calls.FORGE_TOKEN— the general forge PAT (fallback).
When forge_auth == "app", delegates to the library's
github_push_token with the owner/repo derived from the remote
URL, scoped to contents: write and workflows: write.
github_token
github_token(settings, repo_config=None)
Return a forge auth token: either a static FORGE_TOKEN from secrets or a short-lived GitHub App installation token.
Delegates to the robotsix-github-auth library for token resolution
and caching.
invalidate_github_token
invalidate_github_token(settings, repo_config=None)
Remove the cached installation token for settings + repo_config.
Clears the library-level token cache so the next github_token()
call mints a fresh token from the GitHub API. Safe to call when no
entry exists.
robotsix_mill.stages.deliver
Deliver stage: DELIVERABLE -> IMPLEMENT_COMPLETE.
Push the ticket's branch to the configured forge and open a PR/MR
against forge_target_branch. The forge adapter only does the API
call; this stage owns the git push (it has the workspace clone).
When MILL_PR_SUMMARY_ENABLED is true, the stage generates a
structured PR body (Summary / Changes / Test Plan) from the
implementation diff via a cheap one-shot LLM call, falling back to
the raw spec on error. Otherwise the raw spec is used as-is.
Anything that isn't success is BLOCKED-resumable (move back to DELIVERABLE to retry) — never terminal FAILED, so a transient forge/ network problem doesn't lose the implemented branch. The PR URL is recorded in history + an artifact.
Multi-repo delivery (meta-board tickets)
When the implement stage produced a multi-repo workspace, it writes a
touched_repos.json manifest into artifacts/ listing every
repo that received a commit::
[
{"repo_id": str, "branch": str, "repo_path": str},
...
]
The deliver stage detects that manifest and iterates it, pushing each
repo's branch and opening one PR per repo via that repo's
RepoConfig. The resulting PR URLs are written to a second
artifact, pr_urls.json, with the schema::
[
{"repo_id": str, "branch": str, "url": str},
...
]
pr_urls.json is the seam downstream stages (merge polling,
_pr_url enrichment) will consume to find all PRs opened for a
single meta ticket. It is written ONLY in the multi-repo branch and
ONLY after at least one PR succeeds; its presence is the multi-repo
discriminator for downstream stages. The file is rewritten atomically
(.json.tmp → os.replace) after every successful PR so a
mid-loop BLOCKED leaves a consistent partial manifest the resume run
can read.
DeliverStage
Bases: Stage
Push the implemented branch to the remote forge for review.
run
run(ticket, ctx)
Push the implemented branch to the remote forge and open (or update) a pull/merge request, transitioning the ticket toward review.
generate_pr_description
generate_pr_description(diff, spec, settings)
Generate a structured PR body from the implementation diff.
Falls back to spec when PR summary is disabled or the LLM call fails.
robotsix_mill.stages.retrospect
Retrospect stage: DONE -> CLOSED.
Post-delivery audit. Analyses the finished ticket's workflow (state history + notes) and its Langfuse session (cost/latency/retries/errors, workflow-only if Langfuse is unconfigured), records findings, and — when MILL_RETROSPECT_SPAWN_DRAFTS is on and the agent proposes one — files an improvement DRAFT linked back via parent_id. Then -> CLOSED.
Agent/analysis failure is BLOCKED-resumable, never terminal.
RetrospectStage
Bases: Stage
Run a deep-analysis retrospective on completed tickets and optionally spawn follow-up draft tickets.
run
run(ticket, ctx)
Run a retrospective over a DONE ticket's history, comments, and description; emit findings and optionally spawn follow-up draft tickets.
robotsix_mill.stages.answer
Answer stage: picks up an ASKED inquiry, grounds the answering agent
in the real repo (best-effort clone), runs the agent, writes the answer
into description.md, preserves the original question as an artifact,
and transitions to ANSWERED (or BLOCKED on failure).
Inquiries are read-only — no branches, no PRs, no forge side effects.
AnswerStage
Bases: Stage
Answer a user question by cloning the repo for context and invoking an answering agent against the ticket description.
run
run(ticket, ctx)
Answer an ASKED inquiry: clone the repo for grounding, run the answering agent against the question, write the answer into description.md, and transition to ANSWERED (or BLOCKED on failure).
robotsix_mill.stages.dependency_fix
Shared spawn-or-reuse + wire-dependency + park-BLOCKED helper.
Extracted from :class:~.ci_fix.CIFixStage._handle_out_of_scope so that
other stages (implement baseline check, verify, review, merge) can
reuse the same idempotent pattern instead of dead-ending on BLOCKED
without queuing a fix.
find_merged_fix
find_merged_fix(ctx, dedup_labels, board_id)
Return (id, merged_at, merge_sha) of a just-merged fix for dedup_labels.
Looks at the MOST RECENT ticket on board_id carrying any of
dedup_labels (any state). Returns it only when it is DONE/CLOSED
and its history shows it reached DONE (PR merged); merged_at is
the time of that first DONE event and merge_sha the merged PR's
merge commit, resolved from the event's merged: <PR url> note
(None when it cannot be resolved). Returns None otherwise — an
open match is handled by :func:_label_dedup, and a ticket closed
without a merge (e.g. "no change needed") fixed nothing.
resolve_existing_fix
resolve_existing_fix(
ctx,
*,
dedup_labels,
title,
source_kind,
board_id,
exclude_id=None,
)
Return the id of an existing open fix ticket matching dedup_labels
(label match) or title (title match), else None.
Mirrors the dedup ordering used by :func:spawn_dependency_fix (label
match first, title fallback) so a caller can enrich the reused ticket's
spec before parking without racing the spawn's own dedup. A reused
ticket may be in any non-terminal state — including BLOCKED (a
parked fix from an earlier vague spec) — so a later pass that knows the
concrete remediation can re-drive the same ticket instead of spawning
a duplicate that parks on the stuck anchor.
spawn_dependency_fix
spawn_dependency_fix(
ticket,
ctx,
*,
title,
description,
source_kind,
block_reason_prefix,
priority=False,
dedup_labels=None,
)
Spawn (or reuse) a dependency fix ticket, wire both ways, park BLOCKED.
The caller provides a deterministic title so the spawn is idempotent across retries — the helper de-duplicates against still-open tickets from source_kind with the same title.
When dedup_labels is a non-empty list, a label-based dedup
search runs first (across all non-terminal tickets on the same
board, regardless of source kind). On a label match the existing
ticket is reused; otherwise a fresh ticket is created and the
fingerprint labels are stored on it via set_labels. The
existing title-based dedup still runs as a fallback when
dedup_labels is empty or no label match is found.
Returns a BLOCKED :class:Outcome whose note includes the fix
ticket id and the auto-resume guarantee.
robotsix_mill.stages.document
Document stage: DOCUMENTING -> CODE_REVIEW | DELIVERABLE.
Inspects the implementation diff and, when the change is user-facing, updates the relevant documentation files. For internal-only changes (pure refactors, bug fixes with no doc impact) this stage is a no-op and passes straight through.
The doc agent runs with warn-and-pass semantics: if it raises an exception the ticket still progresses — losing a finished implementation over a doc-update hiccup is the wrong trade.
DocumentStage
Bases: Stage
Generate or update project documentation from the implemented code changes in the cloned repo.
run
run(ticket, ctx)
Run the documentation agent against the post-implement clone to update project docs reflecting the code changes on the ticket branch.
robotsix_mill.stages.pause
Shared pause-detection helpers for refine and implement stage runners.
These detect ask_user invocations in the agent's message history,
persist/load the conversation state for cheap resume, and reconstruct
the message history with the operator's reply appended so the agent can
continue from exactly where it paused.
check_for_pause
check_for_pause(new_messages)
Return True when new_messages contains an ask_user
tool-return carrying the pause sentinel.
new_messages MUST be result.new_messages_json() — the bytes
pydantic-ai produces for messages added during the current run
only. Passing the full all_messages_json() re-triggers on the
prior turn's ask_user after a resume (the saved transcript
keeps the old sentinel forever) and was the source of the
"ticket re-pauses without a new question" bug fixed in 61a9709.
Scanning every tool-return in the new messages — not just the
last — is necessary because ask_user does NOT actually halt
the agent: pydantic-ai treats the sentinel as a normal tool
return and the model keeps running, often producing a structured
output before stopping. The final message is the model's
response, not the sentinel; only an earlier tool-return carries
the marker we look for.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_messages
|
bytes | None
|
Raw JSON bytes from
:meth: |
required |
save_conversation_state
save_conversation_state(ws, conversation_state, stage_name)
Persist the full agent conversation to
artifacts/{stage_name}_conversation_state.json.
stage_name ("refine" / "implement") namespaces the file so
a refine pause never gets loaded as an implement resume context — a
cross-stage contamination that masqueraded as "implement BLOCKED
with no changes produced" before 6f7f-2026-05-29.
load_conversation_state
load_conversation_state(ws, stage_name)
Read and return {stage_name}_conversation_state.json if it
exists; return None otherwise.
clear_conversation_state
clear_conversation_state(ws, stage_name)
Remove the saved state file for stage_name if present.
Called when a stage exits the AWAITING_USER_REPLY loop in a way that won't lead to a resume — e.g. when the operator's reply has been consumed and the run completed normally, so the next stage shouldn't pick up the stale file.
build_compact_resume_message_history
build_compact_resume_message_history(
saved_state, reply_text, *, git_stat=None
)
Build a compact 3-message resume history from the prior session.
Unlike the former build_resume_message_history — which replayed
the entire prior transcript — this helper extracts only the last
assistant text summary and constructs a fresh synthetic
message_history that is small and safe to re-upload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
saved_state
|
bytes
|
Raw JSON bytes from a prior
|
required |
reply_text
|
str
|
The operator's answer text. |
required |
git_stat
|
str | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
A |
acknowledge_unanswered_threads
acknowledge_unanswered_threads(ctx, ticket, thread_ids)
Post-agent verification: ensure every reviewer comment thread is either replied to or closed.
This is a deterministic safety net — the refine/implement agent system prompts instruct them to reply-to and close threads, but if the LLM forgets, this function catches it so no comment thread remains open indefinitely.
For each thread_id:
- Already closed → no-op.
- Open with child replies →
close_thread(agent replied but forgot to close). - Open with no child replies →
add_comment("Addressed.", parent_id=...)thenclose_thread(agent neither replied nor closed).
Only threads in thread_ids are touched — threads already closed before the agent ran or created by the agent during its run are never auto-closed.
If list_comments raises, logs a warning and returns (defensive
fallback — never block the pipeline).
robotsix_mill.stages.review
Review stage: CODE_REVIEW -> DOCUMENTING | READY | AWAITING_USER_REPLY.
Runs a blind dual-model review of the implementation diff. The review agent sees ONLY the git diff and ticket spec — no implementation context. APPROVE → DOCUMENTING; REQUEST_CHANGES → READY (with review comments stored); NEEDS_DISCUSSION → AWAITING_USER_REPLY (posts the verdict as an [ASK_USER] thread; operator's reply auto-resumes review).
ReviewStage
Bases: Stage
Check out the target branch and perform automated code review on the ticket's implemented changes.
run
run(ticket, ctx)
Process a CODE_REVIEW ticket: refresh the clone, check out the ticket branch, and run the automated reviewer agent against the diff.
robotsix_mill.stages.short_circuit_verify
Guards for the empty-diff → DONE short-circuit.
A ticket whose implement run produces an empty working-tree diff is normally closed as no change needed: the agent judged the spec already satisfied, so there is nothing to ship. But an empty diff can ALSO mean the run attempted edits that never persisted — the agent called file-mutating tools (and claimed success in its summary) yet the working tree still matches the target branch because the edits were reverted, the workspace was reset mid-run, or the writes landed outside the clone. Routing that case to DONE silently loses the work and falsely completes the ticket.
This is not hypothetical: ticket 904a — whose entire purpose was to add this guard — was itself closed this way. Its implement summary described new files and "341 tests pass", but the committed branch matched main exactly, so the empty-diff→DONE path fired and the work vanished.
:func:detect_edit_claim_contradiction distinguishes the two readings of an
empty diff by scanning the run's new messages for invocations of file-mutating
tools. Pure command-runner tools (run_command / Bash) are deliberately
excluded: a genuine no-change run routinely runs tests or greps without editing,
and counting those as an edit claim would block legitimate no-change closes.
run_invoked_edit_tools
run_invoked_edit_tools(new_messages)
Return the names of file-mutating tools invoked in new_messages.
new_messages MUST be the new_messages_json() payload from the agent
run — the messages added during THIS run only. Passing the full
all_messages_json() would re-count a prior run's edit calls after a
resume and manufacture a false contradiction (the same trap documented in
:func:robotsix_mill.stages.pause.check_for_pause).
Malformed or empty input yields [] (fail-open: never invent a
contradiction from a parse error — that would wrongly BLOCK good runs).
run_claimed_edited_rawpaths
run_claimed_edited_rawpaths(new_messages)
Return the de-duplicated VERBATIM paths edit tool-calls targeted.
Same scan as :func:run_claimed_edited_paths but keeps the full path
exactly as the tool-call carried it (repo-relative for mill fs tools,
absolute for the Claude SDK editors) instead of reducing to a basename.
Used by the gitignored-edit detector, which needs the real location to
ask git check-ignore. Fail-open on malformed input, like every
scanner here.
run_claimed_edited_paths
run_claimed_edited_paths(new_messages)
Return the de-duplicated basenames of files an edit tool-call targeted.
Reuses the same message-scanning skeleton as
:func:run_invoked_edit_tools, but instead of the tool names it
extracts the target file path from each edit tool-call's args and
returns the path basenames (e.g. board.js). The path is read from
args["path"] (mill fs tools write_file / edit_file /
delete_file — see agents/fs_tools.py) when present, else from
args["file_path"] (Claude SDK Write / Edit / MultiEdit /
NotebookEdit).
Basename-level matching is the deterministic v1 anchor: it is robust to the absolute (Claude SDK) vs repo-relative (mill) path mismatch without needing the repo root, at the accepted cost of confusing two like-named files in different directories.
Malformed or empty input — invalid JSON, non-list payload, missing
args, or missing/non-string path keys — fails open exactly like
:func:run_invoked_edit_tools: the offending entry is skipped (or []
is returned). A parse error must never manufacture a contradiction.
claimed_edits_already_on_branch
claimed_edits_already_on_branch(
*, new_messages, branch_changed_files
)
True when every file the run claimed to edit is already changed on the branch — i.e. the edits were an idempotent re-application, not lost work.
This disambiguates the one case where an edit-claim contradiction is a false alarm. On a resuming run whose branch is already ahead of target, prior passes have committed the implementation. A fresh pass re-reads the spec, finds the change present, and writes the same bytes back; git sees no diff, and the plain "edit tools ran but nothing changed" test reads that as work that failed to persist. It did persist — one pass earlier.
Requiring every claimed path to already be part of the branch's diff keeps the guard's teeth. An agent that edited a file the branch never touched really did lose work, and still trips the contradiction.
Matching is by basename, the same deterministic anchor
:func:run_claimed_edited_paths uses, so absolute Claude SDK paths and
repo-relative mill paths compare alike.
Fails closed: no claimed paths, or no branch changes, returns False
so the caller keeps its existing blocking behaviour. This function may only
ever excuse a contradiction on positive evidence.
detect_missing_claimed_files
detect_missing_claimed_files(
*, changed_files, new_messages, summary
)
Basenames the run claims it edited but that are absent from the diff.
This is the per-file generalization of
:func:detect_edit_claim_contradiction: instead of firing only when the
whole net diff is empty, it catches the non-empty-diff case where the
bulk of the work landed but a few specifically-named sub-fixes never
reached disk (the implement summary / thread-reply asserts edits the diff
does not contain). Anchored deterministically on file paths only — no NL
parsing of symbol- or line-level claims.
A basename is reported as missing only when ALL of:
- it was targeted by an
_EDIT_TOOL_NAMEStool-call this run (per :func:run_claimed_edited_paths), AND - it appears as a substring of summary (case-sensitive), AND
- it is NOT among the net-diff
changed_filesbasenames.
The summary gate is a required false-positive guard: a file the agent
edited and then reverted (a legitimate net-zero, e.g. via git
checkout) is targeted by an edit tool-call but is NOT named as a landed
fix in the summary, so it must not be flagged. Requiring presence in
summary filters that edit-then-revert case while staying deterministic.
When summary is falsy nothing is claimed → [].
Returns the sorted basenames that are claimed-but-missing. An empty result
means the run is consistent (safe to proceed). Fail-open: any parse error
upstream yields [] (never invents a contradiction from bad input).
extract_replayable_edits
extract_replayable_edits(new_messages)
Return the run's edit tool-calls as replayable ops, or None.
Each op is a dict {"kind", "path", ...} where kind is one of
"edit" (old + new text), "write" (full content), or
"delete". path is the verbatim tool-call path (repo-relative for
mill fs tools, absolute for the Claude SDK editors).
Returns None (a can't-replay-safely signal the caller MUST treat as
BLOCK) when the run invoked an edit tool that cannot be faithfully
replayed — an un-replayable kind (MultiEdit / NotebookEdit) or a
call missing the args needed to reproduce it. This keeps the work-loss
guard fully intact whenever the formatter-revert check is inapplicable.
Returns [] when no edit tool was invoked at all (no contradiction to
resolve). Fail-closed: malformed top-level JSON yields None.
analyze_pass_progress
analyze_pass_progress(new_messages, *, same_tool_window=5)
Analyze new_messages for stuck-loop signals.
Returns a dict with:
- total: total tool-call count in this pass
- edit_calls: number of file-mutating tool calls
- progress_calls: number of progress-signal tool calls
- stuck_same_tool: name of the tool that was called same_tool_window
consecutive times as the most recent non-progress calls, or None
- last_non_progress_run: length of the trailing run of consecutive
non-progress tool calls
Malformed / empty input returns zeros / None.
detect_edit_claim_contradiction
detect_edit_claim_contradiction(
*, has_changes, new_messages
)
Names of edit tools the run invoked despite producing no diff.
A non-empty result is an edit-claim contradiction: the run mutated files (per its own tool calls) but the working tree matches the target branch, so the work did not persist. The empty-diff→DONE short-circuit MUST be skipped in that case — the caller should BLOCK for inspection instead.
An empty result means the empty diff is consistent with a genuine no-change run (the agent only read / ran commands, or made no tool calls at all), and the short-circuit is safe to take.
When has_changes is True there is a real diff, so no short-circuit is
happening and there is nothing to verify — returns [].
cited_fix_unverified
cited_fix_unverified(repo_dir, text)
Return a diagnostic when a closure rationale claims an already-shipped
fix citing a commit that is NOT present at origin/main, else None.
The empty-diff → DONE short-circuit trusts the agent's "already fixed
elsewhere" rationale. When that rationale cites a commit SHA, verify it
against the live tree before closing: the commit must be a real object AND
an ancestor of origin/main (git cat-file -t reports commit and
git merge-base --is-ancestor <sha> origin/main exits 0). A cited SHA
that is missing or not an ancestor is an unverified merge/completion claim
— the work was never actually merged, so the caller MUST route the ticket
back for the real fix instead of closing it DONE.
Only fires when the rationale actually claims an external fix (reusing the
refine stage's _rationale_claims_external_fix detector) so a stray
hex-like token in a legitimate no-change rationale never triggers a false
block, and only when at least one cited SHA fails verification. Any git
error is treated as "not verified" so a transient failure never lets a
false close through. Returns None when there is no external-fix claim,
no cited SHA, or every cited SHA is verified.
robotsix_mill.stages.registry
Stage registry: name -> Stage instance.
Adding a stage = importing its class here. :data:STAGES is the single
source of truth; it must cover every value in
:data:robotsix_mill.core.states.STAGE_FOR_STATE.
get_stage
get_stage(name)
Retrieve a stage instance by name from the registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The stage name (e.g., 'refine', 'implement', 'deliver'). |
required |
Returns:
| Type | Description |
|---|---|
Stage
|
The Stage instance for the given name. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the stage name is unknown. |