Publish finished milestones as PRs (B2/A3) — step 6a, part 2
CI / checks (push) Successful in 41s
CI / checks (pull_request) Successful in 38s

Completes the B1 loop past EXECUTING, and answers the question raised
reviewing #6: PR acceptance is a milestone's final gate, so there is
no separate FINISHED state — completion returns to milestone planning
or to IDLE.

- publish.py: MilestonePublisher commits the work on a task-namespaced
  branch, pushes, and opens a PR carrying the approved plan. Intent is
  recorded before the first externally visible act, so a crash
  anywhere in the sequence leaves a durable record and boot
  reconciliation asks Gitea whether the PR exists rather than opening
  a second one
- Nothing to commit is reported, not raised: the executor may
  legitimately conclude there was nothing to change
- control.py: PR_OPEN state with EXECUTING -> PR_OPEN and
  PR_OPEN -> {MILESTONE_PLANNING, IDLE}; operator commands
  'next milestone' and 'project complete'
- A configured publisher always contributes its own reconciler at
  boot, so an interrupted publish is settled against external truth
  without the caller having to remember to register it
- A publish failure gates to the operator rather than retrying into a
  possible duplicate

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
dongarandClaude Opus 5 committed 2026-09-07 20:43:20 +00:00
1 parent 4025ac7875
commit 3117565928
4 files changed
+546 -3

No files matched your search

