Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion .github/workflows/upstreaming-worker.lock.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 19 additions & 1 deletion .github/workflows/upstreaming-worker.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,18 @@ jobs:
# 1 rejected / 3 infrastructure are recorded outcomes, not job failures;
# 2 (uncertain) fails the job so it is visible, and discovery resolves it.
exit $(( rc == 1 || rc == 3 ? 0 : rc ))
- name: Answer addressed review feedback and resolve inline threads
if: steps.publish.outputs.status == 'published'
continue-on-error: true
working-directory: control
env:
UPSTREAMING_FORK_TOKEN: ${{ steps.fork-token.outputs.token }}
run: |
uv run --no-project --with-requirements upstreaming/requirements.txt \
python -m upstreaming.review_response \
--record ../in/record.json --task ../in/task.json \
--proposal ../in/proposal.json --outcome ../in/outcome.json \
--out ../in/review-response.json
# Everything the controller needs to record the outcome and, for an
# infrastructure failure, to retry this exact publication without a new
# agent run: the task, the verified artifact identity and the outcome.
Expand All @@ -233,6 +245,7 @@ jobs:
in/outcome.json
in/proposal.json
in/dossier.json
in/review-response.json
if-no-files-found: ignore
retention-days: 30
continuation:
Expand Down Expand Up @@ -296,7 +309,12 @@ call: `{"path": "upstreaming-out"}` (the native handler names the artifact
revision task, `reason_ids` must include every task `reason_ids` entry. In
`diagnosis`, include a checklist with one item per review or CI constraint,
the exact change that addresses it, and how you verified that change. Never
claim `no_change` while required review feedback remains unresolved.
claim `no_change` while required review feedback remains unresolved. For
every item in human-relay `reviews`, `comments`, and `conversation_comments`,
add one `feedback_responses` entry with its numeric ID and a short factual
description of the implemented change. Trusted code posts these responses
only after publication and resolves inline review threads. Do not claim a
change was made unless it is present in the delivered series.
`patch_digest` is the sha256 of `patches.mbox`, or null.
- `patches.mbox`: for `append`, `git -C fork format-patch --stdout <expected_head>`;
for `rewrite`, `git -C fork format-patch --stdout <base_sha>`. Omit it
Expand Down
1 change: 1 addition & 0 deletions SESSIONLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@
- Fixed review and CI reconciliation so pending human feedback survives head changes, every repair carries and acknowledges all feedback evidence, `fix_needed` cannot be overwritten before dispatch, and any executed build or test failure returns handoff to automated development repair.
- Replaced the rejected workflow-glob approach with complete dossier path coverage and natural-language review scope extension: human-relay-backed repairs may add exact changed paths, which trusted publication verifies and persists without requiring command syntax.
- Added an exact-path repair compatibility flag for live contributions whose dossiers predate mandatory path coverage; new dossiers are marked coverage-complete and cannot use the legacy allowance.
- Added trusted post-publication review acknowledgements: every addressed feedback item gets a short App-authored response, inline review threads are resolved after replying, and marker/readback checks make retries idempotent.
7 changes: 6 additions & 1 deletion upstreaming/INTEGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,12 @@ paths actually changed by that repair, applies all existing content and workflow
safety checks, and persists the verified paths into contribution scope. Live
contributions whose dossiers predate mandatory path coverage receive the same
exact-path compatibility only during repair; new dossiers are marked complete
and cannot use that legacy allowance.
and cannot use that legacy allowance. A human-relay-backed proposal also carries
one bounded response per review item. After exact-head publication, trusted code
posts each short response as the destination App and resolves its inline review
thread. PR conversation comments receive the response but are not falsely marked
resolved because GitHub does not expose thread resolution for them. Response
markers and thread-state readback make retries idempotent.

Previously merged implementation:

Expand Down
7 changes: 5 additions & 2 deletions upstreaming/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,11 @@ pilot details are kept in lifecycle state and diagnostic artifacts, not here.
line and text in task context. Ordinary natural-language review feedback may
require another file without any command syntax. A human-relay-backed repair
may identify that exact path; trusted publication validates the actual diff
and persists the verified path into contribution scope. Passing means every
required riscv64 job and
and persists the verified path into contribution scope. After the patch is
published, trusted code posts the worker's short factual response to each
addressed review item as the destination App and resolves inline review
threads. Conversation comments are answered but cannot be marked resolved by
GitHub. Passing means every required riscv64 job and
wheel artifact satisfy the project-specific frozen topology contract.
5. **Upstream handoff.** When the exact development head passes its frozen CI
contract and has no debug commits, observation automatically records it as the
Expand Down
14 changes: 14 additions & 0 deletions upstreaming/fork_publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,20 @@ def check_proposal(proposal: dict, record: dict, task: dict, *, allow_no_change:
missing_reasons = set(task.get("reason_ids") or []) - set(proposal.get("reason_ids") or [])
if missing_reasons:
raise PublishRejected(f"repair proposal did not acknowledge required evidence: {sorted(missing_reasons)}")
required_feedback = {
int(item["id"])
for evidence in (task.get("context") or {}).get("reason_evidence") or []
if evidence.get("kind") == "human_relay"
for key in ("reviews", "comments", "conversation_comments")
for item in ((evidence.get("data") or {}).get(key) or [])
if item.get("id")
}
response_ids = [int(item["comment_id"]) for item in proposal.get("feedback_responses") or []]
if len(response_ids) != len(set(response_ids)):
raise PublishRejected("repair proposal contains duplicate feedback responses")
missing_feedback = required_feedback - set(response_ids)
if missing_feedback:
raise PublishRejected(f"repair proposal did not describe responses for feedback: {sorted(missing_feedback)}")
fork = (record.get("fork") or {}).get("name") or ""
if not fork.startswith(FORK_ORG + "/") or task["fork"] != fork:
raise PublishRejected("task fork is not the recorded contribution fork")
Expand Down
166 changes: 166 additions & 0 deletions upstreaming/review_response.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
# SPDX-FileCopyrightText: 2026 The RISE Project
# SPDX-License-Identifier: MIT
"""Answer addressed development-PR feedback and resolve inline threads.

This runs only in the trusted post-publication job with a one-fork App token.
The worker supplies bounded response text but never receives the token.
"""

from __future__ import annotations

import argparse
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Any


class ResponseError(RuntimeError):
pass


class Api:
def __init__(self, token: str, base: str = "https://api.github.com"):
self.token, self.base = token, base.rstrip("/")

def call(self, method: str, path: str, data: dict | None = None) -> Any:
body = json.dumps(data).encode() if data is not None else None
req = urllib.request.Request(self.base + path, data=body, method=method, headers={
"Authorization": f"Bearer {self.token}", "Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28", "Content-Type": "application/json"})
last: Exception | None = None
for attempt in range(5):
try:
with urllib.request.urlopen(req, timeout=60) as response:
raw = response.read()
return json.loads(raw) if raw else None
except urllib.error.HTTPError as exc:
last = exc
if exc.code not in (429, 500, 502, 503, 504):
raise ResponseError(
f"GitHub {method} {path}: HTTP {exc.code}: {exc.read()[-500:].decode(errors='replace')}") from exc
except urllib.error.URLError as exc:
last = exc
if attempt < 4:
time.sleep(2 ** attempt)
raise ResponseError(f"GitHub {method} {path} failed after retries: {last}")

def graphql(self, query: str, variables: dict) -> dict:
result = self.call("POST", "/graphql", {"query": query, "variables": variables})
if result.get("errors"):
raise ResponseError(f"GraphQL failed: {result['errors']}")
return result["data"]


@dataclass(frozen=True)
class Feedback:
id: int
kind: str
reviewer: str | None


def feedback_items(task: dict) -> dict[int, Feedback]:
found: dict[int, Feedback] = {}
for evidence in (task.get("context") or {}).get("reason_evidence") or []:
if evidence.get("kind") != "human_relay":
continue
data = evidence.get("data") or {}
for key, kind in (("reviews", "review"), ("comments", "inline"),
("conversation_comments", "conversation")):
for item in data.get(key) or []:
if item.get("id"):
found[int(item["id"])] = Feedback(int(item["id"]), kind, item.get("reviewer"))
return found


def marker(comment_id: int, head: str) -> str:
return f"<!-- upstreaming-feedback-response:{comment_id}:{head} -->"


def response_body(item: Feedback, summary: str, head: str) -> str:
mention = f"@{item.reviewer} " if item.reviewer else ""
return f"{mention}{summary.strip()}\n\n{marker(item.id, head)}"


def review_threads(api: Api, owner: str, name: str, number: int) -> list[dict]:
query = """
query($owner:String!,$name:String!,$number:Int!) {
repository(owner:$owner,name:$name) {
pullRequest(number:$number) {
reviewThreads(first:100) {
nodes { id isResolved comments(first:100) { nodes { databaseId body } } }
}
}
}
}
"""
data = api.graphql(query, {"owner": owner, "name": name, "number": number})
return data["repository"]["pullRequest"]["reviewThreads"]["nodes"]


def apply(api: Api, *, record: dict, task: dict, proposal: dict, outcome: dict) -> list[dict]:
if outcome.get("status") != "published" or not outcome.get("candidate"):
return []
fork = record.get("fork") or {}
repository = fork.get("name")
number = fork.get("pr_number")
if not repository or not number:
raise ResponseError("development PR identity is missing")
feedback = feedback_items(task)
responses = {int(item["comment_id"]): item["summary"] for item in proposal.get("feedback_responses") or []}
missing = set(feedback) - set(responses)
if missing:
raise ResponseError(f"missing feedback responses: {sorted(missing)}")
owner, name = repository.split("/", 1)
head = outcome["candidate"]
inline_comments = api.call("GET", f"/repos/{repository}/pulls/{number}/comments?per_page=100")
conversation = api.call("GET", f"/repos/{repository}/issues/{number}/comments?per_page=100")
existing_bodies = [item.get("body") or "" for item in inline_comments + conversation]
threads = review_threads(api, owner, name, int(number)) if any(x.kind == "inline" for x in feedback.values()) else []
actions: list[dict] = []
for comment_id in sorted(feedback):
item = feedback[comment_id]
tag = marker(comment_id, head)
body = response_body(item, responses[comment_id], head)
if not any(tag in existing for existing in existing_bodies):
if item.kind == "inline":
api.call("POST", f"/repos/{repository}/pulls/{number}/comments/{comment_id}/replies", {"body": body})
else:
api.call("POST", f"/repos/{repository}/issues/{number}/comments", {"body": body})
existing_bodies.append(body)
actions.append({"comment_id": comment_id, "action": "replied"})
if item.kind == "inline":
thread = next((thread for thread in threads if any(
comment.get("databaseId") == comment_id for comment in thread["comments"]["nodes"])), None)
if thread is None:
raise ResponseError(f"review thread for comment {comment_id} was not found")
if not thread["isResolved"]:
mutation = "mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{id isResolved}}}"
api.graphql(mutation, {"id": thread["id"]})
actions.append({"comment_id": comment_id, "action": "resolved"})
return actions


def main(argv=None) -> int:
parser = argparse.ArgumentParser()
for name in ("record", "task", "proposal", "outcome"):
parser.add_argument(f"--{name}", required=True, type=Path)
parser.add_argument("--out", required=True, type=Path)
args = parser.parse_args(argv)
values = {name: json.loads(getattr(args, name).read_text()) for name in ("record", "task", "proposal", "outcome")}
token = os.environ.get("UPSTREAMING_FORK_TOKEN")
if not token:
raise ResponseError("UPSTREAMING_FORK_TOKEN is missing")
actions = apply(Api(token), **values)
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_text(json.dumps({"actions": actions}, indent=2) + "\n")
return 0


if __name__ == "__main__":
raise SystemExit(main())
Loading