Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(self-build): ship fit issues from the person's own repos as draft pull requests through their coding agent (#768)
Ruben Lütkeebfad85891a8
diff --git a/docs/self-build-code.md b/docs/self-build-code.mdnew file mode 100644index 0000000000..70bff1a9c1--- /dev/null+++ b/docs/self-build-code.md@@ -0,0 +1,128 @@+# Self-building loop: coding projects++Dodaios knows the person's own repositories well enough to pick a suitable+issue now and then and ship it through their coding agent as a pull request.+It does this rarely, proves the change with the project's tests and CI, opens+a draft unless the person opted the repository in to landing, and every+build can be undone with one click. This is the `code` kind of the+[self-building loop](self-build.md); the code lives in `dodaios/self_build/code/`.++```+ brief ──> intake ──> triage ──> case ──> worktree ──> coding run ──> judge ──> pull request ──> CI ──> trial ──> merged / closed+ (git) (poll) (Python) (ledger) (branch) (subscription) (tests) (draft) (learn)+```++## The project brief++For each project in the Agentic IDE's library, `brief.py` keeps a brief in+`self_build_code.db` (data directory), stored in parts. Each part remembers the+key it was built for, and a refresh rebuilds only the parts whose key changed:++| Part | Holds | Rebuilt when |+|---|---|---|+| `git` | HEAD, branch, default branch, GitHub repository | HEAD moves |+| `structure` | stack, top folders, languages, a file map | the tree changes |+| `commands` | set-up and test commands, what CI runs | the tree changes |+| `conventions` | `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`, `CONTRIBUTING.md`, ... | one of them changes on disk |+| `activity` | recent commits, what the person worked on and where | HEAD moves |+| `github` | open issues and pull requests | each issue poll |+| `outcomes` | loop PRs merged, changed before merge, closed; lessons | each outcome |++Everything is deterministic (git calls and file reads, no model). An+unchanged project costs three git calls and a few file `stat`s per refresh.++## Intake and triage++The loop polls; a desktop has no public webhook URL. A repository is polled+only when all of these hold:++- it is in the IDE's library, and its `origin` is on GitHub;+- the GitHub account the IDE uses owns it, or administers its organisation,+ and has admin or maintain rights; it is not archived;+- it is not Dodaios' own source (that goes through the normal branch, pull+ request and done-gate path);+- the person works on it: opened in the IDE in the last 45 days, or their own+ commits are among the recent ones.++Each repository is asked for issues at most every 30 minutes. Triage+(`triage.py`) is plain Python. An issue is a candidate when it is open and+unassigned; the person wrote it or it carries an agent label (`agent`,+`dodaios`, `good first issue`, ...), so a stranger's text alone never starts+a build; it is labelled for agents or resembles an issue whose loop pull+request the person merged unchanged; its title and description make the scope+clear and it is not a task list or a long discussion; no pull request is open+for it; nothing in it mentions secrets, credentials, deployment, releases or+CI; and the repository has a test command. A repository where the person+closed loop pull requests without merging any is left alone.++A fit issue becomes a build case with signature `code:<owner>/<repo>#<n>`+through `service.admit`, so autonomy, the kill switch, the silent first days+and the daily code-run cap all apply. At most one new case per pass, and an+issue that ever had a build is not offered again. Proposals cost no model+call.++## Execution++A case in `building` runs only while the person is away from the computer+(no keyboard or mouse input and no typing in an IDE pane for 15 minutes) and a+subscription coding CLI is free (`seat.py`): its plan login is signed in, its+own API-key variable is not set (the CLI would bill that key), it is not in a+usage cooldown and no usage window is over 80 %. Otherwise the case waits, for+up to three days; a case that never got to run may be offered again later. The+kill switch stops a running build at its next step and puts the case back in+the queue; an undo stops it the same way and removes what it made.++1. A fresh worktree and a new branch `dodaios/issue-<n>-<slug>` from the+ repository's default branch as GitHub reports it, fetched from `origin`,+ inside the repository (`<repo>/.worktrees/`). A branch of that name that+ already exists, here or on GitHub, stops the build. The person's checkout is+ never touched.+2. At most one planning call on a connected subscription, inside+ `cost.attributed(build_id)`. A `large` estimate stops the build. Without a+ subscription brain there is no call and the coding agent plans itself.+3. A headless coding thread in that worktree (the IDE's thread surface, so the+ person can read every step). The prompt holds the brief, the issue, the+ relevant file outlines and the rules: small change with tests, follow the+ instruction files, never touch CI, deployment, secrets or instruction+ files, do not push. A question or plan card stops the run: the task was not+ clear enough for unattended work.+4. The judge (`judge.py`), which the agent cannot edit: nothing protected was+ changed, and the test commands the brief read before the run pass.+5. Push the branch (only when `origin` fetches from and pushes to that very+ repository) and open a pull request that says `Closes #<n>`, with the agent's summary and what was+ checked. Draft by default.++Nothing else leaves the machine: no issue comments, labels or reviews, and no+push to a repository the person does not own.++## Proof, landing and outcomes++`watch.py` looks at each open loop pull request on every pass (every five+minutes):++- Green CI is the proof (`attach_proof`, judge `tests+ci`) and the build goes+ on trial. Red CI fails it: the lesson is kept, the pull request closed and+ the branch deleted. A repository without CI is judged by the local tests+ once 15 minutes showed no check is coming.+- **Landing** is off by default. A repository listed in+ `[self_build] code_land_repos = ["owner/name"]` gets ready (non-draft) pull+ requests that are merged once CI is green.+- Merged as built counts `accepted`, merged after the person changed it+ counts `corrected`; the build is kept. Closed without merge: the branch and+ worktree go and the build is `undone`. Each outcome feeds the repository's+ profile (triage) and its brief (`outcomes`, read by the next prompt).++## Undo++The undoer closes the open pull request, deletes the remote and local branch+and removes the worktree, and stops a coding run that is still working. It+removes only `dodaios/` branches the build created itself, and a branch only+while it still points at the commit the loop pushed: commits or uncommitted+changes the person added keep the branch and worktree. A merged pull request+cannot be undone from here; revert it in the repository.++## Cost++Idle cost is GitHub reads and git calls, no model. A build costs one optional+planning call and one coding run, both on the person's subscription; the+ledger shows the planning call's tokens under the build.diff --git a/docs/self-build.md b/docs/self-build.mdindex 976f5dd773..81c6a2f8e5 100644--- a/docs/self-build.md+++ b/docs/self-build.md@@ -147,6 +147,7 @@ turn; no model call and no timer unless a need is waiting to be decided.| `max_open_trials` | `5` | || `max_code_runs_per_day` | `1` | || `max_rejections` | `2` | |+| `code_land_repos` | `[]` | repositories (`owner/name`) whose loop pull requests are merged after green CI ([code builds](self-build-code.md)) |At `suggest` a card asks first. At `trial` the build goes live on trial; anunused trial is archived on its own, a used one waits for the person's keep.diff --git a/dodaios/core/config.py b/dodaios/core/config.pyindex b3c6c1488b..4707c36986 100644--- a/dodaios/core/config.py+++ b/dodaios/core/config.py@@ -4724,6 +4724,9 @@ class SelfBuildConfig(BaseModel):max_code_runs_per_day: int = Field(default=1, ge=0, le=20)#: A need the person rejected or undid this often is not offered again.max_rejections: int = Field(default=2, ge=1, le=20)+ #: Repositories (``owner/name``) whose loop pull requests are merged once CI is+ #: green ("land it"). Empty: every loop pull request is a draft the person merges.+ code_land_repos: list[str] = Field(default_factory=list)class JarvisConfig(BaseModel):diff --git a/dodaios/i18n/locales/de.json b/dodaios/i18n/locales/de.jsonindex 141ff73ad2..fddc86bd60 100644--- a/dodaios/i18n/locales/de.json+++ b/dodaios/i18n/locales/de.json@@ -521,6 +521,10 @@},"case": {"counted": "{count}-mal an {days} verschiedenen Tagen gefragt."+ },+ "code": {+ "title": "Issue #{number} in {repo} lösen: {title}",+ "case": "Issue #{number} in {repo} passt für einen Agenten, der allein arbeitet ({signal}). Ein Coding-Agent würde es über dein Abo bearbeiten, während du weg bist, in einem eigenen Worktree und Branch, und die Tests ausführen ({tests}). Das Ergebnis ist ein Pull Request, der das Issue schließt, als Entwurf, außer du lässt dieses Repository selbst mergen. {url}"}}}diff --git a/dodaios/i18n/locales/en.json b/dodaios/i18n/locales/en.jsonindex 5b4c45206d..92728e99d0 100644--- a/dodaios/i18n/locales/en.json+++ b/dodaios/i18n/locales/en.json@@ -521,6 +521,10 @@},"case": {"counted": "Asked {count} times on {days} different days."+ },+ "code": {+ "title": "Fix issue #{number} in {repo}: {title}",+ "case": "Issue #{number} in {repo} looks right for an unattended agent ({signal}). A coding agent would work on it on your subscription while you are away, in its own worktree and branch, and run the tests ({tests}). The result is a pull request that closes the issue, a draft unless you let this repository land on its own. {url}"}}}diff --git a/dodaios/i18n/locales/es.json b/dodaios/i18n/locales/es.jsonindex d34a2ecbed..900213de37 100644--- a/dodaios/i18n/locales/es.json+++ b/dodaios/i18n/locales/es.json@@ -521,6 +521,10 @@},"case": {"counted": "Pedido {count} veces en {days} días distintos."+ },+ "code": {+ "title": "Resolver el issue #{number} en {repo}: {title}",+ "case": "El issue #{number} de {repo} parece adecuado para un agente sin supervisión ({signal}). Un agente de programación trabajaría en él con tu suscripción mientras no estás, en su propio worktree y rama, y ejecutaría las pruebas ({tests}). El resultado es un pull request que cierra el issue, como borrador salvo que permitas que este repositorio se fusione solo. {url}"}}}diff --git a/dodaios/i18n/locales/pt.json b/dodaios/i18n/locales/pt.jsonindex 109452377e..d3ac79936c 100644--- a/dodaios/i18n/locales/pt.json+++ b/dodaios/i18n/locales/pt.json@@ -521,6 +521,10 @@},"case": {"counted": "Pedido {count} vezes em {days} dias diferentes."+ },+ "code": {+ "title": "Resolver o issue #{number} em {repo}: {title}",+ "case": "O issue #{number} de {repo} parece adequado para um agente sem supervisão ({signal}). Um agente de programação trabalharia nele com a sua assinatura enquanto você está ausente, no seu próprio worktree e branch, e executaria os testes ({tests}). O resultado é um pull request que fecha o issue, como rascunho, a menos que você deixe este repositório fazer o merge sozinho. {url}"}}}diff --git a/dodaios/self_build/code/__init__.py b/dodaios/self_build/code/__init__.pyindex b34043e16d..d89b705646 100644--- a/dodaios/self_build/code/__init__.py+++ b/dodaios/self_build/code/__init__.py@@ -1,8 +1,17 @@"""Coding projects for the self-building loop (``Kind.CODE``).Dodaios knows the person's own repositories well enough to pick a suitable-issue now and then and ship it through their coding agent as a pull request.-This part holds what it knows: :mod:`.brief` (the stored project brief),-:mod:`.commands` (how a project is tested), :mod:`.github` (the GitHub reads-and writes it may make) and :mod:`.triage` (which issues qualify).+issue now and then and ship it through their coding agent as a pull request:+rarely, proven by tests and CI, as a draft unless the person opted the+repository in to landing, and undoable with one click. Doc:+``docs/self-build-code.md``.++Modules: :mod:`.brief` (the stored project brief), :mod:`.intake` and+:mod:`.triage` (which issues), :mod:`.builder` (worktree, run, judge, pull+request), :mod:`.watch` (CI, merge, close, learning), :mod:`.loop` (the pass+and :func:`install`)."""++from .loop import CodeLoop, install++__all__ = ["CodeLoop", "install"]diff --git a/dodaios/self_build/code/builder.py b/dodaios/self_build/code/builder.pynew file mode 100644index 0000000000..24e4fdbee0--- /dev/null+++ b/dodaios/self_build/code/builder.py@@ -0,0 +1,555 @@+"""Build one code case: worktree, plan, coding run, judge, pull request.++Called by the loop for a ``Kind.CODE`` record in ``building``. Before each step+the record's undo payload names what the step is about to create, and after+it what was created, so an undo, a pause or a restart at any point knows+exactly what exists:++1. a fresh worktree and branch (``dodaios/issue-<n>-...``) from the remote+ default branch, inside the repository (``<repo>/.worktrees/``); a branch of+ that name that already exists here or on GitHub stops the build;+2. at most one cheap planning call; ``large`` stops here;+3. a headless coding thread on a subscription CLI in that worktree;+4. the judge: nothing protected was touched, the tests pass;+5. push the branch (only when ``origin`` fetches from and pushes to the+ repository) and open a pull request that closes the issue, draft unless the+ person opted the repository in to landing. The record moves to+ ``proving``; ``watch`` waits for CI.++A failure records the lesson in the repository's profile, removes what the+run created and moves the record to ``failed``. A pause puts the case back in+the queue instead (nothing is lost); an undo leaves the state to the undo.+No pull request is left behind by a failed build.+"""++from __future__ import annotations++import asyncio+import re+from pathlib import Path+from typing import Any, Final++from loguru import logger++from ..ledger import now_ms+from ..records import BuildRecord, State+from . import brief as brief_mod+from . import gitcmd, judge+from .context import BRANCH_PREFIX, Context, branch_name, land_repos, parse_signature+from .github import Issue+from .planner import Plan+from .runner import RunResult++_SUMMARY_CHARS: Final[int] = 2_500+_FOOTER: Final[str] = (+ "Built by Dodaios on its own initiative from issue #{number} (self-build `{build_id}`). "+ 'Undo it in Dodaios under "Built for you", or close this pull request.'+)+#: Untracked output a test run leaves behind, never the person's work.+_JUNK: Final[tuple[str, ...]] = (+ "__pycache__",+ ".pytest_cache",+ ".mypy_cache",+ ".ruff_cache",+ "node_modules",+ ".coverage",+)+#: A failure note with this prefix means the case never ran; intake may offer it again.+NOT_RUN: Final[str] = "not run: "+++class BuildError(RuntimeError):+ """A step failed; the message is the lesson the profile keeps."""+++class Stopped(BuildError):+ """The build was undone (``requeue=False``) or the loop paused (``requeue=True``)."""++ def __init__(self, message: str, *, requeue: bool) -> None:+ super().__init__(message)+ self.requeue = requeue+++# ------------------------------------------------------------------ git steps+++def make_worktree(folder: str, branch: str, base_branch: str) -> dict[str, str]:+ """A fresh worktree on a NEW ``branch`` from ``origin/<base_branch>``."""+ from dodaios.agentic_ide import git_ops++ root = Path(folder)+ if gitcmd.git(["show-ref", "--verify", "--quiet", f"refs/heads/{branch}"], root).ok:+ raise BuildError(f"the branch {branch} already exists here")+ remote = gitcmd.git(+ ["ls-remote", "--exit-code", "--heads", "origin", branch],+ root,+ timeout=gitcmd.NETWORK_TIMEOUT_S,+ )+ if remote.ok:+ raise BuildError(f"the branch {branch} already exists on GitHub")+ if remote.code != 2: # 2 = no such branch; anything else = origin unreachable+ raise BuildError("origin could not be reached")+ fetch = gitcmd.git(["fetch", "origin", base_branch], root, timeout=gitcmd.NETWORK_TIMEOUT_S)+ if not fetch.ok:+ raise BuildError(f"the default branch {base_branch} could not be fetched")+ base_sha = gitcmd.out(["rev-parse", f"origin/{base_branch}^{{commit}}"], root)+ if not base_sha:+ raise BuildError(f"the default branch {base_branch} could not be read")+ try:+ prepared = git_ops.prepare(root, "new_worktree", branch=branch, base=base_sha)+ except git_ops.GitError as exc: # re-raised as the build's lesson+ raise BuildError(f"no worktree: {exc}") from exc+ return {"worktree": prepared.folder, "base_sha": base_sha, "base": base_branch}+++def planned_worktree(folder: str, branch: str) -> str:+ from dodaios.agentic_ide import git_ops++ return str(git_ops.worktree_path(Path(folder), branch))+++def collect(worktree: str, branch: str, base_sha: str, message: str) -> list[str]:+ """Commit whatever the agent left uncommitted; the files changed since the base."""+ root = Path(worktree)+ current = gitcmd.out(["rev-parse", "--abbrev-ref", "HEAD"], root)+ if current != branch:+ raise BuildError(f"the coding agent left the branch (now on {current or 'nothing'})")+ gitcmd.git(["add", "--all"], root)+ if not gitcmd.git(["diff", "--cached", "--quiet"], root).ok:+ done = gitcmd.git(["commit", "-m", message], root)+ if not done.ok:+ raise BuildError(f"the change could not be committed: {done.tail(300)}")+ listing = gitcmd.git(["diff", "--name-only", f"{base_sha}..HEAD"], root)+ if not listing.ok:+ raise BuildError("the change could not be read")+ return [line.strip() for line in listing.out.splitlines() if line.strip()]+++def push(worktree: str, branch: str, repo: str) -> str:+ """Push the branch after checking ``origin`` fetches from and pushes to ``repo``."""+ root = Path(worktree)+ for direction in (False, True):+ if gitcmd.origin_repo(root, push=direction).lower() != repo.lower():+ raise BuildError(f"origin does not point at {repo}")+ if not branch.startswith(BRANCH_PREFIX):+ raise BuildError("refusing to push a branch the loop did not create")+ result = gitcmd.git(+ ["push", "--set-upstream", "origin", f"refs/heads/{branch}:refs/heads/{branch}"],+ root,+ timeout=gitcmd.NETWORK_TIMEOUT_S,+ )+ if not result.ok:+ raise BuildError(f"the branch could not be pushed: {result.tail(300)}")+ return gitcmd.out(["rev-parse", "HEAD"], root)+++def remove_local(+ folder: str, worktree: str, branch: str, *, head: str = "", force: bool = False+) -> bool:+ """Remove the loop's worktree and local branch. Returns False when it kept them.++ Only a ``dodaios/`` branch. Kept when the branch moved past ``head`` (the+ person added commits) or, without ``force``, when the worktree holds+ uncommitted changes. ``force`` is for a run that is still the loop's own.+ """+ if not branch.startswith(BRANCH_PREFIX):+ return False+ root = Path(folder)+ tip = gitcmd.out(["rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], root)+ if head and tip and tip != head:+ logger.info("self-build code: kept {}: it has commits the loop did not make", branch)+ return False+ if worktree and Path(worktree).exists():+ if not force and _unsaved(worktree):+ logger.info("self-build code: kept {}: it has uncommitted changes", worktree)+ return False+ gitcmd.git(["worktree", "remove", *(["--force"] if force else []), worktree], root)+ gitcmd.git(["worktree", "prune"], root)+ if tip:+ gitcmd.git(["branch", "-D", branch], root)+ return True+++def _unsaved(worktree: str) -> list[str]:+ """Changes in the worktree someone would miss (caches and builds do not count)."""+ lines = gitcmd.out(["status", "--porcelain"], worktree).splitlines()+ return [line for line in lines if not any(junk in line for junk in _JUNK)]+++def remove_remote(folder: str, branch: str, head: str) -> None:+ """Delete the pushed branch, only while it still points at the loop's ``head``."""+ if not branch.startswith(BRANCH_PREFIX) or not head:+ return+ result = gitcmd.git(+ [+ "push",+ f"--force-with-lease=refs/heads/{branch}:{head}",+ "origin",+ f":refs/heads/{branch}",+ ],+ Path(folder),+ timeout=gitcmd.NETWORK_TIMEOUT_S,+ )+ if not result.ok and "remote ref does not exist" not in result.err:+ logger.info("self-build code: kept the remote branch {}: {}", branch, result.tail(200))+++# ------------------------------------------------------------------ prompt+++def _relevant_files(worktree: str, issue: Issue) -> str:+ try:+ from dodaios.agentic_ide.code_skeleton import skeletons+ from dodaios.agentic_ide.file_index import build_index++ rels = build_index(worktree).suggest(f"{issue.title}\n{issue.body[:1500]}", limit=6)+ outlines = skeletons(worktree, rels, max_files=4, max_total=12_000)+ except Exception as exc: # noqa: BLE001 - the agent finds the files itself without hints+ logger.debug("self-build code: no file hints: {}", exc)+ return ""+ return "\n\n".join(f"### {rel}\n{text}" for rel, text in outlines.items())+++def compose_prompt(+ *,+ issue: Issue,+ repo: str,+ worktree: str,+ branch: str,+ base: str,+ brief_text: str,+ plan: Plan,+ tests: list[str],+) -> str:+ parts = [+ f"Work on issue #{issue.number} of {repo} on your own. Nobody is at the computer to "+ "answer questions, so decide yourself and follow the repository's conventions.",+ f"You work in {worktree}: a fresh git worktree on branch {branch}, made from "+ f"origin/{base}. Stay in this folder.",+ "",+ f"## Issue #{issue.number}: {issue.title}",+ issue.body.strip()[:4_000] or "(no description)",+ ]+ if plan.text:+ parts += ["", "## Suggested plan", plan.text]+ parts += ["", "## Project brief", brief_text]+ hints = _relevant_files(worktree, issue)+ if hints:+ parts += ["", "## Files that look relevant (outlines)", hints]+ parts += [+ "",+ "## Rules",+ "- Keep the change as small as the issue needs, and add or update tests for it.",+ "- Follow the repository's own instruction files shown in the brief.",+ "- Do not touch CI config (.github and the like), deployment, secrets, .env files or "+ "the instruction files (AGENTS.md, CLAUDE.md). A change that does is thrown away.",+ "- Do not push, open pull requests, comment on GitHub, change git remotes or switch "+ "branches; Dodaios checks your work and does that.",+ "- Run the tests before you finish; they must pass: " + "; ".join(tests) + ".",+ "- Commit your work on this branch with a clear message.",+ "- If the issue cannot be done safely, change nothing and say why in one paragraph.",+ "- End with a short summary of what you changed and how you checked it; it becomes "+ "the pull request description.",+ ]+ return "\n".join(parts)+++def pr_body(+ *,+ issue: Issue,+ summary: str,+ tests_detail: str,+ changed: list[str],+ build_id: str,+ plan: Plan,+) -> str:+ text = re.sub(r"(?im)^\s*(closes|fixes|resolves)\s+#\d+\s*$", "", summary).strip()+ lines = [f"Closes #{issue.number}", "", text[:_SUMMARY_CHARS] or "(no summary)", ""]+ lines += ["### Checked", *[f"- {line}" for line in tests_detail.splitlines() if line]]+ shown = ", ".join(f"`{path}`" for path in changed[:15])+ lines.append(f"- Changed files: {shown}" + (" …" if len(changed) > 15 else ""))+ if plan.size:+ lines.append(f"- Estimated size before the run: {plan.size}")+ lines += ["", _FOOTER.format(number=issue.number, build_id=build_id)]+ return "\n".join(lines)+++# ------------------------------------------------------------------ the build+++def target(ctx: Context, record: BuildRecord) -> tuple[str, Issue, dict[str, Any]]:+ """``(repo, issue, intake data)`` for a code record, from the intake store."""+ parsed = parse_signature(record.signature)+ if parsed is None:+ raise BuildError(f"not a code signature: {record.signature}")+ repo, number = parsed+ seen = ctx.store.issue(repo, number)+ if seen is None or not seen["issue"].get("folder"):+ raise BuildError("the issue is no longer known; it was not seen in the last poll")+ data = seen["issue"]+ return repo, Issue.from_json(data), data+++def checkpoint(ctx: Context, record: BuildRecord) -> None:+ """Raise :class:`Stopped` once the build was undone or the loop paused."""+ if record.id in ctx.stopping or not ctx.still(record, State.BUILDING):+ raise Stopped("stopped: the build was undone", requeue=False)+ if _paused(ctx):+ raise Stopped("stopped: the self-building loop was paused", requeue=True)+++async def _record(+ ctx: Context, record: BuildRecord, stage: str, undo: dict[str, Any], **extra: Any+) -> None:+ artefact = {+ "type": "branch",+ "repo": undo["repo"],+ "branch": undo["branch"],+ "stage": stage,+ **extra,+ }+ await asyncio.to_thread(ctx.ledger.attach_artefact, record.id, artefact, dict(undo))+++async def _fail(ctx: Context, record: BuildRecord, error: BuildError, *, repo: str) -> None:+ from .watch import cleanup++ lesson = str(error).strip()[:400] or "the build failed"+ current = await asyncio.to_thread(ctx.ledger.get, record.id)+ if current is not None and current.undo:+ try:+ await cleanup(ctx, current, close_pull=True, force=True)+ except Exception: # noqa: BLE001 - logged; what is left is listed in the record+ logger.opt(exception=True).warning("self-build code: cleanup of {} failed", record.id)+ if isinstance(error, Stopped):+ if error.requeue and ctx.still(record, State.BUILDING):+ await asyncio.to_thread(ctx.ledger.attach_artefact, record.id, {}, {})+ logger.info("self-build code: {} paused; it waits in the queue", record.signature)+ return # an undo owns the record's state+ logger.info("self-build code: {} failed: {}", record.signature, lesson)+ if repo:+ parsed = parse_signature(record.signature)+ await asyncio.to_thread(+ ctx.store.add_to_profile,+ repo,+ "lessons",+ {"number": parsed[1] if parsed else 0, "lesson": lesson},+ )+ if ctx.still(record, State.BUILDING, State.PROVING):+ await asyncio.to_thread(ctx.ledger.set_state, record.id, State.FAILED, lesson)+++async def _guarded(ctx: Context, record: BuildRecord, step: Any) -> None:+ repo = ""+ try:+ repo, issue, data = target(ctx, record)+ await step(repo, issue, data)+ except BuildError as exc: # _fail logs it, keeps the lesson and settles the record+ await _fail(ctx, record, exc, repo=repo)+ except Exception as exc: # noqa: BLE001 - an unexpected error fails this build only+ logger.opt(exception=exc).warning("self-build code: build {} crashed", record.id)+ await _fail(ctx, record, BuildError(f"unexpected error: {type(exc).__name__}"), repo=repo)+++async def build(ctx: Context, record: BuildRecord, *, provider: str) -> None:+ """Run one build to ``proving`` (pull request open), ``failed``, or back to the queue."""++ async def step(repo: str, issue: Issue, data: dict[str, Any]) -> None:+ await _build(ctx, record, repo=repo, issue=issue, data=data, provider=provider)++ await _guarded(ctx, record, step)+++async def resume(ctx: Context, record: BuildRecord, result: RunResult | None) -> None:+ """Carry on a build whose coding run ended while the app was not running."""++ async def step(repo: str, issue: Issue, data: dict[str, Any]) -> None:+ if result is None or not result.ok:+ error = (result.error if result else "") or "no answer"+ raise BuildError(f"the coding run did not finish: {error}")+ brief, _ = await asyncio.to_thread(+ brief_mod.refresh, ctx.store, str(data["folder"]), repo=repo+ )+ await finish(+ ctx,+ record,+ repo=repo,+ issue=issue,+ undo=dict(record.undo),+ summary=result.summary,+ tests=brief.test_commands,+ setup=brief.setup_commands,+ plan=Plan(),+ )++ await _guarded(ctx, record, step)+++async def _build(+ ctx: Context,+ record: BuildRecord,+ *,+ repo: str,+ issue: Issue,+ data: dict[str, Any],+ provider: str,+) -> None:+ folder = str(data["folder"])+ brief, _ = await asyncio.to_thread(brief_mod.refresh, ctx.store, folder, repo=repo)+ tests = brief.test_commands+ if not tests:+ raise BuildError("no test command in this repository")+ # GitHub's own default branch, read at intake; the local guess only as a fallback.+ base = str(data.get("base") or "") or brief.default_branch or "main"+ branch = branch_name(issue.number, issue.title)+ undo: dict[str, Any] = {+ "repo": repo,+ "folder": folder,+ "branch": branch,+ "base": base,+ "worktree": planned_worktree(folder, branch),+ }+ await _record(ctx, record, "worktree", undo)+ checkpoint(ctx, record)+ made = await asyncio.to_thread(make_worktree, folder, branch, base)+ undo.update(made, created=True)+ await _record(ctx, record, "worktree", undo)+ checkpoint(ctx, record)++ plan = Plan()+ if ctx.plan is not None:+ plan = await ctx.plan(record.id, issue, brief.render())+ if plan.size == "large":+ raise BuildError("estimated as large work, not for an unattended agent")+ checkpoint(ctx, record)++ from . import commands++ prompt = compose_prompt(+ issue=issue,+ repo=repo,+ worktree=undo["worktree"],+ branch=branch,+ base=base,+ brief_text=brief.render(),+ plan=plan,+ tests=[commands.shown(cmd) for cmd in tests],+ )++ async def remember_session(session_id: str) -> None:+ undo["session_id"] = session_id+ await _record(ctx, record, "coding", undo, thread=session_id)++ def should_stop() -> bool:+ try:+ checkpoint(ctx, record)+ except Stopped: # the answer to "should the run stop?", not an error+ return True+ return False++ result = await ctx.runner.run(+ provider=provider,+ folder=undo["worktree"],+ prompt=prompt,+ title=f"#{issue.number} {issue.title}",+ timeout_s=ctx.run_timeout_s,+ should_stop=should_stop,+ on_session=remember_session,+ )+ checkpoint(ctx, record)+ if not result.ok:+ raise BuildError(f"the coding run did not finish: {result.error or 'no answer'}")+ await finish(+ ctx,+ record,+ repo=repo,+ issue=issue,+ undo=undo,+ summary=result.summary,+ tests=tests,+ setup=brief.setup_commands,+ plan=plan,+ )+++async def finish(+ ctx: Context,+ record: BuildRecord,+ *,+ repo: str,+ issue: Issue,+ undo: dict[str, Any],+ summary: str,+ tests: list[list[str]],+ setup: list[list[str]],+ plan: Plan,+) -> None:+ """Judge the finished run and open the pull request (also used on resume)."""+ ledger = ctx.ledger+ worktree, branch = str(undo["worktree"]), str(undo["branch"])+ message = f"fix: {issue.title.strip()[:60]} (#{issue.number})"+ changed = await asyncio.to_thread(collect, worktree, branch, str(undo["base_sha"]), message)+ if not changed:+ raise BuildError(+ "the coding agent changed nothing" + (f": {summary[:200]}" if summary else "")+ )+ blocked = judge.guard(changed)+ if blocked:+ raise BuildError("the change touched protected files: " + ", ".join(blocked[:5]))+ passed, detail = await asyncio.to_thread(judge.run_tests, worktree, setup=setup, tests=tests)+ if not passed:+ await asyncio.to_thread(+ ledger.attach_proof, record.id, passed=False, judge="tests", detail=detail+ )+ raise BuildError("the tests failed: " + detail.splitlines()[0][:200])+ checkpoint(ctx, record)++ api = ctx.github()+ if api is None:+ raise BuildError("GitHub is not connected")+ undo["head"] = gitcmd.out(["rev-parse", "HEAD"], worktree)+ undo["pushed"] = True # before the push: an undo meanwhile still deletes it+ await _record(ctx, record, "pushing", undo)+ undo["head"] = await asyncio.to_thread(push, worktree, branch, repo)+ await _record(ctx, record, "pushed", undo)+ checkpoint(ctx, record)+ draft = repo.lower() not in land_repos(ctx.config())+ pull = await asyncio.to_thread(+ api.create_pull,+ repo,+ head=branch,+ base=str(undo["base"]),+ title=issue.title.strip()[:120] or f"Fix #{issue.number}",+ body=pr_body(+ issue=issue,+ summary=summary,+ tests_detail=detail,+ changed=changed,+ build_id=record.id,+ plan=plan,+ ),+ draft=draft,+ )+ undo.update({"pr_id": pull.id, "pr_number": pull.number, "pr_url": pull.url})+ artefact = {+ "type": "pull_request",+ "repo": repo,+ "number": pull.number,+ "url": pull.url,+ "branch": branch,+ "draft": draft,+ "tests": detail[:500],+ "changed": changed[:30],+ "opened_ms": now_ms(),+ }+ await asyncio.to_thread(ledger.attach_artefact, record.id, artefact, dict(undo))+ checkpoint(ctx, record)+ await asyncio.to_thread(+ ledger.set_state, record.id, State.PROVING, "pull request opened; waiting for CI"+ )+++def _paused(ctx: Context) -> bool:+ from .. import policy++ return policy.paused(ctx.ledger)diff --git a/dodaios/self_build/code/context.py b/dodaios/self_build/code/context.pynew file mode 100644index 0000000000..df9753bc7f--- /dev/null+++ b/dodaios/self_build/code/context.py@@ -0,0 +1,78 @@+"""What every stage of the code builder works with, in one place (and one test seam)."""++from __future__ import annotations++import re+from collections.abc import Awaitable, Callable+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Final++from ..records import BuildRecord+from .github import GitHub+from .runner import Runner+from .seat import Seat+from .store import CodeStore++#: Every branch the loop creates starts with this, and undo removes nothing else.+BRANCH_PREFIX: Final[str] = "dodaios/"+_SIGNATURE: Final[re.Pattern[str]] = re.compile(+ r"^code:(?P<repo>[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100})#(?P<number>\d+)$"+)+++def signature(repo: str, number: int) -> str:+ return f"code:{repo}#{int(number)}"+++def parse_signature(sig: str) -> tuple[str, int] | None:+ match = _SIGNATURE.match(sig.strip())+ if match is None:+ return None+ return match.group("repo"), int(match.group("number"))+++def branch_name(number: int, title: str) -> str:+ slug = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")[:40].strip("-")+ return f"{BRANCH_PREFIX}issue-{int(number)}" + (f"-{slug}" if slug else "")+++def land_repos(config: Any) -> frozenset[str]:+ """Repositories the person opted in to "land it" (merge after green CI)."""+ section = getattr(config, "self_build", None)+ repos = getattr(section, "code_land_repos", None) or []+ return frozenset(str(r).strip().lower() for r in repos if str(r).strip())+++@dataclass+class Context:+ service: Any # dodaios.self_build.service.SelfBuild+ store: CodeStore+ github: Callable[[], GitHub | None]+ runner: Runner+ #: The subscription seat for a coding run, or (None, why not).+ seat: Callable[[], Awaitable[tuple[Seat | None, str]]]+ idle: Callable[[], bool]+ #: The person's projects: objects with ``path``, ``name``, ``last_opened_at``.+ projects: Callable[[], list[Any]]+ #: The one model call before a run (``planner.plan``).+ plan: Callable[..., Awaitable[Any]] | None = None+ run_timeout_s: float = 45 * 60.0+ dodaios_root: Path | None = None+ _viewer: tuple[int, Any] | None = field(default=None, repr=False)+ #: Builds an undo asked to stop; the build stops at its next step.+ stopping: set[str] = field(default_factory=set)+ #: When each project's brief was last checked against its checkout.+ brief_checked: dict[str, float] = field(default_factory=dict)++ @property+ def ledger(self) -> Any:+ return self.service.ledger++ def config(self) -> Any:+ return self.service.config()++ def still(self, record: BuildRecord, *states: Any) -> bool:+ """Is the record still in one of ``states``? (Undo or pause may have moved it.)"""+ current = self.ledger.get(record.id)+ return current is not None and current.state in statesdiff --git a/dodaios/self_build/code/gitcmd.py b/dodaios/self_build/code/gitcmd.pyindex 273f76d64f..120ca1fa2e 100644--- a/dodaios/self_build/code/gitcmd.py+++ b/dodaios/self_build/code/gitcmd.py@@ -3,6 +3,7 @@from __future__ import annotationsimport os+import reimport subprocessfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclass@@ -73,3 +74,20 @@ def out(args: Sequence[str], cwd: str | Path) -> str:"""Trimmed stdout of a git call, ``""`` when it failed."""result = git(args, cwd)return result.out.strip() if result.ok else ""+++_GITHUB_URL = re.compile(+ r"github\.com[:/]+(?P<owner>[A-Za-z0-9-]+)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?$"+)+++def github_repo(url: str) -> str:+ """``owner/name`` of a GitHub remote URL, ``""`` for anything else."""+ match = _GITHUB_URL.search(url.strip())+ return f"{match['owner']}/{match['name']}" if match else ""+++def origin_repo(folder: str | Path, *, push: bool = False) -> str:+ """The GitHub repository ``origin`` fetches from (``push``: pushes to)."""+ args = ["remote", "get-url", *(["--push"] if push else []), "origin"]+ return github_repo(out(args, folder))diff --git a/dodaios/self_build/code/idle.py b/dodaios/self_build/code/idle.pynew file mode 100644index 0000000000..6e7c26114e--- /dev/null+++ b/dodaios/self_build/code/idle.py@@ -0,0 +1,103 @@+"""Is the person away from the computer? Coding runs wait until they are.++Two readings, both must agree:++* the operating system's input idle time (keyboard and mouse), where it can be+ read without a dependency: Windows (``GetLastInputInfo``), macOS+ (``ioreg``'s ``HIDIdleTime``), Linux with ``xprintidle`` on PATH;+* the Agentic IDE: no key typed into a terminal pane lately.++A platform where neither can be read counts as idle only when the IDE shows+no input, which is the honest best a headless machine allows.+"""++from __future__ import annotations++import shutil+import subprocess+import sys+import time+from typing import Final++from loguru import logger++from dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS++#: No input for this long counts as away.+IDLE_AFTER_S: Final[float] = 15 * 60.0+++def _windows_idle_s() -> float | None:+ import ctypes+ from ctypes import wintypes++ class LastInput(ctypes.Structure):+ _fields_ = [("cbSize", wintypes.UINT), ("dwTime", wintypes.DWORD)]++ info = LastInput()+ info.cbSize = ctypes.sizeof(LastInput)+ if not ctypes.windll.user32.GetLastInputInfo(ctypes.byref(info)): # type: ignore[attr-defined]+ return None+ ticks = ctypes.windll.kernel32.GetTickCount() & 0xFFFFFFFF # type: ignore[attr-defined]+ return ((ticks - info.dwTime) & 0xFFFFFFFF) / 1000.0+++def _command_idle_s(argv: list[str], *, scale: float) -> float | None:+ try:+ done = subprocess.run(+ argv,+ capture_output=True,+ text=True,+ timeout=5,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.TimeoutExpired): # unknown idle time: the IDE reading decides+ return None+ if done.returncode != 0:+ return None+ for token in done.stdout.replace('"', " ").replace("=", " ").split():+ if token.isdigit():+ return int(token) / scale+ return None+++def os_idle_s() -> float | None:+ """Seconds since the last keyboard or mouse input, or None when unknown."""+ try:+ if sys.platform == "win32":+ return _windows_idle_s()+ if sys.platform == "darwin":+ argv = ["ioreg", "-c", "IOHIDSystem", "-d", "4", "-k", "HIDIdleTime"]+ return _command_idle_s(argv, scale=1e9)+ if shutil.which("xprintidle"):+ return _command_idle_s(["xprintidle"], scale=1000.0)+ except Exception: # noqa: BLE001 - an unreadable clock is an unknown, not an error+ logger.opt(exception=True).debug("self-build code: idle time unreadable")+ return None+++def ide_idle_s(now: float | None = None) -> float | None:+ """Seconds since a key was typed into any Agentic IDE pane, None without panes."""+ try:+ from dodaios.agentic_ide.session import get_registry++ stamps = [+ float(term.last_input_at)+ for session in get_registry().sessions+ for term in getattr(session, "terminals", []) or []+ if getattr(term, "last_input_at", None)+ ]+ except Exception: # noqa: BLE001 - no registry (tests, CLI) means no pane input+ logger.opt(exception=True).debug("self-build code: pane activity unreadable")+ return None+ if not stamps:+ return None+ return (now if now is not None else time.time()) - max(stamps)+++def person_idle(after_s: float = IDLE_AFTER_S) -> bool:+ for reading in (os_idle_s(), ide_idle_s()):+ if reading is not None and reading < after_s:+ return False+ return Truediff --git a/dodaios/self_build/code/intake.py b/dodaios/self_build/code/intake.pynew file mode 100644index 0000000000..78b6d87a1c--- /dev/null+++ b/dodaios/self_build/code/intake.py@@ -0,0 +1,277 @@+"""Issue intake: which projects are the person's own, and which issues become cases.++A project qualifies when it is in the Agentic IDE's library, is a git+repository whose ``origin`` is on GitHub, that repository is owned by the+person or by an organisation they administer, the person can administer or+maintain it, it is not archived, and it is not Dodaios' own source (that goes+through the normal branch, pull request and done-gate path). Other people's+repositories are never polled, let alone written to.++Only projects the person works on are polled: opened in the IDE lately, or+with their own commits among the recent ones. Each is asked for issues at most+every :data:`INTAKE_EVERY_MS`, triaged in Python (:mod:`.triage`), and a fit+issue becomes a ``Kind.CODE`` case through ``service.admit``. At most one new+case per pass: rarely and correctly, never noisily.+"""++from __future__ import annotations++import asyncio+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Final++from loguru import logger++from ..records import Kind, State+from . import brief as brief_mod+from . import commands, gitcmd+from .brief import Brief+from .context import Context, signature+from .github import OWN_PERMISSIONS, Issue, Snapshot, Viewer+from .triage import triage++INTAKE_EVERY_MS: Final[int] = 30 * 60_000+#: A brief's keys are checked against the checkout at most this often.+BRIEF_EVERY_S: Final[float] = 30 * 60.0+VIEWER_TTL_MS: Final[int] = 6 * 3_600_000+#: A project opened in the IDE within this many days counts as worked on.+RECENT_DAYS: Final[int] = 45+MAX_NEW_CASES: Final[int] = 1+++@dataclass(frozen=True, slots=True)+class OwnedProject:+ folder: str+ name: str+ repo: str+ brief: Brief+++def repo_of(folder: str | Path) -> str:+ """The GitHub repository ``origin`` fetches from and pushes to (both must agree)."""+ from dodaios.agentic_ide.github_link import REPO_RE++ fetch = gitcmd.origin_repo(folder)+ if not fetch or gitcmd.origin_repo(folder, push=True).lower() != fetch.lower():+ return ""+ return fetch if REPO_RE.match(fetch) else ""+++def is_dodaios_source(folder: str | Path, dodaios_root: Path | None) -> bool:+ root = Path(folder)+ if (root / "dodaios" / "self_build").is_dir():+ return True+ if dodaios_root is None:+ return False+ try:+ from dodaios.agentic_ide.git_ops import same_repository++ return bool(same_repository(root, dodaios_root))+ except Exception: # noqa: BLE001 - unknown counts as "not Dodaios" only if the marker said so+ logger.opt(exception=True).debug("self-build code: repository comparison failed")+ return False+++def _repo_root(folder: str) -> str:+ top = gitcmd.out(["rev-parse", "--show-toplevel"], folder)+ return str(Path(top)) if top else ""+++async def viewer(ctx: Context) -> Viewer | None:+ cached = ctx._viewer+ stamp = int(time.time() * 1000)+ if cached is not None and stamp - cached[0] < VIEWER_TTL_MS:+ return cached[1]+ api = ctx.github()+ if api is None:+ return None+ who = await asyncio.to_thread(api.viewer)+ if not who.login:+ return None+ ctx._viewer = (stamp, who)+ return who+++def _brief(ctx: Context, folder: str, repo: str) -> Brief:+ """The project's brief, its keys checked at most every :data:`BRIEF_EVERY_S`."""+ key = folder.lower()+ stored = brief_mod.load(ctx.store, folder)+ checked = ctx.brief_checked.get(key, 0.0)+ if stored is not None and stored.repo == repo and time.monotonic() - checked < BRIEF_EVERY_S:+ return stored+ brief, _rebuilt = brief_mod.refresh(ctx.store, folder, repo=repo)+ ctx.brief_checked[key] = time.monotonic()+ return brief+++def owned_projects(ctx: Context, who: Viewer) -> list[OwnedProject]:+ """Blocking: git calls and brief refreshes for the person's own projects."""+ out: list[OwnedProject] = []+ seen: set[str] = set()+ cutoff = time.time() - RECENT_DAYS * 86_400+ for project in ctx.projects():+ if getattr(project, "scratch", False) or getattr(project, "archived", False):+ continue+ folder = _repo_root(str(getattr(project, "path", "") or ""))+ if not folder or folder.lower() in seen:+ continue+ seen.add(folder.lower())+ repo = repo_of(folder)+ if not repo or not who.owns(repo) or is_dodaios_source(folder, ctx.dodaios_root):+ continue+ brief = _brief(ctx, folder, repo)+ recent = float(getattr(project, "last_opened_at", 0) or 0) >= cutoff+ mine = bool((brief.parts.get("activity") or {}).get("person_active"))+ if not (recent or mine):+ continue+ out.append(+ OwnedProject(+ folder=folder, name=str(getattr(project, "name", "")), repo=repo, brief=brief+ )+ )+ return out+++def offerable(records: list[Any]) -> bool:+ """May an issue be offered again? Only when every earlier case never ran."""+ from .builder import NOT_RUN++ return all(r.state == State.FAILED and r.note.startswith(NOT_RUN) for r in records)+++def _github_part(snap: Snapshot) -> dict[str, Any]:+ return {+ "open_issues": len(snap.issues),+ "issues": [f"#{i.number} {i.title}" for i in snap.issues[:10]],+ "open_pulls": [f"#{p.number} {p.title}" for p in snap.pulls[:10]],+ "permission": snap.permission,+ }+++def _lang(ctx: Context) -> str:+ """The person's interface language (the card is read there)."""+ ui = getattr(ctx.config(), "ui", None)+ return str(getattr(ui, "language", "") or "en")+++def title(ctx: Context, issue: Issue, repo: str) -> str:+ from dodaios.i18n import t++ return t(+ "self_build.code.title",+ _lang(ctx),+ number=issue.number,+ repo=repo,+ title=issue.title.strip()[:120],+ )+++def case(ctx: Context, issue: Issue, repo: str, signal: str, brief: Brief) -> str:+ from dodaios.i18n import t++ tests = " && ".join(commands.shown(c) for c in brief.test_commands) or "-"+ return t(+ "self_build.code.case",+ _lang(ctx),+ number=issue.number,+ repo=repo,+ signal=signal,+ tests=tests,+ url=issue.url,+ )+++async def poll(ctx: Context, project: OwnedProject, who: Viewer, *, budget: int) -> int:+ """Triage one repository's issues; returns how many cases were opened."""+ from dodaios.agentic_ide.github_link import GitHubError++ api = ctx.github()+ if api is None:+ return 0+ store, ledger, repo = ctx.store, ctx.ledger, project.repo+ try:+ snap = await asyncio.to_thread(api.snapshot, repo)+ except GitHubError as exc:+ logger.info("self-build code: issues of {} unreadable: {}", repo, exc)+ return 0+ await asyncio.to_thread(store.set_poll, repo)+ await asyncio.to_thread(store.set_part, project.brief.project_key, "github", _github_part(snap))+ if snap.archived or snap.permission.upper() not in OWN_PERMISSIONS:+ return 0+ if snap.repo.lower() != repo.lower():+ logger.info(+ "self-build code: {} answers as {}; skipped until origin is updated", repo, snap.repo+ )+ return 0+ profile = await asyncio.to_thread(store.profile, repo)+ opened = 0+ for issue in snap.issues:+ if opened >= budget:+ break+ sig = signature(repo, issue.number)+ if not offerable(await asyncio.to_thread(ledger.ever_for, sig)):+ continue # one build per issue: a closed or failed one is not retried+ prev = await asyncio.to_thread(store.issue, repo, issue.number)+ if prev and prev["updated_at"] == issue.updated_at and prev["verdict"] == "unfit":+ continue+ verdict = triage(+ issue,+ login=who.login,+ profile=profile,+ pulls=snap.pulls,+ has_tests=bool(project.brief.test_commands),+ )+ data = {**issue.to_json(), "folder": project.folder, "base": snap.default_branch}+ if not verdict.fit:+ await asyncio.to_thread(+ store.put_issue,+ repo,+ issue.number,+ updated_at=issue.updated_at,+ verdict="unfit",+ reason=verdict.reason,+ issue=data,+ )+ continue+ admission = ctx.service.admit(Kind.CODE, sig)+ await asyncio.to_thread(+ store.put_issue,+ repo,+ issue.number,+ updated_at=issue.updated_at,+ verdict="fit",+ reason=f"{verdict.signal}; {admission.reason}",+ issue=data,+ )+ if admission.start is None:+ logger.debug("self-build code: {} not opened: {}", sig, admission.reason)+ if admission.reason in ("off", "paused"):+ break+ continue+ await asyncio.to_thread(+ ledger.open_case,+ Kind.CODE,+ sig,+ title(ctx, issue, repo),+ case=case(ctx, issue, repo, verdict.signal, project.brief),+ evidence=[issue.url or sig],+ state=admission.start,+ )+ logger.info("self-build code: opened {} as {} ({})", sig, admission.start, verdict.signal)+ opened += 1+ return opened+++async def intake(ctx: Context, projects: list[OwnedProject], who: Viewer) -> int:+ opened = 0+ stamp = int(time.time() * 1000)+ for project in projects:+ if opened >= MAX_NEW_CASES:+ break+ last = await asyncio.to_thread(ctx.store.last_poll, project.repo)+ if stamp - last < INTAKE_EVERY_MS:+ continue+ opened += await poll(ctx, project, who, budget=MAX_NEW_CASES - opened)+ return openeddiff --git a/dodaios/self_build/code/judge.py b/dodaios/self_build/code/judge.pynew file mode 100644index 0000000000..593c6444de--- /dev/null+++ b/dodaios/self_build/code/judge.py@@ -0,0 +1,88 @@+"""The judge of a loop-made change, which the coding agent cannot edit.++Two checks, both in Python:++* :func:`guard` refuses a change that touches what the loop must never touch:+ CI config, deployment, secrets and credentials, and the repository's own+ instruction files (the rules the agent was told to follow).+* :func:`run_tests` runs the test commands the brief read from the project+ BEFORE the run, in the worktree, with a time limit.++CI on the pull request is the second judge (``watch``).+"""++from __future__ import annotations++import os+import re+import time+from pathlib import Path+from typing import Final++from . import commands, gitcmd++PROTECTED: Final[re.Pattern[str]] = re.compile(+ r"(?i)(?:^|/)(?:"+ r"\.github/|\.gitlab-ci\.ya?ml$|\.circleci/|azure-pipelines\.ya?ml$|jenkinsfile$|"+ r"\.env(?:\..*)?$|.*secrets?.*|.*credentials?.*|.*\.pem$|.*\.key$|id_rsa.*|"+ r"\.npmrc$|\.pypirc$|"+ r"deploy(?:ment)?s?/|.*deploy.*\.(?:ya?ml|sh|ps1)$|dockerfile$|docker-compose.*\.ya?ml$|"+ r"terraform/|.*\.tf$|helm/|k8s/|kubernetes/|"+ r"agents\.md$|claude\.md$|gemini\.md$|copilot-instructions\.md$"+ r")"+)+SETUP_TIMEOUT_S: Final[float] = 15 * 60.0+TEST_TIMEOUT_S: Final[float] = 20 * 60.0+++def guard(changed: list[str]) -> list[str]:+ """The changed paths the loop may not ship (empty: the change may go on)."""+ return [path for path in changed if PROTECTED.search(path.replace("\\", "/"))]+++def _env(worktree: Path) -> dict[str, str]:+ env = dict(os.environ)+ paths = [str(worktree)]+ if (worktree / "src").is_dir():+ paths.insert(0, str(worktree / "src"))+ if env.get("PYTHONPATH"):+ paths.append(env["PYTHONPATH"])+ env["PYTHONPATH"] = os.pathsep.join(paths)+ env.setdefault("CI", "1")+ env["PYTHONDONTWRITEBYTECODE"] = "1"+ return env+++def _needs_setup(worktree: Path, argv: list[str]) -> bool:+ if argv and argv[0] in ("npm", "pnpm", "yarn"):+ return not (worktree / "node_modules").is_dir()+ return True+++def run_tests(+ worktree: str | Path,+ *,+ setup: list[list[str]],+ tests: list[list[str]],+ test_timeout_s: float = TEST_TIMEOUT_S,+) -> tuple[bool, str]:+ """``(passed, detail)``. No test command is a failure, never a pass."""+ root = Path(worktree)+ if not tests:+ return False, "no test command"+ env = _env(root)+ for argv in setup:+ if not _needs_setup(root, argv):+ continue+ result = gitcmd.run(argv, root, timeout=SETUP_TIMEOUT_S, env=env)+ if not result.ok:+ return False, f"`{commands.shown(argv)}` failed:\n{result.tail()}"+ lines: list[str] = []+ for argv in tests:+ started = time.monotonic()+ result = gitcmd.run(argv, root, timeout=test_timeout_s, env=env)+ took = int(time.monotonic() - started)+ if not result.ok:+ return False, f"`{commands.shown(argv)}` failed after {took} s:\n{result.tail()}"+ lines.append(f"`{commands.shown(argv)}` passed in {took} s")+ return True, "\n".join(lines)diff --git a/dodaios/self_build/code/loop.py b/dodaios/self_build/code/loop.pynew file mode 100644index 0000000000..6f9a33c2be--- /dev/null+++ b/dodaios/self_build/code/loop.py@@ -0,0 +1,297 @@+"""The code builder's pass: watch open pull requests, take in issues, build one case.++One pass every :data:`TICK_S` (and soon after a proposal is accepted):++1. Nothing at all while ``[self_build].code`` is ``off``, the kill switch is+ on, or GitHub is not connected: no call leaves the machine.+2. Watch the loop's open pull requests (CI, merges, closes; ``watch``).+3. Refresh the briefs of the person's own projects and triage their issues+ (``intake``). Proposals cost no model call.+4. Build at most one ``building`` case, and only while the person is away and+ a subscription coding CLI is free (``seat``, ``idle``). A case can wait for+ that up to :data:`STALE_BUILDING_MS`; then it fails with that reason.++A pass makes git calls and GitHub reads; the only model calls are the one+plan call and the coding run of a build.+"""++from __future__ import annotations++import asyncio+import time+from pathlib import Path+from typing import Any, Final++from loguru import logger++from .. import policy+from ..ledger import now_ms+from ..records import BuildRecord, Kind, State+from . import builder, intake, planner, seat+from .context import Context+from .github import GitHub, GitHubApi+from .idle import person_idle+from .runner import RunResult, ThreadRunner+from .store import DB_NAME, CodeStore+from .watch import cleanup, watch++TICK_S: Final[float] = 300.0+FIRST_TICK_S: Final[float] = 120.0+#: A case that found no idle subscription time for this long fails.+STALE_BUILDING_MS: Final[int] = 3 * 86_400_000+#: Archived builds' pull requests are still watched this long (a late merge).+WATCH_ARCHIVED_MS: Final[int] = 30 * 86_400_000+_GITHUB_TTL_S: Final[float] = 600.0+#: How long an undo waits for a running build to reach its next step.+UNDO_WAIT_S: Final[float] = 20.0+#: A coding run found still working after a restart gets this much past its limit.+RESUME_GRACE_S: Final[float] = 600.0+++class CodeLoop:+ def __init__(self, ctx: Context) -> None:+ self.ctx = ctx+ self._task: asyncio.Task[None] | None = None+ self._building: asyncio.Task[None] | None = None+ self._building_id = ""+ self._wake: asyncio.Event | None = None++ # ------------------------------------------------------------ wiring++ def attach(self) -> None:+ service = self.ctx.service+ service.undo.register(Kind.CODE, self.undo)+ service.register_builder(Kind.CODE, self.on_accepted)++ def start(self) -> None:+ if self._task is not None:+ return+ try:+ self._task = asyncio.get_running_loop().create_task(self._run())+ except RuntimeError: # no loop (CLI, tests): tick() can still be called+ self._task = None++ async def close(self) -> None:+ for task in (self._task, self._building):+ if task is not None and not task.done():+ task.cancel()+ self._task = None++ def kick(self) -> None:+ if self._wake is not None:+ self._wake.set()++ async def _run(self) -> None:+ self._wake = asyncio.Event()+ await asyncio.sleep(FIRST_TICK_S)+ while True:+ try:+ await self.tick()+ except Exception: # noqa: BLE001 - the next pass retries+ logger.opt(exception=True).warning("self-build code: pass failed")+ self._wake.clear()+ try:+ await asyncio.wait_for(self._wake.wait(), timeout=TICK_S)+ except TimeoutError: # the normal end of the wait: time for the next pass+ pass++ # ------------------------------------------------------------ the ledger's hooks++ async def on_accepted(self, record: BuildRecord) -> None:+ """A proposal was accepted: it is ``building`` now and waits for idle time."""+ logger.info("self-build code: {} accepted, waiting for idle time", record.signature)+ self.kick()++ async def undo(self, record: BuildRecord) -> None:+ """Close the loop's pull request and delete its branch and worktree.++ A build still running is asked to stop (it stops at its next step and+ removes what it made after this point itself); nothing is cancelled+ mid-step, so no half-done git or GitHub call is lost track of.+ """+ ctx = self.ctx+ ctx.stopping.add(record.id)+ task = self._building if self._building_id == record.id else None+ if task is not None and not task.done():+ session_id = str(record.undo.get("session_id") or "")+ stop = getattr(ctx.runner, "stop", None)+ if session_id and stop is not None:+ await stop(session_id)+ await asyncio.wait({task}, timeout=UNDO_WAIT_S)+ current = await asyncio.to_thread(ctx.ledger.get, record.id) or record+ await cleanup(ctx, current, close_pull=True, force=current.state == State.BUILDING)++ # ------------------------------------------------------------ one pass++ async def tick(self) -> dict[str, Any]:+ ctx = self.ctx+ cfg = ctx.config()+ if policy.autonomy(cfg, Kind.CODE) == policy.Autonomy.OFF:+ return {"skipped": "off"}+ if policy.paused(ctx.ledger):+ return {"skipped": "paused"}+ if ctx.github() is None:+ return {"skipped": "github not connected"}+ summary: dict[str, Any] = {"watched": await self._watch()}+ who = await intake.viewer(ctx)+ if who is None:+ summary["skipped"] = "github account unknown"+ return summary+ projects = await asyncio.to_thread(intake.owned_projects, ctx, who)+ summary["projects"] = [p.repo for p in projects]+ summary["opened"] = await intake.intake(ctx, projects, who)+ summary["build"] = await self._maybe_build()+ return summary++ async def _watch(self) -> int:+ ctx = self.ctx+ records = await asyncio.to_thread(+ ctx.ledger.list,+ kinds=[Kind.CODE],+ states=[State.PROVING, State.TRIAL, State.ARCHIVED],+ limit=100,+ )+ cutoff = now_ms() - WATCH_ARCHIVED_MS+ seen = 0+ for record in records:+ if record.state == State.ARCHIVED and record.updated_ms < cutoff:+ continue+ try:+ await watch(ctx, record)+ seen += 1+ except Exception: # noqa: BLE001 - one unreadable pull request must not stop the rest+ logger.opt(exception=True).info("self-build code: watch {} failed", record.id)+ return seen++ async def _maybe_build(self) -> str:+ ctx = self.ctx+ if self._building is not None and not self._building.done():+ return "running"+ waiting = await asyncio.to_thread(+ ctx.ledger.list, kinds=[Kind.CODE], states=[State.BUILDING], limit=20+ )+ if not waiting:+ return "nothing to build"+ record = min(waiting, key=lambda r: r.created_ms)+ if record.artefact.get("type") == "pull_request":+ # The app stopped right after opening the pull request: CI decides now.+ await asyncio.to_thread(+ ctx.ledger.set_state, record.id, State.PROVING, "pull request opened"+ )+ return f"proving {record.signature}"+ stage = str(record.artefact.get("stage") or "")+ if stage == "coding":+ return await self._resume(record)+ if stage:+ # The app stopped between steps: start this case over from nothing.+ try:+ await cleanup(ctx, record, close_pull=True, force=True)+ except Exception as exc: # noqa: BLE001 - logged, and the case stops blocking the queue+ logger.opt(exception=exc).warning("self-build code: {} not cleaned", record.id)+ await asyncio.to_thread(+ ctx.ledger.set_state,+ record.id,+ State.FAILED,+ f"an interrupted run could not be cleaned up: {exc}",+ )+ return "failed cleanup"+ record = await asyncio.to_thread(ctx.ledger.attach_artefact, record.id, {}, {})+ if now_ms() - record.updated_ms > STALE_BUILDING_MS:+ await asyncio.to_thread(+ ctx.ledger.set_state,+ record.id,+ State.FAILED,+ builder.NOT_RUN + "no idle time on a subscription coding CLI for three days",+ )+ return "stale"+ if not await asyncio.to_thread(ctx.idle):+ return "waiting: the person is at the computer"+ chosen, why = await ctx.seat()+ if chosen is None:+ return f"waiting: {why}"+ self._start(record, builder.build(ctx, record, provider=chosen.provider))+ return f"building {record.signature} on {chosen.label}"++ async def _resume(self, record: BuildRecord) -> str:+ ctx = self.ctx+ session_id = str(record.undo.get("session_id") or "")+ result = await ctx.runner.outcome(session_id) if session_id else None+ if session_id and result is None:+ if now_ms() - record.updated_ms < (ctx.run_timeout_s + RESUME_GRACE_S) * 1000:+ return "coding run still working"+ stop = getattr(ctx.runner, "stop", None)+ if stop is not None:+ await stop(session_id)+ result = RunResult(False, error="did not finish in time", session_id=session_id)+ self._start(record, builder.resume(ctx, record, result))+ return f"resuming {record.signature}"++ def _start(self, record: BuildRecord, coro: Any) -> None:+ self._building_id = record.id+ self._building = asyncio.ensure_future(coro)+++# ------------------------------------------------------------------ install+++def _projects() -> list[Any]:+ from dodaios.agentic_ide import library++ return list(library.list_projects())+++async def _seat() -> tuple[seat.Seat | None, str]:+ installed = await seat.installed_clis()+ return await asyncio.to_thread(seat.choose, installed)+++def _cached_github() -> Any:+ """``GitHubApi.connect`` reused for minutes (it may ask ``gh`` for a token)."""+ cache: dict[str, Any] = {"at": 0.0, "api": None}++ def get() -> GitHub | None:+ if time.monotonic() - cache["at"] > _GITHUB_TTL_S:+ cache["api"] = GitHubApi.connect()+ cache["at"] = time.monotonic()+ return cache["api"]++ return get+++def _chat_from(state: Any) -> Any:+ """The agent-chat service on ``app.state``, built on first use like its routes do."""++ def get() -> Any:+ service = getattr(state, "agent_chat", None)+ if service is not None:+ return service+ factory = getattr(state, "agent_chat_factory", None)+ if factory is None:+ raise RuntimeError("this app has no agent chat service")+ service = factory()+ state.agent_chat = service+ return service++ return get+++def install(service: Any, app_state: Any = None) -> CodeLoop:+ """Register the code builder with the self-building service and start its pass."""+ import dodaios++ store = CodeStore(Path(service.ledger.path).parent / DB_NAME)+ ctx = Context(+ service=service,+ store=store,+ github=_cached_github(),+ runner=ThreadRunner(_chat_from(app_state) if app_state is not None else None),+ seat=_seat,+ idle=person_idle,+ projects=_projects,+ plan=planner.plan,+ dodaios_root=Path(dodaios.__file__).resolve().parent.parent,+ )+ loop = CodeLoop(ctx)+ loop.attach()+ loop.start()+ return loopdiff --git a/dodaios/self_build/code/planner.py b/dodaios/self_build/code/planner.pynew file mode 100644index 0000000000..29fca05d51--- /dev/null+++ b/dodaios/self_build/code/planner.py@@ -0,0 +1,103 @@+"""The one model call before a coding run: a short plan and a size estimate.++It runs only when a build was admitted to building (or accepted), never for a+proposal, and only on a connected subscription+(``brain.resolver.resolve_subscription_brain``). Without one there is no call+at all: the coding agent plans for itself and the estimate stays unknown.+Every call runs inside :func:`dodaios.self_build.cost.attributed`, so the+ledger shows what it cost.++An estimate of ``large`` stops the build before any coding: large work is not+something to hand an unattended agent.+"""++from __future__ import annotations++import asyncio+import re+from collections.abc import Callable+from dataclasses import dataclass+from typing import Any, Final++from loguru import logger++from ..cost import attributed+from .github import Issue++SIZES: Final[tuple[str, ...]] = ("small", "medium", "large")+_MAX_TOKENS: Final[int] = 900+_SYSTEM: Final[str] = (+ "You plan a change for an unattended coding agent. Read the issue and the project "+ "brief. Answer in exactly this form and nothing else:\n"+ "SIZE: small | medium | large\n"+ "PLAN:\n- step\n- step\n"+ "small = one file or a few lines; medium = a few files with tests; large = design "+ "work, many files, or anything unclear. Say large when unsure."+)+++@dataclass(frozen=True, slots=True)+class Plan:+ text: str = ""+ #: ``small`` | ``medium`` | ``large`` | ``""`` (no estimate).+ size: str = ""+ writer: str = ""+++def parse(answer: str) -> Plan:+ size = ""+ match = re.search(r"(?im)^\s*SIZE\s*:\s*(small|medium|large)\b", answer)+ if match:+ size = match.group(1).lower()+ plan = answer.split("PLAN:", 1)[1] if "PLAN:" in answer else ""+ return Plan(text=plan.strip()[:2_000], size=size)+++def _subscription_brain() -> Any | None:+ from dodaios.brain.resolver import resolve_subscription_brain+ from dodaios.core.config import load_config++ return resolve_subscription_brain(load_config())+++async def plan(+ build_id: str,+ issue: Issue,+ brief_text: str,+ *,+ brain: Callable[[], Any | None] = _subscription_brain,+) -> Plan:+ """At most one call; an empty :class:`Plan` when no subscription can answer."""+ from dodaios.core.protocols import BrainMessage, BrainRequest++ try:+ model = await asyncio.to_thread(brain)+ except Exception: # noqa: BLE001 - no brain is an answer: the agent plans itself+ logger.opt(exception=True).info("self-build code: no subscription brain for the plan")+ model = None+ if model is None:+ return Plan()+ prompt = (+ f"Issue #{issue.number}: {issue.title}\n\n{issue.body[:4_000]}\n\n"+ f"Project brief:\n{brief_text[:5_000]}"+ )+ request = BrainRequest(+ messages=(BrainMessage(role="user", content=prompt),),+ system=_SYSTEM,+ temperature=0.1,+ max_tokens=_MAX_TOKENS,+ stream=True,+ reasoning_effort="low",+ )+ chunks: list[str] = []+ try:+ with attributed(build_id):+ async for delta in model.complete(request):+ if delta.content:+ chunks.append(delta.content)+ except Exception: # noqa: BLE001 - a failed plan call leaves planning to the agent+ logger.opt(exception=True).info("self-build code: plan call failed")+ return Plan()+ result = parse("".join(chunks))+ writer = str(getattr(model, "model", "") or getattr(model, "name", "") or "")+ return Plan(text=result.text, size=result.size, writer=writer)diff --git a/dodaios/self_build/code/runner.py b/dodaios/self_build/code/runner.pynew file mode 100644index 0000000000..b49274477d--- /dev/null+++ b/dodaios/self_build/code/runner.py@@ -0,0 +1,157 @@+"""One headless coding run: a thread on the IDE's surface, in a worktree the loop made.++The run is an ordinary agent-chat thread (``docs/agentic-ide-threads.md``): the+coding CLI runs on its own subscription login, the thread shows up under its+project in the Agentic IDE, and the person can read every step and step in.+Unlike a thread a Jarvis agent opens, it never runs in the person's checkout:+the loop hands it a fresh worktree and branch (``builder``).++The run must finish on its own. A question or a plan card means the task was+not clear enough for unattended work: the turn is stopped and the build fails+with that lesson, rather than waiting on the person.+"""++from __future__ import annotations++import asyncio+import time+from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from typing import Any, Final, Protocol++from loguru import logger++#: The thread's author line: who wrote the prompt.+AUTHOR: Final[dict[str, str]] = {"agent_id": "self_build", "name": "Dodaios"}+POLL_S: Final[float] = 5.0+++@dataclass(frozen=True, slots=True)+class RunResult:+ ok: bool+ summary: str = ""+ error: str = ""+ session_id: str = ""+++class Runner(Protocol):+ async def run(+ self,+ *,+ provider: str,+ folder: str,+ prompt: str,+ title: str,+ timeout_s: float,+ should_stop: Callable[[], bool],+ on_session: Callable[[str], Awaitable[None]] | None = None,+ ) -> RunResult: ...++ async def outcome(self, session_id: str) -> RunResult | None: ...+++def _default_chat() -> Any:+ from dodaios.mcp.agents.context import chat_service++ return chat_service()+++class ThreadRunner:+ """:class:`Runner` on the agent-chat service's coding threads."""++ def __init__(self, chat_service: Callable[[], Any] | None = None) -> None:+ self._chat = chat_service or _default_chat++ async def run(+ self,+ *,+ provider: str,+ folder: str,+ prompt: str,+ title: str,+ timeout_s: float,+ should_stop: Callable[[], bool],+ on_session: Callable[[str], Awaitable[None]] | None = None,+ ) -> RunResult:+ from dodaios.agent_chat.service import resolve_runner+ from dodaios.society.coding_threads import THREAD_SURFACE, access_mode++ service = self._chat()+ runner = resolve_runner(provider, surface=THREAD_SURFACE)+ session = service.create_session(+ provider=provider,+ cwd=folder,+ # A loop run cannot stop for approvals nobody is there to give; it+ # works in its own worktree, never in the person's checkout.+ permission_mode=access_mode(runner, "full"),+ title=title[:80],+ surface=THREAD_SURFACE,+ )+ sid = session.session_id+ if on_session is not None:+ await on_session(sid)+ turn_id = await service.send(sid, prompt, author=dict(AUTHOR))+ deadline = time.monotonic() + timeout_s+ while True:+ result = self._finished(service, sid, turn_id)+ if result is not None:+ if not result.ok and service.is_running(sid):+ # A question or plan card holds the turn open: end it.+ await self._stop(service, sid)+ return result+ if should_stop():+ await self._stop(service, sid)+ return RunResult(+ False, error="stopped: the self-building loop was paused", session_id=sid+ )+ if time.monotonic() > deadline:+ await self._stop(service, sid)+ return RunResult(+ False, error=f"did not finish within {int(timeout_s / 60)} min", session_id=sid+ )+ await asyncio.sleep(POLL_S)++ async def outcome(self, session_id: str) -> RunResult | None:+ """How an earlier run ended (after a restart), None while it still runs."""+ service = self._chat()+ if service.is_running(session_id):+ return None+ return self._finished(service, session_id, "") or RunResult(+ False, error="the run ended without an answer", session_id=session_id+ )++ async def stop(self, session_id: str) -> None:+ """Stop a run that is still working (an undo while it codes)."""+ service = self._chat()+ if service.is_running(session_id):+ await self._stop(service, session_id)++ @staticmethod+ def _finished(service: Any, sid: str, turn_id: str) -> RunResult | None:+ from dodaios.society.coding_threads import last_turn, open_plan, open_question++ events = service.store.list_events(sid, tail=400)+ if open_question(events) is not None:+ return RunResult(False, error="the coding agent asked a question", session_id=sid)+ if open_plan(events) is not None:+ return RunResult(False, error="the coding agent stopped at a plan", session_id=sid)+ done = [+ e+ for e in events+ if e["kind"] == "turn_finished"+ and (not turn_id or str((e.get("payload") or {}).get("turn_id") or "") == turn_id)+ ]+ if not done:+ return None+ status, text, error = last_turn(events)+ if status not in ("done", "complete", "completed", "ok", "success"):+ return RunResult(False, summary=text, error=error or status, session_id=sid)+ return RunResult(True, summary=text, session_id=sid)++ @staticmethod+ async def _stop(service: Any, sid: str) -> None:+ try:+ if not await service.cancel(sid):+ await service.seal_stopped_turn(sid)+ except Exception: # noqa: BLE001 - the run is abandoned either way+ logger.opt(exception=True).warning("self-build code: could not stop thread {}", sid)diff --git a/dodaios/self_build/code/seat.py b/dodaios/self_build/code/seat.pynew file mode 100644index 0000000000..57cc1ce693--- /dev/null+++ b/dodaios/self_build/code/seat.py@@ -0,0 +1,120 @@+"""Which coding CLI may run loop work right now, on the person's subscription only.++The maintainer's rule: once a subscription is connected, background work never+bills a per-token key (``dodaios.brain.background_policy``). A coding run is+the most expensive background work there is, so the rule is strict here:++* only a CLI whose plan login is confirmed signed in right now;+* never while that CLI's own API-key variable is in the environment, since+ the CLI would bill that key instead of the plan;+* never inside a cooldown after the plan reported its usage limit, after a+ dead login, or while a usage window is nearly spent.++Anything else is an unknown and the answer is "wait".+"""++from __future__ import annotations++import os+from dataclasses import dataclass+from typing import Any, Final++from loguru import logger++#: Thread runner -> (the brain provider whose login probe answers for its plan,+#: the account platform, the environment variables that make the CLI bill a key).+SEATS: Final[dict[str, tuple[str, str, tuple[str, ...]]]] = {+ "claude-cli": ("claude-cli", "claude", ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN")),+ "codex-cli": ("codex", "codex", ("OPENAI_API_KEY", "CODEX_API_KEY")),+}+#: A usage window this full leaves the plan to the person.+FULL_PERCENT: Final[float] = 80.0+++@dataclass(frozen=True, slots=True)+class Seat:+ #: The agent-chat provider id the thread opens with.+ provider: str+ runner: str+ label: str+++def _cooling(runner: str) -> bool:+ try:+ if runner == "claude-cli":+ from dodaios.claude_auth_state import claude_auth_dead+ from dodaios.claude_quota_state import claude_in_quota_cooldown++ return bool(claude_in_quota_cooldown() or claude_auth_dead())+ if runner == "codex-cli":+ from dodaios.codex_auth_state import codex_needs_reauth+ from dodaios.codex_quota_state import codex_in_quota_cooldown++ return bool(codex_in_quota_cooldown() or codex_needs_reauth())+ except Exception: # noqa: BLE001 - an unreadable state is a reason to wait+ logger.opt(exception=True).debug("self-build code: cooldown state unreadable")+ return True+ return False+++def _window_full(platform: str) -> bool:+ try:+ from dodaios import agent_accounts, agent_usage++ account = agent_accounts.active_account(platform) # type: ignore[arg-type]+ usage = agent_usage.read_usage(account)+ except Exception: # noqa: BLE001 - no reading is not a full window+ logger.opt(exception=True).debug("self-build code: usage unreadable for {}", platform)+ return False+ return any(window.percent >= FULL_PERCENT for window in usage.windows)+++def _rows() -> list[Any]:+ from dodaios.agent_chat.catalog import rows_for++ return [row for row in rows_for("agent") if row.agent]+++def choose(installed: dict[str, bool] | None = None) -> tuple[Seat | None, str]:+ """The seat to run on, or ``(None, why not)``. Blocking: probes CLIs."""+ from dodaios.agent_chat.service import resolve_runner+ from dodaios.brain.background_policy import login_state++ reasons: list[str] = []+ for row in _rows():+ try:+ runner = resolve_runner(row.id, surface="agent")+ except Exception: # noqa: BLE001 - a row that cannot resolve is not a seat+ logger.opt(exception=True).debug("self-build code: no runner for {}", row.id)+ continue+ seat = SEATS.get(runner)+ if seat is None:+ continue # billing unknown to this module: never used in the background+ brain, platform, key_vars = seat+ if installed is not None and not installed.get(row.agent, False):+ reasons.append(f"{row.label}: not installed")+ continue+ if any(os.environ.get(name) for name in key_vars):+ reasons.append(f"{row.label}: an API key in the environment would be billed")+ continue+ if login_state(brain) is not True:+ reasons.append(f"{row.label}: plan not signed in")+ continue+ if _cooling(runner):+ reasons.append(f"{row.label}: plan cooling down")+ continue+ if _window_full(platform):+ reasons.append(f"{row.label}: usage window nearly spent")+ continue+ return Seat(provider=row.id, runner=runner, label=row.label), ""+ return None, "; ".join(reasons) or "no subscription coding CLI"+++async def installed_clis() -> dict[str, bool]:+ try:+ from dodaios.workspace.agents import detect_agents++ return {info.name: bool(info.installed) for info in await detect_agents()}+ except Exception: # noqa: BLE001 - unknown means "not installed" here: wait+ logger.opt(exception=True).debug("self-build code: CLI detection failed")+ return {}diff --git a/dodaios/self_build/code/watch.py b/dodaios/self_build/code/watch.pynew file mode 100644index 0000000000..998156532e--- /dev/null+++ b/dodaios/self_build/code/watch.py@@ -0,0 +1,242 @@+"""After the pull request: CI as the judge, landing, and learning from the outcome.++For every code record with an open pull request the loop asks GitHub, on each+pass, how it stands:++* ``proving``: green CI is the proof (``attach_proof``) and the build goes on+ trial. Red CI fails it: the lesson is kept, the pull request closed and the+ branch deleted. A repository without CI is judged by the local test run+ alone once a grace period showed that no check is coming.+* ``trial``: in a repository the person opted in to landing+ (``[self_build].code_land_repos``), a green pull request is merged.+* merged by the person: ``accepted`` when merged as the loop left it,+ ``corrected`` when they changed it first; the build is kept, and the+ repository's profile and brief learn which.+* closed without merge: the branch and worktree go, the build is ``undone``+ and the profile notes it (triage stays out of a repository that keeps+ closing loop pull requests).++:func:`cleanup` is also the undo: it removes only what the loop created.+"""++from __future__ import annotations++import asyncio+from typing import Any, Final++from loguru import logger++from ..ledger import now_ms+from ..records import BuildRecord, Outcome, State+from . import brief as brief_mod+from .context import BRANCH_PREFIX, Context, land_repos, parse_signature+from .github import PullState++#: A pull request with no check at all after this long is judged by local tests.+NO_CI_GRACE_MS: Final[int] = 15 * 60_000+#: CI still pending after this long fails the build.+CI_TIMEOUT_MS: Final[int] = 24 * 3_600_000+_RED: Final[frozenset[str]] = frozenset({"FAILURE", "ERROR"})+++async def cleanup(+ ctx: Context, record: BuildRecord, *, close_pull: bool, force: bool = False+) -> None:+ """Remove the loop's own artefacts for ``record``: its open pull request (when+ ``close_pull``), its remote branch, its worktree and local branch.++ Branches are deleted only while they still point at the commit the loop+ pushed, so work the person added on top is never lost. ``force`` is for a+ run that is still the loop's own (``building``): its worktree goes even+ with uncommitted changes.+ """+ from .builder import remove_local, remove_remote++ undo = dict(record.undo)+ branch = str(undo.get("branch") or "")+ folder = str(undo.get("folder") or "")+ # Only a branch this build made itself: a name that already existed is not ours.+ if not branch.startswith(BRANCH_PREFIX) or not folder or not undo.get("created"):+ return+ session_id = str(undo.get("session_id") or "")+ if session_id:+ await _stop_thread(ctx, session_id)+ if close_pull and undo.get("pr_id"):+ api = ctx.github()+ if api is None:+ raise RuntimeError("GitHub is not connected; the pull request cannot be closed")+ state = await asyncio.to_thread(api.pull, str(undo["repo"]), int(undo["pr_number"]))+ if state.state == "MERGED":+ raise RuntimeError("the pull request is merged; revert it in the repository")+ if state.state == "OPEN":+ await asyncio.to_thread(api.close_pull, str(undo["pr_id"]))+ head = str(undo.get("head") or "")+ if undo.get("pushed"):+ await asyncio.to_thread(remove_remote, folder, branch, head)+ await asyncio.to_thread(+ remove_local, folder, str(undo.get("worktree") or ""), branch, head=head, force=force+ )+++async def _stop_thread(ctx: Context, session_id: str) -> None:+ stop = getattr(ctx.runner, "stop", None)+ if stop is None:+ return+ try:+ await stop(session_id)+ except Exception: # noqa: BLE001 - a thread that cannot be stopped ends on its own+ logger.opt(exception=True).debug("self-build code: thread {} not stopped", session_id)+++async def watch(ctx: Context, record: BuildRecord) -> None:+ """One look at the pull request of ``record`` and whatever follows from it."""+ if record.artefact.get("type") != "pull_request":+ return+ api = ctx.github()+ if api is None:+ return+ repo = str(record.artefact.get("repo") or "")+ number = int(record.artefact.get("number") or 0)+ pull = await asyncio.to_thread(api.pull, repo, number)+ if pull.state == "MERGED":+ await _merged(ctx, record, pull)+ elif pull.state == "CLOSED":+ await _closed(ctx, record)+ elif record.state == State.PROVING:+ await _prove(ctx, record, pull)+ elif record.state == State.TRIAL:+ await _land(ctx, record, pull)+++async def _prove(ctx: Context, record: BuildRecord, pull: PullState) -> None:+ ledger = ctx.ledger+ tests = str(record.artefact.get("tests") or "local tests passed")+ age = now_ms() - int(record.artefact.get("opened_ms") or record.updated_ms)+ if pull.checks == "SUCCESS":+ await asyncio.to_thread(+ ledger.attach_proof,+ record.id,+ passed=True,+ judge="tests+ci",+ detail=f"{tests}\nCI passed on {pull.head_oid[:10]}",+ )+ elif pull.checks in _RED:+ failing = ", ".join(pull.failing) or "a check"+ await asyncio.to_thread(+ ledger.attach_proof,+ record.id,+ passed=False,+ judge="tests+ci",+ detail=f"{tests}\nCI failed: {failing}",+ )+ await _fail_after_pull(ctx, record, f"CI failed on the pull request: {failing}")+ return+ elif not pull.checks and age >= NO_CI_GRACE_MS:+ await asyncio.to_thread(+ ledger.attach_proof,+ record.id,+ passed=True,+ judge="tests",+ detail=f"{tests}\nNo CI runs on this repository; the local tests are the proof.",+ )+ elif age >= CI_TIMEOUT_MS:+ await _fail_after_pull(ctx, record, "CI did not finish within a day")+ return+ else:+ return # CI still running+ record = await asyncio.to_thread(+ ledger.set_state, record.id, State.TRIAL, "proven; the pull request waits for review"+ )+ await _land(ctx, record, pull)+++async def _land(ctx: Context, record: BuildRecord, pull: PullState) -> None:+ """Merge a green pull request, only in a repository the person opted in."""+ repo = str(record.artefact.get("repo") or "")+ if repo.lower() not in land_repos(ctx.config()) or pull.draft:+ return+ if pull.checks not in ("SUCCESS", "") or not record.proof.get("passed"):+ return+ api = ctx.github()+ if api is None:+ return+ try:+ await asyncio.to_thread(api.merge_pull, pull.id, head_oid=pull.head_oid)+ except Exception as exc: # noqa: BLE001 - not mergeable yet (review rule, conflict): wait+ logger.info("self-build code: {} not merged yet: {}", record.signature, exc)+ return+ logger.info("self-build code: landed {} (#{})", record.signature, pull.number)+++async def _merged(ctx: Context, record: BuildRecord, pull: PullState) -> None:+ ledger = ctx.ledger+ head = str(record.undo.get("head") or "")+ changed = bool(head) and pull.head_oid != head+ outcome = Outcome.CORRECTED if changed else Outcome.ACCEPTED+ if record.state == State.PROVING:+ await asyncio.to_thread(+ ledger.attach_proof,+ record.id,+ passed=True,+ judge="merged",+ detail="The person merged the pull request.",+ )+ record = await asyncio.to_thread(ledger.set_state, record.id, State.TRIAL, "merged")+ await asyncio.to_thread(ledger.record_use, record.id, outcome)+ if record.state != State.KEPT:+ note = "merged after changes by the person" if changed else "merged as built"+ await asyncio.to_thread(ledger.set_state, record.id, State.KEPT, note)+ await _learn(ctx, record, "merged", changed=changed)+ try:+ await cleanup(ctx, record, close_pull=False)+ except Exception: # noqa: BLE001 - leftovers of a merged build are harmless+ logger.opt(exception=True).info("self-build code: cleanup after merge incomplete")+++async def _closed(ctx: Context, record: BuildRecord) -> None:+ await asyncio.to_thread(ctx.ledger.record_use, record.id, Outcome.IGNORED)+ await cleanup(ctx, record, close_pull=False)+ await _learn(ctx, record, "closed")+ if record.state in (State.PROVING, State.TRIAL, State.ARCHIVED, State.KEPT):+ await asyncio.to_thread(+ ctx.ledger.set_state, record.id, State.UNDONE, "closed on GitHub without merge"+ )+++async def _fail_after_pull(ctx: Context, record: BuildRecord, lesson: str) -> None:+ await cleanup(ctx, record, close_pull=True)+ parsed = parse_signature(record.signature)+ if parsed:+ await asyncio.to_thread(+ ctx.store.add_to_profile,+ parsed[0],+ "lessons",+ {"number": parsed[1], "lesson": lesson},+ )+ await _fold(ctx, record, parsed[0])+ await asyncio.to_thread(ctx.ledger.set_state, record.id, State.FAILED, lesson)+++async def _learn(ctx: Context, record: BuildRecord, field: str, *, changed: bool = False) -> None:+ parsed = parse_signature(record.signature)+ if parsed is None:+ return+ repo, number = parsed+ seen = await asyncio.to_thread(ctx.store.issue, repo, number)+ issue: dict[str, Any] = (seen or {}).get("issue") or {}+ entry = {+ "number": number,+ "title": str(issue.get("title") or record.title),+ "labels": list(issue.get("labels") or []),+ "changed": changed,+ }+ await asyncio.to_thread(ctx.store.add_to_profile, repo, field, entry)+ await _fold(ctx, record, repo)+++async def _fold(ctx: Context, record: BuildRecord, repo: str) -> None:+ folder = str(record.undo.get("folder") or "")+ if not folder:+ return+ profile = await asyncio.to_thread(ctx.store.profile, repo)+ await asyncio.to_thread(brief_mod.note_outcomes, ctx.store, folder, profile)diff --git a/dodaios/ui/web/server.py b/dodaios/ui/web/server.pyindex eb66d5fef2..18e2347071 100644--- a/dodaios/ui/web/server.py+++ b/dodaios/ui/web/server.py@@ -2986,6 +2986,9 @@ class WebServer:from dodaios.self_build.app import install_in_appinstall_in_app(_self_build, self.app.state, self.bus)+ from dodaios.self_build.code import install as install_code_builder++ install_code_builder(_self_build, self.app.state)except Exception as exc: # noqa: BLE001logger.opt(exception=exc).warning("self-build ledger init failed — nothing will be self-built this run"diff --git a/tests/unit/self_build/test_self_build_code.py b/tests/unit/self_build/test_self_build_code.pynew file mode 100644index 0000000000..22c567c24d--- /dev/null+++ b/tests/unit/self_build/test_self_build_code.py@@ -0,0 +1,760 @@+"""The code builder end to end: an issue in a sandbox repository becomes a draft+pull request with a green check, recorded in the ledger and undoable; and every+guard (other people's repositories, risky issues, pause, off, silent days, caps,+failing tests, protected files) produces nothing."""++from __future__ import annotations++import asyncio+import sys+import time+from dataclasses import dataclass, field+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from dodaios.core.config import SelfBuildConfig+from dodaios.self_build import Kind, Outcome, SelfBuild, State, policy+from dodaios.self_build.code import brief as brief_mod+from dodaios.self_build.code import commands, judge, seat+from dodaios.self_build.code.context import Context, branch_name, parse_signature, signature+from dodaios.self_build.code.github import (+ CreatedPull,+ Issue,+ PullRef,+ PullState,+ Snapshot,+ Viewer,+)+from dodaios.self_build.code.loop import CodeLoop+from dodaios.self_build.code.planner import Plan, parse+from dodaios.self_build.code.runner import RunResult+from dodaios.self_build.code.seat import Seat+from dodaios.self_build.code.store import CodeStore++from .code_sandbox import ISSUE_BODY, git, make_issue, sandbox++# ------------------------------------------------------------------ fakes+++@dataclass+class FakeGitHub:+ login: str = "me"+ issues: dict[str, list[Issue]] = field(default_factory=dict)+ pulls: dict[int, dict[str, Any]] = field(default_factory=dict)+ calls: list[str] = field(default_factory=list)+ open_refs: tuple[PullRef, ...] = ()++ def viewer(self) -> Viewer:+ self.calls.append("viewer")+ return Viewer(login=self.login)++ def snapshot(self, repo: str) -> Snapshot:+ self.calls.append(f"snapshot {repo}")+ return Snapshot(+ repo=repo,+ permission="ADMIN",+ default_branch="main",+ issues=tuple(self.issues.get(repo, [])),+ pulls=self.open_refs,+ )++ def create_pull(+ self, repo: str, *, head: str, base: str, title: str, body: str, draft: bool+ ) -> CreatedPull:+ number = 100 + len(self.pulls)+ self.calls.append(f"create {repo} {head}")+ self.pulls[number] = {+ "repo": repo,+ "head": head,+ "base": base,+ "title": title,+ "body": body,+ "draft": draft,+ "state": "OPEN",+ "checks": "PENDING",+ "head_oid": "",+ "merged": 0,+ }+ return CreatedPull(id=f"PR_{number}", number=number, url=f"https://x/{repo}/pull/{number}")++ def pull(self, repo: str, number: int) -> PullState:+ data = self.pulls[number]+ return PullState(+ id=f"PR_{number}",+ number=number,+ url="",+ state=data["state"],+ draft=data["draft"],+ head_oid=data["head_oid"],+ checks=data["checks"],+ failing=("tests",) if data["checks"] == "FAILURE" else (),+ )++ def close_pull(self, pull_id: str) -> None:+ self.calls.append(f"close {pull_id}")+ self.pulls[int(pull_id.split("_")[1])]["state"] = "CLOSED"++ def merge_pull(self, pull_id: str, *, head_oid: str) -> None:+ self.calls.append(f"merge {pull_id}")+ self.pulls[int(pull_id.split("_")[1])]["state"] = "MERGED"+ self.pulls[int(pull_id.split("_")[1])]["head_oid"] = head_oid+++@dataclass+class FakeRunner:+ """The coding agent: writes the change it is told to (or a bad one)."""++ change: str = "good"+ prompts: list[str] = field(default_factory=list)+ stopped: list[str] = field(default_factory=list)++ async def run(+ self,+ *,+ provider: str,+ folder: str,+ prompt: str,+ title: str,+ timeout_s: float,+ should_stop: Any,+ on_session: Any = None,+ ) -> RunResult:+ self.prompts.append(prompt)+ if on_session is not None:+ await on_session("thread-1")+ root = Path(folder)+ if self.change == "nothing":+ return RunResult(True, summary="Nothing to do.", session_id="thread-1")+ if self.change == "fail":+ return RunResult(False, error="the CLI crashed", session_id="thread-1")+ calc = root / "calc.py"+ calc.write_text(+ calc.read_text(encoding="utf-8")+ + "\n\ndef mul(a: int, b: int) -> int:\n"+ + (" return a * b\n" if self.change != "broken" else " return a + b\n"),+ encoding="utf-8",+ )+ (root / "tests" / "test_mul.py").write_text(+ "from calc import mul\n\n\ndef test_mul():\n assert mul(2, 3) == 6\n",+ encoding="utf-8",+ )+ if self.change == "protected":+ (root / ".github" / "workflows").mkdir(parents=True)+ (root / ".github" / "workflows" / "ci.yml").write_text("on: push\n", encoding="utf-8")+ return RunResult(True, summary="Added mul() and a test.", session_id="thread-1")++ async def outcome(self, session_id: str) -> RunResult | None:+ return RunResult(True, summary="Added mul() and a test.", session_id=session_id)++ async def stop(self, session_id: str) -> None:+ self.stopped.append(session_id)+++@dataclass+class World:+ service: SelfBuild+ loop: CodeLoop+ github: FakeGitHub+ runner: FakeRunner+ work: Path+ remote: Path+ cfg: SimpleNamespace+ idle: list[bool]+ seat_calls: list[int]++ def tick(self) -> dict[str, Any]:+ async def go() -> dict[str, Any]:+ summary = await self.loop.tick()+ if self.loop._building is not None:+ await self.loop._building+ return summary++ return asyncio.run(go())++ def records(self) -> list[Any]:+ return self.service.ledger.list(kinds=[Kind.CODE])++ def remote_branches(self) -> list[str]:+ out = git(self.remote, "branch", "--list", "--format=%(refname:short)")+ return [b for b in out.splitlines() if b]+++def world(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> World:+ monkeypatch.setattr(commands, "_python", lambda folder: sys.executable)+ work = sandbox(tmp_path)+ cfg = SimpleNamespace(+ self_build=SelfBuildConfig(silent_days=0, code="trial"),+ ui=SimpleNamespace(language="en"),+ )+ service = SelfBuild(tmp_path / "data", lambda: cfg)+ github = FakeGitHub(issues={"me/proj": [make_issue()]})+ runner = FakeRunner()+ idle = [True]+ seat_calls: list[int] = []++ async def pick() -> tuple[Seat | None, str]:+ seat_calls.append(1)+ return Seat(provider="claude-api", runner="claude-cli", label="Claude Code"), ""++ project = SimpleNamespace(+ path=str(work), name="proj", last_opened_at=time.time(), scratch=False, archived=False+ )+ ctx = Context(+ service=service,+ store=CodeStore(tmp_path / "data" / "self_build_code.db"),+ github=lambda: github,+ runner=runner,+ seat=pick,+ idle=lambda: idle[0],+ projects=lambda: [project],+ plan=None,+ dodaios_root=None,+ )+ loop = CodeLoop(ctx)+ loop.attach()+ yield World(+ service,+ loop,+ github,+ runner,+ work,+ tmp_path / "github.com" / "me" / "proj.git",+ cfg,+ idle,+ seat_calls,+ )+ ctx.store.close()+ service.ledger.close()+++# ------------------------------------------------------------------ the whole way+++def test_issue_becomes_draft_pull_request_proven_by_ci_and_undoable(world: World) -> None:+ summary = world.tick()+ assert summary["projects"] == ["me/proj"]+ assert summary["opened"] == 1+ [record] = world.records()+ assert record.signature == "code:me/proj#1"+ assert record.state == State.PROVING+ assert record.evidence == ("https://github.com/me/proj/issues/1",)+ assert record.title == "Fix issue #1 in me/proj: Add a mul function"++ pull = world.github.pulls[100]+ assert pull["draft"] is True+ assert pull["base"] == "main"+ assert pull["body"].startswith("Closes #1")+ assert "passed in" in pull["body"]+ assert record.artefact["type"] == "pull_request"+ assert record.artefact["draft"] is True+ branch = record.undo["branch"]+ assert branch.startswith("dodaios/issue-1-")+ assert branch in world.remote_branches()+ worktree = Path(record.undo["worktree"])+ assert worktree.is_dir() and ".worktrees" in worktree.parts+ # The person's own checkout was never touched.+ assert git(world.work, "rev-parse", "--abbrev-ref", "HEAD") == "main"+ assert "mul" not in (world.work / "calc.py").read_text(encoding="utf-8")+ # The coding agent got the brief and the repository's rules.+ prompt = world.runner.prompts[0]+ assert "Use type hints in new code." in prompt+ assert "pytest" in prompt and ISSUE_BODY in prompt++ world.github.pulls[100]["checks"] = "SUCCESS"+ world.tick()+ record = world.service.ledger.get(record.id)+ assert record.state == State.TRIAL+ assert record.proof["passed"] is True+ assert record.proof["judge"] == "tests+ci"+ assert "merge PR_100" not in world.github.calls # draft, no opt-in: never merged++ undone = asyncio.run(world.service.undo_build(record.id))+ assert undone.state == State.UNDONE+ assert world.github.pulls[100]["state"] == "CLOSED"+ assert branch not in world.remote_branches()+ assert not worktree.exists()+ assert branch not in git(world.work, "branch", "--list", branch)+++def test_merged_pull_request_is_kept_and_teaches_the_profile(world: World) -> None:+ world.tick()+ [record] = world.records()+ world.github.pulls[100].update(checks="SUCCESS")+ world.tick()+ world.github.pulls[100].update(state="MERGED", head_oid=record.undo["head"])+ world.tick()+ record = world.service.ledger.get(record.id)+ assert record.state == State.KEPT+ assert record.outcomes == {Outcome.ACCEPTED.value: 1}+ profile = world.loop.ctx.store.profile("me/proj")+ assert [e["number"] for e in profile["merged"]] == [1]+ assert profile["merged"][0]["changed"] is False+ stored = brief_mod.load(world.loop.ctx.store, world.work)+ assert stored is not None and stored.parts["outcomes"]["merged"] == 1+ # One build per issue, ever: the merged issue is not offered again.+ world.tick()+ assert len(world.records()) == 1+++def test_changed_before_merge_counts_as_corrected(world: World) -> None:+ world.tick()+ [record] = world.records()+ world.github.pulls[100].update(state="MERGED", head_oid="someone-else-pushed")+ world.tick()+ record = world.service.ledger.get(record.id)+ assert record.state == State.KEPT+ assert record.outcomes == {Outcome.CORRECTED.value: 1}+++def test_red_ci_fails_the_build_closes_the_pull_request_and_keeps_the_lesson(world: World) -> None:+ world.tick()+ [record] = world.records()+ branch = record.undo["branch"]+ world.github.pulls[100]["checks"] = "FAILURE"+ world.tick()+ record = world.service.ledger.get(record.id)+ assert record.state == State.FAILED+ assert record.proof == {"passed": False, "judge": "tests+ci", "detail": record.proof["detail"]}+ assert world.github.pulls[100]["state"] == "CLOSED"+ assert branch not in world.remote_branches()+ lessons = world.loop.ctx.store.profile("me/proj")["lessons"]+ assert "CI failed" in lessons[-1]["lesson"]+++def test_person_closing_the_pull_request_undoes_the_build(world: World) -> None:+ world.tick()+ [record] = world.records()+ world.github.pulls[100]["state"] = "CLOSED"+ world.tick()+ record = world.service.ledger.get(record.id)+ assert record.state == State.UNDONE+ assert world.loop.ctx.store.profile("me/proj")["closed"][0]["number"] == 1+++def test_landing_opt_in_merges_after_green_ci(world: World) -> None:+ world.cfg.self_build = SelfBuildConfig(silent_days=0, code="trial", code_land_repos=["Me/Proj"])+ world.tick()+ assert world.github.pulls[100]["draft"] is False+ world.github.pulls[100]["checks"] = "SUCCESS"+ world.tick()+ assert "merge PR_100" in world.github.calls+ world.tick()+ [record] = world.records()+ assert record.state == State.KEPT+++def test_repository_without_ci_is_judged_by_local_tests(+ world: World, monkeypatch: pytest.MonkeyPatch+) -> None:+ from dodaios.self_build.code import watch++ world.tick()+ world.github.pulls[100]["checks"] = ""+ monkeypatch.setattr(watch, "NO_CI_GRACE_MS", 0)+ world.tick()+ [record] = world.records()+ assert record.state == State.TRIAL+ assert record.proof["judge"] == "tests"+++# ------------------------------------------------------------------ failures without a PR+++ ("change", "lesson"),+ [+ ("broken", "the tests failed"),+ ("protected", "protected files"),+ ("nothing", "changed nothing"),+ ("fail", "did not finish"),+ ],+)+def test_a_bad_run_fails_without_a_pull_request(world: World, change: str, lesson: str) -> None:+ world.runner.change = change+ world.tick()+ [record] = world.records()+ assert record.state == State.FAILED+ assert lesson in record.note+ assert world.github.pulls == {}+ assert world.remote_branches() == ["main"]+ assert not Path(record.undo["worktree"]).exists()+ assert lesson in world.loop.ctx.store.profile("me/proj")["lessons"][-1]["lesson"]+++def test_large_estimate_stops_before_any_coding(world: World) -> None:+ async def big(build_id: str, issue: Issue, text: str) -> Plan:+ return Plan(text="- redesign everything", size="large")++ world.loop.ctx.plan = big+ world.tick()+ [record] = world.records()+ assert record.state == State.FAILED+ assert world.runner.prompts == []+++# ------------------------------------------------------------------ guards: nothing happens+++def test_other_peoples_repositories_are_never_polled(tmp_path: Path, world: World) -> None:+ other = sandbox(tmp_path / "x", owner="someone", name="lib")+ world.loop.ctx.projects = lambda: [+ SimpleNamespace(path=str(other), name="lib", last_opened_at=time.time())+ ]+ world.github.issues = {"someone/lib": [make_issue()]}+ summary = world.tick()+ assert summary["projects"] == []+ assert not [c for c in world.github.calls if c.startswith("snapshot")]+ assert world.records() == []+++def test_dodaios_own_source_is_outside_the_loop(world: World) -> None:+ (world.work / "dodaios" / "self_build").mkdir(parents=True)+ assert world.tick()["projects"] == []+++ "issue",+ [+ make_issue(title="Rotate the API key in settings"),+ make_issue(body="Update the deploy script so production uses the new bucket name."),+ make_issue(body="Fix the GitHub Actions workflow that runs the nightly tests now."),+ make_issue(author="stranger", labels=()),+ make_issue(labels=("agent", "question")),+ make_issue(assignees=1),+ make_issue(labels=()),+ make_issue(body="short"),+ ],+)+def test_unfit_issues_open_nothing(world: World, issue: Issue) -> None:+ world.github.issues = {"me/proj": [issue]}+ assert world.tick()["opened"] == 0+ assert world.records() == []+++def test_paused_or_off_makes_no_call_at_all(world: World) -> None:+ policy.set_paused(world.service.ledger, True)+ assert world.tick() == {"skipped": "paused"}+ policy.set_paused(world.service.ledger, False)+ world.cfg.self_build = SelfBuildConfig(silent_days=0, code="off")+ assert world.tick() == {"skipped": "off"}+ assert world.github.calls == []+ assert world.records() == []+++def test_suggest_and_silent_days_only_propose(world: World) -> None:+ world.cfg.self_build = SelfBuildConfig(silent_days=0, code="suggest")+ world.tick()+ [record] = world.records()+ assert record.state == State.PROPOSED+ assert world.runner.prompts == [] and world.github.pulls == {}+ # Accepting the card builds it (on the next idle pass).+ asyncio.run(world.service.accept(record.id))+ world.tick()+ assert world.service.ledger.get(record.id).state == State.PROVING+++def test_silent_first_days_record_without_building(world: World) -> None:+ world.cfg.self_build = SelfBuildConfig(silent_days=7, code="full")+ world.tick()+ [record] = world.records()+ assert record.state == State.PROPOSED+ assert world.runner.prompts == []+++def test_daily_code_cap_turns_a_build_into_a_proposal(world: World) -> None:+ world.cfg.self_build = SelfBuildConfig(silent_days=0, code="trial", max_code_runs_per_day=0)+ world.tick()+ [record] = world.records()+ assert record.state == State.PROPOSED+ assert world.runner.prompts == []+++def test_one_new_case_per_pass(world: World) -> None:+ world.github.issues = {"me/proj": [make_issue(1), make_issue(2, title="Add a div function")]}+ world.tick()+ assert len(world.records()) == 1+++def test_busy_person_or_no_subscription_waits(world: World) -> None:+ world.idle[0] = False+ world.tick()+ [record] = world.records()+ assert record.state == State.BUILDING+ assert world.runner.prompts == [] and world.seat_calls == []+ world.idle[0] = True++ async def none() -> tuple[Seat | None, str]:+ return None, "Claude Code: plan not signed in"++ world.loop.ctx.seat = none+ assert world.tick()["build"] == "waiting: Claude Code: plan not signed in"+ assert world.service.ledger.get(record.id).state == State.BUILDING+++def _slow_run(world: World) -> asyncio.Event:+ """Make the fake agent work until it is stopped (or the event is set)."""+ released = asyncio.Event()++ async def slow(**kwargs: Any) -> RunResult:+ await kwargs["on_session"]("thread-9")+ while not released.is_set() and not kwargs["should_stop"](): # noqa: ASYNC110 - polls should_stop too+ await asyncio.sleep(0.02)+ return RunResult(False, error="stopped", session_id="thread-9")++ async def stop(session_id: str) -> None:+ world.runner.stopped.append(session_id)+ released.set()++ world.runner.run = slow # type: ignore[method-assign]+ world.runner.stop = stop # type: ignore[method-assign]+ return released+++async def _until_coding(world: World, build_id: str) -> None:+ for _ in range(3000): # up to a minute on a loaded machine+ if world.service.ledger.get(build_id).undo.get("session_id"):+ return+ await asyncio.sleep(0.02)+ raise AssertionError("the run never started")+++def test_undo_while_coding_stops_the_run(world: World) -> None:+ world.idle[0] = False+ world.tick()+ [record] = world.records()+ world.idle[0] = True++ async def go() -> Any:+ _slow_run(world)+ await world.loop.tick()+ await _until_coding(world, record.id)+ undone = await world.service.undo_build(record.id)+ await world.loop._building+ return undone++ undone = asyncio.run(go())+ assert undone.state == State.UNDONE+ assert world.service.ledger.get(record.id).state == State.UNDONE+ assert "thread-9" in world.runner.stopped+ assert not Path(undone.undo["worktree"]).exists()+ assert world.github.pulls == {}+ # An undone issue is not offered again.+ world.tick()+ assert len(world.records()) == 1+++def test_pause_mid_run_puts_the_case_back_in_the_queue(world: World) -> None:+ world.idle[0] = False+ world.tick()+ [record] = world.records()+ world.idle[0] = True++ async def go() -> None:+ _slow_run(world)+ await world.loop.tick()+ await _until_coding(world, record.id)+ policy.set_paused(world.service.ledger, True)+ await world.loop._building++ asyncio.run(go())+ record = world.service.ledger.get(record.id)+ assert record.state == State.BUILDING+ assert record.artefact == {} and record.undo == {}+ assert world.remote_branches() == ["main"]+ assert world.loop.ctx.store.profile("me/proj")["lessons"] == []+ # After the pause the case is built from scratch.+ policy.set_paused(world.service.ledger, False)+ world.runner = FakeRunner()+ world.loop.ctx.runner = world.runner+ world.tick()+ assert world.service.ledger.get(record.id).state == State.PROVING+++def test_undo_keeps_a_branch_the_person_added_commits_to(world: World) -> None:+ world.tick()+ [record] = world.records()+ branch = record.undo["branch"]+ worktree = Path(record.undo["worktree"])+ (worktree / "extra.py").write_text("x = 1\n", encoding="utf-8")+ git(worktree, "add", "extra.py")+ git(worktree, "commit", "-m", "person's own work")+ git(worktree, "push", "origin", branch)+ undone = asyncio.run(world.service.undo_build(record.id))+ assert undone.state == State.UNDONE+ assert world.github.pulls[100]["state"] == "CLOSED"+ assert branch in world.remote_branches() # their commit lives on+ assert worktree.exists()+++def test_existing_branch_stops_the_build(world: World) -> None:+ branch = branch_name(1, "Add a mul function")+ git(world.work, "branch", branch)+ world.tick()+ [record] = world.records()+ assert record.state == State.FAILED+ assert "already exists" in record.note+ assert branch in git(world.work, "branch", "--list", branch) # the person's branch stays+++def test_pull_request_targets_githubs_default_branch(world: World) -> None:+ git(world.work, "checkout", "-b", "feature")+ git(world.work, "push", "-u", "origin", "feature")+ git(world.work, "remote", "set-head", "origin", "feature")+ world.tick()+ assert world.github.pulls[100]["base"] == "main"+++def test_stale_case_may_be_offered_again(world: World, monkeypatch: pytest.MonkeyPatch) -> None:+ from dodaios.self_build.code import loop as loop_mod++ world.idle[0] = False+ world.tick()+ monkeypatch.setattr(loop_mod, "STALE_BUILDING_MS", -1)+ world.tick()+ [record] = world.records()+ assert record.state == State.FAILED and record.note.startswith("not run: ")+ world.loop.ctx.store.set_poll("me/proj", 0)+ world.tick()+ assert len(world.records()) == 2+++# ------------------------------------------------------------------ parts+++def test_judge_guard_and_names() -> None:+ assert judge.guard(["src/a.py", ".github/workflows/ci.yml", "AGENTS.md", ".env.local"]) == [+ ".github/workflows/ci.yml",+ "AGENTS.md",+ ".env.local",+ ]+ assert branch_name(12, "Fix: the CLI's --help!") == "dodaios/issue-12-fix-the-cli-s-help"+ assert parse_signature(signature("me/proj", 4)) == ("me/proj", 4)+ assert parse_signature("routine:weekly") is None+++def test_plan_answer_is_parsed() -> None:+ plan = parse("SIZE: Medium\nPLAN:\n- edit calc.py\n- add a test")+ assert plan.size == "medium" and plan.text.startswith("- edit")+ assert parse("no idea").size == ""+++def test_seat_never_uses_a_cli_that_would_bill_a_key(monkeypatch: pytest.MonkeyPatch) -> None:+ from dodaios.brain import background_policy++ row = SimpleNamespace(id="claude-api", agent="claude", label="Claude Code")+ monkeypatch.setattr(seat, "_rows", lambda: [row])+ monkeypatch.setattr(+ "dodaios.agent_chat.service.resolve_runner", lambda provider, surface="agent": "claude-cli"+ )+ monkeypatch.setattr(seat, "_cooling", lambda runner: False)+ monkeypatch.setattr(seat, "_window_full", lambda platform: False)+ monkeypatch.setattr(background_policy, "login_state", lambda provider: True)+ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)+ monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False)+ chosen, _ = seat.choose({"claude": True})+ assert chosen is not None and chosen.provider == "claude-api"+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test")+ chosen, why = seat.choose({"claude": True})+ assert chosen is None and "API key" in why+ monkeypatch.delenv("ANTHROPIC_API_KEY")+ monkeypatch.setattr(background_policy, "login_state", lambda provider: None)+ assert seat.choose({"claude": True})[0] is None+ assert seat.choose({"claude": False})[0] is None+++# ------------------------------------------------------------------ the thread runner+++class FakeChat:+ """The agent-chat service surface the thread runner uses."""++ def __init__(self, events: list[dict[str, Any]]) -> None:+ self.script = events+ self.events: list[dict[str, Any]] = []+ self.sessions: list[dict[str, Any]] = []+ self.cancelled: list[str] = []+ self.store = SimpleNamespace(list_events=lambda sid, tail=None: list(self.events))++ def create_session(self, **kwargs: Any) -> Any:+ self.sessions.append(kwargs)+ return SimpleNamespace(session_id="s1")++ async def send(self, sid: str, text: str, *, author: dict[str, str]) -> str:+ self.sent = (text, author)+ self.events = [+ {"kind": e["kind"], "payload": {"turn_id": "t1", **e["payload"]}} for e in self.script+ ]+ return "t1"++ def is_running(self, sid: str) -> bool:+ return any(e["kind"] == "question_required" for e in self.events) and not self.cancelled++ async def cancel(self, sid: str) -> bool:+ self.cancelled.append(sid)+ return True+++def test_thread_runner_opens_a_full_access_thread_in_the_worktree(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from dodaios.self_build.code.runner import ThreadRunner++ monkeypatch.setattr(+ "dodaios.agent_chat.service.resolve_runner", lambda provider, surface="agent": "claude-cli"+ )+ chat = FakeChat(+ [+ {"kind": "assistant_text", "payload": {"text": "Added mul()."}},+ {"kind": "turn_finished", "payload": {"status": "done"}},+ ]+ )+ seen: list[str] = []++ async def note(sid: str) -> None:+ seen.append(sid)++ result = asyncio.run(+ ThreadRunner(lambda: chat).run(+ provider="claude-api",+ folder="/w",+ prompt="do it",+ title="#1 x",+ timeout_s=60,+ should_stop=lambda: False,+ on_session=note,+ )+ )+ assert result.ok and result.summary == "Added mul()." and seen == ["s1"]+ [opened] = chat.sessions+ assert opened["cwd"] == "/w" and opened["surface"] == "agent"+ assert opened["permission_mode"] # the runner's bypass mode, never empty+ assert chat.sent[1]["name"] == "Dodaios"+++def test_thread_runner_stops_at_a_question(monkeypatch: pytest.MonkeyPatch) -> None:+ from dodaios.self_build.code.runner import ThreadRunner++ monkeypatch.setattr(+ "dodaios.agent_chat.service.resolve_runner", lambda provider, surface="agent": "claude-cli"+ )+ chat = FakeChat(+ [+ {"kind": "question_required", "payload": {"question_id": "q1", "questions": []}},+ ]+ )+ result = asyncio.run(+ ThreadRunner(lambda: chat).run(+ provider="claude-api",+ folder="/w",+ prompt="do it",+ title="t",+ timeout_s=60,+ should_stop=lambda: False,+ )+ )+ assert not result.ok and "question" in result.error+ assert chat.cancelled == ["s1"] # the waiting turn is ended, not left open