From 9f30b882490d4ec4b56aae1df5879b54fb767115 Mon Sep 17 00:00:00 2001 From: Ludovic Henry Date: Fri, 20 Nov 2026 22:33:55 +0100 Subject: [PATCH] upstreaming: bind complete dossiers to workers --- .github/workflows/upstreaming-worker.lock.yml | 5 +- .github/workflows/upstreaming-worker.md | 35 +++++++- SESSIONLOG.md | 3 + upstreaming/INTEGRATION.md | 13 ++- upstreaming/__main__.py | 87 +++++++++++++++++-- upstreaming/tests/test_pipeline.py | 57 +++++++++++- upstreaming/tests/test_workflow_contracts.py | 15 ++++ 7 files changed, 200 insertions(+), 15 deletions(-) diff --git a/.github/workflows/upstreaming-worker.lock.yml b/.github/workflows/upstreaming-worker.lock.yml index a6575825b4ef..d2181d6f6420 100644 --- a/.github/workflows/upstreaming-worker.lock.yml +++ b/.github/workflows/upstreaming-worker.lock.yml @@ -1,4 +1,4 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"f679f53df8bef4798d2652565464f0a94991cccf0fc695772d9dec94dc6c615d","body_hash":"a5485f6375cccddfa6c5877e1ef63aa857d2aa133a23628102481af74f320fca","compiler_version":"v1.2.2","strict":true,"agent_id":"pi","agent_model":"anthropic/claude-opus-5-5","engine_versions":{"pi":"1.5.0"}} +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"3febd174a0dc2e2b67d84be1bdf017c6cfb884f644523018055656fa36658eed","body_hash":"9f3a022b9aca9ca165071ce3a3a5b6dbe878346f5d813fbb0394e0e9da73bf61","compiler_version":"v1.2.2","strict":true,"agent_id":"pi","agent_model":"anthropic/claude-opus-5-5","engine_versions":{"pi":"1.5.0"}} # gh-aw-manifest: {"version":1,"secrets":["ANTHROPIC_API_KEY","COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN","RISEPROJECT_APP_PRIVATE_KEY","RISEPROJECT_UPSTREAMING_APP_PRIVATE_KEY"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/create-github-app-token","sha":"64ab729a6294000f5aa4a4bc0b73d1f32bc45510","version":"v3.3.0"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"astral-sh/setup-uv","sha":"20cfd1bf945f4377ade1205e4dbc17946fc9a30d","version":"v10.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"53d0749e19424a918acd82b4d140264ce48f2f14","version":"v1.2.2"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.11","digest":"sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.29.11@sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11","digest":"sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11@sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.11","digest":"sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.29.11@sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.6","digest":"sha256:342cd624e1f179d91be2de7a146fc4f387092e62e6c8a47506d7932e113d2311","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.6@sha256:342cd624e1f179d91be2de7a146fc4f387092e62e6c8a47506d7932e113d2311"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"image":"ghcr.io/github/github-mcp-server:v2.1.0","digest":"sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a","pinned_image":"ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a"}],"mcp_servers":[{"name":"github","tools":["get_commit","get_file_contents","get_latest_release","get_me","get_pull_request","get_pull_request_comments","get_pull_request_diff","get_pull_request_files","get_pull_request_review_comments","get_pull_request_reviews","get_pull_request_status","get_release_by_tag","get_tag","issue_read","list_branches","list_commits","list_issue_types","list_issues","list_pull_requests","list_releases","list_starred_repositories","list_tags","pull_request_read","search_code","search_issues","search_pull_requests","search_repositories"]},{"name":"github-authenticated","tools":["actions_list","get_commit","get_file_contents","get_pull_request","get_pull_request_comments","get_pull_request_diff","get_pull_request_files","get_pull_request_review_comments","get_pull_request_reviews","get_pull_request_status","issue_read","list_commits","list_issues","list_pull_requests","pull_request_read","search_code","search_issues","search_pull_requests"]},{"name":"safeoutputs","tools":["noop","report_incomplete","report_missing_data","report_missing_tool","upload_artifact"]},{"name":"work-queue","tools":["work_queue_claim_finish","work_queue_dispatch_next","work_queue_explain","work_queue_read","work_queue_submit"]}],"threat_detection":{"mode":"enabled"},"admission":false,"work_queue":{"worker":true,"logical_contract":"056b332b022951fc3d1ae91c58cb202ea509dcef2a5d2c296a6cc0a9f8abc00a"},"agent_metadata":{}} # This file was automatically generated by gh-aw (v1.2.2). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md # @@ -738,8 +738,9 @@ jobs: run: "set -euo pipefail\ntoken=\"upstreaming-stop-$(openssl rand -hex 32)\"\necho \"token=$token\" >> \"$GITHUB_OUTPUT\"\nprintf '::stop-commands::%s\\n' \"$token\"\n" - env: GH_AW_ACTIONS_DIR: ${{ runner.temp }}/gh-aw/actions + GH_TOKEN: ${{ github.token }} name: Check out the contribution fork at the expected head (read-only) - run: "set -euo pipefail\nnode <<'JS'\nconst fs = require(\"node:fs\");\nconst path = require(\"node:path\");\nconst { normalizeAssignment } = require(path.join(process.env.GH_AW_ACTIONS_DIR, \"work_queue_claim_scope.cjs\"));\nconst event = JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, \"utf8\"));\nconst a = normalizeAssignment(JSON.parse(event.inputs.work_queue_assignment));\nif (a.claims.length !== 1) throw new Error(\"upstreaming worker takes exactly one Claim\");\nconst w = a.claims[0].work;\nfs.mkdirSync(\"/tmp/gh-aw/agent\", { recursive: true });\nfs.writeFileSync(\"/tmp/gh-aw/agent/task.json\", JSON.stringify(w, null, 2));\nJS\ntask=/tmp/gh-aw/agent/task.json\nfork=$(jq -r '.fork // empty' \"$task\")\nupstream=$(jq -r '.upstream' \"$task\")\nhead=$(jq -r '.expected_head // empty' \"$task\")\nbase=$(jq -r '.base_sha // empty' \"$task\")\n[[ \"$upstream\" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || { echo \"bad upstream\"; exit 1; }\nmkdir -p \"$GITHUB_WORKSPACE/fork\"\ncd \"$GITHUB_WORKSPACE/fork\"\ngit init -q\ngit remote add upstream \"https://github.com/$upstream.git\"\nif [ -n \"$fork\" ]; then\n [[ \"$fork\" =~ ^riseproject-upstreaming/[A-Za-z0-9_.-]+$ ]] || { echo \"bad fork\"; exit 1; }\n git remote add origin \"https://github.com/$fork.git\"\nfi\nif [ -n \"$base\" ]; then git fetch -q --no-tags --depth=200 upstream \"$base\"; fi\nif [ -n \"$head\" ]; then\n git fetch -q --no-tags --depth=200 origin \"$head\"\n git checkout -q -B riscv64 \"$head\"\nelif [ -n \"$base\" ]; then\n git checkout -q -B riscv64 \"$base\"\nelse\n git fetch -q --no-tags --depth=200 upstream HEAD\n git checkout -q -B riscv64 FETCH_HEAD\nfi\ngit config user.name \"riseproject-upstreaming[bot]\"\ngit config user.email \"359135081+riseproject-upstreaming[bot]@users.noreply.github.com\"\necho \"checked out $(git rev-parse HEAD) into ./fork\"" + run: "set -euo pipefail\nnode <<'JS'\nconst fs = require(\"node:fs\");\nconst path = require(\"node:path\");\nconst { normalizeAssignment } = require(path.join(process.env.GH_AW_ACTIONS_DIR, \"work_queue_claim_scope.cjs\"));\nconst event = JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, \"utf8\"));\nconst a = normalizeAssignment(JSON.parse(event.inputs.work_queue_assignment));\nif (a.claims.length !== 1) throw new Error(\"upstreaming worker takes exactly one Claim\");\nconst w = a.claims[0].work;\nfs.mkdirSync(\"/tmp/gh-aw/agent\", { recursive: true });\nfs.writeFileSync(\"/tmp/gh-aw/agent/task.json\", JSON.stringify(w, null, 2));\nJS\ntask=/tmp/gh-aw/agent/task.json\ndossier_count=$(jq '[.context.reason_evidence[]? | select(.kind == \"dossier\" and .reference)] | length' \"$task\")\n[ \"$dossier_count\" -le 1 ] || { echo \"multiple dossier references\"; exit 1; }\nif [ \"$dossier_count\" -eq 1 ]; then\n repository=$(jq -r '.context.reason_evidence[] | select(.kind == \"dossier\").reference.repository' \"$task\")\n ref=$(jq -r '.context.reason_evidence[] | select(.kind == \"dossier\").reference.ref' \"$task\")\n path=$(jq -r '.context.reason_evidence[] | select(.kind == \"dossier\").reference.path' \"$task\")\n expected=$(jq -r '.context.reason_evidence[] | select(.kind == \"dossier\").reference.sha256' \"$task\")\n evidence_id=$(jq -r '.context.reason_evidence[] | select(.kind == \"dossier\").evidence_id' \"$task\")\n [ \"$repository\" = \"riseproject-dev/python-wheels\" ] || { echo \"bad dossier repository\"; exit 1; }\n [[ \"$ref\" =~ ^[0-9a-f]{40}$ ]] || { echo \"bad dossier ref\"; exit 1; }\n [[ \"$path\" =~ ^upstreaming-state/evidence/[A-Za-z0-9._-]+\\.json$ ]] || { echo \"bad dossier path\"; exit 1; }\n [[ \"$expected\" =~ ^[0-9a-f]{64}$ ]] || { echo \"bad dossier digest\"; exit 1; }\n gh api -H 'Accept: application/vnd.github.raw+json' \\\n \"/repos/$repository/contents/$path?ref=$ref\" > /tmp/gh-aw/agent/dossier.json\n actual=$(sha256sum /tmp/gh-aw/agent/dossier.json | cut -d' ' -f1)\n [ \"$actual\" = \"$expected\" ] || { echo \"dossier digest mismatch\"; exit 1; }\n jq -e --arg id \"$evidence_id\" '.kind == \"dossier\" and .evidence_id == $id' \\\n /tmp/gh-aw/agent/dossier.json >/dev/null\n echo \"verified complete dossier $evidence_id at /tmp/gh-aw/agent/dossier.json\"\nfi\nfork=$(jq -r '.fork // empty' \"$task\")\nupstream=$(jq -r '.upstream' \"$task\")\nhead=$(jq -r '.expected_head // empty' \"$task\")\nbase=$(jq -r '.base_sha // empty' \"$task\")\n[[ \"$upstream\" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || { echo \"bad upstream\"; exit 1; }\nmkdir -p \"$GITHUB_WORKSPACE/fork\"\ncd \"$GITHUB_WORKSPACE/fork\"\ngit init -q\ngit remote add upstream \"https://github.com/$upstream.git\"\nif [ -n \"$fork\" ]; then\n [[ \"$fork\" =~ ^riseproject-upstreaming/[A-Za-z0-9_.-]+$ ]] || { echo \"bad fork\"; exit 1; }\n git remote add origin \"https://github.com/$fork.git\"\nfi\nif [ -n \"$base\" ]; then git fetch -q --no-tags --depth=200 upstream \"$base\"; fi\nif [ -n \"$head\" ]; then\n git fetch -q --no-tags --depth=200 origin \"$head\"\n git checkout -q -B riscv64 \"$head\"\nelif [ -n \"$base\" ]; then\n git checkout -q -B riscv64 \"$base\"\nelse\n git fetch -q --no-tags --depth=200 upstream HEAD\n git checkout -q -B riscv64 FETCH_HEAD\nfi\ngit config user.name \"riseproject-upstreaming[bot]\"\ngit config user.email \"359135081+riseproject-upstreaming[bot]@users.noreply.github.com\"\necho \"checked out $(git rev-parse HEAD) into ./fork\"" - name: Download container images run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.29.11@sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11@sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c ghcr.io/github/gh-aw-firewall/squid:0.29.11@sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847 ghcr.io/github/gh-aw-mcpg:v0.5.6@sha256:342cd624e1f179d91be2de7a146fc4f387092e62e6c8a47506d7932e113d2311 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a diff --git a/.github/workflows/upstreaming-worker.md b/.github/workflows/upstreaming-worker.md index d4893414e887..ea76ed51d7dd 100644 --- a/.github/workflows/upstreaming-worker.md +++ b/.github/workflows/upstreaming-worker.md @@ -78,6 +78,7 @@ pre-agent-steps: - name: Check out the contribution fork at the expected head (read-only) env: GH_AW_ACTIONS_DIR: ${{ runner.temp }}/gh-aw/actions + GH_TOKEN: ${{ github.token }} run: | set -euo pipefail node <<'JS' @@ -92,6 +93,26 @@ pre-agent-steps: fs.writeFileSync("/tmp/gh-aw/agent/task.json", JSON.stringify(w, null, 2)); JS task=/tmp/gh-aw/agent/task.json + dossier_count=$(jq '[.context.reason_evidence[]? | select(.kind == "dossier" and .reference)] | length' "$task") + [ "$dossier_count" -le 1 ] || { echo "multiple dossier references"; exit 1; } + if [ "$dossier_count" -eq 1 ]; then + repository=$(jq -r '.context.reason_evidence[] | select(.kind == "dossier").reference.repository' "$task") + ref=$(jq -r '.context.reason_evidence[] | select(.kind == "dossier").reference.ref' "$task") + path=$(jq -r '.context.reason_evidence[] | select(.kind == "dossier").reference.path' "$task") + expected=$(jq -r '.context.reason_evidence[] | select(.kind == "dossier").reference.sha256' "$task") + evidence_id=$(jq -r '.context.reason_evidence[] | select(.kind == "dossier").evidence_id' "$task") + [ "$repository" = "riseproject-dev/python-wheels" ] || { echo "bad dossier repository"; exit 1; } + [[ "$ref" =~ ^[0-9a-f]{40}$ ]] || { echo "bad dossier ref"; exit 1; } + [[ "$path" =~ ^upstreaming-state/evidence/[A-Za-z0-9._-]+\.json$ ]] || { echo "bad dossier path"; exit 1; } + [[ "$expected" =~ ^[0-9a-f]{64}$ ]] || { echo "bad dossier digest"; exit 1; } + gh api -H 'Accept: application/vnd.github.raw+json' \ + "/repos/$repository/contents/$path?ref=$ref" > /tmp/gh-aw/agent/dossier.json + actual=$(sha256sum /tmp/gh-aw/agent/dossier.json | cut -d' ' -f1) + [ "$actual" = "$expected" ] || { echo "dossier digest mismatch"; exit 1; } + jq -e --arg id "$evidence_id" '.kind == "dossier" and .evidence_id == $id' \ + /tmp/gh-aw/agent/dossier.json >/dev/null + echo "verified complete dossier $evidence_id at /tmp/gh-aw/agent/dossier.json" + fi fork=$(jq -r '.fork // empty' "$task") upstream=$(jq -r '.upstream' "$task") head=$(jq -r '.expected_head // empty' "$task") @@ -298,10 +319,16 @@ pipeline. The trusted pre-agent step wrote the immutable task to branch in `./fork`. The task's `plan` field says what to do; `reason_ids` and `context` say why. For repair and revision tasks, read every entry in `context.reason_evidence` before researching -or editing. A `dossier` evidence entry includes the latest verified dossier in -`data`; treat its path coverage, dependency findings, architecture precedent and -risks as the authoritative current investigation, while still validating them -against current repository history and CI. Treat every concrete review comment, +or editing. A `dossier` evidence entry identifies the latest verified dossier. +Its complete authoritative record is committed at the immutable `reference`; +`data` is only its queue-safe index. The trusted pre-agent step fetches that +exact-ref file, verifies its SHA-256 and evidence identity, and writes it to +`/tmp/gh-aw/agent/dossier.json`. You MUST read the latest verified dossier from +that complete local file when it exists. The reference also contains its +immutable raw GitHub URL for provenance. Treat the latest verified dossier's +path coverage, dependency findings, architecture precedent and risks as the +authoritative current investigation, while still validating them against +current repository history and CI. Treat every concrete review comment, PR conversation comment and rejected-change description in every reason evidence record as a required repair constraint, then verify each one against repository history. A repair is diff --git a/SESSIONLOG.md b/SESSIONLOG.md index 57ddcbef4155..84e00c549a30 100644 --- a/SESSIONLOG.md +++ b/SESSIONLOG.md @@ -37,3 +37,6 @@ - Corrected paused-feedback ledger wording so actionable feedback remains visibly pending without claiming repair Work was requested while pause prevents allocation. - Changed fast command receipt reactions from `+1` to `eyes` and added an idempotent post-state-commit `+1` only for commands accepted and durably executed by serialized reconciliation. - Made pause the primary visible status in lifecycle ledgers and the public status page while retaining the underlying activity as pending context; paused ledgers no longer suggest another pause command. +- Diagnosed dispatcher failures as queue payload-limit violations from embedding complete dossier research in Work, then added a bounded projection preserving IDs, exact paths, response contracts, path coverage, dependency findings and risks plus a pre-staging byte-budget guard. +- Kept the complete dossier as committed evidence and added an immutable exact-ref path/raw URL/SHA-256 reference; trusted worker setup now fetches and verifies it into `/tmp/gh-aw/agent/dossier.json` for mandatory worker reading while the queue carries only a bounded projection. +- Restored worker-facing wording that names the complete authoritative record as “the latest verified dossier,” while describing bounded `data` only as its queue-safe index. diff --git a/upstreaming/INTEGRATION.md b/upstreaming/INTEGRATION.md index c3431a4adb10..a6bb72647a04 100644 --- a/upstreaming/INTEGRATION.md +++ b/upstreaming/INTEGRATION.md @@ -204,7 +204,18 @@ records processed review/comment IDs, bumps the revision and automatically requests `development_repair`. Pending feedback evidence survives branch-head changes and is attached to every repair until exact-head CI is green. A repair proposal must acknowledge every required evidence record. Observation does not -replace `fix_needed` before the controller can allocate that repair. +replace `fix_needed` before the controller can allocate that repair. Dispatcher +Work carries a deterministic bounded projection of those durable records rather +than embedding the complete dossier research corpus: evidence IDs, response IDs, +exact paths, proposal/path coverage, architecture/build/dependency findings and +risks are retained, while repeated prose and the full source-by-source research +appendix remain in the complete committed dossier evidence file. The Work also +carries an immutable control-repository ref, exact evidence path, raw GitHub URL +and SHA-256 for that file. Before the model starts, trusted worker setup fetches +it with the read-only job token, verifies the digest and evidence identity, and +places the complete dossier at `/tmp/gh-aw/agent/dossier.json`; the worker must +read it. Trusted preparation rejects a payload before queue staging if it +exceeds the queue's safe byte budget. Explanation-only comments are classified separately as `human_inquiry` when an explicit no-change instruction is present, or when they clearly request an explanation without a repair instruction. They are marked processed and retained diff --git a/upstreaming/__main__.py b/upstreaming/__main__.py index d48f391cacd6..47dff7859b66 100644 --- a/upstreaming/__main__.py +++ b/upstreaming/__main__.py @@ -18,17 +18,19 @@ from __future__ import annotations import argparse +import hashlib import json +import re +import subprocess import sys from datetime import datetime, timezone from pathlib import Path from . import capacity, collect, commands, controller, state, triggers -from .common import STATE_ROOT, load_policy +from .common import CONTROL_REPO, STATE_ROOT, load_policy def _root() -> Path: - import subprocess return Path(subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=True).stdout.strip()) @@ -172,6 +174,71 @@ def _pressure(policy: dict) -> capacity.Pressure: return capacity.Pressure(ok=False, reason=f"usage unavailable: {e}") +def _short(value, limit: int): + if not isinstance(value, str): + return value + return value if len(value) <= limit else value[:limit - 1] + "…" + + +def _feedback_data(data: dict) -> dict: + result = {} + for key in ("reviews", "comments", "conversation_comments"): + items = [] + for original in (data.get(key) or []): + item = {name: original.get(name) for name in + ("id", "url", "reviewer", "commit_id", "review_id", "path", "line", "created_at") + if original.get(name) is not None} + item["body"] = _short(original.get("body") or "", 1200) + items.append(item) + result[key] = items + for key in ("review_ids", "comment_ids", "conversation_comment_ids"): + result[key] = list(data.get(key) or []) + return result + + +def _dossier_data(data: dict) -> dict: + proposal = data.get("proposal") or {} + compact = {key: proposal.get(key) for key in + ("decision", "admission_class", "allowed_paths", "architecture_precedent", + "build_backend", "target_matrix", "fork_guards", "risks") + if proposal.get(key) is not None} + for key in ("architecture_precedent", "build_backend", "target_matrix", "fork_guards", "risks"): + if key in compact: + compact[key] = _short(compact[key], 800) + compact["path_coverage"] = [ + {"area": item.get("area"), "paths": item.get("paths") or [], + "assessment": _short(item.get("assessment") or "", 600)} + for item in (proposal.get("path_coverage") or []) + ] + dependency = data.get("dependency_graph") or {} + return {"proposal": compact, + "dependency_graph": {"assessment": _short(dependency.get("assessment") or "", 1600)}} + + +def _dossier_reference(root: Path, evidence_id: str, control_ref: str) -> dict: + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/-]{0,127}", evidence_id) or "/" in evidence_id: + raise ValueError("invalid dossier evidence ID") + if not re.fullmatch(r"[0-9a-f]{40}", control_ref): + raise ValueError("invalid immutable control ref") + relative = Path(STATE_ROOT) / "evidence" / f"{evidence_id}.json" + path = root / relative + raw = path.read_bytes() + return {"repository": CONTROL_REPO, "ref": control_ref, "path": relative.as_posix(), + "sha256": hashlib.sha256(raw).hexdigest(), + "url": f"https://raw.githubusercontent.com/{CONTROL_REPO}/{control_ref}/{relative.as_posix()}"} + + +def _reason_item(evidence: dict) -> dict: + item = {key: evidence.get(key) for key in ("evidence_id", "kind")} + item["summary"] = _short(evidence.get("summary") or "", 1600) + item["limitations"] = [_short(value, 500) for value in (evidence.get("limitations") or [])[:4]] + if evidence.get("kind") == "human_relay": + item["data"] = _feedback_data(evidence.get("data") or {}) + elif evidence.get("kind") == "dossier": + item["data"] = _dossier_data(evidence.get("data") or {}) + return item + + def cmd_plan(args) -> int: """Dispatcher preparation: turn the tasks the controller already requested (``active_work`` in committed state) into a gh-aw staged plan. Selection @@ -181,7 +248,10 @@ def cmd_plan(args) -> int: means nothing to dispatch.""" from . import work policy = load_policy() - _store, snap = _load(Path(args.root or _root()), policy) + root = Path(args.root or _root()) + control_ref = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, + text=True, check=True).stdout.strip() + _store, snap = _load(root, policy) contracts = {e["evidence_id"]: e for e in snap.evidence.values() if e.get("kind") == "target_contract"} nodes, selected = [], [] for rec in sorted(snap.contributions.values(), key=lambda c: (c["active_work"] or {}).get("requested_at", "") @@ -200,16 +270,19 @@ def cmd_plan(args) -> int: for evidence_id in req.get("reason_ids") or []: evidence = snap.evidence.get(evidence_id) if evidence: - item = {key: evidence.get(key) for key in - ("evidence_id", "kind", "summary", "limitations")} - if evidence.get("kind") in ("human_relay", "dossier"): - item["data"] = evidence.get("data") + item = _reason_item(evidence) + if evidence.get("kind") == "dossier": + item["reference"] = _dossier_reference(root, evidence["evidence_id"], control_ref) reason_evidence.append(item) nodes.append(work.node(req, rec, control_repo_id=args.control_repo_id, allowed_paths=rec.get("scope_paths") or ctr.get("allowed_paths") or [".github/workflows/*"], context={"requested_at": rec["active_work"]["requested_at"], "reason_evidence": reason_evidence})) + payload_bytes = len(json.dumps(nodes[-1]["payload"], separators=(",", ":"), + ensure_ascii=False).encode()) + if payload_bytes > 15_500: + raise ValueError(f"requested task payload exceeds safe queue budget: {payload_bytes} bytes") selected.append({"contribution": rec["contribution_id"], "task": req["task"], "worker_profile": nodes[-1]["worker_profile"]}) print(json.dumps({"selected": selected}, indent=2)) diff --git a/upstreaming/tests/test_pipeline.py b/upstreaming/tests/test_pipeline.py index 13d1137b13f3..49aa32db815f 100644 --- a/upstreaming/tests/test_pipeline.py +++ b/upstreaming/tests/test_pipeline.py @@ -16,7 +16,8 @@ from datetime import datetime, timezone from pathlib import Path -from upstreaming import artifact, capacity, controller, fork_publish, publisher, queue_result, reconcile, schemas, work +from upstreaming import (__main__ as cli, artifact, capacity, controller, fork_publish, + publisher, queue_result, reconcile, schemas, work) from upstreaming.tests.helpers import commit_files, contribution, git, init_repo, policy WF = ".github/workflows/upstreaming-worker.lock.yml" @@ -266,6 +267,60 @@ def test_verified_review_paths_are_persisted_in_contribution_scope(self): self.assertEqual(updated["scope_paths"], ["build.yml", "test.yml"]) +class TestDispatcherPayloadBudget(unittest.TestCase): + def test_large_dossier_is_projected_without_losing_worker_contract(self): + paths = [".github/workflows/wheels.yml", ".github/workflows/test.yml"] + evidence = {"evidence_id": "dossier-c-r10", "kind": "dossier", + "summary": "summary " * 1000, "limitations": ["limit " * 500], + "data": {"proposal": {"decision": "develop", + "admission_class": "configuration_integration", + "allowed_paths": paths, + "architecture_precedent": "native " * 2000, + "risks": "risk " * 2000, + "path_coverage": [ + {"area": "build", "paths": [paths[0]], + "assessment": "build details " * 1000}, + {"area": "test", "paths": [paths[1]], + "assessment": "test details " * 1000}]}, + "dependency_graph": {"assessment": "dependency " * 3000}, + "research": {"upstream_issues": {"findings": "x" * 100000}}}} + item = cli._reason_item(evidence) + encoded = json.dumps(item, separators=(",", ":"), ensure_ascii=False).encode() + self.assertLess(len(encoded), 8000) + self.assertEqual(item["evidence_id"], "dossier-c-r10") + self.assertEqual(item["data"]["proposal"]["allowed_paths"], paths) + self.assertEqual([row["area"] for row in item["data"]["proposal"]["path_coverage"]], + ["build", "test"]) + self.assertIn("dependency", item["data"]["dependency_graph"]["assessment"]) + self.assertNotIn("research", item["data"]) + + def test_complete_dossier_reference_is_immutable_and_digest_bound(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + path = root / "upstreaming-state/evidence/dossier-c-r10.json" + path.parent.mkdir(parents=True) + path.write_text('{"kind":"dossier","evidence_id":"dossier-c-r10","data":{"full":"research"}}\n') + reference = cli._dossier_reference(root, "dossier-c-r10", "a" * 40) + self.assertEqual(reference["path"], "upstreaming-state/evidence/dossier-c-r10.json") + self.assertEqual(reference["ref"], "a" * 40) + self.assertEqual(reference["repository"], "riseproject-dev/python-wheels") + self.assertIn("/" + "a" * 40 + "/upstreaming-state/evidence/", reference["url"]) + self.assertEqual(len(reference["sha256"]), 64) + + def test_feedback_projection_preserves_response_ids_and_exact_paths(self): + evidence = {"evidence_id": "review-1", "kind": "human_relay", "summary": "s" * 9000, + "limitations": [], "data": {"reviews": [], "review_ids": [], + "comments": [{"id": 42, "body": "change " * 3000, "path": "test.yml", + "line": 7, "url": "https://example.test/comment"}], + "comment_ids": [42], "conversation_comments": [], + "conversation_comment_ids": []}} + item = cli._reason_item(evidence) + self.assertEqual(item["data"]["comment_ids"], [42]) + self.assertEqual(item["data"]["comments"][0]["path"], "test.yml") + self.assertEqual(item["data"]["comments"][0]["line"], 7) + self.assertLessEqual(len(item["data"]["comments"][0]["body"]), 1200) + + class TestDispatchRecovery(unittest.TestCase): """A requested task whose dispatch never reached the queue (live run 44379808515: the dispatcher failed before submitting, and its rerun was diff --git a/upstreaming/tests/test_workflow_contracts.py b/upstreaming/tests/test_workflow_contracts.py index a629f73093ec..00c72dfbf8a2 100644 --- a/upstreaming/tests/test_workflow_contracts.py +++ b/upstreaming/tests/test_workflow_contracts.py @@ -207,6 +207,21 @@ def test_command_acknowledgement_is_fast_idempotent_and_not_serialized(self): complete_index = reconcile["steps"].index(complete) self.assertGreater(complete_index, publish_index) + def test_worker_fetches_and_verifies_complete_committed_dossier(self): + worker = source("upstreaming-worker") + checkout = worker["pre-agent-steps"][1] + script = checkout["run"] + self.assertEqual(checkout["env"]["GH_TOKEN"], "${{ github.token }}") + self.assertIn("upstreaming-state/evidence/", script) + self.assertIn("application/vnd.github.raw+json", script) + self.assertIn("sha256sum /tmp/gh-aw/agent/dossier.json", script) + self.assertIn("dossier digest mismatch", script) + self.assertIn(".kind == \"dossier\" and .evidence_id == $id", script) + prompt = (WF / "upstreaming-worker.md").read_text() + self.assertIn("identifies the latest verified dossier", prompt) + self.assertIn("data` is only its queue-safe index", prompt) + self.assertIn("read the latest verified dossier", prompt) + def test_worker_brackets_untrusted_output_with_stop_commands(self): worker = source("upstreaming-worker") before = worker["pre-agent-steps"][0]