Skip to content

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.

fix(self-build): re-read the issue right before a code build starts (#776)

Ruben Lütke3038061e67de
diff --git a/docs/self-build-code.md b/docs/self-build-code.md
index b3cf5020bf..c353d277d1 100644
--- a/docs/self-build-code.md
+++ b/docs/self-build-code.md
@@ -72,6 +72,10 @@ 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.
+0. The issue is read again from GitHub. Closed, assigned to someone other than
+ the person, no longer passing triage, or a repository that is no longer the
+ person's own: the case fails with a `not built: ...` note and nothing is
+ done. GitHub not answering only puts the case back in the queue.
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
diff --git a/dodaios/self_build/code/builder.py b/dodaios/self_build/code/builder.py
index 329c9bc4d7..8021bdae67 100644
--- a/dodaios/self_build/code/builder.py
+++ b/dodaios/self_build/code/builder.py
@@ -70,6 +70,10 @@ class Stopped(BuildError):
self.requeue = requeue
+class Obsolete(BuildError):
+ """The issue no longer qualifies; nothing was built and nothing is learned."""
+
+
# ------------------------------------------------------------------ git steps
@@ -290,6 +294,57 @@ def target(ctx: Context, record: BuildRecord) -> tuple[str, Issue, dict[str, Any
return repo, Issue.from_json(data), data
+async def recheck(ctx: Context, repo: str, issue: Issue, data: dict[str, Any]) -> Issue:
+ """The issue as it stands right before the build, or :class:`Obsolete`.
+
+ A proposal can wait days for the person's accept or for idle time; by then
+ the issue may be closed, taken by someone else, relabelled, or the
+ repository may have changed hands. Any of these ends the case before any
+ work. GitHub not answering only puts the case back in the queue.
+ """
+ from dataclasses import replace
+
+ from dodaios.agentic_ide.github_link import GitHubError
+
+ from .intake import repo_of, viewer
+ from .triage import triage
+
+ api = ctx.github()
+ if api is None:
+ raise Stopped("stopped: GitHub is not connected", requeue=True)
+ try:
+ who = await viewer(ctx)
+ fresh = await asyncio.to_thread(api.issue, repo, issue.number)
+ except GitHubError as exc: # re-raised: the case waits for the next pass
+ raise Stopped(f"stopped: GitHub could not be asked ({exc})", requeue=True) from exc
+ if who is None:
+ raise Stopped("stopped: the GitHub account is unknown", requeue=True)
+ folder = str(data["folder"])
+ origin = await asyncio.to_thread(repo_of, folder)
+ if not who.owns(repo) or origin.lower() != repo.lower():
+ raise Obsolete("not built: the repository is no longer the person's own")
+ if fresh is None or fresh.state.upper() != "OPEN":
+ raise Obsolete(f"not built: issue #{issue.number} is closed")
+ others = [login for login in fresh.assigned_to if login.lower() != who.login.lower()]
+ if others or (fresh.assignees and not fresh.assigned_to):
+ raise Obsolete(f"not built: issue #{issue.number} is assigned to someone else")
+ profile = await asyncio.to_thread(ctx.store.profile, repo)
+ # Assigned to the person themselves is fine; the test command is checked next.
+ verdict = triage(replace(fresh, assignees=0), login=who.login, profile=profile, has_tests=True)
+ if not verdict.fit:
+ raise Obsolete(f"not built: issue #{issue.number} no longer fits ({verdict.reason})")
+ await asyncio.to_thread(
+ ctx.store.put_issue,
+ repo,
+ fresh.number,
+ updated_at=fresh.updated_at,
+ verdict="fit",
+ reason=f"{verdict.signal}; rechecked",
+ issue={**data, **fresh.to_json()},
+ )
+ return fresh
+
+
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):
@@ -322,6 +377,11 @@ async def _fail(ctx: Context, record: BuildRecord, error: BuildError, *, repo: s
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, Obsolete):
+ logger.info("self-build code: {} not built: {}", record.signature, lesson)
+ if ctx.still(record, State.BUILDING):
+ await asyncio.to_thread(ctx.ledger.set_state, record.id, State.FAILED, lesson)
+ return
if isinstance(error, Stopped):
if error.requeue and ctx.still(record, State.BUILDING):
await asyncio.to_thread(ctx.ledger.attach_artefact, record.id, {}, {})
@@ -396,6 +456,7 @@ async def _build(
provider: str,
) -> None:
folder = str(data["folder"])
+ issue = await recheck(ctx, repo, issue, data)
brief, _ = await asyncio.to_thread(brief_mod.refresh, ctx.store, folder, repo=repo)
tests = brief.test_commands
if not tests:
diff --git a/dodaios/self_build/code/github.py b/dodaios/self_build/code/github.py
index 1d41867a85..f285d910a9 100644
--- a/dodaios/self_build/code/github.py
+++ b/dodaios/self_build/code/github.py
@@ -46,6 +46,8 @@ class Issue:
comments: int = 0
state: str = "OPEN"
updated_at: str = ""
+ #: Logins of the assignees, where the query read them (:meth:`GitHubApi.issue`).
+ assigned_to: tuple[str, ...] = ()
def to_json(self) -> dict[str, Any]:
return {
@@ -59,6 +61,7 @@ class Issue:
"comments": self.comments,
"state": self.state,
"updated_at": self.updated_at,
+ "assigned_to": list(self.assigned_to),
}
@classmethod
@@ -74,6 +77,7 @@ class Issue:
comments=int(data.get("comments") or 0),
state=str(data.get("state") or "OPEN"),
updated_at=str(data.get("updated_at") or ""),
+ assigned_to=tuple(str(x) for x in data.get("assigned_to") or ()),
)
@@ -128,6 +132,7 @@ class GitHub(Protocol):
self, repo: str, *, head: str, base: str, title: str, body: str, draft: bool
) -> CreatedPull: ...
def pull(self, repo: str, number: int) -> PullState: ...
+ def issue(self, repo: str, number: int) -> Issue | None: ...
def close_pull(self, pull_id: str) -> None: ...
def merge_pull(self, pull_id: str, *, head_oid: str) -> None: ...
@@ -182,6 +187,20 @@ query($owner: String!, $name: String!, $number: Int!) {
}
"""
+_ISSUE = """
+query($owner: String!, $name: String!, $number: Int!) {
+ repository(owner: $owner, name: $name) {
+ issue(number: $number) {
+ number title body url updatedAt state
+ author { login }
+ assignees(first: 10) { totalCount nodes { login } }
+ labels(first: 20) { nodes { name } }
+ comments { totalCount }
+ }
+ }
+}
+"""
+
_REPOSITORY_ID = """
query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { id } }
"""
@@ -216,6 +235,31 @@ def _split(repo: str) -> tuple[str, str]:
return owner, name
+def _issue_from(node: dict[str, Any]) -> Issue:
+ assignees = node.get("assignees") or {}
+ return Issue(
+ number=int(node.get("number") or 0),
+ title=str(node.get("title") or ""),
+ body=str(node.get("body") or "")[:8_000],
+ url=str(node.get("url") or ""),
+ author=str((node.get("author") or {}).get("login") or ""),
+ labels=tuple(
+ str(label.get("name") or "")
+ for label in (node.get("labels") or {}).get("nodes") or []
+ if isinstance(label, dict)
+ ),
+ assignees=int(assignees.get("totalCount") or 0),
+ comments=int((node.get("comments") or {}).get("totalCount") or 0),
+ state=str(node.get("state") or "OPEN"),
+ updated_at=str(node.get("updatedAt") or ""),
+ assigned_to=tuple(
+ str(person.get("login") or "")
+ for person in assignees.get("nodes") or []
+ if isinstance(person, dict) and person.get("login")
+ ),
+ )
+
+
def _first_error(payload: dict[str, Any]) -> str:
for error in payload.get("errors") or []:
if isinstance(error, dict) and error.get("message"):
@@ -251,28 +295,11 @@ class GitHubApi:
data = (self._q(_SNAPSHOT, {"owner": owner, "name": name}).get("data") or {}).get(
"repository"
) or {}
- issues = []
- for node in (data.get("issues") or {}).get("nodes") or []:
- if not isinstance(node, dict):
- continue
- issues.append(
- Issue(
- number=int(node.get("number") or 0),
- title=str(node.get("title") or ""),
- body=str(node.get("body") or "")[:8_000],
- url=str(node.get("url") or ""),
- author=str((node.get("author") or {}).get("login") or ""),
- labels=tuple(
- str(label.get("name") or "")
- for label in (node.get("labels") or {}).get("nodes") or []
- if isinstance(label, dict)
- ),
- assignees=int((node.get("assignees") or {}).get("totalCount") or 0),
- comments=int((node.get("comments") or {}).get("totalCount") or 0),
- state=str(node.get("state") or "OPEN"),
- updated_at=str(node.get("updatedAt") or ""),
- )
- )
+ issues = [
+ _issue_from(node)
+ for node in (data.get("issues") or {}).get("nodes") or []
+ if isinstance(node, dict)
+ ]
pulls = [
PullRef(
number=int(node.get("number") or 0),
@@ -355,6 +382,14 @@ class GitHubApi:
failing=tuple(failing[:10]),
)
+ def issue(self, repo: str, number: int) -> Issue | None:
+ """One issue as it stands now; None when GitHub does not know it."""
+ owner, name = _split(repo)
+ variables = {"owner": owner, "name": name, "number": int(number)}
+ repository = (self._q(_ISSUE, variables).get("data") or {}).get("repository") or {}
+ node = repository.get("issue")
+ return _issue_from(node) if isinstance(node, dict) else None
+
def close_pull(self, pull_id: str) -> None:
payload = self._q(_CLOSE, {"id": pull_id})
if not ((payload.get("data") or {}).get("closePullRequest")):
diff --git a/tests/unit/self_build/test_self_build_code.py b/tests/unit/self_build/test_self_build_code.py
index c1862123d7..22cbce542c 100644
--- a/tests/unit/self_build/test_self_build_code.py
+++ b/tests/unit/self_build/test_self_build_code.py
@@ -46,6 +46,8 @@ class FakeGitHub:
pulls: dict[int, dict[str, Any]] = field(default_factory=dict)
calls: list[str] = field(default_factory=list)
open_refs: tuple[PullRef, ...] = ()
+ #: What :meth:`issue` answers now, when it differs from the poll.
+ fresh: dict[int, Any] = field(default_factory=dict)
def viewer(self) -> Viewer:
self.calls.append("viewer")
@@ -97,6 +99,15 @@ class FakeGitHub:
self.calls.append(f"close {pull_id}")
self.pulls[int(pull_id.split("_")[1])]["state"] = "CLOSED"
+ def issue(self, repo: str, number: int) -> Issue | None:
+ self.calls.append(f"issue {repo}#{number}")
+ if number in self.fresh:
+ found = self.fresh[number]
+ if isinstance(found, Exception):
+ raise found
+ return found
+ return next((i for i in self.issues.get(repo, []) if i.number == number), None)
+
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"
@@ -795,3 +806,75 @@ def test_no_seat_means_no_plan_call(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(brain, "ask", refuse)
plan = asyncio.run(planner.plan("b1", make_issue(), "brief", config=lambda: None))
assert plan == Plan()
+
+
+# ------------------------------------------------------------------ re-check before the build
+
+
+ ("now", "note"),
+ [
+ (None, "is closed"),
+ ("closed", "is closed"),
+ ("someone", "assigned to someone else"),
+ ("unlabelled", "no longer fits"),
+ ("risky", "no longer fits"),
+ ],
+)
+def test_an_issue_that_changed_before_the_build_is_not_built(
+ world: World, now: str | None, note: str
+) -> None:
+ world.cfg.self_build = SelfBuildConfig(silent_days=0, code="suggest")
+ world.tick()
+ [record] = world.records()
+ assert record.state == State.PROPOSED
+ world.github.fresh[1] = {
+ None: None,
+ "closed": make_issue(state="CLOSED"),
+ "someone": make_issue(assignees=1, assigned_to=("someone",)),
+ "unlabelled": make_issue(labels=()),
+ "risky": make_issue(body="Rotate the deploy credentials on the production servers."),
+ }[now]
+ asyncio.run(world.service.accept(record.id))
+ world.tick()
+ record = world.service.ledger.get(record.id)
+ assert record.state == State.FAILED
+ assert record.note.startswith("not built: ") and note in record.note
+ assert world.runner.prompts == [] and world.github.pulls == {}
+ assert world.remote_branches() == ["main"]
+ assert not (world.work / ".worktrees").exists()
+ assert world.loop.ctx.store.profile("me/proj")["lessons"] == [] # not a lesson
+
+
+def test_an_issue_the_person_took_on_themselves_is_still_built(world: World) -> None:
+ world.github.fresh[1] = make_issue(assignees=1, assigned_to=("Me",))
+ world.tick()
+ [record] = world.records()
+ assert record.state == State.PROVING
+ assert "issue me/proj#1" in world.github.calls
+
+
+def test_a_repository_no_longer_owned_is_not_built(world: World) -> None:
+ world.cfg.self_build = SelfBuildConfig(silent_days=0, code="suggest")
+ world.tick()
+ [record] = world.records()
+ asyncio.run(world.service.accept(record.id))
+ world.github.login = "someone-else"
+ world.loop.ctx._viewer = None
+ world.tick()
+ record = world.service.ledger.get(record.id)
+ assert record.state == State.FAILED and "no longer the person's own" in record.note
+ assert world.runner.prompts == []
+
+
+def test_github_not_answering_the_recheck_keeps_the_case_waiting(world: World) -> None:
+ from dodaios.agentic_ide.github_link import GitHubError
+
+ world.github.fresh[1] = GitHubError("GitHub could not be reached.", code="unreachable")
+ world.tick()
+ [record] = world.records()
+ assert record.state == State.BUILDING and record.artefact == {}
+ assert world.runner.prompts == []
+ del world.github.fresh[1]
+ world.tick()
+ assert world.service.ledger.get(record.id).state == State.PROVING