+89 -3
View File
@@ -15,6 +15,8 @@ from typing import Any, Protocol
from nisse_dev.canonical import GateOpened, PlanSubmitted, UserMessage
from nisse_dev.gates import Approved, Gate, Ignored, PlanRevision, Rejected
from nisse_dev.git import GitError
from nisse_dev.gitea import GiteaError
from nisse_dev.llm import RoleMap
from nisse_dev.reconcile import Reconciler, reconcile_on_boot
from nisse_dev.state import StateStore
@@ -26,6 +28,7 @@ AWAIT_ARCH_SIGNOFF = "AWAIT_ARCH_SIGNOFF"
MILESTONE_PLANNING = "MILESTONE_PLANNING"
AWAIT_MILESTONE_SIGNOFF = "AWAIT_MILESTONE_SIGNOFF"
EXECUTING = "EXECUTING"
PR_OPEN = "PR_OPEN"
AWAIT_INPUT = "AWAIT_INPUT"
TRANSITIONS = {
@@ -36,6 +39,12 @@ TRANSITIONS = {
(MILESTONE_PLANNING, AWAIT_MILESTONE_SIGNOFF),
(AWAIT_MILESTONE_SIGNOFF, MILESTONE_PLANNING),
(AWAIT_MILESTONE_SIGNOFF, EXECUTING),
(EXECUTING, PR_OPEN),
# PR acceptance is the milestone's final gate (B1): a merged PR is the
# durable record, so completion returns to planning or to idle rather
# than passing through a separate FINISHED state.
(PR_OPEN, MILESTONE_PLANNING),
(PR_OPEN, IDLE),
}
@@ -67,6 +76,17 @@ class MilestoneExecutor(Protocol):
def run(self, milestone: int) -> Any: ...
class MilestonePublisher(Protocol):
"""What the orchestrator needs to publish a milestone; the concrete one
lives in nisse_dev.publish."""
def reconcilers(self) -> Mapping[str, Reconciler]: ...
def publish(
self, *, task_id: str, milestone: int, project: str, plan: str
) -> Any: ...
class PlanningAgent(Protocol):
def plan(
self,
@@ -105,6 +125,7 @@ def _fresh_data() -> dict[str, Any]:
"milestone": 1,
"task_id": None,
"roles": None, # A11 mapping, pinned at task start
"pr": None, # the open PR for the current milestone, once published
}
@@ -117,19 +138,26 @@ class Orchestrator:
operators: Iterable[str],
roles: RoleMap | None = None,
executor: "MilestoneExecutor | None" = None,
publisher: "MilestonePublisher | None" = None,
) -> None:
self._store = store
self._transport = transport
self._agent = agent
self._roles = roles
self._executor = executor
self._publisher = publisher
self._operators = set(operators)
self._data = _fresh_data()
self._project: str | None = None
transport.on_message(self._handle)
def start(self, reconcilers: Mapping[str, Reconciler] | None = None) -> None:
report = reconcile_on_boot(self._store, reconcilers or {})
# The publisher owns the external-truth query for its own intents, so
# a configured publisher always contributes its reconciler (A3).
registered: dict[str, Reconciler] = dict(reconcilers or {})
if self._publisher is not None:
registered = {**self._publisher.reconcilers(), **registered}
report = reconcile_on_boot(self._store, registered)
state = self._store.get_state()
if state is None:
self._transition(IDLE, cause="boot: fresh state")
@@ -189,6 +217,8 @@ class Orchestrator:
self._transport.send_message("no active project; say 'use <project>'")
elif current in (AWAIT_ARCH_SIGNOFF, AWAIT_MILESTONE_SIGNOFF):
self._handle_gate_reply(msg, text)
elif current == PR_OPEN:
self._handle_pr_open(text)
elif current == AWAIT_INPUT:
self._handle_answer(text)
else:
@@ -337,9 +367,8 @@ class Orchestrator:
self._transport.send_message(f"executing milestone {milestone}")
outcome = self._executor.run(milestone)
if outcome.status == "completed":
# PR_OPEN and the review loop arrive with the Gitea layer (B2);
# until then a finished milestone simply reports and waits.
self._transport.send_message(f"milestone {milestone} done: {outcome.note}")
self._publish_milestone(milestone)
return
self._await_input(
cause=f"milestone {milestone} {outcome.status}",
@@ -347,6 +376,63 @@ class Orchestrator:
pending={"kind": "milestone_stopped", "milestone": milestone},
)
def _publish_milestone(self, milestone: int) -> None:
if self._publisher is None:
return
gate = self._data.get("gate") or {}
try:
result = self._publisher.publish(
task_id=str(self._data.get("task_id")),
milestone=milestone,
project=str(self._project),
plan=str(gate.get("plan", "")),
)
except (GiteaError, GitError) as exc:
# The intent log already records what was in flight, so boot
# reconciliation can settle it against Gitea. Gate rather than
# retry blindly into a possible duplicate.
self._await_input(
cause=f"publishing milestone {milestone} failed: {exc}",
prompt=f"could not publish milestone {milestone}: {exc}",
pending={"kind": "milestone_stopped", "milestone": milestone},
)
return
if result.pull_request is None:
self._transport.send_message(result.note)
return
self._data["pr"] = {
"number": result.pull_request.number,
"url": result.pull_request.url,
"milestone": milestone,
}
self._transition(PR_OPEN, cause=f"milestone {milestone} published")
self._transport.send_message(
f"{result.note} — review it, then say 'next milestone' or "
"'project complete'"
)
def _handle_pr_open(self, text: str) -> None:
if text == "next milestone":
self._data["milestone"] = int(self._data.get("milestone", 1)) + 1
self._data["gate"] = None
self._data["pr"] = None
self._transition(MILESTONE_PLANNING, cause="operator: next milestone")
self._run_planning_turn(f"milestone-{self._data['milestone']}")
elif text == "project complete":
self._data = {**_fresh_data()}
self._project = None
self._store.oplog.task_id = None
self._transition(IDLE, cause="operator: project complete")
self._transport.send_message(
"project closed; say 'use <project>' to start another"
)
else:
pr = self._data.get("pr") or {}
self._transport.send_message(
f"PR #{pr.get('number')} is open; say 'next milestone' or "
"'project complete'"
)
def _await_input(self, *, cause: str, prompt: str, pending: dict[str, Any]) -> None:
self._data["pending"] = pending
self._transition(AWAIT_INPUT, cause=cause)
+103
View File
@@ -0,0 +1,103 @@
"""Publishing a finished milestone as a Gitea PR (spec B2, A2/A3).
The ordering here is the whole point. Intent is recorded *before* the first
externally visible act, so a crash anywhere in the sequence leaves a durable
record of what was in flight. Boot reconciliation then asks Gitea whether the
PR exists rather than repeating the push-and-open — the spec's own example of
an idempotent transition reconciled against external truth.
"""
from dataclasses import dataclass
from nisse_dev.git import GitRepo, authenticated_url
from nisse_dev.gitea import GiteaClient, PullRequest, pull_request_reconciler
from nisse_dev.reconcile import Reconciler
from nisse_dev.state import StateStore
OPEN_PR_INTENT = "open_pr"
@dataclass(frozen=True)
class PublishResult:
pull_request: PullRequest | None
note: str
class MilestonePublisher:
def __init__(
self,
store: StateStore,
client: GiteaClient,
repo: str,
git_repo: GitRepo,
*,
base_url: str,
account: str,
token: str,
base_branch: str = "main",
) -> None:
self._store = store
self._client = client
self._repo = repo
self._git = git_repo
self._base_branch = base_branch
self._remote = authenticated_url(base_url, repo, account, token)
self._token = token
def reconcilers(self) -> dict[str, Reconciler]:
return {OPEN_PR_INTENT: pull_request_reconciler(self._client, self._repo)}
def branch_for(self, task_id: str, milestone: int) -> str:
# Namespaced by task so re-running a project against the same repo
# cannot collide with an earlier run's branch.
return f"{task_id}/milestone-{milestone}"
def publish(
self,
*,
task_id: str,
milestone: int,
project: str,
plan: str,
service_url: str | None = None,
) -> PublishResult:
branch = self.branch_for(task_id, milestone)
if self._git.current_branch() != branch:
self._git.checkout_new_branch(branch)
sha = self._git.commit_all(f"Milestone {milestone}: {project}")
if sha is None:
# Not an error: the executor may have concluded there was nothing
# to change. Report it and let the operator decide.
return PublishResult(None, "no changes to publish")
intent_id = self._store.begin_intent(
OPEN_PR_INTENT,
{"branch": branch, "milestone": milestone, "sha": sha},
cause=f"publishing milestone {milestone}",
)
self._git.push(self._remote, branch, token=self._token)
pr = self._client.open_pull_request(
self._repo,
head=branch,
base=self._base_branch,
title=f"Milestone {milestone}: {project}",
body=_pr_body(milestone, plan, service_url),
)
self._store.commit_intent(intent_id, cause=f"opened PR #{pr.number}")
return PublishResult(pr, f"opened PR #{pr.number}: {pr.url}")
def _pr_body(milestone: int, plan: str, service_url: str | None) -> str:
parts = [
f"Milestone {milestone}, implemented by nisse-dev against the approved plan.",
"",
"## Approved plan",
"",
plan,
]
if service_url:
# B2: a runnable test service's address belongs in the PR description
# so a reviewer can exercise it. Nothing reports one yet; the browser
# tool (A6) is what will.
parts += ["", "## Running test service", "", service_url]
return "\n".join(parts)