M3.3: the trust dial (the agent merges approved PRs)
CI / checks (push) Skipped
CI / checks (pull_request) Successful in 2m29s
CI / e2e (pull_request) Successful in 11m23s

A project's trust.merge is operator (the default) or approved (L3, D5,
#65). Set to approved, the harness, never the model, merges a PR in the
PR watch once an approving review from a gitea.operators account is on
its current commit, its checks pass (none at all counts; pending
waits) and it's mergeable; the item then goes on as after any merge.
Each reason to hold off (failed checks, conflicts, a refused merge) is
said once per commit.

Gitea enforces it: protection requires approvals from an operators-only
whitelist and dismisses stale ones. At start, for each approved
project, the agent checks by behaviour that its own unapproved merge is
refused, with a throwaway branch and PR made through the API (never the
workspace); if it isn't refused, the operator merges until a restart.

- gitea: approvals, combined check status, a PR's head commit and
  mergeability, API-made branches and their deletion.
- Test and bring-up repositories get the protection.
- Tests: the decision (unit), the hard wall on a real Gitea
  (test_trust_live), an e2e test where the operator only approves, and
  a walk property, merges_only_approved, checked against a mutant that
  ignores which commit was approved.

Closes #65

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PPQ14L3LikyefCMFBqEbKE
This commit is contained in:
dongarandClaude Opus 5.5 committed 2026-10-08 13:48:16 +00:00
1 parent 21cbf1682c
commit ab469b60bb
17 files changed
+733 -11

No files matched your search

+10
View File
@@ -67,7 +67,12 @@ PROJECT_OPTIONAL = (
"labels",
"secrets",
"egress",
"trust.merge",
)
# The trust dial (L3, D5): who merges a project's PRs. "approved": the
# harness merges once an operator approved the PR's current commit and its
# checks pass, behind protection that requires that approval.
MERGE_MODES = ("operator", "approved")
# Who may see a project secret (D7, D8): the model's commands get it as an
# environment variable, redacted from what comes back; harness-only ones are
# never in a command the model chose.
@@ -315,6 +320,9 @@ def _parse_project(
errors.append(f"{where}: set a push token or a push key, not both")
labels = _strings(values.get("labels", []), f"{where}.labels", errors)
egress = _strings(values.get("egress", []), f"{where}.egress", errors)
merge = str(values.get("trust.merge") or "operator")
if merge not in MERGE_MODES:
errors.append(f"{where}.trust.merge: must be one of {', '.join(MERGE_MODES)}")
secrets = _parse_secrets(entry.get("secrets"), where, env, errors)
return Project(
name=name,
@@ -333,6 +341,7 @@ def _parse_project(
labels=labels,
secrets=secrets,
egress=egress,
merge=merge,
)
@@ -454,6 +463,7 @@ class Project:
labels: tuple[str, ...] = () # added to every issue's own (D1)
secrets: Mapping[str, Secret] = field(default_factory=dict)
egress: tuple[str, ...] = () # beyond the default; recorded, not yet enforced
merge: str = "operator" # the trust dial (L3): who merges its PRs
def command_secrets(self) -> dict[str, str]:
"""The secrets the model's commands may see, by name."""
+56
View File
@@ -10,6 +10,7 @@ idempotent across a crash: boot reconciliation (L8) asks Gitea whether the
effect already happened rather than repeating it.
"""
import base64
from dataclasses import dataclass
from typing import Any
@@ -33,6 +34,18 @@ class PullRequest:
head: str
url: str
merged: bool = False
head_sha: str = "" # the commit the PR is at now
mergeable: bool | None = None # None: Gitea didn't say
@dataclass(frozen=True)
class Approval:
"""An approving review, and the commit it approved (L3: approvals bind
to exactly what was approved)."""
author: str
commit: str
stale: bool = False # Gitea's mark: commits were pushed since
@dataclass(frozen=True)
@@ -286,6 +299,47 @@ class GiteaClient:
break
return when
def approvals(self, repo: str, index: int) -> list[Approval]:
"""The PR's approving reviews that still stand: not dismissed."""
return [
Approval(
author=(review.get("user") or {}).get("login", ""),
commit=str(review.get("commit_id") or ""),
stale=bool(review.get("stale")),
)
for review in (
self._request("GET", f"/repos/{repo}/pulls/{index}/reviews") or []
)
if review.get("state") == "APPROVED" and not review.get("dismissed")
]
def checks(self, repo: str, sha: str) -> str:
"""A commit's combined check status: success, pending, failure or
error; "none" when no check reported on it at all."""
data = self._request("GET", f"/repos/{repo}/commits/{sha}/status") or {}
if not data.get("total_count") and not data.get("statuses"):
return "none"
return str(data.get("state") or "pending")
def branch_with_file(
self, repo: str, *, base: str, branch: str, path: str, text: str, message: str
) -> None:
"""A new branch off ``base`` with one file added, made through the
API: no clone, no workspace."""
self._request(
"POST",
f"/repos/{repo}/contents/{path}",
json={
"content": base64.b64encode(text.encode()).decode(),
"message": message,
"branch": base,
"new_branch": branch,
},
)
def delete_branch(self, repo: str, name: str) -> None:
self._request("DELETE", f"/repos/{repo}/branches/{name}")
def repository(self, repo: str) -> dict[str, Any]:
"""The repository as this account sees it, permissions included."""
return dict(self._request("GET", f"/repos/{repo}"))
@@ -320,6 +374,8 @@ def _pull_request(data: dict[str, Any]) -> PullRequest:
head=(data.get("head") or {}).get("ref", ""),
url=data.get("html_url", ""),
merged=bool(data.get("merged")),
head_sha=(data.get("head") or {}).get("sha", ""),
mergeable=data.get("mergeable"),
)
+138 -1
View File
@@ -42,7 +42,7 @@ from nisse_dev.config import GENERAL
from nisse_dev.delegation import DELEGATION_INTENT, Delegation
from nisse_dev.expert import BudgetExhausted, ExpertDesk
from nisse_dev.git import GitError
from nisse_dev.gitea import GiteaClient, GiteaError, Issue
from nisse_dev.gitea import GiteaClient, GiteaError, Issue, PullRequest
from nisse_dev.llm import LLMError, RoleMap
from nisse_dev.loop.actions import classify
from nisse_dev.loop.classifier import IN_SCOPE, ActionClassifier, Scope
@@ -227,6 +227,8 @@ class Project:
workspace: Workspace | None = None
milestones: Milestones | None = None
labels: tuple[str, ...] = ()
base: str = "main"
merge: str = "operator" # the trust dial (L3): who merges its PRs
def _restatement_problem(args: dict[str, object]) -> str | None:
@@ -297,6 +299,9 @@ class LoopAgent:
self._helpers = helpers
# L4: judges what the fast path doesn't know; without one, it runs.
self._classifier = classifier
# The trust dial (M3.3): projects whose protection was checked, and
# whether the harness may merge their approved PRs.
self._merging: dict[str, bool] = {}
# Verdicts by (item, agreed revision, action): judged once (M3.2).
self._judged: dict[tuple[str, int, str], tuple[Verdict, tuple[str, str]]] = {}
self._clock = clock
@@ -385,6 +390,9 @@ class LoopAgent:
"""Resume waiting points as they were, and never resume interrupted
work blindly: an item cut off mid-run waits on the operator."""
self._store.set_active(None, cause="boot")
for project in self._projects.values():
if project.merge == "approved":
self._may_merge(project) # D4: verified at start, not assumed
self._reconcile_publishing()
self._reconcile_filing()
self._reconcile_delegations()
@@ -408,6 +416,126 @@ class LoopAgent:
thread=loop.thread,
)
# -- the trust dial (L3, D5; M3.3) --------------------------------------------
def _merge_if_approved(
self, item: WorkItem, loop: Loop, repo: str, pr: PullRequest
) -> tuple[PullRequest, Loop]:
"""Merge the PR when an operator approved its current commit and its
checks pass. Gitea enforces the approval (protection); this only
decides when to ask it. Each reason to hold off is said once."""
try:
approvals = self._gitea.approvals(repo, pr.number)
checks = self._gitea.checks(repo, pr.head_sha)
except GiteaError as exc:
self._oplog.emit("loop.watch_unavailable", cause=str(exc))
return pr, loop
by = [
a.author
for a in approvals
if a.author in self._gitea_operators
and a.commit == pr.head_sha
and not a.stale
]
if not by:
return pr, loop
held = ""
if checks in ("failure", "error"):
held = f"its checks failed ({checks}), so I'll leave it unmerged"
elif checks not in ("success", "none"):
return pr, loop # pending: wait for them
elif pr.mergeable is False:
held = "it has conflicts with the base branch, so I can't merge it"
elif not self._may_merge(self._at(item)):
return pr, loop # protection unverified: said when checked
if not held:
try:
self._gitea.merge_pull_request(repo, pr.number)
except GiteaError as exc:
held = (
f"Gitea refused my merge ({exc}); I'll try again, or you "
"can merge it"
)
else:
self._fact(item, f"merged PR #{pr.number} after {by[0]}'s approval")
self._transport.post(
f"Merged PR #{pr.number} after {by[0]}'s approval.",
thread=loop.thread,
)
return replace(pr, merged=True, state="closed"), loop
mark = f"{pr.head_sha}:{held}"
if loop.merge_held != mark:
self._transport.post(
f"{by[0]} approved PR #{pr.number}, but {held}.", thread=loop.thread
)
loop = replace(loop, merge_held=mark)
return pr, loop
def _may_merge(self, project: Project) -> bool:
"""D4: protection verified, not assumed. Once per start, a check
that Gitea refuses the agent's merge without an approval; if it
doesn't, the operator merges until it's fixed."""
if project.merge != "approved":
return False
if project.name not in self._merging:
problem = self._merge_protection_problem(project)
self._merging[project.name] = problem is None
self._oplog.emit(
"loop.merge_protection",
cause="start" if problem is None else problem,
project=project.name,
verified=problem is None,
)
if problem is not None:
self._transport.post(
f"{project.repo} is set to have me merge approved PRs, but "
f"{problem}. I'll leave merging to you until that's fixed "
"and I've restarted."
)
return self._merging[project.name]
def _merge_protection_problem(self, project: Project) -> str | None:
"""A throwaway branch and PR, made through the API (never the
workspace, which may hold an item's work): merging it must be
refused. Closed and deleted either way."""
branch = f"nisse-check-{uuid.uuid4().hex[:6]}"
try:
self._gitea.branch_with_file(
project.repo,
base=project.base,
branch=branch,
path=".nisse-merge-check",
text="Checks that merging needs an approval; never merged.\n",
message="nisse-dev: merge check",
)
except GiteaError as exc:
return f"I couldn't make a branch to check merging: {exc}"
pr = None
try:
pr = self._gitea.open_pull_request(
project.repo,
head=branch,
base=project.base,
title="nisse-dev merge check (never merged)",
body="Checks that merging needs an approval; closed straight away.",
)
try:
self._gitea.merge_pull_request(project.repo, pr.number)
except GiteaError:
return None # refused, as it should be
return (
f"I could merge my own PR #{pr.number} without an approval "
f"(it added .nisse-merge-check to {project.base})"
)
except GiteaError as exc:
return f"I couldn't open a PR to check merging: {exc}"
finally:
if pr is not None:
with contextlib.suppress(GiteaError):
self._gitea.close_pull_request(project.repo, pr.number)
with contextlib.suppress(GiteaError):
self._gitea.delete_branch(project.repo, branch)
def _reconcile_delegations(self) -> None:
"""L8, L9: a delegation cut off by a crash is discarded, its branch
deleted and the milestone's left as it was. The item, cut off mid-
@@ -613,6 +741,15 @@ class LoopAgent:
)
new = True
position = item.position
if (
not pr.merged
and pr.state == "open"
and not new
and item.position == WAITING
and loop.wait == MERGE
and self._at(item).merge == "approved"
):
pr, loop = self._merge_if_approved(item, loop, repo, pr)
if pr.merged:
self._fact(item, f"PR #{loop.pr} merged")
loop, position = replace(loop, pr=0, pr_url="", branch=""), READY
+2
View File
@@ -230,6 +230,8 @@ def project_runtime(
name=entry.name,
repo=entry.repo,
labels=entry.labels,
base=entry.base_branch,
merge=entry.merge,
workspace=Workspace(
host,
entry.workspace,
+3
View File
@@ -74,6 +74,9 @@ class Loop:
# exactly that action, by its key).
pending_action: str = ""
allowed: str = ""
# The trust dial (M3.3): why an approved PR was last left unmerged, so
# it's said once per commit and reason.
merge_held: str = ""
def to_data(self) -> dict[str, Any]:
return asdict(self)