From c584aeb1350e304cc3f3048322bce2cb8e08f1e0 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Thu, 1 Oct 2026 13:13:52 +0300 Subject: [PATCH 01/18] feat(review): fetch human-resolved review threads before agent runs Add pre-fetch-resolved-threads.sh alongside pre-fetch-prior-review.sh. The script queries pullRequest.reviewThreads via GraphQL, filters for threads a human explicitly resolved (excluding bot auto-resolutions), extracts finding IDs from markers when present, and writes human-resolved-threads.json for the review agent to consume. Wire the script into reusable-review.yml and pass HUMAN_RESOLVED_FILE to the agent run step. If the script fails, the review proceeds without resolution data (current behavior preserved). Addresses: AISDLC-118 workstream A (fullsend#3515, fullsend#7435) Co-authored-by: Cursor Signed-off-by: csoceanu Co-authored-by: Cursor Signed-off-by: csoceanu --- .../pre-fetch-resolved-threads-test.sh | 346 ++++++++++++++++++ .../scripts/pre-fetch-resolved-threads.sh | 204 +++++++++++ 2 files changed, 550 insertions(+) create mode 100644 internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh create mode 100644 internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh new file mode 100644 index 0000000000..847ba74d3a --- /dev/null +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh @@ -0,0 +1,346 @@ +#!/usr/bin/env bash +# pre-fetch-resolved-threads-test.sh — Tests for pre-fetch-resolved-threads.sh +# +# Verifies GraphQL response parsing, human vs. bot filtering, finding id +# extraction, and fail-safe behavior. +# +# Run from the repo root: +# bash internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT="${SCRIPT_DIR}/pre-fetch-resolved-threads.sh" +FAILURES=0 + +TMPDIR="$(mktemp -d)" +trap 'rm -rf "${TMPDIR}"' EXIT + +# --- Helpers --- + +# build_mock creates a mock gh binary that returns a preconfigured +# GraphQL response. +# $1 — the JSON response to return (empty string = error) +build_mock() { + local response_json="$1" + local mock_bin="${TMPDIR}/bin" + + rm -rf "${mock_bin}" + mkdir -p "${mock_bin}" + + printf '%s' "${response_json}" > "${TMPDIR}/graphql-response.txt" + + cat > "${mock_bin}/gh" <<'MOCKEOF' +#!/usr/bin/env bash +RESPONSE_FILE="RESPONSE_PLACEHOLDER" + +if [[ "$1" == "api" && "$2" == "graphql" ]]; then + if [[ ! -s "${RESPONSE_FILE}" ]]; then + exit 1 + fi + cat "${RESPONSE_FILE}" + exit 0 +fi + +exit 0 +MOCKEOF + + local escaped="${TMPDIR//\//\\/}\/graphql-response.txt" + perl -pi -e "s/RESPONSE_PLACEHOLDER/${escaped}/g" "${mock_bin}/gh" + chmod +x "${mock_bin}/gh" + + echo "${mock_bin}" +} + +# make_graphql_response builds a GraphQL response wrapping the given +# thread nodes array. +make_graphql_response() { + local nodes_json="$1" + cat < "${github_output}" + + local exit_code=0 + env \ + PATH="${mock_bin}:${PATH}" \ + GH_TOKEN="fake-token" \ + ORG_NAME="test-org" \ + PR_NUM="42" \ + SOURCE_REPO="test-org/test-repo" \ + GITHUB_OUTPUT="${github_output}" \ + GITHUB_WORKSPACE="${workspace}" \ + bash "${SCRIPT}" > "${TMPDIR}/stdout.log" 2>&1 || exit_code=$? + + if [[ ${exit_code} -ne 0 ]]; then + echo "FAIL: ${test_name} — script exited with ${exit_code}" + echo "--- stdout ---" + cat "${TMPDIR}/stdout.log" + FAILURES=$((FAILURES + 1)) + return + fi + + local output_file + output_file="$(grep '^human_resolved_file=' "${github_output}" | head -1 | cut -d= -f2)" + + if [[ -z "${output_file}" || ! -f "${output_file}" ]]; then + echo "FAIL: ${test_name} — output file not found" + FAILURES=$((FAILURES + 1)) + return + fi + + local actual_count + actual_count="$(jq '.resolved_threads | length' "${output_file}")" + + if [[ "${actual_count}" -ne "${expected_count}" ]]; then + echo "FAIL: ${test_name} — expected ${expected_count} resolved threads, got ${actual_count}" + echo "--- output ---" + jq . "${output_file}" + echo "--- stdout ---" + cat "${TMPDIR}/stdout.log" + FAILURES=$((FAILURES + 1)) + return + fi + + if [[ -n "${extra_check}" ]]; then + if ! jq -e "${extra_check}" "${output_file}" >/dev/null 2>&1; then + echo "FAIL: ${test_name} — extra check failed: ${extra_check}" + echo "--- output ---" + jq . "${output_file}" + FAILURES=$((FAILURES + 1)) + return + fi + fi + + echo "PASS: ${test_name}" +} + +# --- Test cases --- + +# 1. No review threads at all. +run_test "no-threads" \ + "$(make_graphql_response '[]')" \ + 0 + +# 2. One human-resolved thread with explicit dismissal. +THREAD_HUMAN_RESOLVED='[{ + "id": "T_1", + "isResolved": true, + "path": "internal/cli/github.go", + "line": 42, + "originalLine": 42, + "resolvedBy": {"login": "alice", "type": "User"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding: MarkHidden vs MarkDeprecated", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "alice", "type": "User"}, "body": "We explicitly asked for MarkHidden.", "createdAt": "2026-09-01T11:00:00Z"} + ] + } +}]' + +run_test "human-resolved-explicit" \ + "$(make_graphql_response "${THREAD_HUMAN_RESOLVED}")" \ + 1 \ + '.resolved_threads[0].resolved_by == "alice" and .resolved_threads[0].resolution_context == "explicit_dismissal"' + +# 3. Bot-resolved thread (auto-resolution) — should be excluded. +THREAD_BOT_RESOLVED='[{ + "id": "T_2", + "isResolved": true, + "path": "internal/cli/github.go", + "line": 10, + "originalLine": 10, + "resolvedBy": {"login": "test-org-review[bot]", "type": "Bot"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding: something", "createdAt": "2026-09-01T10:00:00Z"} + ] + } +}]' + +run_test "bot-resolved-excluded" \ + "$(make_graphql_response "${THREAD_BOT_RESOLVED}")" \ + 0 + +# 4. Unresolved thread — should be excluded. +THREAD_UNRESOLVED='[{ + "id": "T_3", + "isResolved": false, + "path": "internal/cli/github.go", + "line": 20, + "originalLine": 20, + "resolvedBy": null, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding: open issue", "createdAt": "2026-09-01T10:00:00Z"} + ] + } +}]' + +run_test "unresolved-excluded" \ + "$(make_graphql_response "${THREAD_UNRESOLVED}")" \ + 0 + +# 5. Human-resolved with finding id marker in bot comment. +THREAD_WITH_FINDING_ID='[{ + "id": "T_4", + "isResolved": true, + "path": "cmd/main.go", + "line": 100, + "originalLine": 100, + "resolvedBy": {"login": "developer", "type": "User"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "\n**[logic-error]** Missing nil check", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "developer", "type": "User"}, "body": "Handled by the caller.", "createdAt": "2026-09-01T11:00:00Z"} + ] + } +}]' + +run_test "finding-id-extracted" \ + "$(make_graphql_response "${THREAD_WITH_FINDING_ID}")" \ + 1 \ + '.resolved_threads[0].finding_id == "f_abc123"' + +# 6. Human-resolved without any human comment (silent resolution). +THREAD_SILENT='[{ + "id": "T_5", + "isResolved": true, + "path": "pkg/util.go", + "line": 55, + "originalLine": 55, + "resolvedBy": {"login": "reviewer", "type": "User"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding: naming convention", "createdAt": "2026-09-01T10:00:00Z"} + ] + } +}]' + +run_test "silent-resolution" \ + "$(make_graphql_response "${THREAD_SILENT}")" \ + 1 \ + '.resolved_threads[0].resolution_context == "silent_resolution" and .resolved_threads[0].human_response == null' + +# 7. Mixed threads — only the human-resolved ones are included. +THREAD_MIXED='[ + { + "id": "T_6", + "isResolved": true, + "path": "a.go", + "line": 1, + "originalLine": 1, + "resolvedBy": {"login": "human1", "type": "User"}, + "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ + {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding 1", "createdAt": "2026-09-01T10:00:00Z"} + ]} + }, + { + "id": "T_7", + "isResolved": false, + "path": "b.go", + "line": 2, + "originalLine": 2, + "resolvedBy": null, + "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ + {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding 2", "createdAt": "2026-09-01T10:00:00Z"} + ]} + }, + { + "id": "T_8", + "isResolved": true, + "path": "c.go", + "line": 3, + "originalLine": 3, + "resolvedBy": {"login": "test-org-review[bot]", "type": "Bot"}, + "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ + {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding 3", "createdAt": "2026-09-01T10:00:00Z"} + ]} + }, + { + "id": "T_9", + "isResolved": true, + "path": "d.go", + "line": 4, + "originalLine": 4, + "resolvedBy": {"login": "human2", "type": "User"}, + "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ + {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding 4", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "human2", "type": "User"}, "body": "Not applicable.", "createdAt": "2026-09-01T11:00:00Z"} + ]} + } +]' + +run_test "mixed-threads" \ + "$(make_graphql_response "${THREAD_MIXED}")" \ + 2 + +# 8. GraphQL failure — script should exit 0 with empty file. +run_test "graphql-failure" \ + "" \ + 0 + +# 9. Shared vendor bot identity (fullsend-ai-review[bot]) resolved — excluded. +THREAD_SHARED_BOT_RESOLVED='[{ + "id": "T_10", + "isResolved": true, + "path": "x.go", + "line": 1, + "originalLine": 1, + "resolvedBy": {"login": "fullsend-ai-review[bot]", "type": "Bot"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "fullsend-ai-review[bot]", "type": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} + ] + } +}]' + +run_test "shared-bot-resolved-excluded" \ + "$(make_graphql_response "${THREAD_SHARED_BOT_RESOLVED}")" \ + 0 + +# 10. Metadata fields are populated. +run_test "metadata-populated" \ + "$(make_graphql_response "${THREAD_HUMAN_RESOLVED}")" \ + 1 \ + '.metadata.pr_number == 42 and .metadata.repo == "test-org/test-repo" and .metadata.thread_count > 0' + +# --- Summary --- + +echo "" +if [[ ${FAILURES} -gt 0 ]]; then + echo "${FAILURES} test(s) failed" + exit 1 +fi +echo "All tests passed" diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh new file mode 100644 index 0000000000..e1e70e6cb4 --- /dev/null +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh @@ -0,0 +1,204 @@ +#!/usr/bin/env bash +# pre-fetch-resolved-threads.sh — Fetch human-resolved review threads before the review agent runs +# +# Queries the PR's review threads via the GitHub GraphQL API and writes +# a JSON file listing threads that a human explicitly resolved. The +# review agent uses this to avoid re-raising findings that a person +# already dismissed. +# +# Threads resolved by the bot itself (auto-resolution of outdated +# comments) are excluded — only human resolutions count. +# +# If a thread's inline comment contains a finding id marker +# (), the id is included in the output so the +# agent can match by exact id instead of fuzzy file+line. +# +# Best-effort: if the GraphQL query fails or any step errors, the +# script writes an empty file and exits 0 so the review proceeds +# without resolution data (current behavior preserved). +# +# Required environment variables (set by the workflow): +# +# - GH_TOKEN — token with read access to the PR +# - SOURCE_REPO — owner/repo (e.g., "fullsend-ai/fullsend") +# - PR_NUM — PR number +# - ORG_NAME — org name for bot identity filtering +# +# Outputs (via GITHUB_OUTPUT): +# - human_resolved_file — path to the JSON file +set -euo pipefail + +OUTPUT_FILE="${GITHUB_WORKSPACE:-/tmp}/human-resolved-threads.json" +REVIEW_BOT="${ORG_NAME}-review[bot]" +SHARED_REVIEW_BOT="fullsend-ai-review[bot]" + +OWNER="${SOURCE_REPO%%/*}" +NAME="${SOURCE_REPO##*/}" + +# --- GraphQL query --- +# Fetches review threads with resolution state, path, line, and comments. +# Paginated at 100 threads per page with a 20-page cap (matching the +# pattern in forge_resolve_outdated_review_threads from agents PR #1415). +QUERY='query($owner: String!, $name: String!, $number: Int!, $cursor: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + reviewThreads(first: 100, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { + id + isResolved + path + line + originalLine + resolvedBy { login type } + comments(first: 10) { + pageInfo { hasNextPage } + nodes { + author { login type } + body + createdAt + } + } + } + } + } + } +}' + +# --- Pagination --- +cursor="" +has_next="true" +page=0 +nodes_json="[]" + +while [[ "${has_next}" == "true" ]]; do + page=$((page + 1)) + if [[ "${page}" -gt 20 ]]; then + echo "::warning::Resolved-threads pagination hit page cap — remaining threads skipped" + break + fi + + gh_args=(api graphql + -f owner="${OWNER}" + -f name="${NAME}" + -F number="${PR_NUM}" + -f query="${QUERY}") + if [[ -n "${cursor}" ]]; then + gh_args+=(-f cursor="${cursor}") + fi + + if ! response=$(gh "${gh_args[@]}" 2>/dev/null); then + echo "::warning::Failed to fetch review threads — writing empty resolved-threads file" + echo '{"resolved_threads":[],"metadata":{"error":"graphql_fetch_failed"}}' > "${OUTPUT_FILE}" + echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" + exit 0 + fi + + if echo "${response}" | jq -e '.errors | type == "array" and length > 0' >/dev/null 2>&1; then + echo "::warning::Review threads query returned errors — writing empty resolved-threads file" + echo '{"resolved_threads":[],"metadata":{"error":"graphql_errors"}}' > "${OUTPUT_FILE}" + echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" + exit 0 + fi + + page_nodes=$(echo "${response}" | jq -c '.data.repository.pullRequest.reviewThreads.nodes // []' 2>/dev/null) || { + echo "::warning::Failed to parse review threads — writing empty resolved-threads file" + echo '{"resolved_threads":[],"metadata":{"error":"parse_failed"}}' > "${OUTPUT_FILE}" + echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" + exit 0 + } + + nodes_json=$(jq -c --argjson page "${page_nodes}" '. + $page' <<< "${nodes_json}" 2>/dev/null) || { + echo "::warning::Failed to merge review thread pages — writing empty resolved-threads file" + echo '{"resolved_threads":[],"metadata":{"error":"merge_failed"}}' > "${OUTPUT_FILE}" + echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" + exit 0 + } + + has_next=$(echo "${response}" | jq -r '.data.repository.pullRequest.reviewThreads.pageInfo.hasNextPage // false' 2>/dev/null) || has_next="false" + cursor=$(echo "${response}" | jq -r '.data.repository.pullRequest.reviewThreads.pageInfo.endCursor // empty' 2>/dev/null) || cursor="" + if [[ "${has_next}" == "true" && -z "${cursor}" ]]; then + echo "::warning::Review threads page missing cursor — stopping pagination" + break + fi +done + +# --- Filter and transform --- +# Select threads that: +# - are resolved +# - were resolved by a human (not the review bot) +# - have at least one comment +# - comment pagination is complete (incomplete pages might hide context) +# +# For each matching thread, extract: +# - file, line, original_line from the thread +# - resolved_by and resolved_by_type from resolvedBy +# - the first bot comment body (for snippet matching) +# - the last human comment body (the resolution rationale) +# - finding_id if present in the bot comment () +# - resolution_context classification + +RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ + --arg bot "${REVIEW_BOT}" \ + --arg shared_bot "${SHARED_REVIEW_BOT}" \ + '[.[] + | select(.isResolved == true) + | select(.resolvedBy != null) + | select(.resolvedBy.login != $bot and .resolvedBy.login != $shared_bot) + | select(.resolvedBy.type == "User") + | select((.comments.nodes // [] | length) > 0) + | select((.comments.pageInfo.hasNextPage // false) == false) + | { + file: .path, + line: .line, + original_line: .originalLine, + resolved_by: .resolvedBy.login, + resolved_by_type: .resolvedBy.type, + bot_finding_snippet: ( + [.comments.nodes[] | select(.author.login == $bot or .author.login == $shared_bot)] + | first // null + | if . then (.body | .[0:200]) else null end + ), + finding_id: ( + [.comments.nodes[] | select(.author.login == $bot or .author.login == $shared_bot)] + | first // null + | if . then (.body | capture("") // null | .id // null) else null end + ), + human_response: ( + [.comments.nodes[] | select(.author.login != $bot and .author.login != $shared_bot and .author.type == "User")] + | last // null + | if . then (.body | .[0:500]) else null end + ), + resolution_context: ( + if ([.comments.nodes[] | select(.author.login != $bot and .author.login != $shared_bot and .author.type == "User")] | length) > 0 + then "explicit_dismissal" + else "silent_resolution" + end + ) + } + ]' 2>/dev/null) || RESOLVED_THREADS="[]" + +THREAD_COUNT=$(echo "${nodes_json}" | jq 'length' 2>/dev/null) || THREAD_COUNT=0 +RESOLVED_COUNT=$(echo "${RESOLVED_THREADS}" | jq 'length' 2>/dev/null) || RESOLVED_COUNT=0 + +# --- Write output --- +jq -n \ + --argjson threads "${RESOLVED_THREADS}" \ + --argjson pr_num "${PR_NUM}" \ + --arg repo "${SOURCE_REPO}" \ + --argjson thread_count "${THREAD_COUNT}" \ + --argjson resolved_count "${RESOLVED_COUNT}" \ + --arg fetched_at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + '{ + resolved_threads: $threads, + metadata: { + pr_number: $pr_num, + repo: $repo, + thread_count: $thread_count, + human_resolved_count: $resolved_count, + fetched_at: $fetched_at + } + }' > "${OUTPUT_FILE}" + +echo "Resolved threads: ${RESOLVED_COUNT} human-resolved out of ${THREAD_COUNT} total" +echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" From 298bad1f9801e0201ffb393009dc2c6c7c634743 Mon Sep 17 00:00:00 2001 From: Benjamin Kapner Date: Thu, 1 Oct 2026 13:41:36 +0300 Subject: [PATCH 02/18] fix(review): query GraphQL __typename instead of REST type The reviewThreads query requested author/resolvedBy.type, which GitHub GraphQL does not expose. The API returns errors, we fail-open, and resolved threads never reach the agent. Tests mocked the REST shape. Fetch 100 comments per thread to match github-review-ops, fail-open on the output write, and run the unit tests from script-test. Co-authored-by: Cursor Signed-off-by: csoceanu --- Makefile | 1 + .../pre-fetch-resolved-threads-test.sh | 82 ++++++++++++++----- .../scripts/pre-fetch-resolved-threads.sh | 26 +++--- 3 files changed, 78 insertions(+), 31 deletions(-) diff --git a/Makefile b/Makefile index 951b3a9e3b..5dd4c4938e 100644 --- a/Makefile +++ b/Makefile @@ -192,6 +192,7 @@ script-test: $(call run-timed,bash scripts/check-agents-gate-pin-test.sh) $(call run-timed,bash scripts/verify-release-tag-test.sh) $(call run-timed,bash internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh) + $(call run-timed,bash internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh) $(call run-timed,bash internal/scaffold/fullsend-repo/.github/scripts/setup-agent-env-test.sh) $(call run-timed,bash hack/gitlab-runner-vm/executor/prepare_validation_test.sh) $(call run-timed,bash hack/gitlab-runner-vm/executor/gateway_test.sh) diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh index 847ba74d3a..f9309b9e41 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh @@ -154,12 +154,12 @@ THREAD_HUMAN_RESOLVED='[{ "path": "internal/cli/github.go", "line": 42, "originalLine": 42, - "resolvedBy": {"login": "alice", "type": "User"}, + "resolvedBy": {"login": "alice", "__typename": "User"}, "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding: MarkHidden vs MarkDeprecated", "createdAt": "2026-09-01T10:00:00Z"}, - {"author": {"login": "alice", "type": "User"}, "body": "We explicitly asked for MarkHidden.", "createdAt": "2026-09-01T11:00:00Z"} + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: MarkHidden vs MarkDeprecated", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "alice", "__typename": "User"}, "body": "We explicitly asked for MarkHidden.", "createdAt": "2026-09-01T11:00:00Z"} ] } }]' @@ -176,11 +176,11 @@ THREAD_BOT_RESOLVED='[{ "path": "internal/cli/github.go", "line": 10, "originalLine": 10, - "resolvedBy": {"login": "test-org-review[bot]", "type": "Bot"}, + "resolvedBy": {"login": "test-org-review[bot]", "__typename": "Bot"}, "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding: something", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: something", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' @@ -200,7 +200,7 @@ THREAD_UNRESOLVED='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding: open issue", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: open issue", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' @@ -216,12 +216,12 @@ THREAD_WITH_FINDING_ID='[{ "path": "cmd/main.go", "line": 100, "originalLine": 100, - "resolvedBy": {"login": "developer", "type": "User"}, + "resolvedBy": {"login": "developer", "__typename": "User"}, "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "\n**[logic-error]** Missing nil check", "createdAt": "2026-09-01T10:00:00Z"}, - {"author": {"login": "developer", "type": "User"}, "body": "Handled by the caller.", "createdAt": "2026-09-01T11:00:00Z"} + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "\n**[logic-error]** Missing nil check", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "developer", "__typename": "User"}, "body": "Handled by the caller.", "createdAt": "2026-09-01T11:00:00Z"} ] } }]' @@ -238,11 +238,11 @@ THREAD_SILENT='[{ "path": "pkg/util.go", "line": 55, "originalLine": 55, - "resolvedBy": {"login": "reviewer", "type": "User"}, + "resolvedBy": {"login": "reviewer", "__typename": "User"}, "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding: naming convention", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: naming convention", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' @@ -260,9 +260,9 @@ THREAD_MIXED='[ "path": "a.go", "line": 1, "originalLine": 1, - "resolvedBy": {"login": "human1", "type": "User"}, + "resolvedBy": {"login": "human1", "__typename": "User"}, "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding 1", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding 1", "createdAt": "2026-09-01T10:00:00Z"} ]} }, { @@ -273,7 +273,7 @@ THREAD_MIXED='[ "originalLine": 2, "resolvedBy": null, "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding 2", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding 2", "createdAt": "2026-09-01T10:00:00Z"} ]} }, { @@ -282,9 +282,9 @@ THREAD_MIXED='[ "path": "c.go", "line": 3, "originalLine": 3, - "resolvedBy": {"login": "test-org-review[bot]", "type": "Bot"}, + "resolvedBy": {"login": "test-org-review[bot]", "__typename": "Bot"}, "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding 3", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding 3", "createdAt": "2026-09-01T10:00:00Z"} ]} }, { @@ -293,10 +293,10 @@ THREAD_MIXED='[ "path": "d.go", "line": 4, "originalLine": 4, - "resolvedBy": {"login": "human2", "type": "User"}, + "resolvedBy": {"login": "human2", "__typename": "User"}, "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "type": "Bot"}, "body": "Finding 4", "createdAt": "2026-09-01T10:00:00Z"}, - {"author": {"login": "human2", "type": "User"}, "body": "Not applicable.", "createdAt": "2026-09-01T11:00:00Z"} + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding 4", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "human2", "__typename": "User"}, "body": "Not applicable.", "createdAt": "2026-09-01T11:00:00Z"} ]} } ]' @@ -317,11 +317,11 @@ THREAD_SHARED_BOT_RESOLVED='[{ "path": "x.go", "line": 1, "originalLine": 1, - "resolvedBy": {"login": "fullsend-ai-review[bot]", "type": "Bot"}, + "resolvedBy": {"login": "fullsend-ai-review[bot]", "__typename": "Bot"}, "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "fullsend-ai-review[bot]", "type": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "fullsend-ai-review[bot]", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' @@ -336,6 +336,46 @@ run_test "metadata-populated" \ 1 \ '.metadata.pr_number == 42 and .metadata.repo == "test-org/test-repo" and .metadata.thread_count > 0' +# 11. Incomplete comment page — skip rather than guess hidden context. +THREAD_INCOMPLETE_COMMENTS='[{ + "id": "T_11", + "isResolved": true, + "path": "e.go", + "line": 8, + "originalLine": 8, + "resolvedBy": {"login": "alice", "__typename": "User"}, + "comments": { + "pageInfo": {"hasNextPage": true}, + "nodes": [ + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} + ] + } +}]' + +run_test "incomplete-comment-page-excluded" \ + "$(make_graphql_response "${THREAD_INCOMPLETE_COMMENTS}")" \ + 0 + +# 12. Other GitHub App resolver (login ends with [bot]) — excluded. +THREAD_DEPENDABOT_RESOLVED='[{ + "id": "T_12", + "isResolved": true, + "path": "f.go", + "line": 9, + "originalLine": 9, + "resolvedBy": {"login": "dependabot[bot]", "__typename": "Bot"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} + ] + } +}]' + +run_test "other-bot-resolved-excluded" \ + "$(make_graphql_response "${THREAD_DEPENDABOT_RESOLVED}")" \ + 0 + # --- Summary --- echo "" diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh index e1e70e6cb4..351c8b151b 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh @@ -50,11 +50,11 @@ QUERY='query($owner: String!, $name: String!, $number: Int!, $cursor: String) { path line originalLine - resolvedBy { login type } - comments(first: 10) { + resolvedBy { login } + comments(first: 100) { pageInfo { hasNextPage } nodes { - author { login type } + author { login __typename } body createdAt } @@ -132,11 +132,15 @@ done # # For each matching thread, extract: # - file, line, original_line from the thread -# - resolved_by and resolved_by_type from resolvedBy +# - resolved_by from resolvedBy.login # - the first bot comment body (for snippet matching) # - the last human comment body (the resolution rationale) # - finding_id if present in the bot comment () # - resolution_context classification +# +# GitHub GraphQL has no Actor/User.type (that is REST). Bots are +# __typename Bot on comment authors, and login ending in "[bot]" on +# resolvedBy (typed User in the schema even for GitHub Apps). RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ --arg bot "${REVIEW_BOT}" \ @@ -145,7 +149,7 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ | select(.isResolved == true) | select(.resolvedBy != null) | select(.resolvedBy.login != $bot and .resolvedBy.login != $shared_bot) - | select(.resolvedBy.type == "User") + | select((.resolvedBy.login | endswith("[bot]")) | not) | select((.comments.nodes // [] | length) > 0) | select((.comments.pageInfo.hasNextPage // false) == false) | { @@ -153,7 +157,6 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ line: .line, original_line: .originalLine, resolved_by: .resolvedBy.login, - resolved_by_type: .resolvedBy.type, bot_finding_snippet: ( [.comments.nodes[] | select(.author.login == $bot or .author.login == $shared_bot)] | first // null @@ -165,12 +168,12 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ | if . then (.body | capture("") // null | .id // null) else null end ), human_response: ( - [.comments.nodes[] | select(.author.login != $bot and .author.login != $shared_bot and .author.type == "User")] + [.comments.nodes[] | select(.author.login != $bot and .author.login != $shared_bot and .author.__typename == "User")] | last // null | if . then (.body | .[0:500]) else null end ), resolution_context: ( - if ([.comments.nodes[] | select(.author.login != $bot and .author.login != $shared_bot and .author.type == "User")] | length) > 0 + if ([.comments.nodes[] | select(.author.login != $bot and .author.login != $shared_bot and .author.__typename == "User")] | length) > 0 then "explicit_dismissal" else "silent_resolution" end @@ -182,7 +185,7 @@ THREAD_COUNT=$(echo "${nodes_json}" | jq 'length' 2>/dev/null) || THREAD_COUNT=0 RESOLVED_COUNT=$(echo "${RESOLVED_THREADS}" | jq 'length' 2>/dev/null) || RESOLVED_COUNT=0 # --- Write output --- -jq -n \ +if ! jq -n \ --argjson threads "${RESOLVED_THREADS}" \ --argjson pr_num "${PR_NUM}" \ --arg repo "${SOURCE_REPO}" \ @@ -198,7 +201,10 @@ jq -n \ human_resolved_count: $resolved_count, fetched_at: $fetched_at } - }' > "${OUTPUT_FILE}" + }' > "${OUTPUT_FILE}"; then + echo "::warning::Failed to write resolved-threads file — writing empty resolved-threads file" + echo '{"resolved_threads":[],"metadata":{"error":"write_failed"}}' > "${OUTPUT_FILE}" +fi echo "Resolved threads: ${RESOLVED_COUNT} human-resolved out of ${THREAD_COUNT} total" echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" From d0bc73a532479e216b2485a428315d02938894da Mon Sep 17 00:00:00 2001 From: csoceanu Date: Thu, 1 Oct 2026 17:05:52 +0300 Subject: [PATCH 03/18] fix(review): match resolver's comments only and flag truncated threads Address Qodo review findings on PR #7907: 1. human_response and resolution_context now only consider comments from the resolvedBy user, not any human. When one reviewer comments and another resolves the thread, the first reviewer's reply is no longer misattributed as the resolution rationale. 2. Add truncated flag to metadata when the 20-page cap is hit, so consumers know the resolved-threads list may be incomplete. Add test cases: different commenter produces silent_resolution, resolver's own comment produces explicit_dismissal, truncated flag is false under the page cap. Signed-off-by: csoceanu Co-authored-by: Cursor --- .../pre-fetch-resolved-threads-test.sh | 53 +++++++++++++++++++ .../scripts/pre-fetch-resolved-threads.sh | 17 ++++-- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh index f9309b9e41..89f14512f1 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh @@ -376,6 +376,59 @@ run_test "other-bot-resolved-excluded" \ "$(make_graphql_response "${THREAD_DEPENDABOT_RESOLVED}")" \ 0 +# 13. Resolver's comment is used, not another human's. +# Bob comments but Alice resolves — human_response should be from +# Alice (the resolver), and if Alice didn't comment it's silent. +THREAD_DIFFERENT_COMMENTER='[{ + "id": "T_13", + "isResolved": true, + "path": "g.go", + "line": 15, + "originalLine": 15, + "resolvedBy": {"login": "alice", "__typename": "User"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: something wrong", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "bob", "__typename": "User"}, "body": "I will fix this.", "createdAt": "2026-09-01T11:00:00Z"} + ] + } +}]' + +run_test "different-commenter-silent-resolution" \ + "$(make_graphql_response "${THREAD_DIFFERENT_COMMENTER}")" \ + 1 \ + '.resolved_threads[0].resolution_context == "silent_resolution" and .resolved_threads[0].human_response == null' + +# 14. Resolver left a comment — should be explicit_dismissal with their text. +THREAD_RESOLVER_COMMENTED='[{ + "id": "T_14", + "isResolved": true, + "path": "h.go", + "line": 20, + "originalLine": 20, + "resolvedBy": {"login": "alice", "__typename": "User"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: issue here", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "bob", "__typename": "User"}, "body": "I think this is fine.", "createdAt": "2026-09-01T10:30:00Z"}, + {"author": {"login": "alice", "__typename": "User"}, "body": "Intentional, closing.", "createdAt": "2026-09-01T11:00:00Z"} + ] + } +}]' + +run_test "resolver-commented-explicit-dismissal" \ + "$(make_graphql_response "${THREAD_RESOLVER_COMMENTED}")" \ + 1 \ + '.resolved_threads[0].resolution_context == "explicit_dismissal" and .resolved_threads[0].human_response == "Intentional, closing."' + +# 15. Metadata includes truncated flag (false when under page cap). +run_test "metadata-truncated-false" \ + "$(make_graphql_response "${THREAD_HUMAN_RESOLVED}")" \ + 1 \ + '.metadata.truncated == false' + # --- Summary --- echo "" diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh index 351c8b151b..6987c3aaa7 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh @@ -70,11 +70,13 @@ cursor="" has_next="true" page=0 nodes_json="[]" +truncated="false" while [[ "${has_next}" == "true" ]]; do page=$((page + 1)) if [[ "${page}" -gt 20 ]]; then echo "::warning::Resolved-threads pagination hit page cap — remaining threads skipped" + truncated="true" break fi @@ -134,9 +136,11 @@ done # - file, line, original_line from the thread # - resolved_by from resolvedBy.login # - the first bot comment body (for snippet matching) -# - the last human comment body (the resolution rationale) +# - the resolver's last comment (the resolution rationale) — only +# comments from the resolvedBy user count, not any human # - finding_id if present in the bot comment () -# - resolution_context classification +# - resolution_context classification: explicit_dismissal when the +# resolver left a comment, silent_resolution otherwise # # GitHub GraphQL has no Actor/User.type (that is REST). Bots are # __typename Bot on comment authors, and login ending in "[bot]" on @@ -152,11 +156,12 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ | select((.resolvedBy.login | endswith("[bot]")) | not) | select((.comments.nodes // [] | length) > 0) | select((.comments.pageInfo.hasNextPage // false) == false) + | .resolvedBy.login as $resolver | { file: .path, line: .line, original_line: .originalLine, - resolved_by: .resolvedBy.login, + resolved_by: $resolver, bot_finding_snippet: ( [.comments.nodes[] | select(.author.login == $bot or .author.login == $shared_bot)] | first // null @@ -168,12 +173,12 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ | if . then (.body | capture("") // null | .id // null) else null end ), human_response: ( - [.comments.nodes[] | select(.author.login != $bot and .author.login != $shared_bot and .author.__typename == "User")] + [.comments.nodes[] | select(.author.login == $resolver)] | last // null | if . then (.body | .[0:500]) else null end ), resolution_context: ( - if ([.comments.nodes[] | select(.author.login != $bot and .author.login != $shared_bot and .author.__typename == "User")] | length) > 0 + if ([.comments.nodes[] | select(.author.login == $resolver)] | length) > 0 then "explicit_dismissal" else "silent_resolution" end @@ -191,6 +196,7 @@ if ! jq -n \ --arg repo "${SOURCE_REPO}" \ --argjson thread_count "${THREAD_COUNT}" \ --argjson resolved_count "${RESOLVED_COUNT}" \ + --argjson truncated "${truncated}" \ --arg fetched_at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ '{ resolved_threads: $threads, @@ -199,6 +205,7 @@ if ! jq -n \ repo: $repo, thread_count: $thread_count, human_resolved_count: $resolved_count, + truncated: $truncated, fetched_at: $fetched_at } }' > "${OUTPUT_FILE}"; then From 8af24ea6bfa4964919d7f531bedca821b5b037ad Mon Sep 17 00:00:00 2001 From: csoceanu Date: Sun, 4 Oct 2026 14:35:49 +0300 Subject: [PATCH 04/18] fix(review): route resolved threads through forge client Fetch review-thread context through the forge abstraction and expose it to the review workflow via the fullsend CLI. Normalize GitHub bot identities, preserve fail-open behavior, and keep agent-side consumption as a separate follow-up change. Co-authored-by: Codex Signed-off-by: csoceanu --- .github/workflows/reusable-dispatch.yml | 24 +++ internal/cli/fetchreviewthreads.go | 54 ++++++ internal/cli/root.go | 1 + internal/forge/fake.go | 18 ++ internal/forge/forge.go | 34 ++++ internal/forge/github/github.go | 134 +++++++++++++++ internal/forge/gitlab/mr.go | 7 + .../pre-fetch-resolved-threads-test.sh | 41 +++-- .../scripts/pre-fetch-resolved-threads.sh | 161 ++++++------------ 9 files changed, 353 insertions(+), 121 deletions(-) create mode 100644 internal/cli/fetchreviewthreads.go diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 24b32ede78..93638598e1 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -945,6 +945,16 @@ jobs: repos: ${{ steps.workspace.outputs.repo_name }} mint_url: ${{ inputs.mint_url }} + - name: Install fullsend CLI for review context + id: install-fullsend + uses: ./.defaults/.github/actions/install-fullsend-cli + with: + mode: ${{ inputs.install_mode == 'per-repo' && 'vendored' || 'upstream' }} + vendored_path: .fullsend/bin/fullsend + workflow_repository: ${{ job.workflow_repository }} + workflow_sha: ${{ job.workflow_sha }} + github_token: ${{ steps.app-token.outputs.token }} + - name: Checkout target repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -968,6 +978,19 @@ jobs: FULLSEND_DIR: .fullsend run: bash "${FULLSEND_DIR:+$FULLSEND_DIR/}scripts/pre-fetch-prior-review.sh" + - name: Pre-fetch human-resolved review threads + id: resolved-threads + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + SOURCE_REPO: ${{ github.repository }} + PR_NUM: >- + ${{ fromJSON(needs.route.outputs.event_payload).pull_request.number + || fromJSON(needs.route.outputs.event_payload).issue.number }} + ORG_NAME: ${{ github.repository_owner }} + FULLSEND_BIN: ${{ steps.install-fullsend.outputs.fullsend-path }} + FULLSEND_DIR: ${{ inputs.install_mode == 'per-repo' && '.fullsend' || '' }} + run: bash "${FULLSEND_DIR:+$FULLSEND_DIR/}scripts/pre-fetch-resolved-threads.sh" + - name: Setup agent environment env: AGENT_PREFIX: REVIEW_ @@ -990,6 +1013,7 @@ jobs: PRIOR_REVIEW_SHA: ${{ steps.prior-review.outputs.prior_sha }} PRIOR_REVIEW_FILE: ${{ steps.prior-review.outputs.prior_review_file }} PRIOR_REVIEW_PROVENANCE: ${{ steps.prior-review.outputs.prior_review_provenance }} + HUMAN_RESOLVED_FILE: ${{ steps.resolved-threads.outputs.human_resolved_file }} OTEL_EXPORTER_OTLP_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_ENDPOINT }} OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} diff --git a/internal/cli/fetchreviewthreads.go b/internal/cli/fetchreviewthreads.go new file mode 100644 index 0000000000..7f82c86437 --- /dev/null +++ b/internal/cli/fetchreviewthreads.go @@ -0,0 +1,54 @@ +package cli + +import ( + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" +) + +func newFetchReviewThreadsCmd() *cobra.Command { + var ( + repo string + pr int + forgeName string + token string + baseURL string + ) + + cmd := &cobra.Command{ + Use: "fetch-review-threads", + Short: "Fetch pull-request review threads through the forge client", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if pr <= 0 { + return fmt.Errorf("--pr must be a positive integer, got %d", pr) + } + parts := strings.SplitN(repo, "/", 2) + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return fmt.Errorf("--repo must be in owner/repo format, got %q", repo) + } + + client, err := resolvePostReviewClient(forgeName, token, baseURL) + if err != nil { + return err + } + threads, err := client.ListPullRequestReviewThreads(cmd.Context(), parts[0], parts[1], pr) + if err != nil { + return err + } + return json.NewEncoder(os.Stdout).Encode(threads) + }, + } + + cmd.Flags().StringVar(&repo, "repo", "", "repository in owner/repo format (required)") + cmd.Flags().IntVar(&pr, "pr", 0, "pull request number (required)") + cmd.Flags().StringVar(&forgeName, "forge", "github", "forge backend (github or gitlab)") + cmd.Flags().StringVar(&token, "token", "", "forge token (defaults to the forge environment token)") + cmd.Flags().StringVar(&baseURL, "base-url", "", "forge API base URL") + _ = cmd.MarkFlagRequired("repo") + _ = cmd.MarkFlagRequired("pr") + return cmd +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 6512398ea4..8222748db9 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -76,6 +76,7 @@ func newRootCmd() *cobra.Command { cmd.AddCommand(newScanCmd()) cmd.AddCommand(newReposCmd()) cmd.AddCommand(newPostReviewCmd()) + cmd.AddCommand(newFetchReviewThreadsCmd()) cmd.AddCommand(newIssuesCmd()) cmd.AddCommand(newPostCommentCmd()) cmd.AddCommand(newReconcileStatusCmd()) diff --git a/internal/forge/fake.go b/internal/forge/fake.go index 7aae3c5f21..5ac85e803b 100644 --- a/internal/forge/fake.go +++ b/internal/forge/fake.go @@ -354,6 +354,9 @@ type FakeClient struct { // Pull request reviews for ListPullRequestReviews. PRReviews map[string][]PullRequestReview // key: "owner/repo/number" + // Pull request review threads for ListPullRequestReviewThreads. + PRReviewThreads map[string]ReviewThreadPage // key: "owner/repo/number" + // WorkflowRunJobs for ListWorkflowRunJobs. WorkflowRunJobs map[int][]WorkflowJob // key: runID @@ -1950,6 +1953,21 @@ func (f *FakeClient) ListPullRequestReviews(_ context.Context, owner, repo strin return nil, nil } +func (f *FakeClient) ListPullRequestReviewThreads(_ context.Context, owner, repo string, number int) (ReviewThreadPage, error) { + f.mu.Lock() + defer f.mu.Unlock() + if e := f.err("ListPullRequestReviewThreads"); e != nil { + return ReviewThreadPage{}, e + } + if f.PRReviewThreads != nil { + key := fmt.Sprintf("%s/%s/%d", owner, repo, number) + if threads, ok := f.PRReviewThreads[key]; ok { + return threads, nil + } + } + return ReviewThreadPage{}, nil +} + func (f *FakeClient) DismissPullRequestReview(_ context.Context, owner, repo string, number, reviewID int, message string) error { f.mu.Lock() defer f.mu.Unlock() diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 13e70bc5d2..3824462bb7 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -466,6 +466,36 @@ type ReviewComment struct { Body string // comment body (Markdown) } +// ReviewThreadComment is a comment belonging to a pull-request review thread. +// AuthorType is the forge's actor type (for example, "Bot" or "User"). +type ReviewThreadComment struct { + Author string `json:"author"` + AuthorType string `json:"author_type"` + Body string `json:"body"` + CreatedAt string `json:"created_at"` +} + +// ReviewThread represents the resolution state and comments of a pull-request +// review thread. Forges that do not expose review threads return +// ErrNotSupported. +type ReviewThread struct { + ID string `json:"id"` + IsResolved bool `json:"is_resolved"` + Path string `json:"path"` + Line *int `json:"line"` + OriginalLine *int `json:"original_line"` + ResolvedBy string `json:"resolved_by"` + Comments []ReviewThreadComment `json:"comments"` + CommentsTruncated bool `json:"comments_truncated"` +} + +// ReviewThreadPage contains a complete fetch of a pull request's review +// threads. Truncated is true when the implementation hit its safety cap. +type ReviewThreadPage struct { + Threads []ReviewThread `json:"threads"` + Truncated bool `json:"truncated"` +} + // PullRequestFileDiff represents a file changed in a pull request along // with its unified diff patch. The patch may be empty for binary files, // rename-only changes, or when GitHub truncates large diffs. @@ -933,6 +963,10 @@ type Client interface { // comments, when non-nil, attaches inline diff comments to the review. CreatePullRequestReview(ctx context.Context, owner, repo string, number int, event, body, commitSHA string, comments []ReviewComment) error ListPullRequestReviews(ctx context.Context, owner, repo string, number int) ([]PullRequestReview, error) + // ListPullRequestReviewThreads returns review threads, including their + // resolution state and comments. It returns ErrNotSupported when the forge + // has no equivalent review-thread API. + ListPullRequestReviewThreads(ctx context.Context, owner, repo string, number int) (ReviewThreadPage, error) DismissPullRequestReview(ctx context.Context, owner, repo string, number, reviewID int, message string) error // Change proposal merge diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 73438c1c3a..3dd3911401 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -3634,6 +3634,140 @@ func (c *LiveClient) ListPullRequestReviews(ctx context.Context, owner, repo str return result, nil } +// ListPullRequestReviewThreads returns the pull request's review threads and +// their comments through GitHub's GraphQL API. GitHub exposes review threads +// only through GraphQL, so keeping this operation here prevents callers from +// bypassing the forge abstraction with a raw `gh api` invocation. +func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, repo string, number int) (forge.ReviewThreadPage, error) { + const query = `query($owner: String!, $name: String!, $number: Int!, $cursor: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + reviewThreads(first: 100, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { + id + isResolved + path + line + originalLine + resolvedBy { login } + comments(first: 100) { + pageInfo { hasNextPage } + nodes { + author { login __typename } + body + createdAt + } + } + } + } + } + } + }` + + type gqlThread struct { + ID string `json:"id"` + IsResolved bool `json:"isResolved"` + Path string `json:"path"` + Line *int `json:"line"` + OriginalLine *int `json:"originalLine"` + ResolvedBy *struct { + Login string `json:"login"` + } `json:"resolvedBy"` + Comments struct { + PageInfo struct { + HasNextPage bool `json:"hasNextPage"` + } `json:"pageInfo"` + Nodes []struct { + Author struct { + Login string `json:"login"` + Type string `json:"__typename"` + } `json:"author"` + Body string `json:"body"` + CreatedAt string `json:"createdAt"` + } `json:"nodes"` + } `json:"comments"` + } + + type gqlResult struct { + Data struct { + Repository struct { + PullRequest struct { + ReviewThreads struct { + PageInfo struct { + HasNextPage bool `json:"hasNextPage"` + EndCursor string `json:"endCursor"` + } `json:"pageInfo"` + Nodes []gqlThread `json:"nodes"` + } `json:"reviewThreads"` + } `json:"pullRequest"` + } `json:"repository"` + } `json:"data"` + Errors []struct { + Message string `json:"message"` + } `json:"errors"` + } + + result := forge.ReviewThreadPage{} + var cursor *string + for page := 1; page <= 20; page++ { + variables := map[string]any{ + "owner": owner, + "name": repo, + "number": number, + "cursor": cursor, + } + resp, err := c.post(ctx, "/graphql", map[string]any{"query": query, "variables": variables}) + if err != nil { + return forge.ReviewThreadPage{}, fmt.Errorf("list pull request review threads page %d: %w", page, err) + } + var decoded gqlResult + if err := decodeJSON(resp, &decoded); err != nil { + return forge.ReviewThreadPage{}, fmt.Errorf("decode pull request review threads page %d: %w", page, err) + } + if len(decoded.Errors) > 0 { + return forge.ReviewThreadPage{}, fmt.Errorf("list pull request review threads: %s", decoded.Errors[0].Message) + } + + threads := decoded.Data.Repository.PullRequest.ReviewThreads + for _, thread := range threads.Nodes { + converted := forge.ReviewThread{ + ID: thread.ID, + IsResolved: thread.IsResolved, + Path: thread.Path, + Line: thread.Line, + OriginalLine: thread.OriginalLine, + CommentsTruncated: thread.Comments.PageInfo.HasNextPage, + } + if thread.ResolvedBy != nil { + converted.ResolvedBy = thread.ResolvedBy.Login + } + for _, comment := range thread.Comments.Nodes { + converted.Comments = append(converted.Comments, forge.ReviewThreadComment{ + Author: comment.Author.Login, + AuthorType: comment.Author.Type, + Body: comment.Body, + CreatedAt: comment.CreatedAt, + }) + } + result.Threads = append(result.Threads, converted) + } + + if !threads.PageInfo.HasNextPage { + break + } + if threads.PageInfo.EndCursor == "" { + return forge.ReviewThreadPage{}, fmt.Errorf("list pull request review threads page %d: missing pagination cursor", page) + } + next := threads.PageInfo.EndCursor + cursor = &next + if page == 20 { + result.Truncated = true + } + } + return result, nil +} + // DismissPullRequestReview dismisses a review, changing its state to DISMISSED. func (c *LiveClient) DismissPullRequestReview(ctx context.Context, owner, repo string, number, reviewID int, message string) error { payload := map[string]string{ diff --git a/internal/forge/gitlab/mr.go b/internal/forge/gitlab/mr.go index deae0b99a8..b859ac8b9d 100644 --- a/internal/forge/gitlab/mr.go +++ b/internal/forge/gitlab/mr.go @@ -770,6 +770,13 @@ func (c *LiveClient) ListPullRequestReviews(ctx context.Context, owner, repo str return result, nil } +// ListPullRequestReviewThreads is not available as a portable GitLab +// equivalent. GitLab discussions do not expose the GitHub review-thread +// resolution contract used by the review agent. +func (c *LiveClient) ListPullRequestReviewThreads(_ context.Context, _ string, _ string, _ int) (forge.ReviewThreadPage, error) { + return forge.ReviewThreadPage{}, forge.ErrNotSupported +} + // DismissPullRequestReview dismisses a review on a merge request. // // On GitLab, if the review was an approval, this unapproves the MR. diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh index 89f14512f1..c9ddd69cd2 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh @@ -18,8 +18,8 @@ trap 'rm -rf "${TMPDIR}"' EXIT # --- Helpers --- -# build_mock creates a mock gh binary that returns a preconfigured -# GraphQL response. +# build_mock creates a mock fullsend binary that returns a normalized +# review-thread response from a preconfigured GraphQL-shaped fixture. # $1 — the JSON response to return (empty string = error) build_mock() { local response_json="$1" @@ -30,15 +30,31 @@ build_mock() { printf '%s' "${response_json}" > "${TMPDIR}/graphql-response.txt" - cat > "${mock_bin}/gh" <<'MOCKEOF' + cat > "${mock_bin}/fullsend" <<'MOCKEOF' #!/usr/bin/env bash RESPONSE_FILE="RESPONSE_PLACEHOLDER" -if [[ "$1" == "api" && "$2" == "graphql" ]]; then +if [[ "$1" == "fetch-review-threads" ]]; then if [[ ! -s "${RESPONSE_FILE}" ]]; then exit 1 fi - cat "${RESPONSE_FILE}" + jq -c '{threads: ([.data.repository.pullRequest.reviewThreads.nodes[] | + { + id, + is_resolved: .isResolved, + path, + line, + original_line: .originalLine, + resolved_by: (.resolvedBy.login // ""), + comments_truncated: (.comments.pageInfo.hasNextPage // false), + comments: [(.comments.nodes // [])[] | { + author: .author.login, + author_type: .author.__typename, + body, + created_at: .createdAt + }] + } + ]), truncated: false}' "${RESPONSE_FILE}" exit 0 fi @@ -46,8 +62,8 @@ exit 0 MOCKEOF local escaped="${TMPDIR//\//\\/}\/graphql-response.txt" - perl -pi -e "s/RESPONSE_PLACEHOLDER/${escaped}/g" "${mock_bin}/gh" - chmod +x "${mock_bin}/gh" + perl -pi -e "s/RESPONSE_PLACEHOLDER/${escaped}/g" "${mock_bin}/fullsend" + chmod +x "${mock_bin}/fullsend" echo "${mock_bin}" } @@ -89,6 +105,7 @@ run_test() { local exit_code=0 env \ PATH="${mock_bin}:${PATH}" \ + GITHUB_ACTIONS="true" \ GH_TOKEN="fake-token" \ ORG_NAME="test-org" \ PR_NUM="42" \ @@ -158,7 +175,7 @@ THREAD_HUMAN_RESOLVED='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: MarkHidden vs MarkDeprecated", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: MarkHidden vs MarkDeprecated", "createdAt": "2026-09-01T10:00:00Z"}, {"author": {"login": "alice", "__typename": "User"}, "body": "We explicitly asked for MarkHidden.", "createdAt": "2026-09-01T11:00:00Z"} ] } @@ -180,7 +197,7 @@ THREAD_BOT_RESOLVED='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: something", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: something", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' @@ -200,7 +217,7 @@ THREAD_UNRESOLVED='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: open issue", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: open issue", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' @@ -220,7 +237,7 @@ THREAD_WITH_FINDING_ID='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "\n**[logic-error]** Missing nil check", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "\n**[logic-error]** Missing nil check", "createdAt": "2026-09-01T10:00:00Z"}, {"author": {"login": "developer", "__typename": "User"}, "body": "Handled by the caller.", "createdAt": "2026-09-01T11:00:00Z"} ] } @@ -242,7 +259,7 @@ THREAD_SILENT='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: naming convention", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: naming convention", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh index 6987c3aaa7..07a1cf1df1 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # pre-fetch-resolved-threads.sh — Fetch human-resolved review threads before the review agent runs # -# Queries the PR's review threads via the GitHub GraphQL API and writes +# Queries the PR's review threads through the fullsend forge client and writes # a JSON file listing threads that a human explicitly resolved. The # review agent uses this to avoid re-raising findings that a person # already dismissed. @@ -17,113 +17,48 @@ # script writes an empty file and exits 0 so the review proceeds # without resolution data (current behavior preserved). # -# Required environment variables (set by the workflow): +# Required environment variables (set by the review agent): # # - GH_TOKEN — token with read access to the PR # - SOURCE_REPO — owner/repo (e.g., "fullsend-ai/fullsend") # - PR_NUM — PR number # - ORG_NAME — org name for bot identity filtering +# - FULLSEND_BIN — optional path to the fullsend CLI (defaults to fullsend) # # Outputs (via GITHUB_OUTPUT): # - human_resolved_file — path to the JSON file set -euo pipefail OUTPUT_FILE="${GITHUB_WORKSPACE:-/tmp}/human-resolved-threads.json" -REVIEW_BOT="${ORG_NAME}-review[bot]" -SHARED_REVIEW_BOT="fullsend-ai-review[bot]" - -OWNER="${SOURCE_REPO%%/*}" -NAME="${SOURCE_REPO##*/}" - -# --- GraphQL query --- -# Fetches review threads with resolution state, path, line, and comments. -# Paginated at 100 threads per page with a 20-page cap (matching the -# pattern in forge_resolve_outdated_review_threads from agents PR #1415). -QUERY='query($owner: String!, $name: String!, $number: Int!, $cursor: String) { - repository(owner: $owner, name: $name) { - pullRequest(number: $number) { - reviewThreads(first: 100, after: $cursor) { - pageInfo { hasNextPage endCursor } - nodes { - id - isResolved - path - line - originalLine - resolvedBy { login } - comments(first: 100) { - pageInfo { hasNextPage } - nodes { - author { login __typename } - body - createdAt - } - } - } - } - } - } -}' - -# --- Pagination --- -cursor="" -has_next="true" -page=0 -nodes_json="[]" -truncated="false" - -while [[ "${has_next}" == "true" ]]; do - page=$((page + 1)) - if [[ "${page}" -gt 20 ]]; then - echo "::warning::Resolved-threads pagination hit page cap — remaining threads skipped" - truncated="true" - break - fi - gh_args=(api graphql - -f owner="${OWNER}" - -f name="${NAME}" - -F number="${PR_NUM}" - -f query="${QUERY}") - if [[ -n "${cursor}" ]]; then - gh_args+=(-f cursor="${cursor}") - fi - - if ! response=$(gh "${gh_args[@]}" 2>/dev/null); then - echo "::warning::Failed to fetch review threads — writing empty resolved-threads file" - echo '{"resolved_threads":[],"metadata":{"error":"graphql_fetch_failed"}}' > "${OUTPUT_FILE}" - echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" - exit 0 - fi - - if echo "${response}" | jq -e '.errors | type == "array" and length > 0' >/dev/null 2>&1; then - echo "::warning::Review threads query returned errors — writing empty resolved-threads file" - echo '{"resolved_threads":[],"metadata":{"error":"graphql_errors"}}' > "${OUTPUT_FILE}" - echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" - exit 0 - fi - - page_nodes=$(echo "${response}" | jq -c '.data.repository.pullRequest.reviewThreads.nodes // []' 2>/dev/null) || { - echo "::warning::Failed to parse review threads — writing empty resolved-threads file" - echo '{"resolved_threads":[],"metadata":{"error":"parse_failed"}}' > "${OUTPUT_FILE}" - echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" - exit 0 - } +# This helper is intended for the review-agent pre-script. Local invocations +# and non-GitHub runners must not attempt a GitHub review-thread lookup. +if [[ "${GITHUB_ACTIONS:-}" != "true" ]]; then + printf '%s\n' '{"resolved_threads":[],"metadata":{"skipped":"not_github_actions"}}' > "${OUTPUT_FILE}" + echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" + exit 0 +fi - nodes_json=$(jq -c --argjson page "${page_nodes}" '. + $page' <<< "${nodes_json}" 2>/dev/null) || { - echo "::warning::Failed to merge review thread pages — writing empty resolved-threads file" - echo '{"resolved_threads":[],"metadata":{"error":"merge_failed"}}' > "${OUTPUT_FILE}" - echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" - exit 0 - } +REVIEW_BOT="${ORG_NAME}-review[bot]" +SHARED_REVIEW_BOT="fullsend-ai-review[bot]" +REVIEW_BOT_LOGIN="${ORG_NAME}-review" +SHARED_REVIEW_BOT_LOGIN="fullsend-ai-review" + +FULLSEND_BIN="${FULLSEND_BIN:-fullsend}" +if ! response=$("${FULLSEND_BIN}" fetch-review-threads --repo "${SOURCE_REPO}" --pr "${PR_NUM}" 2>/dev/null); then + echo "::warning::Failed to fetch review threads through forge client — writing empty resolved-threads file" + echo '{"resolved_threads":[],"metadata":{"error":"forge_fetch_failed"}}' > "${OUTPUT_FILE}" + echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" + exit 0 +fi - has_next=$(echo "${response}" | jq -r '.data.repository.pullRequest.reviewThreads.pageInfo.hasNextPage // false' 2>/dev/null) || has_next="false" - cursor=$(echo "${response}" | jq -r '.data.repository.pullRequest.reviewThreads.pageInfo.endCursor // empty' 2>/dev/null) || cursor="" - if [[ "${has_next}" == "true" && -z "${cursor}" ]]; then - echo "::warning::Review threads page missing cursor — stopping pagination" - break - fi -done +nodes_json=$(echo "${response}" | jq -c '.threads // []' 2>/dev/null) || { + echo "::warning::Failed to parse review threads — writing empty resolved-threads file" + echo '{"resolved_threads":[],"metadata":{"error":"parse_failed"}}' > "${OUTPUT_FILE}" + echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" + exit 0 +} +truncated=$(echo "${response}" | jq -r '.truncated // false' 2>/dev/null) || truncated="false" # --- Filter and transform --- # Select threads that: @@ -142,43 +77,51 @@ done # - resolution_context classification: explicit_dismissal when the # resolver left a comment, silent_resolution otherwise # -# GitHub GraphQL has no Actor/User.type (that is REST). Bots are -# __typename Bot on comment authors, and login ending in "[bot]" on -# resolvedBy (typed User in the schema even for GitHub Apps). +# The forge client normalizes the GraphQL actor type into author_type. Bots +# are author_type "Bot" on comments, while resolvedBy is filtered by the +# GitHub App login suffix. RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ --arg bot "${REVIEW_BOT}" \ --arg shared_bot "${SHARED_REVIEW_BOT}" \ + --arg bot_login "${REVIEW_BOT_LOGIN}" \ + --arg shared_bot_login "${SHARED_REVIEW_BOT_LOGIN}" \ '[.[] - | select(.isResolved == true) - | select(.resolvedBy != null) - | select(.resolvedBy.login != $bot and .resolvedBy.login != $shared_bot) - | select((.resolvedBy.login | endswith("[bot]")) | not) - | select((.comments.nodes // [] | length) > 0) - | select((.comments.pageInfo.hasNextPage // false) == false) - | .resolvedBy.login as $resolver + | select(.is_resolved == true) + | select(.resolved_by != null and .resolved_by != "") + | select(.resolved_by != $bot and .resolved_by != $shared_bot) + | select((.resolved_by | endswith("[bot]")) | not) + | select((.comments // [] | length) > 0) + | select((.comments_truncated // false) == false) + | .resolved_by as $resolver | { file: .path, line: .line, - original_line: .originalLine, + original_line: .original_line, resolved_by: $resolver, bot_finding_snippet: ( - [.comments.nodes[] | select(.author.login == $bot or .author.login == $shared_bot)] + [.comments[] + | select(.author_type == "Bot") + | select(.author == $bot_login or .author == $shared_bot_login or + .author == $bot or .author == $shared_bot)] | first // null | if . then (.body | .[0:200]) else null end ), finding_id: ( - [.comments.nodes[] | select(.author.login == $bot or .author.login == $shared_bot)] + [.comments[] + | select(.author_type == "Bot") + | select(.author == $bot_login or .author == $shared_bot_login or + .author == $bot or .author == $shared_bot)] | first // null | if . then (.body | capture("") // null | .id // null) else null end ), human_response: ( - [.comments.nodes[] | select(.author.login == $resolver)] + [.comments[] | select(.author == $resolver)] | last // null | if . then (.body | .[0:500]) else null end ), resolution_context: ( - if ([.comments.nodes[] | select(.author.login == $resolver)] | length) > 0 + if ([.comments[] | select(.author == $resolver)] | length) > 0 then "explicit_dismissal" else "silent_resolution" end From 8416cd30eb1f236f639c1ba4a12bc9053fae8c59 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Sun, 4 Oct 2026 14:50:23 +0300 Subject: [PATCH 05/18] test(review): cover resolved thread fetching Add coverage for GitHub GraphQL review-thread pagination and errors, CLI output and validation, and forge fallback implementations. Co-authored-by: Codex Signed-off-by: csoceanu --- internal/cli/fetchreviewthreads.go | 3 +- internal/cli/fetchreviewthreads_test.go | 67 ++++++++++ internal/forge/fake_test.go | 21 +++ internal/forge/github/review_threads_test.go | 132 +++++++++++++++++++ internal/forge/gitlab/methods_test.go | 7 + 5 files changed, 228 insertions(+), 2 deletions(-) create mode 100644 internal/cli/fetchreviewthreads_test.go create mode 100644 internal/forge/github/review_threads_test.go diff --git a/internal/cli/fetchreviewthreads.go b/internal/cli/fetchreviewthreads.go index 7f82c86437..e02b88c2fa 100644 --- a/internal/cli/fetchreviewthreads.go +++ b/internal/cli/fetchreviewthreads.go @@ -3,7 +3,6 @@ package cli import ( "encoding/json" "fmt" - "os" "strings" "github.com/spf13/cobra" @@ -39,7 +38,7 @@ func newFetchReviewThreadsCmd() *cobra.Command { if err != nil { return err } - return json.NewEncoder(os.Stdout).Encode(threads) + return json.NewEncoder(cmd.OutOrStdout()).Encode(threads) }, } diff --git a/internal/cli/fetchreviewthreads_test.go b/internal/cli/fetchreviewthreads_test.go new file mode 100644 index 0000000000..e1410cce21 --- /dev/null +++ b/internal/cli/fetchreviewthreads_test.go @@ -0,0 +1,67 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestFetchReviewThreadsCommand(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodPost, r.Method) + assert.Equal(t, "/api/v3/graphql", r.URL.Path) + _, _ = w.Write([]byte(`{"data":{"repository":{"pullRequest":{"reviewThreads":{"pageInfo":{"hasNextPage":false,"endCursor":""},"nodes":[{"id":"thread-1","isResolved":true,"path":"main.go","line":12,"originalLine":11,"resolvedBy":{"login":"reviewer"},"comments":{"pageInfo":{"hasNextPage":false},"nodes":[]}}]}}}}}`)) + })) + defer srv.Close() + + var output bytes.Buffer + cmd := newFetchReviewThreadsCmd() + cmd.SetOut(&output) + cmd.SetErr(&output) + cmd.SetArgs([]string{"--repo", "owner/repo", "--pr", "42", "--token", "test-token", "--base-url", srv.URL}) + cmd.SetContext(context.Background()) + + // The forge client owns its HTTP transport, so point the GitHub client at + // the TLS test server through the environment used by the command factory. + // The command's client uses the default transport; install the test server's + // transport for the duration of this test. + oldTransport := http.DefaultTransport + http.DefaultTransport = srv.Client().Transport + t.Cleanup(func() { http.DefaultTransport = oldTransport }) + + require.NoError(t, cmd.Execute()) + var got forge.ReviewThreadPage + require.NoError(t, json.Unmarshal(output.Bytes(), &got)) + require.Len(t, got.Threads, 1) + assert.Equal(t, "thread-1", got.Threads[0].ID) + assert.True(t, got.Threads[0].IsResolved) +} + +func TestFetchReviewThreadsCommand_ValidatesFlags(t *testing.T) { + tests := []struct { + name string + args []string + want string + }{ + {name: "non-positive pull request", args: []string{"--repo", "owner/repo", "--pr", "0"}, want: "positive integer"}, + {name: "invalid repository", args: []string{"--repo", "owner", "--pr", "1"}, want: "owner/repo format"}, + {name: "unsupported forge", args: []string{"--repo", "owner/repo", "--pr", "1", "--forge", "bitbucket", "--token", "token"}, want: "unsupported forge"}, + {name: "gitlab review threads unsupported", args: []string{"--repo", "owner/repo", "--pr", "1", "--forge", "gitlab", "--token", "token", "--base-url", "https://gitlab.example.com"}, want: "not supported"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cmd := newFetchReviewThreadsCmd() + cmd.SetArgs(tt.args) + err := cmd.Execute() + require.Error(t, err) + assert.Contains(t, err.Error(), tt.want) + }) + } +} diff --git a/internal/forge/fake_test.go b/internal/forge/fake_test.go index 07baf1c2bf..70e743bbc6 100644 --- a/internal/forge/fake_test.go +++ b/internal/forge/fake_test.go @@ -31,6 +31,27 @@ func TestFakeClient_ListPullRequestCommits(t *testing.T) { require.Error(t, err) } +func TestFakeClient_ListPullRequestReviewThreads(t *testing.T) { + page := ReviewThreadPage{ + Threads: []ReviewThread{{ID: "thread-1", IsResolved: true, Path: "main.go"}}, + Truncated: true, + } + f := NewFakeClient() + f.PRReviewThreads = map[string]ReviewThreadPage{"o/r/7": page} + + got, err := f.ListPullRequestReviewThreads(context.Background(), "o", "r", 7) + require.NoError(t, err) + assert.Equal(t, page, got) + + got, err = f.ListPullRequestReviewThreads(context.Background(), "o", "r", 8) + require.NoError(t, err) + assert.Empty(t, got.Threads) + + f.Errors["ListPullRequestReviewThreads"] = errors.New("boom") + _, err = f.ListPullRequestReviewThreads(context.Background(), "o", "r", 7) + require.Error(t, err) +} + func TestFakeClient_ListOrgRepos(t *testing.T) { ctx := context.Background() fc := &FakeClient{ diff --git a/internal/forge/github/review_threads_test.go b/internal/forge/github/review_threads_test.go new file mode 100644 index 0000000000..e41e7f6111 --- /dev/null +++ b/internal/forge/github/review_threads_test.go @@ -0,0 +1,132 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestListPullRequestReviewThreads(t *testing.T) { + line := 17 + originalLine := 16 + var request map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "/graphql", r.URL.Path) + require.Equal(t, "Bearer test-token", r.Header.Get("Authorization")) + require.NoError(t, json.NewDecoder(r.Body).Decode(&request)) + json.NewEncoder(w).Encode(map[string]any{ + "data": map[string]any{ + "repository": map[string]any{ + "pullRequest": map[string]any{ + "reviewThreads": map[string]any{ + "pageInfo": map[string]any{"hasNextPage": false, "endCursor": ""}, + "nodes": []any{ + map[string]any{ + "id": "PRRT_1", "isResolved": true, "path": "main.go", + "line": line, "originalLine": originalLine, + "resolvedBy": map[string]any{"login": "reviewer"}, + "comments": map[string]any{ + "pageInfo": map[string]any{"hasNextPage": true}, + "nodes": []any{map[string]any{ + "author": map[string]any{"login": "reviewer", "__typename": "User"}, + "body": "please update this", "createdAt": "2026-10-04T10:00:00Z", + }}, + }, + }, + map[string]any{ + "id": "PRRT_2", "isResolved": false, "path": "README.md", + "line": nil, "originalLine": nil, "resolvedBy": nil, + "comments": map[string]any{"pageInfo": map[string]any{"hasNextPage": false}, "nodes": []any{}}, + }, + }, + }, + }, + }, + }, + }) + })) + defer srv.Close() + + got, err := newTestClient(t, srv).ListPullRequestReviewThreads(context.Background(), "owner", "repo", 42) + require.NoError(t, err) + assert.Equal(t, "owner", request["variables"].(map[string]any)["owner"]) + assert.Equal(t, "repo", request["variables"].(map[string]any)["name"]) + assert.Equal(t, float64(42), request["variables"].(map[string]any)["number"]) + assert.Len(t, got.Threads, 2) + assert.Equal(t, forge.ReviewThread{ + ID: "PRRT_1", IsResolved: true, Path: "main.go", Line: &line, + OriginalLine: &originalLine, ResolvedBy: "reviewer", + Comments: []forge.ReviewThreadComment{{ + Author: "reviewer", AuthorType: "User", Body: "please update this", CreatedAt: "2026-10-04T10:00:00Z", + }}, CommentsTruncated: true, + }, got.Threads[0]) + assert.Nil(t, got.Threads[1].Line) + assert.Empty(t, got.Threads[1].ResolvedBy) +} + +func TestListPullRequestReviewThreads_PaginatesAndCaps(t *testing.T) { + var calls int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + var body struct { + Variables struct { + Cursor *string `json:"cursor"` + } `json:"variables"` + } + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + if calls == 1 { + assert.Nil(t, body.Variables.Cursor) + } else { + require.NotNil(t, body.Variables.Cursor) + assert.Equal(t, fmt.Sprintf("cursor-%d", calls-1), *body.Variables.Cursor) + } + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"repository": map[string]any{ + "pullRequest": map[string]any{"reviewThreads": map[string]any{ + "pageInfo": map[string]any{"hasNextPage": true, "endCursor": fmt.Sprintf("cursor-%d", calls)}, + "nodes": []any{map[string]any{"id": fmt.Sprintf("thread-%d", calls), "comments": map[string]any{"pageInfo": map[string]any{"hasNextPage": false}, "nodes": []any{}}}}, + }}, + }}}) + })) + defer srv.Close() + + got, err := newTestClient(t, srv).ListPullRequestReviewThreads(context.Background(), "owner", "repo", 1) + require.NoError(t, err) + assert.Equal(t, 20, calls) + assert.True(t, got.Truncated) + assert.Len(t, got.Threads, 20) +} + +func TestListPullRequestReviewThreads_Errors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {name: "graphql error", status: http.StatusOK, body: `{"errors":[{"message":"forbidden"}]}`, wantErr: "forbidden"}, + {name: "invalid json", status: http.StatusOK, body: `{`, wantErr: "decode pull request review threads"}, + {name: "missing cursor", status: http.StatusOK, body: `{"data":{"repository":{"pullRequest":{"reviewThreads":{"pageInfo":{"hasNextPage":true,"endCursor":""},"nodes":[]}}}}}`, wantErr: "missing pagination cursor"}, + {name: "http error", status: http.StatusForbidden, body: `{"message":"denied"}`, wantErr: "page 1"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(tt.status) + _, _ = w.Write([]byte(tt.body)) + })) + defer srv.Close() + + _, err := newTestClient(t, srv).ListPullRequestReviewThreads(context.Background(), "o", "r", 1) + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + }) + } +} diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index d1571dc50b..bcdb48fccd 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -471,6 +471,13 @@ func TestMinimizeComment(t *testing.T) { require.ErrorIs(t, err, forge.ErrNotSupported) } +func TestListPullRequestReviewThreads_NotSupported(t *testing.T) { + client, _ := setupTest(t) + + _, err := client.ListPullRequestReviewThreads(context.Background(), "myorg", "myrepo", 42) + require.ErrorIs(t, err, forge.ErrNotSupported) +} + // --------------------------------------------------------------------------- // mr.go tests // --------------------------------------------------------------------------- From 6d2da39ee9ef9e7631de880f854684003eaeeba7 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Mon, 5 Oct 2026 09:52:25 +0300 Subject: [PATCH 06/18] test(review): normalize bot fixture identities Use GraphQL-shaped unsuffixed bot logins for comment fixtures while retaining suffixed resolver fixtures for exclusion coverage. Co-authored-by: Codex Signed-off-by: csoceanu --- .../scripts/pre-fetch-resolved-threads-test.sh | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh index c9ddd69cd2..e1d5f6f371 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh @@ -279,7 +279,7 @@ THREAD_MIXED='[ "originalLine": 1, "resolvedBy": {"login": "human1", "__typename": "User"}, "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding 1", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding 1", "createdAt": "2026-09-01T10:00:00Z"} ]} }, { @@ -290,7 +290,7 @@ THREAD_MIXED='[ "originalLine": 2, "resolvedBy": null, "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding 2", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding 2", "createdAt": "2026-09-01T10:00:00Z"} ]} }, { @@ -301,7 +301,7 @@ THREAD_MIXED='[ "originalLine": 3, "resolvedBy": {"login": "test-org-review[bot]", "__typename": "Bot"}, "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding 3", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding 3", "createdAt": "2026-09-01T10:00:00Z"} ]} }, { @@ -312,7 +312,7 @@ THREAD_MIXED='[ "originalLine": 4, "resolvedBy": {"login": "human2", "__typename": "User"}, "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding 4", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding 4", "createdAt": "2026-09-01T10:00:00Z"}, {"author": {"login": "human2", "__typename": "User"}, "body": "Not applicable.", "createdAt": "2026-09-01T11:00:00Z"} ]} } @@ -338,7 +338,7 @@ THREAD_SHARED_BOT_RESOLVED='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "fullsend-ai-review[bot]", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "fullsend-ai-review", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' @@ -364,7 +364,7 @@ THREAD_INCOMPLETE_COMMENTS='[{ "comments": { "pageInfo": {"hasNextPage": true}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' @@ -384,7 +384,7 @@ THREAD_DEPENDABOT_RESOLVED='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} ] } }]' @@ -406,7 +406,7 @@ THREAD_DIFFERENT_COMMENTER='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: something wrong", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: something wrong", "createdAt": "2026-09-01T10:00:00Z"}, {"author": {"login": "bob", "__typename": "User"}, "body": "I will fix this.", "createdAt": "2026-09-01T11:00:00Z"} ] } @@ -428,7 +428,7 @@ THREAD_RESOLVER_COMMENTED='[{ "comments": { "pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review[bot]", "__typename": "Bot"}, "body": "Finding: issue here", "createdAt": "2026-09-01T10:00:00Z"}, + {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: issue here", "createdAt": "2026-09-01T10:00:00Z"}, {"author": {"login": "bob", "__typename": "User"}, "body": "I think this is fine.", "createdAt": "2026-09-01T10:30:00Z"}, {"author": {"login": "alice", "__typename": "User"}, "body": "Intentional, closing.", "createdAt": "2026-09-01T11:00:00Z"} ] From 6dcaecebcfd1f8ecec809907a6ababd5af505309 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 10:21:16 +0300 Subject: [PATCH 07/18] fix(review): detect CLI install mode from checkout Filter resolved review threads to Fullsend findings, honor custom review bot identities, document fetch-review-threads, and cover the workflow install-mode wiring. Co-authored-by: Codex Signed-off-by: csoceanu --- .github/workflows/reusable-dispatch.yml | 14 +- docs/guides/dev/cli-internals.md | 11 + .../pre-fetch-resolved-threads-test.sh | 50 ++- .../scripts/pre-fetch-resolved-threads.sh | 19 +- .../scaffold/workflow_call_alignment_test.go | 359 ++++++++++++++++-- 5 files changed, 412 insertions(+), 41 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 93638598e1..6f57dadada 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -945,11 +945,22 @@ jobs: repos: ${{ steps.workspace.outputs.repo_name }} mint_url: ${{ inputs.mint_url }} + - name: Detect review CLI install mode + id: review-cli-mode + shell: bash + run: | + set -euo pipefail + if [[ -f .defaults/action.yml || -f .fullsend/.defaults/action.yml ]]; then + echo "mode=vendored" >> "${GITHUB_OUTPUT}" + else + echo "mode=upstream" >> "${GITHUB_OUTPUT}" + fi + - name: Install fullsend CLI for review context id: install-fullsend uses: ./.defaults/.github/actions/install-fullsend-cli with: - mode: ${{ inputs.install_mode == 'per-repo' && 'vendored' || 'upstream' }} + mode: ${{ steps.review-cli-mode.outputs.mode }} vendored_path: .fullsend/bin/fullsend workflow_repository: ${{ job.workflow_repository }} workflow_sha: ${{ job.workflow_sha }} @@ -987,6 +998,7 @@ jobs: ${{ fromJSON(needs.route.outputs.event_payload).pull_request.number || fromJSON(needs.route.outputs.event_payload).issue.number }} ORG_NAME: ${{ github.repository_owner }} + FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }} FULLSEND_BIN: ${{ steps.install-fullsend.outputs.fullsend-path }} FULLSEND_DIR: ${{ inputs.install_mode == 'per-repo' && '.fullsend' || '' }} run: bash "${FULLSEND_DIR:+$FULLSEND_DIR/}scripts/pre-fetch-resolved-threads.sh" diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index ea1d05786d..6b354b202d 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -169,6 +169,12 @@ fullsend │ ├── --dry-run # Print what would be posted without API calls │ ├── --keep-history # Append previous content as collapsed history (default true) │ └── --fullsend-dir # .fullsend config directory (default: $FULLSEND_DIR; resolves keep_history default) +├── fetch-review-threads # Fetch PR/MR review threads as JSON +│ ├── --repo # Repository in owner/repo format (required) +│ ├── --pr # Pull request / merge request number (required) +│ ├── --forge # Forge backend: github (default) or gitlab +│ ├── --token # Forge token (default: forge environment token) +│ └── --base-url # Forge API base URL ├── post-comment # Post issue/PR comments to GitHub (deprecated) │ └── --token # GitHub token (default: $GH_TOKEN / $GITHUB_TOKEN / gh auth token) ├── eval-measure # Score wild-run traces (eval measurements) @@ -206,6 +212,11 @@ fullsend ### Command Decomposition +`fetch-review-threads` emits a JSON object containing `threads` and a +`truncated` flag. GitHub review threads are capped at 20 pages; consumers +must treat `truncated: true` as an incomplete result. GitLab does not +support this operation and returns an unsupported-operation error. + The `mint`, `inference`, and `github` subcommands decompose setup into role-specific operations for organizations that separate GCP and GitHub responsibilities: | Install Phase | Standalone Command | Required Access | diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh index e1d5f6f371..aba4c60a23 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh @@ -93,6 +93,7 @@ run_test() { local graphql_response="$2" local expected_count="$3" local extra_check="${4:-}" # optional jq expression to validate output + local app_set="${5:-}" # optional FULLSEND_APP_SET identity local mock_bin mock_bin="$(build_mock "${graphql_response}")" @@ -110,6 +111,7 @@ run_test() { ORG_NAME="test-org" \ PR_NUM="42" \ SOURCE_REPO="test-org/test-repo" \ + FULLSEND_APP_SET="${app_set}" \ GITHUB_OUTPUT="${github_output}" \ GITHUB_WORKSPACE="${workspace}" \ bash "${SCRIPT}" > "${TMPDIR}/stdout.log" 2>&1 || exit_code=$? @@ -393,7 +395,49 @@ run_test "other-bot-resolved-excluded" \ "$(make_graphql_response "${THREAD_DEPENDABOT_RESOLVED}")" \ 0 -# 13. Resolver's comment is used, not another human's. +# 13. Human-only resolved threads are not review findings. +THREAD_HUMAN_ONLY='[{ + "id": "T_HUMAN_ONLY", + "isResolved": true, + "path": "human.go", + "line": 11, + "originalLine": 11, + "resolvedBy": {"login": "alice", "__typename": "User"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "alice", "__typename": "User"}, "body": "Not a bot finding", "createdAt": "2026-09-01T10:00:00Z"} + ] + } +}]' + +run_test "human-only-resolved-excluded" \ + "$(make_graphql_response "${THREAD_HUMAN_ONLY}")" \ + 0 + +# 14. Custom Fullsend App-set bot identities are recognized. +THREAD_CUSTOM_APP='[{ + "id": "T_CUSTOM_APP", + "isResolved": true, + "path": "custom.go", + "line": 12, + "originalLine": 12, + "resolvedBy": {"login": "alice", "__typename": "User"}, + "comments": { + "pageInfo": {"hasNextPage": false}, + "nodes": [ + {"author": {"login": "custom-review", "__typename": "Bot"}, "body": "", "createdAt": "2026-09-01T10:00:00Z"} + ] + } +}]' + +run_test "custom-app-set-finding-id" \ + "$(make_graphql_response "${THREAD_CUSTOM_APP}")" \ + 1 \ + '.resolved_threads[0].finding_id == "f_custom"' \ + "custom" + +# 15. Resolver's comment is used, not another human's. # Bob comments but Alice resolves — human_response should be from # Alice (the resolver), and if Alice didn't comment it's silent. THREAD_DIFFERENT_COMMENTER='[{ @@ -417,7 +461,7 @@ run_test "different-commenter-silent-resolution" \ 1 \ '.resolved_threads[0].resolution_context == "silent_resolution" and .resolved_threads[0].human_response == null' -# 14. Resolver left a comment — should be explicit_dismissal with their text. +# 16. Resolver left a comment — should be explicit_dismissal with their text. THREAD_RESOLVER_COMMENTED='[{ "id": "T_14", "isResolved": true, @@ -440,7 +484,7 @@ run_test "resolver-commented-explicit-dismissal" \ 1 \ '.resolved_threads[0].resolution_context == "explicit_dismissal" and .resolved_threads[0].human_response == "Intentional, closing."' -# 15. Metadata includes truncated flag (false when under page cap). +# 17. Metadata includes truncated flag (false when under page cap). run_test "metadata-truncated-false" \ "$(make_graphql_response "${THREAD_HUMAN_RESOLVED}")" \ 1 \ diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh index 07a1cf1df1..c51243033a 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh @@ -43,6 +43,12 @@ REVIEW_BOT="${ORG_NAME}-review[bot]" SHARED_REVIEW_BOT="fullsend-ai-review[bot]" REVIEW_BOT_LOGIN="${ORG_NAME}-review" SHARED_REVIEW_BOT_LOGIN="fullsend-ai-review" +APP_SET_REVIEW_BOT="" +APP_SET_REVIEW_BOT_LOGIN="" +if [[ -n "${FULLSEND_APP_SET:-}" ]]; then + APP_SET_REVIEW_BOT="${FULLSEND_APP_SET}-review[bot]" + APP_SET_REVIEW_BOT_LOGIN="${FULLSEND_APP_SET}-review" +fi FULLSEND_BIN="${FULLSEND_BIN:-fullsend}" if ! response=$("${FULLSEND_BIN}" fetch-review-threads --repo "${SOURCE_REPO}" --pr "${PR_NUM}" 2>/dev/null); then @@ -86,6 +92,8 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ --arg shared_bot "${SHARED_REVIEW_BOT}" \ --arg bot_login "${REVIEW_BOT_LOGIN}" \ --arg shared_bot_login "${SHARED_REVIEW_BOT_LOGIN}" \ + --arg app_set_bot "${APP_SET_REVIEW_BOT}" \ + --arg app_set_bot_login "${APP_SET_REVIEW_BOT_LOGIN}" \ '[.[] | select(.is_resolved == true) | select(.resolved_by != null and .resolved_by != "") @@ -93,6 +101,11 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ | select((.resolved_by | endswith("[bot]")) | not) | select((.comments // [] | length) > 0) | select((.comments_truncated // false) == false) + | select(any(.comments[]; + .author_type == "Bot" and + (.author == $bot_login or .author == $shared_bot_login or + .author == $app_set_bot_login or .author == $bot or + .author == $shared_bot or .author == $app_set_bot))) | .resolved_by as $resolver | { file: .path, @@ -103,7 +116,8 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ [.comments[] | select(.author_type == "Bot") | select(.author == $bot_login or .author == $shared_bot_login or - .author == $bot or .author == $shared_bot)] + .author == $app_set_bot_login or .author == $bot or + .author == $shared_bot or .author == $app_set_bot)] | first // null | if . then (.body | .[0:200]) else null end ), @@ -111,7 +125,8 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ [.comments[] | select(.author_type == "Bot") | select(.author == $bot_login or .author == $shared_bot_login or - .author == $bot or .author == $shared_bot)] + .author == $app_set_bot_login or .author == $bot or + .author == $shared_bot or .author == $app_set_bot)] | first // null | if . then (.body | capture("") // null | .id // null) else null end ), diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 5244dc218d..a501ca1f85 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -65,6 +65,26 @@ type stageConcurrencyExpectation struct { } var thinCallerConcurrencyExpectations = map[string]stageConcurrencyExpectation{ + "triage": { + groupPrefix: "fullsend-triage-", + groupMust: []string{"inputs.source_repo", "issue.number"}, + }, + "code": { + groupPrefix: "fullsend-code-", + groupMust: []string{"inputs.source_repo", "issue.number"}, + }, + "review": { + groupPrefix: "fullsend-review-", + groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number"}, + }, + "fix": { + groupPrefix: "fullsend-fix-", + groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number", "inputs.pr_number"}, + }, + "retro": { + groupPrefix: "fullsend-retro-", + groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number"}, + }, "prioritize": { groupPrefix: "fullsend-prioritize-", groupMust: []string{"inputs.source_repo", "issue.number"}, @@ -72,6 +92,26 @@ var thinCallerConcurrencyExpectations = map[string]stageConcurrencyExpectation{ } var reusableAgentConcurrencyExpectations = map[string]stageConcurrencyExpectation{ + "triage": { + groupPrefix: "fullsend-triage-agent-", + groupMust: []string{"inputs.source_repo", "issue.number", "pull_request.number"}, + }, + "code": { + groupPrefix: "fullsend-code-agent-", + groupMust: []string{"inputs.source_repo", "issue.number", "pull_request.number"}, + }, + "review": { + groupPrefix: "fullsend-review-agent-", + groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number"}, + }, + "fix": { + groupPrefix: "fullsend-fix-agent-", + groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number", "inputs.pr_number"}, + }, + "retro": { + groupPrefix: "fullsend-retro-agent-", + groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number"}, + }, "prioritize": { groupPrefix: "fullsend-prioritize-agent-", groupMust: []string{"inputs.source_repo", "issue.number", "pull_request.number"}, @@ -146,6 +186,11 @@ type callerPair struct { } var workflowCallPairs = []callerPair{ + {"scaffold/triage.yml", loadRenderedScaffoldCaller(".github/workflows/triage.yml"), "triage"}, + {"scaffold/code.yml", loadRenderedScaffoldCaller(".github/workflows/code.yml"), "code"}, + {"scaffold/review.yml", loadRenderedScaffoldCaller(".github/workflows/review.yml"), "review"}, + {"scaffold/fix.yml", loadRenderedScaffoldCaller(".github/workflows/fix.yml"), "fix"}, + {"scaffold/retro.yml", loadRenderedScaffoldCaller(".github/workflows/retro.yml"), "retro"}, {"scaffold/prioritize.yml", loadRenderedScaffoldCaller(".github/workflows/prioritize.yml"), "prioritize"}, } @@ -154,7 +199,7 @@ func loadRenderedScaffoldCaller(path string) func(t *testing.T) []byte { t.Helper() raw, err := FullsendRepoFile(path) require.NoError(t, err) - rendered, err := RenderTemplate(path, raw, RenderOptionsForInstall(false, "", "")) + rendered, err := RenderTemplate(path, raw, RenderOptionsForInstall(false, false, "", "")) require.NoError(t, err) return rendered } @@ -250,9 +295,17 @@ func TestReusableWorkflowInputContractAlignment(t *testing.T) { var dispatch reusableWorkflow require.NoError(t, yaml.Unmarshal(dispatchContent, &dispatch)) - for _, stageName := range []string{"prioritize"} { - match := fmt.Sprintf("reusable-%s.yml", stageName) - t.Run(match, func(t *testing.T) { + for _, pair := range workflowCallPairs { + t.Run(pair.callerName, func(t *testing.T) { + callerContent := pair.callerSource(t) + var caller callerWorkflow + require.NoError(t, yaml.Unmarshal(callerContent, &caller)) + + job, ok := caller.Jobs[pair.jobName] + require.True(t, ok, "job %q not found in caller workflow", pair.jobName) + match := reusableWorkflowRef.FindString(job.Uses) + require.NotEmpty(t, match, "could not extract reusable workflow filename from uses: %q", job.Uses) + stageContent, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", match)) require.NoError(t, err, "could not read reusable workflow %s", match) @@ -265,6 +318,16 @@ func TestReusableWorkflowInputContractAlignment(t *testing.T) { continue } if name == "install_mode" { + // Dispatch defaults to per-repo; standalone stage workflows + // default to per-org until that deprecated chain is removed. + assert.False(t, dispatchInput.Required, + "reusable-dispatch.yml install_mode must remain optional") + assert.Equal(t, "per-repo", dispatchInput.Default, + "reusable-dispatch.yml install_mode default changed") + assert.False(t, stageInput.Required, + "%s install_mode must remain optional", match) + assert.Equal(t, "per-org", stageInput.Default, + "%s install_mode default changed", match) continue } assert.Equal(t, dispatchInput.Required, stageInput.Required, @@ -290,6 +353,7 @@ func TestReusableWorkflowsShareCommonInputs(t *testing.T) { "mint_url", "gcp_region", "fullsend_version", + "install_mode", "fullsend_ai_ref", "runner_image", } @@ -302,7 +366,7 @@ func TestReusableWorkflowsShareCommonInputs(t *testing.T) { "OTEL_EXPORTER_OTLP_HEADERS", } - stages := []string{"prioritize"} + stages := []string{"triage", "code", "review", "fix", "retro", "prioritize"} for _, stage := range stages { t.Run(stage, func(t *testing.T) { @@ -418,6 +482,11 @@ func TestOpenAIAPIKeySecretThreading(t *testing.T) { content func(t *testing.T) []byte }{ {"scaffold/templates/shim-per-repo.yaml", loadScaffoldFile("templates/shim-per-repo.yaml")}, + {"scaffold/triage.yml", loadScaffoldFile(".github/workflows/triage.yml")}, + {"scaffold/code.yml", loadScaffoldFile(".github/workflows/code.yml")}, + {"scaffold/review.yml", loadScaffoldFile(".github/workflows/review.yml")}, + {"scaffold/fix.yml", loadScaffoldFile(".github/workflows/fix.yml")}, + {"scaffold/retro.yml", loadScaffoldFile(".github/workflows/retro.yml")}, {"scaffold/prioritize.yml", loadScaffoldFile(".github/workflows/prioritize.yml")}, // This repo's own installed shims (not just the scaffold templates // new installs get) must forward the secret too, or fullsend's own @@ -435,9 +504,9 @@ func TestOpenAIAPIKeySecretThreading(t *testing.T) { declaration := "FULLSEND_OPENAI_API_KEY:\n required: false" export := "OPENAI_API_KEY: ${{ secrets.FULLSEND_OPENAI_API_KEY }}" - // The standalone reusable-prioritize.yml has exactly one job/one agent - // step, so a whole-file substring check is unambiguous. - standaloneStages := []string{"prioritize"} + // Standalone reusable-{stage}.yml files have exactly one job/one agent + // step each, so a whole-file substring check is unambiguous. + standaloneStages := []string{"triage", "code", "review", "fix", "retro", "prioritize"} for _, stage := range standaloneStages { t.Run("reusable-"+stage+".yml", func(t *testing.T) { content := string(loadRepoFile(fmt.Sprintf(".github/workflows/reusable-%s.yml", stage))(t)) @@ -477,8 +546,8 @@ func TestOpenAIAPIKeySecretThreading(t *testing.T) { } // TestOTELHeadersSecretThreading validates that the optional OTLP headers -// secrets (#2862, #5886) are forwarded by the scaffold callers and injected -// by every reusable stage workflow. TestWorkflowCallInputAlignment only +// secrets (#2862, #5886) are forwarded along both installation-mode chains +// to every reusable stage workflow. TestWorkflowCallInputAlignment only // enforces required secrets; an omitted optional forward silently arrives // empty, which turns into a 401 at authenticated backends instead of // failing loudly. @@ -494,7 +563,17 @@ func TestOTELHeadersSecretThreading(t *testing.T) { }{ // per-repo chain: shim → reusable-dispatch {"scaffold/templates/shim-per-repo.yaml", loadScaffoldFile("templates/shim-per-repo.yaml")}, - // standalone reusable-{stage} workflows (prioritize thin caller chain) + // per-org chain: thin caller → reusable-{stage} + {"reusable-triage.yml", loadRepoFile(".github/workflows/reusable-triage.yml")}, + {"scaffold/triage.yml", loadScaffoldFile(".github/workflows/triage.yml")}, + {"reusable-code.yml", loadRepoFile(".github/workflows/reusable-code.yml")}, + {"scaffold/code.yml", loadScaffoldFile(".github/workflows/code.yml")}, + {"reusable-review.yml", loadRepoFile(".github/workflows/reusable-review.yml")}, + {"scaffold/review.yml", loadScaffoldFile(".github/workflows/review.yml")}, + {"reusable-fix.yml", loadRepoFile(".github/workflows/reusable-fix.yml")}, + {"scaffold/fix.yml", loadScaffoldFile(".github/workflows/fix.yml")}, + {"reusable-retro.yml", loadRepoFile(".github/workflows/reusable-retro.yml")}, + {"scaffold/retro.yml", loadScaffoldFile(".github/workflows/retro.yml")}, {"reusable-prioritize.yml", loadRepoFile(".github/workflows/reusable-prioritize.yml")}, {"scaffold/prioritize.yml", loadScaffoldFile(".github/workflows/prioritize.yml")}, } @@ -557,8 +636,8 @@ func TestOTELVariableForwarding(t *testing.T) { return v + ": ${{ vars." + v + " }}" } - // Standalone reusable stage workflows (single agent step each). - stages := []string{"prioritize"} + // Reusable stage workflows (single agent step each). + stages := []string{"triage", "code", "review", "fix", "retro", "prioritize"} for _, stage := range stages { t.Run("reusable-"+stage+".yml", func(t *testing.T) { content := string(loadRepoFile(fmt.Sprintf(".github/workflows/reusable-%s.yml", stage))(t)) @@ -639,8 +718,7 @@ func TestReusableAgentWorkflowConcurrency(t *testing.T) { assert.True(t, wf.Concurrency.CancelInProgress, "reusable-%s.yml should cancel in-progress runs", stage) - callerExpect := dispatchStageConcurrencyExpectations[stage] - require.NotEmpty(t, callerExpect.groupPrefix, "missing dispatch expectation for %s", stage) + callerExpect := thinCallerConcurrencyExpectations[stage] assert.NotEqual(t, callerExpect.groupPrefix, expect.groupPrefix, "reusable-%s.yml must use a distinct agent-scoped group prefix", stage) assert.Contains(t, wf.Concurrency.Group, "-agent-", @@ -650,7 +728,7 @@ func TestReusableAgentWorkflowConcurrency(t *testing.T) { } // TestThinCallerStageConcurrency validates per-role cancel-in-progress groups on -// thin caller workflows in the scaffold (#981, ADR 0033). +// per-org thin caller workflows in the scaffold (#981, ADR 0033). func TestThinCallerStageConcurrency(t *testing.T) { for stage, expect := range thinCallerConcurrencyExpectations { t.Run(stage, func(t *testing.T) { @@ -672,7 +750,7 @@ func TestThinCallerStageConcurrency(t *testing.T) { } // TestReusableDispatchWorkflowContent validates PR-context gating in per-repo -// reusable-dispatch.yml routing. +// reusable-dispatch.yml routing (per-org dispatch.yml unchanged). func TestReusableDispatchWorkflowContent(t *testing.T) { content, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "reusable-dispatch.yml")) require.NoError(t, err) @@ -683,7 +761,9 @@ func TestReusableDispatchWorkflowContent(t *testing.T) { // TestCustomAppSetReviewBotWiring ensures every GitHub review/fix dispatch // path receives the configured app-set prefix and recognizes its exact review -// bot identity. +// bot identity. The scaffold dispatch workflow is a legacy, deprecated +// per-org compatibility path retained only until ADR 0044 removal; workflow +// parity requires it to stay aligned with the supported per-repo path. func TestCustomAppSetReviewBotWiring(t *testing.T) { cases := []struct { name string @@ -691,6 +771,9 @@ func TestCustomAppSetReviewBotWiring(t *testing.T) { assertCustom bool }{ {"reusable-dispatch", loadRepoFile(".github/workflows/reusable-dispatch.yml"), true}, + {"reusable-fix", loadRepoFile(".github/workflows/reusable-fix.yml"), true}, + {"reusable-review", loadRepoFile(".github/workflows/reusable-review.yml"), false}, + {"scaffold-dispatch", loadScaffoldFile(".github/workflows/dispatch.yml"), true}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -707,6 +790,7 @@ func TestCustomAppSetReviewBotWiring(t *testing.T) { content func(*testing.T) []byte }{ {"reusable-dispatch", loadRepoFile(".github/workflows/reusable-dispatch.yml")}, + {"scaffold-dispatch", loadScaffoldFile(".github/workflows/dispatch.yml")}, } { t.Run(tc.name+"-route", func(t *testing.T) { s := string(tc.content(t)) @@ -730,6 +814,16 @@ func TestCustomAppSetReviewBotWiring(t *testing.T) { loadRepoFile(".github/workflows/reusable-dispatch.yml"), []string{"Pre-fetch prior review context", "Check fix eligibility", "Pre-fetch review body"}, }, + { + "reusable-fix", + loadRepoFile(".github/workflows/reusable-fix.yml"), + []string{"Check fix eligibility", "Pre-fetch review body"}, + }, + { + "reusable-review", + loadRepoFile(".github/workflows/reusable-review.yml"), + []string{"Pre-fetch prior review context"}, + }, } { t.Run(tc.name+"-consumers", func(t *testing.T) { s := string(tc.content(t)) @@ -746,7 +840,7 @@ func TestCustomAppSetReviewBotWiring(t *testing.T) { } } -// TestDispatchPunctuationStrip ensures reusable-dispatch.yml strips trailing +// TestDispatchPunctuationStrip ensures both dispatch files strip trailing // punctuation clusters (not just a single char) from COMMAND and SECOND_WORD. // See #5582. func TestDispatchPunctuationStrip(t *testing.T) { @@ -756,6 +850,7 @@ func TestDispatchPunctuationStrip(t *testing.T) { } cases := []workflowCase{ {"reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml")}, + {"scaffold/dispatch.yml", loadScaffoldFile(".github/workflows/dispatch.yml")}, } for _, wc := range cases { t.Run(wc.name, func(t *testing.T) { @@ -782,6 +877,10 @@ func TestDispatchPerStageAuthorization(t *testing.T) { "reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml"), }, + { + "scaffold/dispatch.yml", + loadScaffoldFile(".github/workflows/dispatch.yml"), + }, } for _, wc := range cases { @@ -855,6 +954,7 @@ func TestOwnersCheckoutRefPin(t *testing.T) { content func(t *testing.T) []byte }{ {"reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml")}, + {"scaffold/dispatch.yml", loadScaffoldFile(".github/workflows/dispatch.yml")}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -882,7 +982,7 @@ func TestOwnersCheckoutRefPin(t *testing.T) { } } -// TestShimScaffoldBranchFilter validates that the shim template skips dispatch +// TestShimScaffoldBranchFilter validates that both shim templates skip dispatch // for PRs from the fullsend/scaffold branch. Without this filter, the shim // fires pull_request_target on the scaffold PR, causing dispatch noise (#5470). func TestShimScaffoldBranchFilter(t *testing.T) { @@ -890,6 +990,7 @@ func TestShimScaffoldBranchFilter(t *testing.T) { name string content func(t *testing.T) []byte }{ + {"shim-workflow-call", loadScaffoldFile("templates/shim-workflow-call.yaml")}, {"shim-per-repo", loadScaffoldFile("templates/shim-per-repo.yaml")}, } for _, tc := range cases { @@ -928,6 +1029,7 @@ func TestShimPerRepoNoFullsendAlias(t *testing.T) { content func(t *testing.T) []byte } cases := []workflowCase{ + {"scaffold/dispatch.yml", loadScaffoldFile(".github/workflows/dispatch.yml")}, {"reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml")}, } for _, wc := range cases { @@ -958,7 +1060,7 @@ func TestLiveShimSlashCommandFilter(t *testing.T) { "fullsend.yaml must retain bot-type filter for defense-in-depth alongside /fs- prefix check") } -// TestDispatchPRHeadResolution validates that reusable-dispatch.yml contains +// TestDispatchPRHeadResolution validates that both dispatch workflows contain // the "Resolve PR head for issue_comment events" step and the pull_request // merge into event_payload, ensuring issue_comment-triggered agents receive // the correct PR head SHA. @@ -973,6 +1075,10 @@ func TestDispatchPRHeadResolution(t *testing.T) { "reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml"), }, + { + "scaffold/dispatch.yml", + loadScaffoldFile(".github/workflows/dispatch.yml"), + }, } for _, wc := range cases { @@ -1017,6 +1123,10 @@ func TestDispatchPRCheckBotFilter(t *testing.T) { "reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml"), }, + { + "scaffold/dispatch.yml", + loadScaffoldFile(".github/workflows/dispatch.yml"), + }, } for _, wc := range cases { @@ -1095,6 +1205,17 @@ func TestReusableDispatchPRHeadSHAPassthrough(t *testing.T) { // common harness-dispatch path expose the forge-neutral key alongside the // backwards-compatible GitHub issue number (#6760). func TestWorkItemKeyEnvCompatibility(t *testing.T) { + t.Run("legacy reusable code", func(t *testing.T) { + content := string(loadRepoFile(".github/workflows/reusable-code.yml")(t)) + section := extractStepSection(t, content, "Run code agent") + assert.Contains(t, section, + "FULLSEND_WORK_ITEM_URL: ${{ fromJSON(inputs.event_payload).issue.html_url }}") + assert.Contains(t, section, + "FULLSEND_WORK_ITEM_KEY: ${{ fromJSON(inputs.event_payload).issue.number }}") + assert.Contains(t, section, + "ISSUE_NUMBER: ${{ fromJSON(inputs.event_payload).issue.number }}") + }) + t.Run("route based code", func(t *testing.T) { content := string(loadRepoFile(".github/workflows/reusable-dispatch.yml")(t)) section := extractStepSection(t, content, "Run code agent") @@ -1183,21 +1304,57 @@ func TestPrioritizeThinCallerThreadsProjectNumber(t *testing.T) { "prioritize thin caller must fall back to vars.FULLSEND_PROJECT_NUMBER when input is empty") } -// TestShimLabeledEventFiltering validates that per-repo shims do not filter -// labeled events on a routing-label prefix and carry no job-level -// concurrency group (#2452, ADR 0034). BYOA harness agents may trigger on -// arbitrary labels, and per-role groups live in reusable-dispatch.yml. +// TestShimLabeledEventFiltering validates that shim workflows use the ready- +// prefix filter at the if: guard level and label-aware concurrency keys so +// routing labels don't cancel each other (#2452). +// +// The per-repo shim is exempt from the prefix filter because it has no +// concurrency group and BYOA harness agents may trigger on arbitrary labels. func TestShimLabeledEventFiltering(t *testing.T) { - cases := []struct { - name string - content func(t *testing.T) []byte - }{ - {"fullsend.yaml", loadRepoFile(".github/workflows/fullsend.yaml")}, - {"scaffold/shim-per-repo.yaml", loadScaffoldFile("templates/shim-per-repo.yaml")}, + type shimCase struct { + name string + content func(t *testing.T) []byte + hasConcurrency bool + } + + cases := []shimCase{ + {"fullsend.yaml", loadRepoFile(".github/workflows/fullsend.yaml"), false}, + {"scaffold/shim-workflow-call.yaml", loadScaffoldFile("templates/shim-workflow-call.yaml"), true}, + {"scaffold/shim-per-repo.yaml", loadScaffoldFile("templates/shim-per-repo.yaml"), false}, } + // Workflow-call shims must have the ready- prefix filter in the if: guard. + // The per-repo shim is exempt (no concurrency group, BYOA compat). for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { + if !tc.hasConcurrency { + continue + } + t.Run(tc.name+"/guard", func(t *testing.T) { + var wf callerWorkflow + require.NoError(t, yaml.Unmarshal(tc.content(t), &wf)) + job, ok := wf.Jobs["dispatch"] + require.True(t, ok, "%s must have a dispatch job", tc.name) + + // Pin the full composed clause including enclosing parens and the + // joining && that conjoins it with the preceding guards. Without + // the parens, && binds tighter than || in GHA expressions and the + // ready- prefix gate floats to the top of the entire if:. Without + // the joining &&, the clause could be OR'd, bypassing the + // scaffold-install and bot-comment guards. Whitespace is flexible + // via \s* to tolerate reformatting. + assert.Regexp(t, + `\)\s*&&\s*\(\s*github\.event\.action\s*!=\s*'labeled'\s*\|\|\s*startsWith\(github\.event\.label\.name,\s*'ready-'\)\s*\)`, + job.If, + "%s if: guard must AND-conjoin the ready- prefix filter with enclosing parens", tc.name) + }) + } + + // Per-repo shim must NOT have the ready- prefix filter (BYOA compat). + for _, tc := range cases { + if tc.hasConcurrency { + continue + } + t.Run(tc.name+"/no-label-guard", func(t *testing.T) { var wf callerWorkflow require.NoError(t, yaml.Unmarshal(tc.content(t), &wf)) job, ok := wf.Jobs["dispatch"] @@ -1205,14 +1362,142 @@ func TestShimLabeledEventFiltering(t *testing.T) { assert.NotContains(t, job.If, "startsWith(github.event.label.name", "%s per-repo shim must not filter on label prefix — BYOA harness agents may use arbitrary labels", tc.name) + }) + } + + // Workflow-call shims must have a label-aware concurrency key (#2452). + for _, tc := range cases { + if !tc.hasConcurrency { + continue + } + t.Run(tc.name+"/concurrency", func(t *testing.T) { + var wf callerWorkflow + require.NoError(t, yaml.Unmarshal(tc.content(t), &wf)) + job, ok := wf.Jobs["dispatch"] + require.True(t, ok, "%s must have a dispatch job", tc.name) + require.NotNil(t, job.Concurrency, "%s dispatch job must have a concurrency group", tc.name) + + assert.Regexp(t, + `fullsend-dispatch-\$\{\{\s*github\.event\.issue\.number\s*\|\|\s*github\.event\.pull_request\.number\s*\}\}-\$\{\{\s*github\.event\.action\s*==\s*'labeled'\s*&&\s*format\('label-\{0\}',\s*github\.event\.label\.name\)\s*\|\|\s*'dispatch'\s*\}\}`, + job.Concurrency.Group, + "%s concurrency group must match full label-aware structure", tc.name) + assert.False(t, job.Concurrency.CancelInProgress, + "%s concurrency group must have cancel-in-progress: false", tc.name) + }) + } + + // Per-repo shim must NOT have a job-level concurrency group (ADR 0034); + // per-role groups live in reusable-dispatch.yml stage jobs. + for _, tc := range cases { + if tc.hasConcurrency { + continue + } + t.Run(tc.name+"/no-concurrency", func(t *testing.T) { + var wf callerWorkflow + require.NoError(t, yaml.Unmarshal(tc.content(t), &wf)) + job, ok := wf.Jobs["dispatch"] + require.True(t, ok, "%s must have a dispatch job", tc.name) assert.Nil(t, job.Concurrency, "%s per-repo shim must not have job-level concurrency (ADR 0034: per-role groups live in reusable-dispatch.yml)", tc.name) }) } } +// TestReviewCLIInstallModeDetection protects the per-repo review path from +// selecting the CLI install mode from the caller's input instead of the files +// actually present in the checkout. Vendored installs must use the checked-in +// action, while upstream installs must use the downloaded CLI. +func TestReviewCLIInstallModeDetection(t *testing.T) { + workflows := []string{ + ".github/workflows/reusable-dispatch.yml", + ".github/workflows/reusable-review.yml", + } + + for _, workflowPath := range workflows { + t.Run(workflowPath, func(t *testing.T) { + content, err := os.ReadFile(filepath.Join("..", "..", workflowPath)) + require.NoError(t, err) + workflow := string(content) + + require.Contains(t, workflow, "- name: Detect review CLI install mode") + require.Contains(t, workflow, "if [[ -f .defaults/action.yml || -f .fullsend/.defaults/action.yml ]]; then") + require.Contains(t, workflow, `echo "mode=vendored" >> "${GITHUB_OUTPUT}"`) + require.Contains(t, workflow, `echo "mode=upstream" >> "${GITHUB_OUTPUT}"`) + require.Contains(t, workflow, "mode: ${{ steps.review-cli-mode.outputs.mode }}") + assert.NotContains(t, workflow, "mode: ${{ inputs.install_mode == 'per-repo' && 'vendored' || 'upstream' }}") + }) + } +} + +// TestRoutingLabelPrefixDrift validates that every TRIGGERING_LABEL comparison +// in the per-org scaffold dispatch workflow satisfies the ready- prefix +// predicate used by the workflow-call shim if: guard. If someone adds a +// routing label without the prefix, this test converts a silent production +// skip into a build break (#2452). +// +// Scope: scaffold/dispatch.yml only — the router that per-org (workflow-call) +// shims deploy. reusable-dispatch.yml serves per-repo installs whose shim +// has no prefix guard (BYOA compat), so it is intentionally excluded. +func TestRoutingLabelPrefixDrift(t *testing.T) { + dispatchFiles := []struct { + name string + content func(t *testing.T) []byte + }{ + {"scaffold/dispatch.yml", loadScaffoldFile(".github/workflows/dispatch.yml")}, + } + + // Match all forms of TRIGGERING_LABEL comparison. Braces and quotes + // are optional so unbraced ($TRIGGERING_LABEL) and unquoted RHS forms + // are visible. For case blocks, the header is matched first and then + // every arm up to esac is collected, splitting on | for joined arms. + eqPattern := regexp.MustCompile(`TRIGGERING_LABEL\}?"?\s*={1,2}\s*"?([^")\s]+)"?`) + rePattern := regexp.MustCompile(`TRIGGERING_LABEL\}?"?\s*=~\s*"?([^")\s]+)"?`) + caseHeader := regexp.MustCompile(`(?m)case\s+"?\$\{?TRIGGERING_LABEL\}?"?\s+in\b`) + caseArm := regexp.MustCompile(`(?m)^\s*([\w|*?-]+)\)`) + + extractLabels := func(content string) []string { + var labels []string + for _, m := range eqPattern.FindAllStringSubmatch(content, -1) { + labels = append(labels, m[1]) + } + for _, m := range rePattern.FindAllStringSubmatch(content, -1) { + labels = append(labels, m[1]) + } + for _, headerLoc := range caseHeader.FindAllStringIndex(content, -1) { + block := content[headerLoc[1]:] + esacIdx := strings.Index(block, "esac") + if esacIdx >= 0 { + block = block[:esacIdx] + } + for _, m := range caseArm.FindAllStringSubmatch(block, -1) { + for _, arm := range strings.Split(m[1], "|") { + labels = append(labels, arm) + } + } + } + return labels + } + + for _, df := range dispatchFiles { + t.Run(df.name, func(t *testing.T) { + content := string(df.content(t)) + labels := extractLabels(content) + require.Len(t, labels, 4, + "%s: expected exactly 4 TRIGGERING_LABEL comparisons (found %d) — "+ + "if a comparison was added or restyled, update this count and verify "+ + "the new label satisfies the ready- prefix predicate", df.name, len(labels)) + + for _, label := range labels { + assert.True(t, strings.HasPrefix(label, "ready-"), + "%s: routing label %q does not satisfy the ready- prefix predicate — "+ + "per-org workflow-call shim if: guard will silently skip it (#2452)", df.name, label) + } + }) + } +} + // TestRoleCheckCaseBranches validates the role-check step's case mapping and -// backward-compat logic in reusable-dispatch.yml (#2298). +// backward-compat logic in both dispatch workflows (#2298). func TestRoleCheckCaseBranches(t *testing.T) { type workflowCase struct { name string @@ -1224,6 +1509,10 @@ func TestRoleCheckCaseBranches(t *testing.T) { "reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml"), }, + { + "scaffold/dispatch.yml", + loadScaffoldFile(".github/workflows/dispatch.yml"), + }, } for _, wc := range cases { @@ -1272,7 +1561,7 @@ func TestOpenAIVariableForwarding(t *testing.T) { return v + ": ${{ vars." + v + " }}" } - stages := []string{"prioritize"} + stages := []string{"triage", "code", "review", "fix", "retro", "prioritize"} for _, stage := range stages { t.Run("reusable-"+stage+".yml", func(t *testing.T) { content := string(loadRepoFile(fmt.Sprintf(".github/workflows/reusable-%s.yml", stage))(t)) @@ -1376,7 +1665,7 @@ func TestLayeredDirsMatchWorkspacePreparation(t *testing.T) { }{ {"actions/prepare-workspace/action.yml", loadRepoFile(".github/actions/prepare-workspace/action.yml")}, } - for _, stage := range []string{"prioritize", "dispatch"} { + for _, stage := range []string{"triage", "code", "review", "fix", "retro", "prioritize", "dispatch"} { files = append(files, struct { name string content func(t *testing.T) []byte From f07187de35fb13e93a0e369a9b4b02d3d4f60e9c Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 11:18:58 +0300 Subject: [PATCH 08/18] fix(review): validate resolved thread identities Detect CLI mode before default checkout, preserve resolver actor types, use the GitHub Enterprise GraphQL endpoint, and tighten the per-repo review-thread workflow. Co-authored-by: Codex Signed-off-by: csoceanu --- .github/workflows/reusable-dispatch.yml | 28 ++++++----- docs/contributing/documentation.md | 2 +- internal/cli/fetchreviewthreads_test.go | 2 +- internal/forge/forge.go | 1 + internal/forge/github/github.go | 13 ++++- internal/forge/github/review_threads_test.go | 4 +- .../pre-fetch-resolved-threads-test.sh | 47 ++++++++++++++++--- .../scripts/pre-fetch-resolved-threads.sh | 9 ++-- .../scaffold/workflow_call_alignment_test.go | 23 ++++++--- 9 files changed, 95 insertions(+), 34 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 6f57dadada..59c4f3d7a6 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -917,6 +917,19 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' }} + - name: Detect review CLI install mode + id: review-cli-mode + shell: bash + run: | + set -euo pipefail + # Detect the caller's binary before upstream defaults can populate + # .defaults/action.yml and make every checkout look vendored. + if [[ -f .fullsend/bin/fullsend ]]; then + echo "mode=vendored" >> "${GITHUB_OUTPUT}" + else + echo "mode=upstream" >> "${GITHUB_OUTPUT}" + fi + - name: Checkout upstream defaults if: hashFiles('.defaults/action.yml', '.fullsend/.defaults/action.yml') == '' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -945,17 +958,6 @@ jobs: repos: ${{ steps.workspace.outputs.repo_name }} mint_url: ${{ inputs.mint_url }} - - name: Detect review CLI install mode - id: review-cli-mode - shell: bash - run: | - set -euo pipefail - if [[ -f .defaults/action.yml || -f .fullsend/.defaults/action.yml ]]; then - echo "mode=vendored" >> "${GITHUB_OUTPUT}" - else - echo "mode=upstream" >> "${GITHUB_OUTPUT}" - fi - - name: Install fullsend CLI for review context id: install-fullsend uses: ./.defaults/.github/actions/install-fullsend-cli @@ -991,6 +993,7 @@ jobs: - name: Pre-fetch human-resolved review threads id: resolved-threads + if: inputs.install_mode == 'per-repo' env: GH_TOKEN: ${{ steps.app-token.outputs.token }} SOURCE_REPO: ${{ github.repository }} @@ -1000,8 +1003,7 @@ jobs: ORG_NAME: ${{ github.repository_owner }} FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }} FULLSEND_BIN: ${{ steps.install-fullsend.outputs.fullsend-path }} - FULLSEND_DIR: ${{ inputs.install_mode == 'per-repo' && '.fullsend' || '' }} - run: bash "${FULLSEND_DIR:+$FULLSEND_DIR/}scripts/pre-fetch-resolved-threads.sh" + run: bash .fullsend/scripts/pre-fetch-resolved-threads.sh - name: Setup agent environment env: diff --git a/docs/contributing/documentation.md b/docs/contributing/documentation.md index f9bb50a1f8..1d4f741e9b 100644 --- a/docs/contributing/documentation.md +++ b/docs/contributing/documentation.md @@ -122,6 +122,6 @@ The `admin` command group's `uninstall`/`analyze`/`enable`/`disable` subcommands The commands below have lighter documentation footprints. Apply the general `grep` rule when changing them: -`dispatch`, `scan`, `lock`, `poll`, `fetch-skill`, `post-review`, `post-comment`, `reconcile-status`, `resolve-mr-source`, `check-protected-branch` +`dispatch`, `scan`, `lock`, `poll`, `fetch-skill`, `fetch-review-threads`, `post-review`, `post-comment`, `reconcile-status`, `resolve-mr-source`, `check-protected-branch` The most comprehensive single reference for all commands (including minor ones) is `docs/guides/dev/cli-internals.md`, which documents the full command tree with flags. diff --git a/internal/cli/fetchreviewthreads_test.go b/internal/cli/fetchreviewthreads_test.go index e1410cce21..ec14ba82fd 100644 --- a/internal/cli/fetchreviewthreads_test.go +++ b/internal/cli/fetchreviewthreads_test.go @@ -16,7 +16,7 @@ import ( func TestFetchReviewThreadsCommand(t *testing.T) { srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, http.MethodPost, r.Method) - assert.Equal(t, "/api/v3/graphql", r.URL.Path) + assert.Equal(t, "/api/graphql", r.URL.Path) _, _ = w.Write([]byte(`{"data":{"repository":{"pullRequest":{"reviewThreads":{"pageInfo":{"hasNextPage":false,"endCursor":""},"nodes":[{"id":"thread-1","isResolved":true,"path":"main.go","line":12,"originalLine":11,"resolvedBy":{"login":"reviewer"},"comments":{"pageInfo":{"hasNextPage":false},"nodes":[]}}]}}}}}`)) })) defer srv.Close() diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 3824462bb7..d40b0f0d5a 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -485,6 +485,7 @@ type ReviewThread struct { Line *int `json:"line"` OriginalLine *int `json:"original_line"` ResolvedBy string `json:"resolved_by"` + ResolvedByType string `json:"resolved_by_type"` Comments []ReviewThreadComment `json:"comments"` CommentsTruncated bool `json:"comments_truncated"` } diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 3dd3911401..925dfd6bce 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -306,6 +306,9 @@ func (c *LiveClient) do(ctx context.Context, method, path string, body any, head func (c *LiveClient) doRequest(ctx context.Context, method, path string, contentLength int64, open func() (io.ReadCloser, error), headers ...requestHeader) (*http.Response, error) { url := c.baseURL + path + if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") { + url = path + } for attempt := range maxRetries { var reqBody io.Reader @@ -3650,7 +3653,7 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re path line originalLine - resolvedBy { login } + resolvedBy { login __typename } comments(first: 100) { pageInfo { hasNextPage } nodes { @@ -3673,6 +3676,7 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re OriginalLine *int `json:"originalLine"` ResolvedBy *struct { Login string `json:"login"` + Type string `json:"__typename"` } `json:"resolvedBy"` Comments struct { PageInfo struct { @@ -3717,7 +3721,11 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re "number": number, "cursor": cursor, } - resp, err := c.post(ctx, "/graphql", map[string]any{"query": query, "variables": variables}) + graphqlURL := strings.TrimRight(c.baseURL, "/") + "/graphql" + if strings.HasSuffix(strings.TrimRight(c.baseURL, "/"), "/api/v3") { + graphqlURL = strings.TrimSuffix(strings.TrimRight(c.baseURL, "/"), "/api/v3") + "/api/graphql" + } + resp, err := c.post(ctx, graphqlURL, map[string]any{"query": query, "variables": variables}) if err != nil { return forge.ReviewThreadPage{}, fmt.Errorf("list pull request review threads page %d: %w", page, err) } @@ -3741,6 +3749,7 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re } if thread.ResolvedBy != nil { converted.ResolvedBy = thread.ResolvedBy.Login + converted.ResolvedByType = thread.ResolvedBy.Type } for _, comment := range thread.Comments.Nodes { converted.Comments = append(converted.Comments, forge.ReviewThreadComment{ diff --git a/internal/forge/github/review_threads_test.go b/internal/forge/github/review_threads_test.go index e41e7f6111..eaf9db27ea 100644 --- a/internal/forge/github/review_threads_test.go +++ b/internal/forge/github/review_threads_test.go @@ -32,7 +32,7 @@ func TestListPullRequestReviewThreads(t *testing.T) { map[string]any{ "id": "PRRT_1", "isResolved": true, "path": "main.go", "line": line, "originalLine": originalLine, - "resolvedBy": map[string]any{"login": "reviewer"}, + "resolvedBy": map[string]any{"login": "reviewer", "__typename": "User"}, "comments": map[string]any{ "pageInfo": map[string]any{"hasNextPage": true}, "nodes": []any{map[string]any{ @@ -63,7 +63,7 @@ func TestListPullRequestReviewThreads(t *testing.T) { assert.Len(t, got.Threads, 2) assert.Equal(t, forge.ReviewThread{ ID: "PRRT_1", IsResolved: true, Path: "main.go", Line: &line, - OriginalLine: &originalLine, ResolvedBy: "reviewer", + OriginalLine: &originalLine, ResolvedBy: "reviewer", ResolvedByType: "User", Comments: []forge.ReviewThreadComment{{ Author: "reviewer", AuthorType: "User", Body: "please update this", CreatedAt: "2026-10-04T10:00:00Z", }}, CommentsTruncated: true, diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh index aba4c60a23..872ca788f0 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh @@ -46,6 +46,7 @@ if [[ "$1" == "fetch-review-threads" ]]; then line, original_line: .originalLine, resolved_by: (.resolvedBy.login // ""), + resolved_by_type: (.resolvedBy.__typename // ""), comments_truncated: (.comments.pageInfo.hasNextPage // false), comments: [(.comments.nodes // [])[] | { author: .author.login, @@ -159,6 +160,33 @@ run_test() { echo "PASS: ${test_name}" } +run_unsuffixed_bot_resolver_test() { + local test_name="$1" + local resolver_login="$2" + local app_set="${3:-}" + local finding_login="test-org-review" + if [[ -n "${app_set}" ]]; then + finding_login="${app_set}-review" + fi + + run_test "${test_name}" \ + "$(make_graphql_response "[{ + \"id\": \"T_${test_name}\", + \"isResolved\": true, + \"path\": \"resolver.go\", + \"line\": 7, + \"originalLine\": 7, + \"resolvedBy\": {\"login\": \"${resolver_login}\", \"__typename\": \"Bot\"}, + \"comments\": { + \"pageInfo\": {\"hasNextPage\": false}, + \"nodes\": [{\"author\": {\"login\": \"${finding_login}\", \"__typename\": \"Bot\"}, \"body\": \"Finding\", \"createdAt\": \"2026-09-01T10:00:00Z\"}] + } + }]")" \ + 0 \ + "" \ + "${app_set}" +} + # --- Test cases --- # 1. No review threads at all. @@ -349,13 +377,20 @@ run_test "shared-bot-resolved-excluded" \ "$(make_graphql_response "${THREAD_SHARED_BOT_RESOLVED}")" \ 0 -# 10. Metadata fields are populated. +# 10. Unsuffixed GraphQL bot resolvers are excluded by actor type, including +# the organization, shared, custom app-set, and unrelated bot identities. +run_unsuffixed_bot_resolver_test "org-unsuffixed-bot-resolved-excluded" "test-org-review" +run_unsuffixed_bot_resolver_test "shared-unsuffixed-bot-resolved-excluded" "fullsend-ai-review" +run_unsuffixed_bot_resolver_test "custom-unsuffixed-bot-resolved-excluded" "custom-review" "custom" +run_unsuffixed_bot_resolver_test "unrelated-unsuffixed-bot-resolved-excluded" "dependabot" + +# 11. Metadata fields are populated. run_test "metadata-populated" \ "$(make_graphql_response "${THREAD_HUMAN_RESOLVED}")" \ 1 \ '.metadata.pr_number == 42 and .metadata.repo == "test-org/test-repo" and .metadata.thread_count > 0' -# 11. Incomplete comment page — skip rather than guess hidden context. +# 12. Incomplete comment page — skip rather than guess hidden context. THREAD_INCOMPLETE_COMMENTS='[{ "id": "T_11", "isResolved": true, @@ -375,7 +410,7 @@ run_test "incomplete-comment-page-excluded" \ "$(make_graphql_response "${THREAD_INCOMPLETE_COMMENTS}")" \ 0 -# 12. Other GitHub App resolver (login ends with [bot]) — excluded. +# 13. Other GitHub App resolver (login ends with [bot]) — excluded. THREAD_DEPENDABOT_RESOLVED='[{ "id": "T_12", "isResolved": true, @@ -395,7 +430,7 @@ run_test "other-bot-resolved-excluded" \ "$(make_graphql_response "${THREAD_DEPENDABOT_RESOLVED}")" \ 0 -# 13. Human-only resolved threads are not review findings. +# 14. Human-only resolved threads are not review findings. THREAD_HUMAN_ONLY='[{ "id": "T_HUMAN_ONLY", "isResolved": true, @@ -415,7 +450,7 @@ run_test "human-only-resolved-excluded" \ "$(make_graphql_response "${THREAD_HUMAN_ONLY}")" \ 0 -# 14. Custom Fullsend App-set bot identities are recognized. +# 15. Custom Fullsend App-set bot identities are recognized. THREAD_CUSTOM_APP='[{ "id": "T_CUSTOM_APP", "isResolved": true, @@ -437,7 +472,7 @@ run_test "custom-app-set-finding-id" \ '.resolved_threads[0].finding_id == "f_custom"' \ "custom" -# 15. Resolver's comment is used, not another human's. +# 16. Resolver's comment is used, not another human's. # Bob comments but Alice resolves — human_response should be from # Alice (the resolver), and if Alice didn't comment it's silent. THREAD_DIFFERENT_COMMENTER='[{ diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh index c51243033a..1f62add2c7 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh @@ -83,9 +83,9 @@ truncated=$(echo "${response}" | jq -r '.truncated // false' 2>/dev/null) || tru # - resolution_context classification: explicit_dismissal when the # resolver left a comment, silent_resolution otherwise # -# The forge client normalizes the GraphQL actor type into author_type. Bots -# are author_type "Bot" on comments, while resolvedBy is filtered by the -# GitHub App login suffix. +# The forge client preserves GraphQL actor types for both comments and +# resolvedBy. Only a positively identified User may provide a human +# resolution; login suffixes are retained as a defense-in-depth check. RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ --arg bot "${REVIEW_BOT}" \ @@ -97,7 +97,10 @@ RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ '[.[] | select(.is_resolved == true) | select(.resolved_by != null and .resolved_by != "") + | select(.resolved_by_type == "User") | select(.resolved_by != $bot and .resolved_by != $shared_bot) + | select(.resolved_by != $bot_login and .resolved_by != $shared_bot_login) + | select(.resolved_by != $app_set_bot and .resolved_by != $app_set_bot_login) | select((.resolved_by | endswith("[bot]")) | not) | select((.comments // [] | length) > 0) | select((.comments_truncated // false) == false) diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index a501ca1f85..0cd975c0bc 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -1418,13 +1418,24 @@ func TestReviewCLIInstallModeDetection(t *testing.T) { content, err := os.ReadFile(filepath.Join("..", "..", workflowPath)) require.NoError(t, err) workflow := string(content) + section := workflow + if workflowPath == ".github/workflows/reusable-dispatch.yml" { + start := strings.Index(workflow, "\n review:\n") + require.NotEqual(t, -1, start, "review job must be present") + section = workflow[start:] + } - require.Contains(t, workflow, "- name: Detect review CLI install mode") - require.Contains(t, workflow, "if [[ -f .defaults/action.yml || -f .fullsend/.defaults/action.yml ]]; then") - require.Contains(t, workflow, `echo "mode=vendored" >> "${GITHUB_OUTPUT}"`) - require.Contains(t, workflow, `echo "mode=upstream" >> "${GITHUB_OUTPUT}"`) - require.Contains(t, workflow, "mode: ${{ steps.review-cli-mode.outputs.mode }}") - assert.NotContains(t, workflow, "mode: ${{ inputs.install_mode == 'per-repo' && 'vendored' || 'upstream' }}") + detect := strings.Index(section, "- name: Detect review CLI install mode") + checkout := strings.Index(section, "- name: Checkout upstream defaults") + require.NotEqual(t, -1, detect, "review CLI mode detection step must be present") + require.NotEqual(t, -1, checkout, "upstream defaults checkout step must be present") + assert.Less(t, detect, checkout, + "review CLI mode must be detected before upstream defaults are checked out") + require.Contains(t, section, "if [[ -f .fullsend/bin/fullsend ]]; then") + require.Contains(t, section, `echo "mode=vendored" >> "${GITHUB_OUTPUT}"`) + require.Contains(t, section, `echo "mode=upstream" >> "${GITHUB_OUTPUT}"`) + require.Contains(t, section, "mode: ${{ steps.review-cli-mode.outputs.mode }}") + assert.NotContains(t, section, "mode: ${{ inputs.install_mode == 'per-repo' && 'vendored' || 'upstream' }}") }) } } From a3ca00cd66ae96dc5bf2c2d933d7c51f4f81c188 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 12:00:36 +0300 Subject: [PATCH 09/18] fix(review): isolate CLI source builds Co-authored-by: Codex Signed-off-by: csoceanu --- .../actions/install-fullsend-cli/action.yml | 11 +++++++---- action.yml | 10 ++++++---- internal/cli/fetchreviewthreads.go | 3 ++- internal/cli/fetchreviewthreads_test.go | 9 +++++++++ .../scripts/pre-fetch-resolved-threads.sh | 8 ++++++-- .../scaffold/workflow_call_alignment_test.go | 18 ++++++++++++++++++ 6 files changed, 48 insertions(+), 11 deletions(-) diff --git a/.github/actions/install-fullsend-cli/action.yml b/.github/actions/install-fullsend-cli/action.yml index 1ea0d689d1..92bed11fa8 100644 --- a/.github/actions/install-fullsend-cli/action.yml +++ b/.github/actions/install-fullsend-cli/action.yml @@ -178,7 +178,10 @@ runs: echo "::warning::Release download failed; falling back to source build" fi echo "::add-mask::${GH_TOKEN}" - SRC="${RUNNER_TEMP}/fullsend-src" + # This action can run before the root action.yml in the same job. Keep + # its source checkout separate so the later installer can initialize + # its own repository without colliding with this one. + SRC="${RUNNER_TEMP}/fullsend-cli-src" REMOTE="https://x-access-token:${GH_TOKEN}@github.com/${WORKFLOW_REPOSITORY}.git" echo "Cloning ${WORKFLOW_REPOSITORY} at ref: ${WORKFLOW_SHA}" git init "${SRC}" @@ -196,8 +199,8 @@ runs: if: inputs.mode == 'upstream' && (steps.resolve-tag.outputs.tag == '' || steps.install-release.outcome == 'failure') uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 with: - go-version-file: ${{ runner.temp }}/fullsend-src/go.mod - cache-dependency-path: ${{ runner.temp }}/fullsend-src/go.sum + go-version-file: ${{ runner.temp }}/fullsend-cli-src/go.mod + cache-dependency-path: ${{ runner.temp }}/fullsend-cli-src/go.sum - name: Build fullsend from source id: install-upstream @@ -206,7 +209,7 @@ runs: run: | set -euo pipefail mkdir -p "${RUNNER_TEMP}/fullsend" - cd "${RUNNER_TEMP}/fullsend-src" + cd "${RUNNER_TEMP}/fullsend-cli-src" make go-build cp bin/fullsend "${RUNNER_TEMP}/fullsend/fullsend" echo "${RUNNER_TEMP}/fullsend" >> "${GITHUB_PATH}" diff --git a/action.yml b/action.yml index 0cbeab4d0a..fbc43363d7 100644 --- a/action.yml +++ b/action.yml @@ -333,7 +333,9 @@ runs: echo "::warning::Release download failed; falling back to source build" fi echo "::add-mask::${GH_TOKEN}" - SRC="${RUNNER_TEMP}/fullsend-src" + # Keep the agent source checkout separate from the review-context CLI + # installer, which may have run earlier in the same job. + SRC="${RUNNER_TEMP}/fullsend-agent-src" REMOTE="https://x-access-token:${GH_TOKEN}@github.com/fullsend-ai/fullsend.git" echo "Cloning fullsend at ref: ${SOURCE_REF}" git init "${SRC}" @@ -353,8 +355,8 @@ runs: if: steps.detect.outputs.install-method == 'source' || steps.download-release.outcome == 'failure' uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 with: - go-version-file: ${{ runner.temp }}/fullsend-src/go.mod - cache-dependency-path: ${{ runner.temp }}/fullsend-src/go.sum + go-version-file: ${{ runner.temp }}/fullsend-agent-src/go.mod + cache-dependency-path: ${{ runner.temp }}/fullsend-agent-src/go.sum - name: Build fullsend from source if: steps.detect.outputs.install-method == 'source' || steps.download-release.outcome == 'failure' @@ -362,7 +364,7 @@ runs: run: | set -euo pipefail mkdir -p "${RUNNER_TEMP}/fullsend" - cd "${RUNNER_TEMP}/fullsend-src" + cd "${RUNNER_TEMP}/fullsend-agent-src" make go-build cp bin/fullsend "${RUNNER_TEMP}/fullsend/fullsend" echo "${RUNNER_TEMP}/fullsend" >> "${GITHUB_PATH}" diff --git a/internal/cli/fetchreviewthreads.go b/internal/cli/fetchreviewthreads.go index e02b88c2fa..cf6a64b6f1 100644 --- a/internal/cli/fetchreviewthreads.go +++ b/internal/cli/fetchreviewthreads.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/fullsend-ai/fullsend/internal/repos" "github.com/spf13/cobra" ) @@ -44,7 +45,7 @@ func newFetchReviewThreadsCmd() *cobra.Command { cmd.Flags().StringVar(&repo, "repo", "", "repository in owner/repo format (required)") cmd.Flags().IntVar(&pr, "pr", 0, "pull request number (required)") - cmd.Flags().StringVar(&forgeName, "forge", "github", "forge backend (github or gitlab)") + cmd.Flags().StringVar(&forgeName, "forge", repos.ForgeGitHub, "forge backend (github or gitlab)") cmd.Flags().StringVar(&token, "token", "", "forge token (defaults to the forge environment token)") cmd.Flags().StringVar(&baseURL, "base-url", "", "forge API base URL") _ = cmd.MarkFlagRequired("repo") diff --git a/internal/cli/fetchreviewthreads_test.go b/internal/cli/fetchreviewthreads_test.go index ec14ba82fd..14bc4e29d2 100644 --- a/internal/cli/fetchreviewthreads_test.go +++ b/internal/cli/fetchreviewthreads_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/repos" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -44,6 +45,14 @@ func TestFetchReviewThreadsCommand(t *testing.T) { assert.True(t, got.Threads[0].IsResolved) } +func TestFetchReviewThreadsCommand_DefaultsToGitHubForge(t *testing.T) { + cmd := newFetchReviewThreadsCmd() + + flag := cmd.Flags().Lookup("forge") + require.NotNil(t, flag) + assert.Equal(t, repos.ForgeGitHub, flag.DefValue) +} + func TestFetchReviewThreadsCommand_ValidatesFlags(t *testing.T) { tests := []struct { name string diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh index 1f62add2c7..03465cced7 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh @@ -17,13 +17,17 @@ # script writes an empty file and exits 0 so the review proceeds # without resolution data (current behavior preserved). # -# Required environment variables (set by the review agent): +# Required environment variables (set by the review workflow): # # - GH_TOKEN — token with read access to the PR # - SOURCE_REPO — owner/repo (e.g., "fullsend-ai/fullsend") # - PR_NUM — PR number # - ORG_NAME — org name for bot identity filtering -# - FULLSEND_BIN — optional path to the fullsend CLI (defaults to fullsend) +# +# Optional environment variables: +# +# - FULLSEND_BIN — path to the fullsend CLI (defaults to fullsend) +# - FULLSEND_APP_SET — custom review app-set prefix for bot identity filtering # # Outputs (via GITHUB_OUTPUT): # - human_resolved_file — path to the JSON file diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 0cd975c0bc..f777464da1 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -1440,6 +1440,24 @@ func TestReviewCLIInstallModeDetection(t *testing.T) { } } +// TestReviewCLIInstallersUseDistinctSourceDirs protects the review job from +// reusing the source checkout created by the context-fetch installer. Both +// installers can build from source for an unreleased workflow SHA, and each +// must be able to initialize its own git repository. +func TestReviewCLIInstallersUseDistinctSourceDirs(t *testing.T) { + cliAction, err := os.ReadFile(filepath.Join("..", "..", ".github/actions/install-fullsend-cli/action.yml")) + require.NoError(t, err) + rootAction, err := os.ReadFile(filepath.Join("..", "..", "action.yml")) + require.NoError(t, err) + + assert.Contains(t, string(cliAction), `SRC="${RUNNER_TEMP}/fullsend-cli-src"`) + assert.Contains(t, string(rootAction), `SRC="${RUNNER_TEMP}/fullsend-agent-src"`) + assert.NotEqual(t, + "${RUNNER_TEMP}/fullsend-cli-src", + "${RUNNER_TEMP}/fullsend-agent-src", + "context and agent installers must not share a source checkout") +} + // TestRoutingLabelPrefixDrift validates that every TRIGGERING_LABEL comparison // in the per-org scaffold dispatch workflow satisfies the ready- prefix // predicate used by the workflow-call shim if: guard. If someone adds a From 455e59bbc78ca995c95f8ba7dd148fb4b675e55c Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 12:13:35 +0300 Subject: [PATCH 10/18] fix(review): run thread fetch in agent pre-script Co-authored-by: Codex Signed-off-by: csoceanu --- .github/workflows/reusable-dispatch.yml | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 59c4f3d7a6..378b0a83e6 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -991,20 +991,6 @@ jobs: FULLSEND_DIR: .fullsend run: bash "${FULLSEND_DIR:+$FULLSEND_DIR/}scripts/pre-fetch-prior-review.sh" - - name: Pre-fetch human-resolved review threads - id: resolved-threads - if: inputs.install_mode == 'per-repo' - env: - GH_TOKEN: ${{ steps.app-token.outputs.token }} - SOURCE_REPO: ${{ github.repository }} - PR_NUM: >- - ${{ fromJSON(needs.route.outputs.event_payload).pull_request.number - || fromJSON(needs.route.outputs.event_payload).issue.number }} - ORG_NAME: ${{ github.repository_owner }} - FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }} - FULLSEND_BIN: ${{ steps.install-fullsend.outputs.fullsend-path }} - run: bash .fullsend/scripts/pre-fetch-resolved-threads.sh - - name: Setup agent environment env: AGENT_PREFIX: REVIEW_ @@ -1027,7 +1013,10 @@ jobs: PRIOR_REVIEW_SHA: ${{ steps.prior-review.outputs.prior_sha }} PRIOR_REVIEW_FILE: ${{ steps.prior-review.outputs.prior_review_file }} PRIOR_REVIEW_PROVENANCE: ${{ steps.prior-review.outputs.prior_review_provenance }} - HUMAN_RESOLVED_FILE: ${{ steps.resolved-threads.outputs.human_resolved_file }} + FULLSEND_BIN: ${{ steps.install-fullsend.outputs.fullsend-path }} + FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }} + HUMAN_RESOLVED_FETCH_SCRIPT: ${{ inputs.install_mode == 'per-repo' && '.fullsend/scripts/pre-fetch-resolved-threads.sh' || '' }} + HUMAN_RESOLVED_FILE: ${{ github.workspace }}/human-resolved-threads.json OTEL_EXPORTER_OTLP_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_ENDPOINT }} OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} From b2694e8414e1fd7d7a1d3c476a72fa08af5eb82a Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 13:37:18 +0300 Subject: [PATCH 11/18] fix(review): rely on agent pre-script for thread fetch Co-authored-by: Codex Signed-off-by: csoceanu --- .../actions/install-fullsend-cli/action.yml | 11 ++--- .github/workflows/reusable-dispatch.yml | 24 --------- action.yml | 10 ++-- .../scaffold/workflow_call_alignment_test.go | 49 ++++++------------- 4 files changed, 23 insertions(+), 71 deletions(-) diff --git a/.github/actions/install-fullsend-cli/action.yml b/.github/actions/install-fullsend-cli/action.yml index 92bed11fa8..1ea0d689d1 100644 --- a/.github/actions/install-fullsend-cli/action.yml +++ b/.github/actions/install-fullsend-cli/action.yml @@ -178,10 +178,7 @@ runs: echo "::warning::Release download failed; falling back to source build" fi echo "::add-mask::${GH_TOKEN}" - # This action can run before the root action.yml in the same job. Keep - # its source checkout separate so the later installer can initialize - # its own repository without colliding with this one. - SRC="${RUNNER_TEMP}/fullsend-cli-src" + SRC="${RUNNER_TEMP}/fullsend-src" REMOTE="https://x-access-token:${GH_TOKEN}@github.com/${WORKFLOW_REPOSITORY}.git" echo "Cloning ${WORKFLOW_REPOSITORY} at ref: ${WORKFLOW_SHA}" git init "${SRC}" @@ -199,8 +196,8 @@ runs: if: inputs.mode == 'upstream' && (steps.resolve-tag.outputs.tag == '' || steps.install-release.outcome == 'failure') uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 with: - go-version-file: ${{ runner.temp }}/fullsend-cli-src/go.mod - cache-dependency-path: ${{ runner.temp }}/fullsend-cli-src/go.sum + go-version-file: ${{ runner.temp }}/fullsend-src/go.mod + cache-dependency-path: ${{ runner.temp }}/fullsend-src/go.sum - name: Build fullsend from source id: install-upstream @@ -209,7 +206,7 @@ runs: run: | set -euo pipefail mkdir -p "${RUNNER_TEMP}/fullsend" - cd "${RUNNER_TEMP}/fullsend-cli-src" + cd "${RUNNER_TEMP}/fullsend-src" make go-build cp bin/fullsend "${RUNNER_TEMP}/fullsend/fullsend" echo "${RUNNER_TEMP}/fullsend" >> "${GITHUB_PATH}" diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 378b0a83e6..8469796df5 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -917,19 +917,6 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' }} - - name: Detect review CLI install mode - id: review-cli-mode - shell: bash - run: | - set -euo pipefail - # Detect the caller's binary before upstream defaults can populate - # .defaults/action.yml and make every checkout look vendored. - if [[ -f .fullsend/bin/fullsend ]]; then - echo "mode=vendored" >> "${GITHUB_OUTPUT}" - else - echo "mode=upstream" >> "${GITHUB_OUTPUT}" - fi - - name: Checkout upstream defaults if: hashFiles('.defaults/action.yml', '.fullsend/.defaults/action.yml') == '' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -958,16 +945,6 @@ jobs: repos: ${{ steps.workspace.outputs.repo_name }} mint_url: ${{ inputs.mint_url }} - - name: Install fullsend CLI for review context - id: install-fullsend - uses: ./.defaults/.github/actions/install-fullsend-cli - with: - mode: ${{ steps.review-cli-mode.outputs.mode }} - vendored_path: .fullsend/bin/fullsend - workflow_repository: ${{ job.workflow_repository }} - workflow_sha: ${{ job.workflow_sha }} - github_token: ${{ steps.app-token.outputs.token }} - - name: Checkout target repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -1013,7 +990,6 @@ jobs: PRIOR_REVIEW_SHA: ${{ steps.prior-review.outputs.prior_sha }} PRIOR_REVIEW_FILE: ${{ steps.prior-review.outputs.prior_review_file }} PRIOR_REVIEW_PROVENANCE: ${{ steps.prior-review.outputs.prior_review_provenance }} - FULLSEND_BIN: ${{ steps.install-fullsend.outputs.fullsend-path }} FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }} HUMAN_RESOLVED_FETCH_SCRIPT: ${{ inputs.install_mode == 'per-repo' && '.fullsend/scripts/pre-fetch-resolved-threads.sh' || '' }} HUMAN_RESOLVED_FILE: ${{ github.workspace }}/human-resolved-threads.json diff --git a/action.yml b/action.yml index fbc43363d7..0cbeab4d0a 100644 --- a/action.yml +++ b/action.yml @@ -333,9 +333,7 @@ runs: echo "::warning::Release download failed; falling back to source build" fi echo "::add-mask::${GH_TOKEN}" - # Keep the agent source checkout separate from the review-context CLI - # installer, which may have run earlier in the same job. - SRC="${RUNNER_TEMP}/fullsend-agent-src" + SRC="${RUNNER_TEMP}/fullsend-src" REMOTE="https://x-access-token:${GH_TOKEN}@github.com/fullsend-ai/fullsend.git" echo "Cloning fullsend at ref: ${SOURCE_REF}" git init "${SRC}" @@ -355,8 +353,8 @@ runs: if: steps.detect.outputs.install-method == 'source' || steps.download-release.outcome == 'failure' uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 with: - go-version-file: ${{ runner.temp }}/fullsend-agent-src/go.mod - cache-dependency-path: ${{ runner.temp }}/fullsend-agent-src/go.sum + go-version-file: ${{ runner.temp }}/fullsend-src/go.mod + cache-dependency-path: ${{ runner.temp }}/fullsend-src/go.sum - name: Build fullsend from source if: steps.detect.outputs.install-method == 'source' || steps.download-release.outcome == 'failure' @@ -364,7 +362,7 @@ runs: run: | set -euo pipefail mkdir -p "${RUNNER_TEMP}/fullsend" - cd "${RUNNER_TEMP}/fullsend-agent-src" + cd "${RUNNER_TEMP}/fullsend-src" make go-build cp bin/fullsend "${RUNNER_TEMP}/fullsend/fullsend" echo "${RUNNER_TEMP}/fullsend" >> "${GITHUB_PATH}" diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index f777464da1..ee68dace44 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -1403,11 +1403,11 @@ func TestShimLabeledEventFiltering(t *testing.T) { } } -// TestReviewCLIInstallModeDetection protects the per-repo review path from -// selecting the CLI install mode from the caller's input instead of the files -// actually present in the checkout. Vendored installs must use the checked-in -// action, while upstream installs must use the downloaded CLI. -func TestReviewCLIInstallModeDetection(t *testing.T) { +// TestReviewWorkflowUsesAgentPreScriptForHumanResolvedThreads protects the +// review paths from growing a second CLI installation. The root action already +// installs fullsend before the agent pre-script runs, so the workflows only +// need to pass the fetch helper and its output path to the agent. +func TestReviewWorkflowUsesAgentPreScriptForHumanResolvedThreads(t *testing.T) { workflows := []string{ ".github/workflows/reusable-dispatch.yml", ".github/workflows/reusable-review.yml", @@ -1423,41 +1423,22 @@ func TestReviewCLIInstallModeDetection(t *testing.T) { start := strings.Index(workflow, "\n review:\n") require.NotEqual(t, -1, start, "review job must be present") section = workflow[start:] + if end := strings.Index(section, "\n fix:\n"); end != -1 { + section = section[:end] + } } - detect := strings.Index(section, "- name: Detect review CLI install mode") - checkout := strings.Index(section, "- name: Checkout upstream defaults") - require.NotEqual(t, -1, detect, "review CLI mode detection step must be present") - require.NotEqual(t, -1, checkout, "upstream defaults checkout step must be present") - assert.Less(t, detect, checkout, - "review CLI mode must be detected before upstream defaults are checked out") - require.Contains(t, section, "if [[ -f .fullsend/bin/fullsend ]]; then") - require.Contains(t, section, `echo "mode=vendored" >> "${GITHUB_OUTPUT}"`) - require.Contains(t, section, `echo "mode=upstream" >> "${GITHUB_OUTPUT}"`) - require.Contains(t, section, "mode: ${{ steps.review-cli-mode.outputs.mode }}") - assert.NotContains(t, section, "mode: ${{ inputs.install_mode == 'per-repo' && 'vendored' || 'upstream' }}") + assert.Contains(t, section, "HUMAN_RESOLVED_FETCH_SCRIPT:") + assert.Contains(t, section, "HUMAN_RESOLVED_FILE:") + assert.Contains(t, section, "FULLSEND_APP_SET:") + assert.NotContains(t, section, "Detect review CLI install mode") + assert.NotContains(t, section, "Install fullsend CLI for review context") + assert.NotContains(t, section, "steps.install-fullsend") + assert.NotContains(t, section, "FULLSEND_BIN:") }) } } -// TestReviewCLIInstallersUseDistinctSourceDirs protects the review job from -// reusing the source checkout created by the context-fetch installer. Both -// installers can build from source for an unreleased workflow SHA, and each -// must be able to initialize its own git repository. -func TestReviewCLIInstallersUseDistinctSourceDirs(t *testing.T) { - cliAction, err := os.ReadFile(filepath.Join("..", "..", ".github/actions/install-fullsend-cli/action.yml")) - require.NoError(t, err) - rootAction, err := os.ReadFile(filepath.Join("..", "..", "action.yml")) - require.NoError(t, err) - - assert.Contains(t, string(cliAction), `SRC="${RUNNER_TEMP}/fullsend-cli-src"`) - assert.Contains(t, string(rootAction), `SRC="${RUNNER_TEMP}/fullsend-agent-src"`) - assert.NotEqual(t, - "${RUNNER_TEMP}/fullsend-cli-src", - "${RUNNER_TEMP}/fullsend-agent-src", - "context and agent installers must not share a source checkout") -} - // TestRoutingLabelPrefixDrift validates that every TRIGGERING_LABEL comparison // in the per-org scaffold dispatch workflow satisfies the ready- prefix // predicate used by the workflow-call shim if: guard. If someone adds a From 6ca6ff6da0d730389796fe0c5e341982b7593832 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 14:26:57 +0300 Subject: [PATCH 12/18] fix(review): limit thread wiring to per-repo workflow Co-authored-by: Codex Signed-off-by: csoceanu --- internal/scaffold/workflow_call_alignment_test.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index ee68dace44..0d02d7f58d 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -1404,13 +1404,12 @@ func TestShimLabeledEventFiltering(t *testing.T) { } // TestReviewWorkflowUsesAgentPreScriptForHumanResolvedThreads protects the -// review paths from growing a second CLI installation. The root action already -// installs fullsend before the agent pre-script runs, so the workflows only -// need to pass the fetch helper and its output path to the agent. +// per-repo review path from growing a second CLI installation. The root action +// already installs fullsend before the agent pre-script runs, so the workflow +// only needs to pass the fetch helper and its output path to the agent. func TestReviewWorkflowUsesAgentPreScriptForHumanResolvedThreads(t *testing.T) { workflows := []string{ ".github/workflows/reusable-dispatch.yml", - ".github/workflows/reusable-review.yml", } for _, workflowPath := range workflows { @@ -1437,6 +1436,12 @@ func TestReviewWorkflowUsesAgentPreScriptForHumanResolvedThreads(t *testing.T) { assert.NotContains(t, section, "FULLSEND_BIN:") }) } + + perOrgContent, err := os.ReadFile(filepath.Join("..", "..", ".github/workflows/reusable-review.yml")) + require.NoError(t, err) + perOrgAgent := extractStepSection(t, string(perOrgContent), "Run review agent") + assert.NotContains(t, perOrgAgent, "HUMAN_RESOLVED_FETCH_SCRIPT:") + assert.NotContains(t, perOrgAgent, "HUMAN_RESOLVED_FILE:") } // TestRoutingLabelPrefixDrift validates that every TRIGGERING_LABEL comparison From 811671d0f282f7fc6e964efdfc649a326512a6c7 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 15:36:04 +0300 Subject: [PATCH 13/18] fix(review): move thread fetch to agent pre-script Add GitLab review-thread resolution support and keep workflow wiring thin. Co-authored-by: Codex Signed-off-by: csoceanu --- .github/workflows/reusable-dispatch.yml | 1 - Makefile | 1 - internal/cli/fetchreviewthreads_test.go | 1 - internal/forge/gitlab/methods_test.go | 45 +- internal/forge/gitlab/mr.go | 101 +++- .../pre-fetch-resolved-threads-test.sh | 535 ------------------ .../scripts/pre-fetch-resolved-threads.sh | 182 ------ .../scaffold/workflow_call_alignment_test.go | 52 +- 8 files changed, 154 insertions(+), 764 deletions(-) delete mode 100644 internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh delete mode 100644 internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 8469796df5..410abb5f4b 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -991,7 +991,6 @@ jobs: PRIOR_REVIEW_FILE: ${{ steps.prior-review.outputs.prior_review_file }} PRIOR_REVIEW_PROVENANCE: ${{ steps.prior-review.outputs.prior_review_provenance }} FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }} - HUMAN_RESOLVED_FETCH_SCRIPT: ${{ inputs.install_mode == 'per-repo' && '.fullsend/scripts/pre-fetch-resolved-threads.sh' || '' }} HUMAN_RESOLVED_FILE: ${{ github.workspace }}/human-resolved-threads.json OTEL_EXPORTER_OTLP_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_ENDPOINT }} OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} diff --git a/Makefile b/Makefile index 5dd4c4938e..951b3a9e3b 100644 --- a/Makefile +++ b/Makefile @@ -192,7 +192,6 @@ script-test: $(call run-timed,bash scripts/check-agents-gate-pin-test.sh) $(call run-timed,bash scripts/verify-release-tag-test.sh) $(call run-timed,bash internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh) - $(call run-timed,bash internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh) $(call run-timed,bash internal/scaffold/fullsend-repo/.github/scripts/setup-agent-env-test.sh) $(call run-timed,bash hack/gitlab-runner-vm/executor/prepare_validation_test.sh) $(call run-timed,bash hack/gitlab-runner-vm/executor/gateway_test.sh) diff --git a/internal/cli/fetchreviewthreads_test.go b/internal/cli/fetchreviewthreads_test.go index 14bc4e29d2..2e6526569a 100644 --- a/internal/cli/fetchreviewthreads_test.go +++ b/internal/cli/fetchreviewthreads_test.go @@ -62,7 +62,6 @@ func TestFetchReviewThreadsCommand_ValidatesFlags(t *testing.T) { {name: "non-positive pull request", args: []string{"--repo", "owner/repo", "--pr", "0"}, want: "positive integer"}, {name: "invalid repository", args: []string{"--repo", "owner", "--pr", "1"}, want: "owner/repo format"}, {name: "unsupported forge", args: []string{"--repo", "owner/repo", "--pr", "1", "--forge", "bitbucket", "--token", "token"}, want: "unsupported forge"}, - {name: "gitlab review threads unsupported", args: []string{"--repo", "owner/repo", "--pr", "1", "--forge", "gitlab", "--token", "token", "--base-url", "https://gitlab.example.com"}, want: "not supported"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index bcdb48fccd..9387ad0aa5 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -72,6 +72,46 @@ func TestCreateIssue(t *testing.T) { assert.Equal(t, []string{"bug", "urgent"}, issue.Labels) } +func TestListPullRequestReviewThreads(t *testing.T) { + client, mux := setupTest(t) + mux.HandleFunc("/api/v4/projects/myorg%2Fmyrepo/merge_requests/42/discussions", func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "100", r.URL.Query().Get("per_page")) + assert.Equal(t, "1", r.URL.Query().Get("page")) + writeJSON(t, w, http.StatusOK, []map[string]any{ + { + "id": "discussion-1", + "notes": []map[string]any{ + { + "id": 7, "body": "Please update this", "created_at": "2026-10-06T10:00:00Z", + "resolvable": true, "resolved": true, + "author": map[string]any{"username": "botuser", "bot": true}, + "resolved_by": map[string]any{"username": "reviewer", "bot": false}, + "position": map[string]any{"new_path": "main.go", "old_path": "main.go", "new_line": 17, "old_line": 16}, + }, + }, + }, + { + "id": "discussion-2", + "notes": []map[string]any{ + {"id": 8, "body": "unresolved", "resolvable": true, "resolved": false, "author": map[string]any{"username": "reviewer", "bot": false}}, + }, + }, + }) + }) + + got, err := client.ListPullRequestReviewThreads(context.Background(), "myorg", "myrepo", 42) + require.NoError(t, err) + require.Len(t, got.Threads, 2) + assert.Equal(t, "discussion-1", got.Threads[0].ID) + assert.True(t, got.Threads[0].IsResolved) + assert.Equal(t, "reviewer", got.Threads[0].ResolvedBy) + assert.Equal(t, "User", got.Threads[0].ResolvedByType) + assert.Equal(t, "main.go", got.Threads[0].Path) + assert.Equal(t, 17, *got.Threads[0].Line) + assert.Equal(t, "Bot", got.Threads[0].Comments[0].AuthorType) + assert.False(t, got.Threads[1].IsResolved) +} + func TestCreateIssue_NoLabels(t *testing.T) { client, mux := setupTest(t) ctx := context.Background() @@ -471,11 +511,12 @@ func TestMinimizeComment(t *testing.T) { require.ErrorIs(t, err, forge.ErrNotSupported) } -func TestListPullRequestReviewThreads_NotSupported(t *testing.T) { +func TestListPullRequestReviewThreads_APIError(t *testing.T) { client, _ := setupTest(t) _, err := client.ListPullRequestReviewThreads(context.Background(), "myorg", "myrepo", 42) - require.ErrorIs(t, err, forge.ErrNotSupported) + require.Error(t, err) + assert.Contains(t, err.Error(), "list discussions for !42 page 1") } // --------------------------------------------------------------------------- diff --git a/internal/forge/gitlab/mr.go b/internal/forge/gitlab/mr.go index b859ac8b9d..bec1faadfb 100644 --- a/internal/forge/gitlab/mr.go +++ b/internal/forge/gitlab/mr.go @@ -770,11 +770,102 @@ func (c *LiveClient) ListPullRequestReviews(ctx context.Context, owner, repo str return result, nil } -// ListPullRequestReviewThreads is not available as a portable GitLab -// equivalent. GitLab discussions do not expose the GitHub review-thread -// resolution contract used by the review agent. -func (c *LiveClient) ListPullRequestReviewThreads(_ context.Context, _ string, _ string, _ int) (forge.ReviewThreadPage, error) { - return forge.ReviewThreadPage{}, forge.ErrNotSupported +// ListPullRequestReviewThreads maps GitLab merge-request discussions to the +// common review-thread model. A discussion is resolved when one of its +// resolvable notes is marked resolved; the resolver and note authors are +// preserved so consumers can distinguish human and bot resolutions. +func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, repo string, number int) (forge.ReviewThreadPage, error) { + proj := projectPath(owner, repo) + result := forge.ReviewThreadPage{} + + for page := 1; page <= 20; page++ { + path := fmt.Sprintf("/projects/%s/merge_requests/%d/discussions?per_page=100&page=%d", + proj, number, page) + resp, err := c.get(ctx, path) + if err != nil { + return forge.ReviewThreadPage{}, fmt.Errorf("list discussions for !%d page %d: %w", number, page, err) + } + + var discussions []struct { + ID string `json:"id"` + Notes []struct { + ID int `json:"id"` + Body string `json:"body"` + System bool `json:"system"` + CreatedAt string `json:"created_at"` + Resolvable bool `json:"resolvable"` + Resolved bool `json:"resolved"` + Author struct { + Username string `json:"username"` + Bot bool `json:"bot"` + } `json:"author"` + ResolvedBy *struct { + Username string `json:"username"` + Bot bool `json:"bot"` + } `json:"resolved_by"` + Position *struct { + NewPath string `json:"new_path"` + OldPath string `json:"old_path"` + NewLine *int `json:"new_line"` + OldLine *int `json:"old_line"` + } `json:"position"` + } `json:"notes"` + } + if err := decodeJSON(resp, &discussions); err != nil { + return forge.ReviewThreadPage{}, fmt.Errorf("decode discussions for !%d page %d: %w", number, page, err) + } + + for _, discussion := range discussions { + thread := forge.ReviewThread{ID: discussion.ID} + for _, note := range discussion.Notes { + if note.System { + continue + } + + authorType := "User" + if note.Author.Bot { + authorType = "Bot" + } + thread.Comments = append(thread.Comments, forge.ReviewThreadComment{ + Author: note.Author.Username, + AuthorType: authorType, + Body: note.Body, + CreatedAt: note.CreatedAt, + }) + + if !note.Resolvable || !note.Resolved { + continue + } + thread.IsResolved = true + if note.ResolvedBy != nil { + thread.ResolvedBy = note.ResolvedBy.Username + if note.ResolvedBy.Bot { + thread.ResolvedByType = "Bot" + } else { + thread.ResolvedByType = "User" + } + } + if note.Position != nil { + thread.Path = note.Position.NewPath + if thread.Path == "" { + thread.Path = note.Position.OldPath + } + thread.Line = note.Position.NewLine + thread.OriginalLine = note.Position.OldLine + } + } + result.Threads = append(result.Threads, thread) + } + + if len(discussions) < 100 { + break + } + if page == 20 { + result.Truncated = true + } + } + + return result, nil } // DismissPullRequestReview dismisses a review on a merge request. diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh deleted file mode 100644 index 872ca788f0..0000000000 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh +++ /dev/null @@ -1,535 +0,0 @@ -#!/usr/bin/env bash -# pre-fetch-resolved-threads-test.sh — Tests for pre-fetch-resolved-threads.sh -# -# Verifies GraphQL response parsing, human vs. bot filtering, finding id -# extraction, and fail-safe behavior. -# -# Run from the repo root: -# bash internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads-test.sh - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -SCRIPT="${SCRIPT_DIR}/pre-fetch-resolved-threads.sh" -FAILURES=0 - -TMPDIR="$(mktemp -d)" -trap 'rm -rf "${TMPDIR}"' EXIT - -# --- Helpers --- - -# build_mock creates a mock fullsend binary that returns a normalized -# review-thread response from a preconfigured GraphQL-shaped fixture. -# $1 — the JSON response to return (empty string = error) -build_mock() { - local response_json="$1" - local mock_bin="${TMPDIR}/bin" - - rm -rf "${mock_bin}" - mkdir -p "${mock_bin}" - - printf '%s' "${response_json}" > "${TMPDIR}/graphql-response.txt" - - cat > "${mock_bin}/fullsend" <<'MOCKEOF' -#!/usr/bin/env bash -RESPONSE_FILE="RESPONSE_PLACEHOLDER" - -if [[ "$1" == "fetch-review-threads" ]]; then - if [[ ! -s "${RESPONSE_FILE}" ]]; then - exit 1 - fi - jq -c '{threads: ([.data.repository.pullRequest.reviewThreads.nodes[] | - { - id, - is_resolved: .isResolved, - path, - line, - original_line: .originalLine, - resolved_by: (.resolvedBy.login // ""), - resolved_by_type: (.resolvedBy.__typename // ""), - comments_truncated: (.comments.pageInfo.hasNextPage // false), - comments: [(.comments.nodes // [])[] | { - author: .author.login, - author_type: .author.__typename, - body, - created_at: .createdAt - }] - } - ]), truncated: false}' "${RESPONSE_FILE}" - exit 0 -fi - -exit 0 -MOCKEOF - - local escaped="${TMPDIR//\//\\/}\/graphql-response.txt" - perl -pi -e "s/RESPONSE_PLACEHOLDER/${escaped}/g" "${mock_bin}/fullsend" - chmod +x "${mock_bin}/fullsend" - - echo "${mock_bin}" -} - -# make_graphql_response builds a GraphQL response wrapping the given -# thread nodes array. -make_graphql_response() { - local nodes_json="$1" - cat < "${github_output}" - - local exit_code=0 - env \ - PATH="${mock_bin}:${PATH}" \ - GITHUB_ACTIONS="true" \ - GH_TOKEN="fake-token" \ - ORG_NAME="test-org" \ - PR_NUM="42" \ - SOURCE_REPO="test-org/test-repo" \ - FULLSEND_APP_SET="${app_set}" \ - GITHUB_OUTPUT="${github_output}" \ - GITHUB_WORKSPACE="${workspace}" \ - bash "${SCRIPT}" > "${TMPDIR}/stdout.log" 2>&1 || exit_code=$? - - if [[ ${exit_code} -ne 0 ]]; then - echo "FAIL: ${test_name} — script exited with ${exit_code}" - echo "--- stdout ---" - cat "${TMPDIR}/stdout.log" - FAILURES=$((FAILURES + 1)) - return - fi - - local output_file - output_file="$(grep '^human_resolved_file=' "${github_output}" | head -1 | cut -d= -f2)" - - if [[ -z "${output_file}" || ! -f "${output_file}" ]]; then - echo "FAIL: ${test_name} — output file not found" - FAILURES=$((FAILURES + 1)) - return - fi - - local actual_count - actual_count="$(jq '.resolved_threads | length' "${output_file}")" - - if [[ "${actual_count}" -ne "${expected_count}" ]]; then - echo "FAIL: ${test_name} — expected ${expected_count} resolved threads, got ${actual_count}" - echo "--- output ---" - jq . "${output_file}" - echo "--- stdout ---" - cat "${TMPDIR}/stdout.log" - FAILURES=$((FAILURES + 1)) - return - fi - - if [[ -n "${extra_check}" ]]; then - if ! jq -e "${extra_check}" "${output_file}" >/dev/null 2>&1; then - echo "FAIL: ${test_name} — extra check failed: ${extra_check}" - echo "--- output ---" - jq . "${output_file}" - FAILURES=$((FAILURES + 1)) - return - fi - fi - - echo "PASS: ${test_name}" -} - -run_unsuffixed_bot_resolver_test() { - local test_name="$1" - local resolver_login="$2" - local app_set="${3:-}" - local finding_login="test-org-review" - if [[ -n "${app_set}" ]]; then - finding_login="${app_set}-review" - fi - - run_test "${test_name}" \ - "$(make_graphql_response "[{ - \"id\": \"T_${test_name}\", - \"isResolved\": true, - \"path\": \"resolver.go\", - \"line\": 7, - \"originalLine\": 7, - \"resolvedBy\": {\"login\": \"${resolver_login}\", \"__typename\": \"Bot\"}, - \"comments\": { - \"pageInfo\": {\"hasNextPage\": false}, - \"nodes\": [{\"author\": {\"login\": \"${finding_login}\", \"__typename\": \"Bot\"}, \"body\": \"Finding\", \"createdAt\": \"2026-09-01T10:00:00Z\"}] - } - }]")" \ - 0 \ - "" \ - "${app_set}" -} - -# --- Test cases --- - -# 1. No review threads at all. -run_test "no-threads" \ - "$(make_graphql_response '[]')" \ - 0 - -# 2. One human-resolved thread with explicit dismissal. -THREAD_HUMAN_RESOLVED='[{ - "id": "T_1", - "isResolved": true, - "path": "internal/cli/github.go", - "line": 42, - "originalLine": 42, - "resolvedBy": {"login": "alice", "__typename": "User"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: MarkHidden vs MarkDeprecated", "createdAt": "2026-09-01T10:00:00Z"}, - {"author": {"login": "alice", "__typename": "User"}, "body": "We explicitly asked for MarkHidden.", "createdAt": "2026-09-01T11:00:00Z"} - ] - } -}]' - -run_test "human-resolved-explicit" \ - "$(make_graphql_response "${THREAD_HUMAN_RESOLVED}")" \ - 1 \ - '.resolved_threads[0].resolved_by == "alice" and .resolved_threads[0].resolution_context == "explicit_dismissal"' - -# 3. Bot-resolved thread (auto-resolution) — should be excluded. -THREAD_BOT_RESOLVED='[{ - "id": "T_2", - "isResolved": true, - "path": "internal/cli/github.go", - "line": 10, - "originalLine": 10, - "resolvedBy": {"login": "test-org-review[bot]", "__typename": "Bot"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: something", "createdAt": "2026-09-01T10:00:00Z"} - ] - } -}]' - -run_test "bot-resolved-excluded" \ - "$(make_graphql_response "${THREAD_BOT_RESOLVED}")" \ - 0 - -# 4. Unresolved thread — should be excluded. -THREAD_UNRESOLVED='[{ - "id": "T_3", - "isResolved": false, - "path": "internal/cli/github.go", - "line": 20, - "originalLine": 20, - "resolvedBy": null, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: open issue", "createdAt": "2026-09-01T10:00:00Z"} - ] - } -}]' - -run_test "unresolved-excluded" \ - "$(make_graphql_response "${THREAD_UNRESOLVED}")" \ - 0 - -# 5. Human-resolved with finding id marker in bot comment. -THREAD_WITH_FINDING_ID='[{ - "id": "T_4", - "isResolved": true, - "path": "cmd/main.go", - "line": 100, - "originalLine": 100, - "resolvedBy": {"login": "developer", "__typename": "User"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "\n**[logic-error]** Missing nil check", "createdAt": "2026-09-01T10:00:00Z"}, - {"author": {"login": "developer", "__typename": "User"}, "body": "Handled by the caller.", "createdAt": "2026-09-01T11:00:00Z"} - ] - } -}]' - -run_test "finding-id-extracted" \ - "$(make_graphql_response "${THREAD_WITH_FINDING_ID}")" \ - 1 \ - '.resolved_threads[0].finding_id == "f_abc123"' - -# 6. Human-resolved without any human comment (silent resolution). -THREAD_SILENT='[{ - "id": "T_5", - "isResolved": true, - "path": "pkg/util.go", - "line": 55, - "originalLine": 55, - "resolvedBy": {"login": "reviewer", "__typename": "User"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: naming convention", "createdAt": "2026-09-01T10:00:00Z"} - ] - } -}]' - -run_test "silent-resolution" \ - "$(make_graphql_response "${THREAD_SILENT}")" \ - 1 \ - '.resolved_threads[0].resolution_context == "silent_resolution" and .resolved_threads[0].human_response == null' - -# 7. Mixed threads — only the human-resolved ones are included. -THREAD_MIXED='[ - { - "id": "T_6", - "isResolved": true, - "path": "a.go", - "line": 1, - "originalLine": 1, - "resolvedBy": {"login": "human1", "__typename": "User"}, - "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding 1", "createdAt": "2026-09-01T10:00:00Z"} - ]} - }, - { - "id": "T_7", - "isResolved": false, - "path": "b.go", - "line": 2, - "originalLine": 2, - "resolvedBy": null, - "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding 2", "createdAt": "2026-09-01T10:00:00Z"} - ]} - }, - { - "id": "T_8", - "isResolved": true, - "path": "c.go", - "line": 3, - "originalLine": 3, - "resolvedBy": {"login": "test-org-review[bot]", "__typename": "Bot"}, - "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding 3", "createdAt": "2026-09-01T10:00:00Z"} - ]} - }, - { - "id": "T_9", - "isResolved": true, - "path": "d.go", - "line": 4, - "originalLine": 4, - "resolvedBy": {"login": "human2", "__typename": "User"}, - "comments": {"pageInfo": {"hasNextPage": false}, "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding 4", "createdAt": "2026-09-01T10:00:00Z"}, - {"author": {"login": "human2", "__typename": "User"}, "body": "Not applicable.", "createdAt": "2026-09-01T11:00:00Z"} - ]} - } -]' - -run_test "mixed-threads" \ - "$(make_graphql_response "${THREAD_MIXED}")" \ - 2 - -# 8. GraphQL failure — script should exit 0 with empty file. -run_test "graphql-failure" \ - "" \ - 0 - -# 9. Shared vendor bot identity (fullsend-ai-review[bot]) resolved — excluded. -THREAD_SHARED_BOT_RESOLVED='[{ - "id": "T_10", - "isResolved": true, - "path": "x.go", - "line": 1, - "originalLine": 1, - "resolvedBy": {"login": "fullsend-ai-review[bot]", "__typename": "Bot"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "fullsend-ai-review", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} - ] - } -}]' - -run_test "shared-bot-resolved-excluded" \ - "$(make_graphql_response "${THREAD_SHARED_BOT_RESOLVED}")" \ - 0 - -# 10. Unsuffixed GraphQL bot resolvers are excluded by actor type, including -# the organization, shared, custom app-set, and unrelated bot identities. -run_unsuffixed_bot_resolver_test "org-unsuffixed-bot-resolved-excluded" "test-org-review" -run_unsuffixed_bot_resolver_test "shared-unsuffixed-bot-resolved-excluded" "fullsend-ai-review" -run_unsuffixed_bot_resolver_test "custom-unsuffixed-bot-resolved-excluded" "custom-review" "custom" -run_unsuffixed_bot_resolver_test "unrelated-unsuffixed-bot-resolved-excluded" "dependabot" - -# 11. Metadata fields are populated. -run_test "metadata-populated" \ - "$(make_graphql_response "${THREAD_HUMAN_RESOLVED}")" \ - 1 \ - '.metadata.pr_number == 42 and .metadata.repo == "test-org/test-repo" and .metadata.thread_count > 0' - -# 12. Incomplete comment page — skip rather than guess hidden context. -THREAD_INCOMPLETE_COMMENTS='[{ - "id": "T_11", - "isResolved": true, - "path": "e.go", - "line": 8, - "originalLine": 8, - "resolvedBy": {"login": "alice", "__typename": "User"}, - "comments": { - "pageInfo": {"hasNextPage": true}, - "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} - ] - } -}]' - -run_test "incomplete-comment-page-excluded" \ - "$(make_graphql_response "${THREAD_INCOMPLETE_COMMENTS}")" \ - 0 - -# 13. Other GitHub App resolver (login ends with [bot]) — excluded. -THREAD_DEPENDABOT_RESOLVED='[{ - "id": "T_12", - "isResolved": true, - "path": "f.go", - "line": 9, - "originalLine": 9, - "resolvedBy": {"login": "dependabot[bot]", "__typename": "Bot"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding", "createdAt": "2026-09-01T10:00:00Z"} - ] - } -}]' - -run_test "other-bot-resolved-excluded" \ - "$(make_graphql_response "${THREAD_DEPENDABOT_RESOLVED}")" \ - 0 - -# 14. Human-only resolved threads are not review findings. -THREAD_HUMAN_ONLY='[{ - "id": "T_HUMAN_ONLY", - "isResolved": true, - "path": "human.go", - "line": 11, - "originalLine": 11, - "resolvedBy": {"login": "alice", "__typename": "User"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "alice", "__typename": "User"}, "body": "Not a bot finding", "createdAt": "2026-09-01T10:00:00Z"} - ] - } -}]' - -run_test "human-only-resolved-excluded" \ - "$(make_graphql_response "${THREAD_HUMAN_ONLY}")" \ - 0 - -# 15. Custom Fullsend App-set bot identities are recognized. -THREAD_CUSTOM_APP='[{ - "id": "T_CUSTOM_APP", - "isResolved": true, - "path": "custom.go", - "line": 12, - "originalLine": 12, - "resolvedBy": {"login": "alice", "__typename": "User"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "custom-review", "__typename": "Bot"}, "body": "", "createdAt": "2026-09-01T10:00:00Z"} - ] - } -}]' - -run_test "custom-app-set-finding-id" \ - "$(make_graphql_response "${THREAD_CUSTOM_APP}")" \ - 1 \ - '.resolved_threads[0].finding_id == "f_custom"' \ - "custom" - -# 16. Resolver's comment is used, not another human's. -# Bob comments but Alice resolves — human_response should be from -# Alice (the resolver), and if Alice didn't comment it's silent. -THREAD_DIFFERENT_COMMENTER='[{ - "id": "T_13", - "isResolved": true, - "path": "g.go", - "line": 15, - "originalLine": 15, - "resolvedBy": {"login": "alice", "__typename": "User"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: something wrong", "createdAt": "2026-09-01T10:00:00Z"}, - {"author": {"login": "bob", "__typename": "User"}, "body": "I will fix this.", "createdAt": "2026-09-01T11:00:00Z"} - ] - } -}]' - -run_test "different-commenter-silent-resolution" \ - "$(make_graphql_response "${THREAD_DIFFERENT_COMMENTER}")" \ - 1 \ - '.resolved_threads[0].resolution_context == "silent_resolution" and .resolved_threads[0].human_response == null' - -# 16. Resolver left a comment — should be explicit_dismissal with their text. -THREAD_RESOLVER_COMMENTED='[{ - "id": "T_14", - "isResolved": true, - "path": "h.go", - "line": 20, - "originalLine": 20, - "resolvedBy": {"login": "alice", "__typename": "User"}, - "comments": { - "pageInfo": {"hasNextPage": false}, - "nodes": [ - {"author": {"login": "test-org-review", "__typename": "Bot"}, "body": "Finding: issue here", "createdAt": "2026-09-01T10:00:00Z"}, - {"author": {"login": "bob", "__typename": "User"}, "body": "I think this is fine.", "createdAt": "2026-09-01T10:30:00Z"}, - {"author": {"login": "alice", "__typename": "User"}, "body": "Intentional, closing.", "createdAt": "2026-09-01T11:00:00Z"} - ] - } -}]' - -run_test "resolver-commented-explicit-dismissal" \ - "$(make_graphql_response "${THREAD_RESOLVER_COMMENTED}")" \ - 1 \ - '.resolved_threads[0].resolution_context == "explicit_dismissal" and .resolved_threads[0].human_response == "Intentional, closing."' - -# 17. Metadata includes truncated flag (false when under page cap). -run_test "metadata-truncated-false" \ - "$(make_graphql_response "${THREAD_HUMAN_RESOLVED}")" \ - 1 \ - '.metadata.truncated == false' - -# --- Summary --- - -echo "" -if [[ ${FAILURES} -gt 0 ]]; then - echo "${FAILURES} test(s) failed" - exit 1 -fi -echo "All tests passed" diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh deleted file mode 100644 index 03465cced7..0000000000 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-resolved-threads.sh +++ /dev/null @@ -1,182 +0,0 @@ -#!/usr/bin/env bash -# pre-fetch-resolved-threads.sh — Fetch human-resolved review threads before the review agent runs -# -# Queries the PR's review threads through the fullsend forge client and writes -# a JSON file listing threads that a human explicitly resolved. The -# review agent uses this to avoid re-raising findings that a person -# already dismissed. -# -# Threads resolved by the bot itself (auto-resolution of outdated -# comments) are excluded — only human resolutions count. -# -# If a thread's inline comment contains a finding id marker -# (), the id is included in the output so the -# agent can match by exact id instead of fuzzy file+line. -# -# Best-effort: if the GraphQL query fails or any step errors, the -# script writes an empty file and exits 0 so the review proceeds -# without resolution data (current behavior preserved). -# -# Required environment variables (set by the review workflow): -# -# - GH_TOKEN — token with read access to the PR -# - SOURCE_REPO — owner/repo (e.g., "fullsend-ai/fullsend") -# - PR_NUM — PR number -# - ORG_NAME — org name for bot identity filtering -# -# Optional environment variables: -# -# - FULLSEND_BIN — path to the fullsend CLI (defaults to fullsend) -# - FULLSEND_APP_SET — custom review app-set prefix for bot identity filtering -# -# Outputs (via GITHUB_OUTPUT): -# - human_resolved_file — path to the JSON file -set -euo pipefail - -OUTPUT_FILE="${GITHUB_WORKSPACE:-/tmp}/human-resolved-threads.json" - -# This helper is intended for the review-agent pre-script. Local invocations -# and non-GitHub runners must not attempt a GitHub review-thread lookup. -if [[ "${GITHUB_ACTIONS:-}" != "true" ]]; then - printf '%s\n' '{"resolved_threads":[],"metadata":{"skipped":"not_github_actions"}}' > "${OUTPUT_FILE}" - echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" - exit 0 -fi - -REVIEW_BOT="${ORG_NAME}-review[bot]" -SHARED_REVIEW_BOT="fullsend-ai-review[bot]" -REVIEW_BOT_LOGIN="${ORG_NAME}-review" -SHARED_REVIEW_BOT_LOGIN="fullsend-ai-review" -APP_SET_REVIEW_BOT="" -APP_SET_REVIEW_BOT_LOGIN="" -if [[ -n "${FULLSEND_APP_SET:-}" ]]; then - APP_SET_REVIEW_BOT="${FULLSEND_APP_SET}-review[bot]" - APP_SET_REVIEW_BOT_LOGIN="${FULLSEND_APP_SET}-review" -fi - -FULLSEND_BIN="${FULLSEND_BIN:-fullsend}" -if ! response=$("${FULLSEND_BIN}" fetch-review-threads --repo "${SOURCE_REPO}" --pr "${PR_NUM}" 2>/dev/null); then - echo "::warning::Failed to fetch review threads through forge client — writing empty resolved-threads file" - echo '{"resolved_threads":[],"metadata":{"error":"forge_fetch_failed"}}' > "${OUTPUT_FILE}" - echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" - exit 0 -fi - -nodes_json=$(echo "${response}" | jq -c '.threads // []' 2>/dev/null) || { - echo "::warning::Failed to parse review threads — writing empty resolved-threads file" - echo '{"resolved_threads":[],"metadata":{"error":"parse_failed"}}' > "${OUTPUT_FILE}" - echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" - exit 0 -} -truncated=$(echo "${response}" | jq -r '.truncated // false' 2>/dev/null) || truncated="false" - -# --- Filter and transform --- -# Select threads that: -# - are resolved -# - were resolved by a human (not the review bot) -# - have at least one comment -# - comment pagination is complete (incomplete pages might hide context) -# -# For each matching thread, extract: -# - file, line, original_line from the thread -# - resolved_by from resolvedBy.login -# - the first bot comment body (for snippet matching) -# - the resolver's last comment (the resolution rationale) — only -# comments from the resolvedBy user count, not any human -# - finding_id if present in the bot comment () -# - resolution_context classification: explicit_dismissal when the -# resolver left a comment, silent_resolution otherwise -# -# The forge client preserves GraphQL actor types for both comments and -# resolvedBy. Only a positively identified User may provide a human -# resolution; login suffixes are retained as a defense-in-depth check. - -RESOLVED_THREADS=$(echo "${nodes_json}" | jq -c \ - --arg bot "${REVIEW_BOT}" \ - --arg shared_bot "${SHARED_REVIEW_BOT}" \ - --arg bot_login "${REVIEW_BOT_LOGIN}" \ - --arg shared_bot_login "${SHARED_REVIEW_BOT_LOGIN}" \ - --arg app_set_bot "${APP_SET_REVIEW_BOT}" \ - --arg app_set_bot_login "${APP_SET_REVIEW_BOT_LOGIN}" \ - '[.[] - | select(.is_resolved == true) - | select(.resolved_by != null and .resolved_by != "") - | select(.resolved_by_type == "User") - | select(.resolved_by != $bot and .resolved_by != $shared_bot) - | select(.resolved_by != $bot_login and .resolved_by != $shared_bot_login) - | select(.resolved_by != $app_set_bot and .resolved_by != $app_set_bot_login) - | select((.resolved_by | endswith("[bot]")) | not) - | select((.comments // [] | length) > 0) - | select((.comments_truncated // false) == false) - | select(any(.comments[]; - .author_type == "Bot" and - (.author == $bot_login or .author == $shared_bot_login or - .author == $app_set_bot_login or .author == $bot or - .author == $shared_bot or .author == $app_set_bot))) - | .resolved_by as $resolver - | { - file: .path, - line: .line, - original_line: .original_line, - resolved_by: $resolver, - bot_finding_snippet: ( - [.comments[] - | select(.author_type == "Bot") - | select(.author == $bot_login or .author == $shared_bot_login or - .author == $app_set_bot_login or .author == $bot or - .author == $shared_bot or .author == $app_set_bot)] - | first // null - | if . then (.body | .[0:200]) else null end - ), - finding_id: ( - [.comments[] - | select(.author_type == "Bot") - | select(.author == $bot_login or .author == $shared_bot_login or - .author == $app_set_bot_login or .author == $bot or - .author == $shared_bot or .author == $app_set_bot)] - | first // null - | if . then (.body | capture("") // null | .id // null) else null end - ), - human_response: ( - [.comments[] | select(.author == $resolver)] - | last // null - | if . then (.body | .[0:500]) else null end - ), - resolution_context: ( - if ([.comments[] | select(.author == $resolver)] | length) > 0 - then "explicit_dismissal" - else "silent_resolution" - end - ) - } - ]' 2>/dev/null) || RESOLVED_THREADS="[]" - -THREAD_COUNT=$(echo "${nodes_json}" | jq 'length' 2>/dev/null) || THREAD_COUNT=0 -RESOLVED_COUNT=$(echo "${RESOLVED_THREADS}" | jq 'length' 2>/dev/null) || RESOLVED_COUNT=0 - -# --- Write output --- -if ! jq -n \ - --argjson threads "${RESOLVED_THREADS}" \ - --argjson pr_num "${PR_NUM}" \ - --arg repo "${SOURCE_REPO}" \ - --argjson thread_count "${THREAD_COUNT}" \ - --argjson resolved_count "${RESOLVED_COUNT}" \ - --argjson truncated "${truncated}" \ - --arg fetched_at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ - '{ - resolved_threads: $threads, - metadata: { - pr_number: $pr_num, - repo: $repo, - thread_count: $thread_count, - human_resolved_count: $resolved_count, - truncated: $truncated, - fetched_at: $fetched_at - } - }' > "${OUTPUT_FILE}"; then - echo "::warning::Failed to write resolved-threads file — writing empty resolved-threads file" - echo '{"resolved_threads":[],"metadata":{"error":"write_failed"}}' > "${OUTPUT_FILE}" -fi - -echo "Resolved threads: ${RESOLVED_COUNT} human-resolved out of ${THREAD_COUNT} total" -echo "human_resolved_file=${OUTPUT_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 0d02d7f58d..09dd54a55c 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -1403,45 +1403,23 @@ func TestShimLabeledEventFiltering(t *testing.T) { } } -// TestReviewWorkflowUsesAgentPreScriptForHumanResolvedThreads protects the -// per-repo review path from growing a second CLI installation. The root action -// already installs fullsend before the agent pre-script runs, so the workflow -// only needs to pass the fetch helper and its output path to the agent. -func TestReviewWorkflowUsesAgentPreScriptForHumanResolvedThreads(t *testing.T) { - workflows := []string{ - ".github/workflows/reusable-dispatch.yml", - } - - for _, workflowPath := range workflows { - t.Run(workflowPath, func(t *testing.T) { - content, err := os.ReadFile(filepath.Join("..", "..", workflowPath)) - require.NoError(t, err) - workflow := string(content) - section := workflow - if workflowPath == ".github/workflows/reusable-dispatch.yml" { - start := strings.Index(workflow, "\n review:\n") - require.NotEqual(t, -1, start, "review job must be present") - section = workflow[start:] - if end := strings.Index(section, "\n fix:\n"); end != -1 { - section = section[:end] - } - } - - assert.Contains(t, section, "HUMAN_RESOLVED_FETCH_SCRIPT:") - assert.Contains(t, section, "HUMAN_RESOLVED_FILE:") - assert.Contains(t, section, "FULLSEND_APP_SET:") - assert.NotContains(t, section, "Detect review CLI install mode") - assert.NotContains(t, section, "Install fullsend CLI for review context") - assert.NotContains(t, section, "steps.install-fullsend") - assert.NotContains(t, section, "FULLSEND_BIN:") - }) +// TestReviewWorkflowPassesHumanResolutionOutput verifies that the per-repo +// workflow exposes the output location to the agent while leaving fetch +// orchestration to the agent pre-script. +func TestReviewWorkflowPassesHumanResolutionOutput(t *testing.T) { + content, err := os.ReadFile(filepath.Join("..", "..", ".github/workflows/reusable-dispatch.yml")) + require.NoError(t, err) + workflow := string(content) + start := strings.Index(workflow, "\n review:\n") + require.NotEqual(t, -1, start, "review job must be present") + section := workflow[start:] + if end := strings.Index(section, "\n fix:\n"); end != -1 { + section = section[:end] } - perOrgContent, err := os.ReadFile(filepath.Join("..", "..", ".github/workflows/reusable-review.yml")) - require.NoError(t, err) - perOrgAgent := extractStepSection(t, string(perOrgContent), "Run review agent") - assert.NotContains(t, perOrgAgent, "HUMAN_RESOLVED_FETCH_SCRIPT:") - assert.NotContains(t, perOrgAgent, "HUMAN_RESOLVED_FILE:") + assert.Contains(t, section, "FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }}") + assert.Contains(t, section, "HUMAN_RESOLVED_FILE: ${{ github.workspace }}/human-resolved-threads.json") + assert.NotContains(t, section, "HUMAN_RESOLVED_FETCH_SCRIPT:") } // TestRoutingLabelPrefixDrift validates that every TRIGGERING_LABEL comparison From 76f8b11790206c3d9633b2584ad9acc3286ffe2b Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 16:01:57 +0300 Subject: [PATCH 14/18] fix(review): fail closed for unknown GitLab actors Preserve unknown bot fields and document GitLab review-thread support. Co-authored-by: Codex Signed-off-by: csoceanu --- docs/guides/dev/cli-internals.md | 5 +++-- internal/forge/gitlab/methods_test.go | 14 +++++++++++++- internal/forge/gitlab/mr.go | 28 +++++++++++++++------------ 3 files changed, 32 insertions(+), 15 deletions(-) diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 6b354b202d..8d4a7120ee 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -214,8 +214,9 @@ fullsend `fetch-review-threads` emits a JSON object containing `threads` and a `truncated` flag. GitHub review threads are capped at 20 pages; consumers -must treat `truncated: true` as an incomplete result. GitLab does not -support this operation and returns an unsupported-operation error. +must treat `truncated: true` as an incomplete result. GitLab merge-request +discussions are mapped to the same thread model, including resolution state, +comments, positions, and resolver identity when GitLab provides it. The `mint`, `inference`, and `github` subcommands decompose setup into role-specific operations for organizations that separate GCP and GitHub responsibilities: diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index 9387ad0aa5..1822a68bc3 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -96,12 +96,22 @@ func TestListPullRequestReviewThreads(t *testing.T) { {"id": 8, "body": "unresolved", "resolvable": true, "resolved": false, "author": map[string]any{"username": "reviewer", "bot": false}}, }, }, + { + "id": "discussion-3", + "notes": []map[string]any{ + { + "id": 9, "body": "resolved without actor type", "resolvable": true, "resolved": true, + "author": map[string]any{"username": "reviewer"}, + "resolved_by": map[string]any{"username": "unknown-resolver"}, + }, + }, + }, }) }) got, err := client.ListPullRequestReviewThreads(context.Background(), "myorg", "myrepo", 42) require.NoError(t, err) - require.Len(t, got.Threads, 2) + require.Len(t, got.Threads, 3) assert.Equal(t, "discussion-1", got.Threads[0].ID) assert.True(t, got.Threads[0].IsResolved) assert.Equal(t, "reviewer", got.Threads[0].ResolvedBy) @@ -110,6 +120,8 @@ func TestListPullRequestReviewThreads(t *testing.T) { assert.Equal(t, 17, *got.Threads[0].Line) assert.Equal(t, "Bot", got.Threads[0].Comments[0].AuthorType) assert.False(t, got.Threads[1].IsResolved) + assert.True(t, got.Threads[2].IsResolved) + assert.Equal(t, "Unknown", got.Threads[2].ResolvedByType) } func TestCreateIssue_NoLabels(t *testing.T) { diff --git a/internal/forge/gitlab/mr.go b/internal/forge/gitlab/mr.go index bec1faadfb..97f1460e2c 100644 --- a/internal/forge/gitlab/mr.go +++ b/internal/forge/gitlab/mr.go @@ -797,11 +797,11 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re Resolved bool `json:"resolved"` Author struct { Username string `json:"username"` - Bot bool `json:"bot"` + Bot *bool `json:"bot"` } `json:"author"` ResolvedBy *struct { Username string `json:"username"` - Bot bool `json:"bot"` + Bot *bool `json:"bot"` } `json:"resolved_by"` Position *struct { NewPath string `json:"new_path"` @@ -822,13 +822,9 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re continue } - authorType := "User" - if note.Author.Bot { - authorType = "Bot" - } thread.Comments = append(thread.Comments, forge.ReviewThreadComment{ Author: note.Author.Username, - AuthorType: authorType, + AuthorType: gitlabActorType(note.Author.Bot), Body: note.Body, CreatedAt: note.CreatedAt, }) @@ -839,11 +835,7 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re thread.IsResolved = true if note.ResolvedBy != nil { thread.ResolvedBy = note.ResolvedBy.Username - if note.ResolvedBy.Bot { - thread.ResolvedByType = "Bot" - } else { - thread.ResolvedByType = "User" - } + thread.ResolvedByType = gitlabActorType(note.ResolvedBy.Bot) } if note.Position != nil { thread.Path = note.Position.NewPath @@ -868,6 +860,18 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re return result, nil } +// gitlabActorType fails closed when GitLab does not identify whether an actor +// is a bot. Callers use the User value to trust a human resolution. +func gitlabActorType(bot *bool) string { + if bot == nil { + return "Unknown" + } + if *bot { + return "Bot" + } + return "User" +} + // DismissPullRequestReview dismisses a review on a merge request. // // On GitLab, if the review was an approval, this unapproves the MR. From 6ee403ec0c066aa8fe17ead52be3913549d6769b Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 16:41:42 +0300 Subject: [PATCH 15/18] fix(review): verify GitLab discussion actors Co-authored-by: Codex Signed-off-by: csoceanu --- internal/forge/gitlab/methods_test.go | 29 +- internal/forge/gitlab/mr.go | 71 ++-- .../scaffold/workflow_call_alignment_test.go | 371 +++--------------- 3 files changed, 124 insertions(+), 347 deletions(-) diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index 1822a68bc3..1457ab39b1 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -74,6 +74,19 @@ func TestCreateIssue(t *testing.T) { func TestListPullRequestReviewThreads(t *testing.T) { client, mux := setupTest(t) + actorRequests := map[string]int{} + mux.HandleFunc("/api/v4/users/", func(w http.ResponseWriter, r *http.Request) { + actorID := strings.TrimPrefix(r.URL.Path, "/api/v4/users/") + actorRequests[actorID]++ + switch actorID { + case "10": + writeJSON(t, w, http.StatusOK, map[string]any{"id": 10, "username": "botuser", "bot": true}) + case "20": + writeJSON(t, w, http.StatusOK, map[string]any{"id": 20, "username": "reviewer", "bot": false}) + default: + writeJSON(t, w, http.StatusNotFound, map[string]string{"message": "404 User Not Found"}) + } + }) mux.HandleFunc("/api/v4/projects/myorg%2Fmyrepo/merge_requests/42/discussions", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, "100", r.URL.Query().Get("per_page")) assert.Equal(t, "1", r.URL.Query().Get("page")) @@ -84,8 +97,8 @@ func TestListPullRequestReviewThreads(t *testing.T) { { "id": 7, "body": "Please update this", "created_at": "2026-10-06T10:00:00Z", "resolvable": true, "resolved": true, - "author": map[string]any{"username": "botuser", "bot": true}, - "resolved_by": map[string]any{"username": "reviewer", "bot": false}, + "author": map[string]any{"id": 10, "username": "botuser"}, + "resolved_by": map[string]any{"id": 20, "username": "reviewer"}, "position": map[string]any{"new_path": "main.go", "old_path": "main.go", "new_line": 17, "old_line": 16}, }, }, @@ -93,7 +106,7 @@ func TestListPullRequestReviewThreads(t *testing.T) { { "id": "discussion-2", "notes": []map[string]any{ - {"id": 8, "body": "unresolved", "resolvable": true, "resolved": false, "author": map[string]any{"username": "reviewer", "bot": false}}, + {"id": 8, "body": "unresolved", "resolvable": true, "resolved": false, "author": map[string]any{"id": 20, "username": "reviewer"}, "position": map[string]any{"new_path": "unresolved.go", "new_line": 3}}, }, }, { @@ -101,8 +114,8 @@ func TestListPullRequestReviewThreads(t *testing.T) { "notes": []map[string]any{ { "id": 9, "body": "resolved without actor type", "resolvable": true, "resolved": true, - "author": map[string]any{"username": "reviewer"}, - "resolved_by": map[string]any{"username": "unknown-resolver"}, + "author": map[string]any{"id": 20, "username": "reviewer"}, + "resolved_by": map[string]any{"id": 30, "username": "unknown-resolver"}, }, }, }, @@ -120,8 +133,14 @@ func TestListPullRequestReviewThreads(t *testing.T) { assert.Equal(t, 17, *got.Threads[0].Line) assert.Equal(t, "Bot", got.Threads[0].Comments[0].AuthorType) assert.False(t, got.Threads[1].IsResolved) + assert.Equal(t, "unresolved.go", got.Threads[1].Path, "position data is retained before unresolved notes are skipped") + require.NotNil(t, got.Threads[1].Line) + assert.Equal(t, 3, *got.Threads[1].Line) assert.True(t, got.Threads[2].IsResolved) assert.Equal(t, "Unknown", got.Threads[2].ResolvedByType) + assert.Equal(t, 1, actorRequests["10"]) + assert.Equal(t, 1, actorRequests["20"], "the actor lookup should be cached per request") + assert.Equal(t, 1, actorRequests["30"]) } func TestCreateIssue_NoLabels(t *testing.T) { diff --git a/internal/forge/gitlab/mr.go b/internal/forge/gitlab/mr.go index 97f1460e2c..25468ed251 100644 --- a/internal/forge/gitlab/mr.go +++ b/internal/forge/gitlab/mr.go @@ -770,6 +770,11 @@ func (c *LiveClient) ListPullRequestReviews(ctx context.Context, owner, repo str return result, nil } +type gitlabDiscussionActor struct { + ID int `json:"id"` + Username string `json:"username"` +} + // ListPullRequestReviewThreads maps GitLab merge-request discussions to the // common review-thread model. A discussion is resolved when one of its // resolvable notes is marked resolved; the resolver and note authors are @@ -777,6 +782,28 @@ func (c *LiveClient) ListPullRequestReviews(ctx context.Context, owner, repo str func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, repo string, number int) (forge.ReviewThreadPage, error) { proj := projectPath(owner, repo) result := forge.ReviewThreadPage{} + actorTypes := make(map[int]string) + lookupActorType := func(actor *gitlabDiscussionActor) string { + if actor == nil || actor.ID == 0 { + return "Unknown" + } + if actorType, ok := actorTypes[actor.ID]; ok { + return actorType + } + + actorType := "Unknown" + resp, err := c.get(ctx, fmt.Sprintf("/users/%d", actor.ID)) + if err == nil { + var user struct { + Bot *bool `json:"bot"` + } + if decodeErr := decodeJSON(resp, &user); decodeErr == nil { + actorType = gitlabActorType(user.Bot) + } + } + actorTypes[actor.ID] = actorType + return actorType + } for page := 1; page <= 20; page++ { path := fmt.Sprintf("/projects/%s/merge_requests/%d/discussions?per_page=100&page=%d", @@ -789,21 +816,15 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re var discussions []struct { ID string `json:"id"` Notes []struct { - ID int `json:"id"` - Body string `json:"body"` - System bool `json:"system"` - CreatedAt string `json:"created_at"` - Resolvable bool `json:"resolvable"` - Resolved bool `json:"resolved"` - Author struct { - Username string `json:"username"` - Bot *bool `json:"bot"` - } `json:"author"` - ResolvedBy *struct { - Username string `json:"username"` - Bot *bool `json:"bot"` - } `json:"resolved_by"` - Position *struct { + ID int `json:"id"` + Body string `json:"body"` + System bool `json:"system"` + CreatedAt string `json:"created_at"` + Resolvable bool `json:"resolvable"` + Resolved bool `json:"resolved"` + Author gitlabDiscussionActor `json:"author"` + ResolvedBy *gitlabDiscussionActor `json:"resolved_by"` + Position *struct { NewPath string `json:"new_path"` OldPath string `json:"old_path"` NewLine *int `json:"new_line"` @@ -824,19 +845,10 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re thread.Comments = append(thread.Comments, forge.ReviewThreadComment{ Author: note.Author.Username, - AuthorType: gitlabActorType(note.Author.Bot), + AuthorType: lookupActorType(¬e.Author), Body: note.Body, CreatedAt: note.CreatedAt, }) - - if !note.Resolvable || !note.Resolved { - continue - } - thread.IsResolved = true - if note.ResolvedBy != nil { - thread.ResolvedBy = note.ResolvedBy.Username - thread.ResolvedByType = gitlabActorType(note.ResolvedBy.Bot) - } if note.Position != nil { thread.Path = note.Position.NewPath if thread.Path == "" { @@ -845,6 +857,15 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re thread.Line = note.Position.NewLine thread.OriginalLine = note.Position.OldLine } + + if !note.Resolvable || !note.Resolved { + continue + } + thread.IsResolved = true + if note.ResolvedBy != nil { + thread.ResolvedBy = note.ResolvedBy.Username + thread.ResolvedByType = lookupActorType(note.ResolvedBy) + } } result.Threads = append(result.Threads, thread) } diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 09dd54a55c..d2bf6b38bc 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -25,6 +25,25 @@ type reusableWorkflow struct { } `yaml:"on"` } +// TestReviewWorkflowPassesHumanResolutionOutput verifies that the supported +// per-repo review workflow exposes the output location to the agent while the +// agent pre-script owns fetch orchestration. +func TestReviewWorkflowPassesHumanResolutionOutput(t *testing.T) { + content, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "reusable-dispatch.yml")) + require.NoError(t, err) + workflow := string(content) + start := strings.Index(workflow, "\n review:\n") + require.NotEqual(t, -1, start, "review job must be present") + section := workflow[start:] + if end := strings.Index(section, "\n fix:\n"); end != -1 { + section = section[:end] + } + + assert.Contains(t, section, "FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }}") + assert.Contains(t, section, "HUMAN_RESOLVED_FILE: ${{ github.workspace }}/human-resolved-threads.json") + assert.NotContains(t, section, "HUMAN_RESOLVED_FETCH_SCRIPT:") +} + type workflowInput struct { Required bool `yaml:"required"` Type string `yaml:"type"` @@ -65,26 +84,6 @@ type stageConcurrencyExpectation struct { } var thinCallerConcurrencyExpectations = map[string]stageConcurrencyExpectation{ - "triage": { - groupPrefix: "fullsend-triage-", - groupMust: []string{"inputs.source_repo", "issue.number"}, - }, - "code": { - groupPrefix: "fullsend-code-", - groupMust: []string{"inputs.source_repo", "issue.number"}, - }, - "review": { - groupPrefix: "fullsend-review-", - groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number"}, - }, - "fix": { - groupPrefix: "fullsend-fix-", - groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number", "inputs.pr_number"}, - }, - "retro": { - groupPrefix: "fullsend-retro-", - groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number"}, - }, "prioritize": { groupPrefix: "fullsend-prioritize-", groupMust: []string{"inputs.source_repo", "issue.number"}, @@ -92,26 +91,6 @@ var thinCallerConcurrencyExpectations = map[string]stageConcurrencyExpectation{ } var reusableAgentConcurrencyExpectations = map[string]stageConcurrencyExpectation{ - "triage": { - groupPrefix: "fullsend-triage-agent-", - groupMust: []string{"inputs.source_repo", "issue.number", "pull_request.number"}, - }, - "code": { - groupPrefix: "fullsend-code-agent-", - groupMust: []string{"inputs.source_repo", "issue.number", "pull_request.number"}, - }, - "review": { - groupPrefix: "fullsend-review-agent-", - groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number"}, - }, - "fix": { - groupPrefix: "fullsend-fix-agent-", - groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number", "inputs.pr_number"}, - }, - "retro": { - groupPrefix: "fullsend-retro-agent-", - groupMust: []string{"inputs.source_repo", "pull_request.number", "issue.number"}, - }, "prioritize": { groupPrefix: "fullsend-prioritize-agent-", groupMust: []string{"inputs.source_repo", "issue.number", "pull_request.number"}, @@ -186,11 +165,6 @@ type callerPair struct { } var workflowCallPairs = []callerPair{ - {"scaffold/triage.yml", loadRenderedScaffoldCaller(".github/workflows/triage.yml"), "triage"}, - {"scaffold/code.yml", loadRenderedScaffoldCaller(".github/workflows/code.yml"), "code"}, - {"scaffold/review.yml", loadRenderedScaffoldCaller(".github/workflows/review.yml"), "review"}, - {"scaffold/fix.yml", loadRenderedScaffoldCaller(".github/workflows/fix.yml"), "fix"}, - {"scaffold/retro.yml", loadRenderedScaffoldCaller(".github/workflows/retro.yml"), "retro"}, {"scaffold/prioritize.yml", loadRenderedScaffoldCaller(".github/workflows/prioritize.yml"), "prioritize"}, } @@ -199,7 +173,7 @@ func loadRenderedScaffoldCaller(path string) func(t *testing.T) []byte { t.Helper() raw, err := FullsendRepoFile(path) require.NoError(t, err) - rendered, err := RenderTemplate(path, raw, RenderOptionsForInstall(false, false, "", "")) + rendered, err := RenderTemplate(path, raw, RenderOptionsForInstall(false, "", "")) require.NoError(t, err) return rendered } @@ -295,17 +269,9 @@ func TestReusableWorkflowInputContractAlignment(t *testing.T) { var dispatch reusableWorkflow require.NoError(t, yaml.Unmarshal(dispatchContent, &dispatch)) - for _, pair := range workflowCallPairs { - t.Run(pair.callerName, func(t *testing.T) { - callerContent := pair.callerSource(t) - var caller callerWorkflow - require.NoError(t, yaml.Unmarshal(callerContent, &caller)) - - job, ok := caller.Jobs[pair.jobName] - require.True(t, ok, "job %q not found in caller workflow", pair.jobName) - match := reusableWorkflowRef.FindString(job.Uses) - require.NotEmpty(t, match, "could not extract reusable workflow filename from uses: %q", job.Uses) - + for _, stageName := range []string{"prioritize"} { + match := fmt.Sprintf("reusable-%s.yml", stageName) + t.Run(match, func(t *testing.T) { stageContent, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", match)) require.NoError(t, err, "could not read reusable workflow %s", match) @@ -318,16 +284,6 @@ func TestReusableWorkflowInputContractAlignment(t *testing.T) { continue } if name == "install_mode" { - // Dispatch defaults to per-repo; standalone stage workflows - // default to per-org until that deprecated chain is removed. - assert.False(t, dispatchInput.Required, - "reusable-dispatch.yml install_mode must remain optional") - assert.Equal(t, "per-repo", dispatchInput.Default, - "reusable-dispatch.yml install_mode default changed") - assert.False(t, stageInput.Required, - "%s install_mode must remain optional", match) - assert.Equal(t, "per-org", stageInput.Default, - "%s install_mode default changed", match) continue } assert.Equal(t, dispatchInput.Required, stageInput.Required, @@ -353,7 +309,6 @@ func TestReusableWorkflowsShareCommonInputs(t *testing.T) { "mint_url", "gcp_region", "fullsend_version", - "install_mode", "fullsend_ai_ref", "runner_image", } @@ -366,7 +321,7 @@ func TestReusableWorkflowsShareCommonInputs(t *testing.T) { "OTEL_EXPORTER_OTLP_HEADERS", } - stages := []string{"triage", "code", "review", "fix", "retro", "prioritize"} + stages := []string{"prioritize"} for _, stage := range stages { t.Run(stage, func(t *testing.T) { @@ -482,11 +437,6 @@ func TestOpenAIAPIKeySecretThreading(t *testing.T) { content func(t *testing.T) []byte }{ {"scaffold/templates/shim-per-repo.yaml", loadScaffoldFile("templates/shim-per-repo.yaml")}, - {"scaffold/triage.yml", loadScaffoldFile(".github/workflows/triage.yml")}, - {"scaffold/code.yml", loadScaffoldFile(".github/workflows/code.yml")}, - {"scaffold/review.yml", loadScaffoldFile(".github/workflows/review.yml")}, - {"scaffold/fix.yml", loadScaffoldFile(".github/workflows/fix.yml")}, - {"scaffold/retro.yml", loadScaffoldFile(".github/workflows/retro.yml")}, {"scaffold/prioritize.yml", loadScaffoldFile(".github/workflows/prioritize.yml")}, // This repo's own installed shims (not just the scaffold templates // new installs get) must forward the secret too, or fullsend's own @@ -504,9 +454,9 @@ func TestOpenAIAPIKeySecretThreading(t *testing.T) { declaration := "FULLSEND_OPENAI_API_KEY:\n required: false" export := "OPENAI_API_KEY: ${{ secrets.FULLSEND_OPENAI_API_KEY }}" - // Standalone reusable-{stage}.yml files have exactly one job/one agent - // step each, so a whole-file substring check is unambiguous. - standaloneStages := []string{"triage", "code", "review", "fix", "retro", "prioritize"} + // The standalone reusable-prioritize.yml has exactly one job/one agent + // step, so a whole-file substring check is unambiguous. + standaloneStages := []string{"prioritize"} for _, stage := range standaloneStages { t.Run("reusable-"+stage+".yml", func(t *testing.T) { content := string(loadRepoFile(fmt.Sprintf(".github/workflows/reusable-%s.yml", stage))(t)) @@ -546,8 +496,8 @@ func TestOpenAIAPIKeySecretThreading(t *testing.T) { } // TestOTELHeadersSecretThreading validates that the optional OTLP headers -// secrets (#2862, #5886) are forwarded along both installation-mode chains -// to every reusable stage workflow. TestWorkflowCallInputAlignment only +// secrets (#2862, #5886) are forwarded by the scaffold callers and injected +// by every reusable stage workflow. TestWorkflowCallInputAlignment only // enforces required secrets; an omitted optional forward silently arrives // empty, which turns into a 401 at authenticated backends instead of // failing loudly. @@ -563,17 +513,7 @@ func TestOTELHeadersSecretThreading(t *testing.T) { }{ // per-repo chain: shim → reusable-dispatch {"scaffold/templates/shim-per-repo.yaml", loadScaffoldFile("templates/shim-per-repo.yaml")}, - // per-org chain: thin caller → reusable-{stage} - {"reusable-triage.yml", loadRepoFile(".github/workflows/reusable-triage.yml")}, - {"scaffold/triage.yml", loadScaffoldFile(".github/workflows/triage.yml")}, - {"reusable-code.yml", loadRepoFile(".github/workflows/reusable-code.yml")}, - {"scaffold/code.yml", loadScaffoldFile(".github/workflows/code.yml")}, - {"reusable-review.yml", loadRepoFile(".github/workflows/reusable-review.yml")}, - {"scaffold/review.yml", loadScaffoldFile(".github/workflows/review.yml")}, - {"reusable-fix.yml", loadRepoFile(".github/workflows/reusable-fix.yml")}, - {"scaffold/fix.yml", loadScaffoldFile(".github/workflows/fix.yml")}, - {"reusable-retro.yml", loadRepoFile(".github/workflows/reusable-retro.yml")}, - {"scaffold/retro.yml", loadScaffoldFile(".github/workflows/retro.yml")}, + // standalone reusable-{stage} workflows (prioritize thin caller chain) {"reusable-prioritize.yml", loadRepoFile(".github/workflows/reusable-prioritize.yml")}, {"scaffold/prioritize.yml", loadScaffoldFile(".github/workflows/prioritize.yml")}, } @@ -636,8 +576,8 @@ func TestOTELVariableForwarding(t *testing.T) { return v + ": ${{ vars." + v + " }}" } - // Reusable stage workflows (single agent step each). - stages := []string{"triage", "code", "review", "fix", "retro", "prioritize"} + // Standalone reusable stage workflows (single agent step each). + stages := []string{"prioritize"} for _, stage := range stages { t.Run("reusable-"+stage+".yml", func(t *testing.T) { content := string(loadRepoFile(fmt.Sprintf(".github/workflows/reusable-%s.yml", stage))(t)) @@ -718,7 +658,8 @@ func TestReusableAgentWorkflowConcurrency(t *testing.T) { assert.True(t, wf.Concurrency.CancelInProgress, "reusable-%s.yml should cancel in-progress runs", stage) - callerExpect := thinCallerConcurrencyExpectations[stage] + callerExpect := dispatchStageConcurrencyExpectations[stage] + require.NotEmpty(t, callerExpect.groupPrefix, "missing dispatch expectation for %s", stage) assert.NotEqual(t, callerExpect.groupPrefix, expect.groupPrefix, "reusable-%s.yml must use a distinct agent-scoped group prefix", stage) assert.Contains(t, wf.Concurrency.Group, "-agent-", @@ -728,7 +669,7 @@ func TestReusableAgentWorkflowConcurrency(t *testing.T) { } // TestThinCallerStageConcurrency validates per-role cancel-in-progress groups on -// per-org thin caller workflows in the scaffold (#981, ADR 0033). +// thin caller workflows in the scaffold (#981, ADR 0033). func TestThinCallerStageConcurrency(t *testing.T) { for stage, expect := range thinCallerConcurrencyExpectations { t.Run(stage, func(t *testing.T) { @@ -750,7 +691,7 @@ func TestThinCallerStageConcurrency(t *testing.T) { } // TestReusableDispatchWorkflowContent validates PR-context gating in per-repo -// reusable-dispatch.yml routing (per-org dispatch.yml unchanged). +// reusable-dispatch.yml routing. func TestReusableDispatchWorkflowContent(t *testing.T) { content, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "reusable-dispatch.yml")) require.NoError(t, err) @@ -761,9 +702,7 @@ func TestReusableDispatchWorkflowContent(t *testing.T) { // TestCustomAppSetReviewBotWiring ensures every GitHub review/fix dispatch // path receives the configured app-set prefix and recognizes its exact review -// bot identity. The scaffold dispatch workflow is a legacy, deprecated -// per-org compatibility path retained only until ADR 0044 removal; workflow -// parity requires it to stay aligned with the supported per-repo path. +// bot identity. func TestCustomAppSetReviewBotWiring(t *testing.T) { cases := []struct { name string @@ -771,9 +710,6 @@ func TestCustomAppSetReviewBotWiring(t *testing.T) { assertCustom bool }{ {"reusable-dispatch", loadRepoFile(".github/workflows/reusable-dispatch.yml"), true}, - {"reusable-fix", loadRepoFile(".github/workflows/reusable-fix.yml"), true}, - {"reusable-review", loadRepoFile(".github/workflows/reusable-review.yml"), false}, - {"scaffold-dispatch", loadScaffoldFile(".github/workflows/dispatch.yml"), true}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -790,7 +726,6 @@ func TestCustomAppSetReviewBotWiring(t *testing.T) { content func(*testing.T) []byte }{ {"reusable-dispatch", loadRepoFile(".github/workflows/reusable-dispatch.yml")}, - {"scaffold-dispatch", loadScaffoldFile(".github/workflows/dispatch.yml")}, } { t.Run(tc.name+"-route", func(t *testing.T) { s := string(tc.content(t)) @@ -814,16 +749,6 @@ func TestCustomAppSetReviewBotWiring(t *testing.T) { loadRepoFile(".github/workflows/reusable-dispatch.yml"), []string{"Pre-fetch prior review context", "Check fix eligibility", "Pre-fetch review body"}, }, - { - "reusable-fix", - loadRepoFile(".github/workflows/reusable-fix.yml"), - []string{"Check fix eligibility", "Pre-fetch review body"}, - }, - { - "reusable-review", - loadRepoFile(".github/workflows/reusable-review.yml"), - []string{"Pre-fetch prior review context"}, - }, } { t.Run(tc.name+"-consumers", func(t *testing.T) { s := string(tc.content(t)) @@ -840,7 +765,7 @@ func TestCustomAppSetReviewBotWiring(t *testing.T) { } } -// TestDispatchPunctuationStrip ensures both dispatch files strip trailing +// TestDispatchPunctuationStrip ensures reusable-dispatch.yml strips trailing // punctuation clusters (not just a single char) from COMMAND and SECOND_WORD. // See #5582. func TestDispatchPunctuationStrip(t *testing.T) { @@ -850,7 +775,6 @@ func TestDispatchPunctuationStrip(t *testing.T) { } cases := []workflowCase{ {"reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml")}, - {"scaffold/dispatch.yml", loadScaffoldFile(".github/workflows/dispatch.yml")}, } for _, wc := range cases { t.Run(wc.name, func(t *testing.T) { @@ -877,10 +801,6 @@ func TestDispatchPerStageAuthorization(t *testing.T) { "reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml"), }, - { - "scaffold/dispatch.yml", - loadScaffoldFile(".github/workflows/dispatch.yml"), - }, } for _, wc := range cases { @@ -954,7 +874,6 @@ func TestOwnersCheckoutRefPin(t *testing.T) { content func(t *testing.T) []byte }{ {"reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml")}, - {"scaffold/dispatch.yml", loadScaffoldFile(".github/workflows/dispatch.yml")}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -982,7 +901,7 @@ func TestOwnersCheckoutRefPin(t *testing.T) { } } -// TestShimScaffoldBranchFilter validates that both shim templates skip dispatch +// TestShimScaffoldBranchFilter validates that the shim template skips dispatch // for PRs from the fullsend/scaffold branch. Without this filter, the shim // fires pull_request_target on the scaffold PR, causing dispatch noise (#5470). func TestShimScaffoldBranchFilter(t *testing.T) { @@ -990,7 +909,6 @@ func TestShimScaffoldBranchFilter(t *testing.T) { name string content func(t *testing.T) []byte }{ - {"shim-workflow-call", loadScaffoldFile("templates/shim-workflow-call.yaml")}, {"shim-per-repo", loadScaffoldFile("templates/shim-per-repo.yaml")}, } for _, tc := range cases { @@ -1029,7 +947,6 @@ func TestShimPerRepoNoFullsendAlias(t *testing.T) { content func(t *testing.T) []byte } cases := []workflowCase{ - {"scaffold/dispatch.yml", loadScaffoldFile(".github/workflows/dispatch.yml")}, {"reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml")}, } for _, wc := range cases { @@ -1060,7 +977,7 @@ func TestLiveShimSlashCommandFilter(t *testing.T) { "fullsend.yaml must retain bot-type filter for defense-in-depth alongside /fs- prefix check") } -// TestDispatchPRHeadResolution validates that both dispatch workflows contain +// TestDispatchPRHeadResolution validates that reusable-dispatch.yml contains // the "Resolve PR head for issue_comment events" step and the pull_request // merge into event_payload, ensuring issue_comment-triggered agents receive // the correct PR head SHA. @@ -1075,10 +992,6 @@ func TestDispatchPRHeadResolution(t *testing.T) { "reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml"), }, - { - "scaffold/dispatch.yml", - loadScaffoldFile(".github/workflows/dispatch.yml"), - }, } for _, wc := range cases { @@ -1123,10 +1036,6 @@ func TestDispatchPRCheckBotFilter(t *testing.T) { "reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml"), }, - { - "scaffold/dispatch.yml", - loadScaffoldFile(".github/workflows/dispatch.yml"), - }, } for _, wc := range cases { @@ -1205,17 +1114,6 @@ func TestReusableDispatchPRHeadSHAPassthrough(t *testing.T) { // common harness-dispatch path expose the forge-neutral key alongside the // backwards-compatible GitHub issue number (#6760). func TestWorkItemKeyEnvCompatibility(t *testing.T) { - t.Run("legacy reusable code", func(t *testing.T) { - content := string(loadRepoFile(".github/workflows/reusable-code.yml")(t)) - section := extractStepSection(t, content, "Run code agent") - assert.Contains(t, section, - "FULLSEND_WORK_ITEM_URL: ${{ fromJSON(inputs.event_payload).issue.html_url }}") - assert.Contains(t, section, - "FULLSEND_WORK_ITEM_KEY: ${{ fromJSON(inputs.event_payload).issue.number }}") - assert.Contains(t, section, - "ISSUE_NUMBER: ${{ fromJSON(inputs.event_payload).issue.number }}") - }) - t.Run("route based code", func(t *testing.T) { content := string(loadRepoFile(".github/workflows/reusable-dispatch.yml")(t)) section := extractStepSection(t, content, "Run code agent") @@ -1304,57 +1202,21 @@ func TestPrioritizeThinCallerThreadsProjectNumber(t *testing.T) { "prioritize thin caller must fall back to vars.FULLSEND_PROJECT_NUMBER when input is empty") } -// TestShimLabeledEventFiltering validates that shim workflows use the ready- -// prefix filter at the if: guard level and label-aware concurrency keys so -// routing labels don't cancel each other (#2452). -// -// The per-repo shim is exempt from the prefix filter because it has no -// concurrency group and BYOA harness agents may trigger on arbitrary labels. +// TestShimLabeledEventFiltering validates that per-repo shims do not filter +// labeled events on a routing-label prefix and carry no job-level +// concurrency group (#2452, ADR 0034). BYOA harness agents may trigger on +// arbitrary labels, and per-role groups live in reusable-dispatch.yml. func TestShimLabeledEventFiltering(t *testing.T) { - type shimCase struct { - name string - content func(t *testing.T) []byte - hasConcurrency bool - } - - cases := []shimCase{ - {"fullsend.yaml", loadRepoFile(".github/workflows/fullsend.yaml"), false}, - {"scaffold/shim-workflow-call.yaml", loadScaffoldFile("templates/shim-workflow-call.yaml"), true}, - {"scaffold/shim-per-repo.yaml", loadScaffoldFile("templates/shim-per-repo.yaml"), false}, - } - - // Workflow-call shims must have the ready- prefix filter in the if: guard. - // The per-repo shim is exempt (no concurrency group, BYOA compat). - for _, tc := range cases { - if !tc.hasConcurrency { - continue - } - t.Run(tc.name+"/guard", func(t *testing.T) { - var wf callerWorkflow - require.NoError(t, yaml.Unmarshal(tc.content(t), &wf)) - job, ok := wf.Jobs["dispatch"] - require.True(t, ok, "%s must have a dispatch job", tc.name) - - // Pin the full composed clause including enclosing parens and the - // joining && that conjoins it with the preceding guards. Without - // the parens, && binds tighter than || in GHA expressions and the - // ready- prefix gate floats to the top of the entire if:. Without - // the joining &&, the clause could be OR'd, bypassing the - // scaffold-install and bot-comment guards. Whitespace is flexible - // via \s* to tolerate reformatting. - assert.Regexp(t, - `\)\s*&&\s*\(\s*github\.event\.action\s*!=\s*'labeled'\s*\|\|\s*startsWith\(github\.event\.label\.name,\s*'ready-'\)\s*\)`, - job.If, - "%s if: guard must AND-conjoin the ready- prefix filter with enclosing parens", tc.name) - }) + cases := []struct { + name string + content func(t *testing.T) []byte + }{ + {"fullsend.yaml", loadRepoFile(".github/workflows/fullsend.yaml")}, + {"scaffold/shim-per-repo.yaml", loadScaffoldFile("templates/shim-per-repo.yaml")}, } - // Per-repo shim must NOT have the ready- prefix filter (BYOA compat). for _, tc := range cases { - if tc.hasConcurrency { - continue - } - t.Run(tc.name+"/no-label-guard", func(t *testing.T) { + t.Run(tc.name, func(t *testing.T) { var wf callerWorkflow require.NoError(t, yaml.Unmarshal(tc.content(t), &wf)) job, ok := wf.Jobs["dispatch"] @@ -1362,135 +1224,14 @@ func TestShimLabeledEventFiltering(t *testing.T) { assert.NotContains(t, job.If, "startsWith(github.event.label.name", "%s per-repo shim must not filter on label prefix — BYOA harness agents may use arbitrary labels", tc.name) - }) - } - - // Workflow-call shims must have a label-aware concurrency key (#2452). - for _, tc := range cases { - if !tc.hasConcurrency { - continue - } - t.Run(tc.name+"/concurrency", func(t *testing.T) { - var wf callerWorkflow - require.NoError(t, yaml.Unmarshal(tc.content(t), &wf)) - job, ok := wf.Jobs["dispatch"] - require.True(t, ok, "%s must have a dispatch job", tc.name) - require.NotNil(t, job.Concurrency, "%s dispatch job must have a concurrency group", tc.name) - - assert.Regexp(t, - `fullsend-dispatch-\$\{\{\s*github\.event\.issue\.number\s*\|\|\s*github\.event\.pull_request\.number\s*\}\}-\$\{\{\s*github\.event\.action\s*==\s*'labeled'\s*&&\s*format\('label-\{0\}',\s*github\.event\.label\.name\)\s*\|\|\s*'dispatch'\s*\}\}`, - job.Concurrency.Group, - "%s concurrency group must match full label-aware structure", tc.name) - assert.False(t, job.Concurrency.CancelInProgress, - "%s concurrency group must have cancel-in-progress: false", tc.name) - }) - } - - // Per-repo shim must NOT have a job-level concurrency group (ADR 0034); - // per-role groups live in reusable-dispatch.yml stage jobs. - for _, tc := range cases { - if tc.hasConcurrency { - continue - } - t.Run(tc.name+"/no-concurrency", func(t *testing.T) { - var wf callerWorkflow - require.NoError(t, yaml.Unmarshal(tc.content(t), &wf)) - job, ok := wf.Jobs["dispatch"] - require.True(t, ok, "%s must have a dispatch job", tc.name) assert.Nil(t, job.Concurrency, "%s per-repo shim must not have job-level concurrency (ADR 0034: per-role groups live in reusable-dispatch.yml)", tc.name) }) } } -// TestReviewWorkflowPassesHumanResolutionOutput verifies that the per-repo -// workflow exposes the output location to the agent while leaving fetch -// orchestration to the agent pre-script. -func TestReviewWorkflowPassesHumanResolutionOutput(t *testing.T) { - content, err := os.ReadFile(filepath.Join("..", "..", ".github/workflows/reusable-dispatch.yml")) - require.NoError(t, err) - workflow := string(content) - start := strings.Index(workflow, "\n review:\n") - require.NotEqual(t, -1, start, "review job must be present") - section := workflow[start:] - if end := strings.Index(section, "\n fix:\n"); end != -1 { - section = section[:end] - } - - assert.Contains(t, section, "FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }}") - assert.Contains(t, section, "HUMAN_RESOLVED_FILE: ${{ github.workspace }}/human-resolved-threads.json") - assert.NotContains(t, section, "HUMAN_RESOLVED_FETCH_SCRIPT:") -} - -// TestRoutingLabelPrefixDrift validates that every TRIGGERING_LABEL comparison -// in the per-org scaffold dispatch workflow satisfies the ready- prefix -// predicate used by the workflow-call shim if: guard. If someone adds a -// routing label without the prefix, this test converts a silent production -// skip into a build break (#2452). -// -// Scope: scaffold/dispatch.yml only — the router that per-org (workflow-call) -// shims deploy. reusable-dispatch.yml serves per-repo installs whose shim -// has no prefix guard (BYOA compat), so it is intentionally excluded. -func TestRoutingLabelPrefixDrift(t *testing.T) { - dispatchFiles := []struct { - name string - content func(t *testing.T) []byte - }{ - {"scaffold/dispatch.yml", loadScaffoldFile(".github/workflows/dispatch.yml")}, - } - - // Match all forms of TRIGGERING_LABEL comparison. Braces and quotes - // are optional so unbraced ($TRIGGERING_LABEL) and unquoted RHS forms - // are visible. For case blocks, the header is matched first and then - // every arm up to esac is collected, splitting on | for joined arms. - eqPattern := regexp.MustCompile(`TRIGGERING_LABEL\}?"?\s*={1,2}\s*"?([^")\s]+)"?`) - rePattern := regexp.MustCompile(`TRIGGERING_LABEL\}?"?\s*=~\s*"?([^")\s]+)"?`) - caseHeader := regexp.MustCompile(`(?m)case\s+"?\$\{?TRIGGERING_LABEL\}?"?\s+in\b`) - caseArm := regexp.MustCompile(`(?m)^\s*([\w|*?-]+)\)`) - - extractLabels := func(content string) []string { - var labels []string - for _, m := range eqPattern.FindAllStringSubmatch(content, -1) { - labels = append(labels, m[1]) - } - for _, m := range rePattern.FindAllStringSubmatch(content, -1) { - labels = append(labels, m[1]) - } - for _, headerLoc := range caseHeader.FindAllStringIndex(content, -1) { - block := content[headerLoc[1]:] - esacIdx := strings.Index(block, "esac") - if esacIdx >= 0 { - block = block[:esacIdx] - } - for _, m := range caseArm.FindAllStringSubmatch(block, -1) { - for _, arm := range strings.Split(m[1], "|") { - labels = append(labels, arm) - } - } - } - return labels - } - - for _, df := range dispatchFiles { - t.Run(df.name, func(t *testing.T) { - content := string(df.content(t)) - labels := extractLabels(content) - require.Len(t, labels, 4, - "%s: expected exactly 4 TRIGGERING_LABEL comparisons (found %d) — "+ - "if a comparison was added or restyled, update this count and verify "+ - "the new label satisfies the ready- prefix predicate", df.name, len(labels)) - - for _, label := range labels { - assert.True(t, strings.HasPrefix(label, "ready-"), - "%s: routing label %q does not satisfy the ready- prefix predicate — "+ - "per-org workflow-call shim if: guard will silently skip it (#2452)", df.name, label) - } - }) - } -} - // TestRoleCheckCaseBranches validates the role-check step's case mapping and -// backward-compat logic in both dispatch workflows (#2298). +// backward-compat logic in reusable-dispatch.yml (#2298). func TestRoleCheckCaseBranches(t *testing.T) { type workflowCase struct { name string @@ -1502,10 +1243,6 @@ func TestRoleCheckCaseBranches(t *testing.T) { "reusable-dispatch.yml", loadRepoFile(".github/workflows/reusable-dispatch.yml"), }, - { - "scaffold/dispatch.yml", - loadScaffoldFile(".github/workflows/dispatch.yml"), - }, } for _, wc := range cases { @@ -1554,7 +1291,7 @@ func TestOpenAIVariableForwarding(t *testing.T) { return v + ": ${{ vars." + v + " }}" } - stages := []string{"triage", "code", "review", "fix", "retro", "prioritize"} + stages := []string{"prioritize"} for _, stage := range stages { t.Run("reusable-"+stage+".yml", func(t *testing.T) { content := string(loadRepoFile(fmt.Sprintf(".github/workflows/reusable-%s.yml", stage))(t)) @@ -1658,7 +1395,7 @@ func TestLayeredDirsMatchWorkspacePreparation(t *testing.T) { }{ {"actions/prepare-workspace/action.yml", loadRepoFile(".github/actions/prepare-workspace/action.yml")}, } - for _, stage := range []string{"triage", "code", "review", "fix", "retro", "prioritize", "dispatch"} { + for _, stage := range []string{"prioritize", "dispatch"} { files = append(files, struct { name string content func(t *testing.T) []byte From eff119cf14990eb30adcb7981c7ce82599931077 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 17:04:51 +0300 Subject: [PATCH 16/18] test(review): cover review thread fetch paths Cover forge pagination, actor types, endpoints, and CLI errors. Co-authored-by: Codex Signed-off-by: csoceanu --- internal/cli/fetchreviewthreads_test.go | 19 +++++++ internal/forge/github/review_threads_test.go | 12 +++++ internal/forge/gitlab/methods_test.go | 53 +++++++++++++++++++- 3 files changed, 83 insertions(+), 1 deletion(-) diff --git a/internal/cli/fetchreviewthreads_test.go b/internal/cli/fetchreviewthreads_test.go index 2e6526569a..34c76dcba7 100644 --- a/internal/cli/fetchreviewthreads_test.go +++ b/internal/cli/fetchreviewthreads_test.go @@ -53,6 +53,25 @@ func TestFetchReviewThreadsCommand_DefaultsToGitHubForge(t *testing.T) { assert.Equal(t, repos.ForgeGitHub, flag.DefValue) } +func TestFetchReviewThreadsCommand_ReturnsForgeError(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"message":"denied"}`)) + })) + defer srv.Close() + oldTransport := http.DefaultTransport + http.DefaultTransport = srv.Client().Transport + t.Cleanup(func() { http.DefaultTransport = oldTransport }) + + cmd := newFetchReviewThreadsCmd() + cmd.SetArgs([]string{"--repo", "owner/repo", "--pr", "42", "--token", "test-token", "--base-url", srv.URL}) + cmd.SetContext(context.Background()) + + err := cmd.Execute() + require.Error(t, err) + assert.Contains(t, err.Error(), "list pull request review threads page 1") +} + func TestFetchReviewThreadsCommand_ValidatesFlags(t *testing.T) { tests := []struct { name string diff --git a/internal/forge/github/review_threads_test.go b/internal/forge/github/review_threads_test.go index eaf9db27ea..9089c4afab 100644 --- a/internal/forge/github/review_threads_test.go +++ b/internal/forge/github/review_threads_test.go @@ -72,6 +72,18 @@ func TestListPullRequestReviewThreads(t *testing.T) { assert.Empty(t, got.Threads[1].ResolvedBy) } +func TestListPullRequestReviewThreads_GHESGraphQLEndpoint(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, "/api/graphql", r.URL.Path) + _, _ = w.Write([]byte(`{"data":{"repository":{"pullRequest":{"reviewThreads":{"pageInfo":{"hasNextPage":false,"endCursor":""},"nodes":[]}}}}}`)) + })) + defer srv.Close() + + client := New("test-token").WithBaseURL(srv.URL + "/api/v3").WithAfterFunc(noWaitAfter) + _, err := client.ListPullRequestReviewThreads(context.Background(), "owner", "repo", 1) + require.NoError(t, err) +} + func TestListPullRequestReviewThreads_PaginatesAndCaps(t *testing.T) { var calls int srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index 1457ab39b1..132549c289 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -83,6 +83,8 @@ func TestListPullRequestReviewThreads(t *testing.T) { writeJSON(t, w, http.StatusOK, map[string]any{"id": 10, "username": "botuser", "bot": true}) case "20": writeJSON(t, w, http.StatusOK, map[string]any{"id": 20, "username": "reviewer", "bot": false}) + case "40": + writeJSON(t, w, http.StatusOK, map[string]any{"id": 40, "username": "unknown", "bot": nil}) default: writeJSON(t, w, http.StatusNotFound, map[string]string{"message": "404 User Not Found"}) } @@ -119,12 +121,23 @@ func TestListPullRequestReviewThreads(t *testing.T) { }, }, }, + { + "id": "discussion-4", + "notes": []map[string]any{ + {"id": 10, "body": "system note", "system": true, "author": map[string]any{"id": 10, "username": "botuser"}}, + { + "id": 11, "body": "resolved with unknown actors", "resolvable": true, "resolved": true, + "resolved_by": map[string]any{"id": 40, "username": "unknown-resolver"}, + "position": map[string]any{"new_path": "", "old_path": "renamed.go", "old_line": 7}, + }, + }, + }, }) }) got, err := client.ListPullRequestReviewThreads(context.Background(), "myorg", "myrepo", 42) require.NoError(t, err) - require.Len(t, got.Threads, 3) + require.Len(t, got.Threads, 4) assert.Equal(t, "discussion-1", got.Threads[0].ID) assert.True(t, got.Threads[0].IsResolved) assert.Equal(t, "reviewer", got.Threads[0].ResolvedBy) @@ -138,9 +151,47 @@ func TestListPullRequestReviewThreads(t *testing.T) { assert.Equal(t, 3, *got.Threads[1].Line) assert.True(t, got.Threads[2].IsResolved) assert.Equal(t, "Unknown", got.Threads[2].ResolvedByType) + assert.True(t, got.Threads[3].IsResolved) + assert.Equal(t, "renamed.go", got.Threads[3].Path) + require.Len(t, got.Threads[3].Comments, 1, "system notes must not be returned") + assert.Equal(t, "Unknown", got.Threads[3].Comments[0].AuthorType) + assert.Equal(t, "Unknown", got.Threads[3].ResolvedByType) assert.Equal(t, 1, actorRequests["10"]) assert.Equal(t, 1, actorRequests["20"], "the actor lookup should be cached per request") assert.Equal(t, 1, actorRequests["30"]) + assert.Equal(t, 1, actorRequests["40"]) +} + +func TestListPullRequestReviewThreads_DecodeError(t *testing.T) { + client, mux := setupTest(t) + mux.HandleFunc("/api/v4/projects/myorg%2Fmyrepo/merge_requests/42/discussions", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("{")) + }) + + _, err := client.ListPullRequestReviewThreads(context.Background(), "myorg", "myrepo", 42) + require.Error(t, err) + assert.Contains(t, err.Error(), "decode discussions") +} + +func TestListPullRequestReviewThreads_PaginatesAndCaps(t *testing.T) { + client, mux := setupTest(t) + var pages int + mux.HandleFunc("/api/v4/projects/myorg%2Fmyrepo/merge_requests/42/discussions", func(w http.ResponseWriter, r *http.Request) { + pages++ + assert.Equal(t, strconv.Itoa(pages), r.URL.Query().Get("page")) + discussions := make([]map[string]any, 100) + for i := range discussions { + discussions[i] = map[string]any{"id": fmt.Sprintf("discussion-%d-%d", pages, i), "notes": []any{}} + } + writeJSON(t, w, http.StatusOK, discussions) + }) + + got, err := client.ListPullRequestReviewThreads(context.Background(), "myorg", "myrepo", 42) + require.NoError(t, err) + assert.Equal(t, 20, pages) + assert.True(t, got.Truncated) + assert.Len(t, got.Threads, 2000) } func TestCreateIssue_NoLabels(t *testing.T) { From 8f38dc08514eb2392215bd8fb467a718c07ccc89 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Tue, 6 Oct 2026 17:17:26 +0300 Subject: [PATCH 17/18] fix(review): let agent own thread output path Remove obsolete workflow output wiring. Co-authored-by: Codex Signed-off-by: csoceanu --- .github/workflows/reusable-dispatch.yml | 1 - internal/scaffold/workflow_call_alignment_test.go | 10 +++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 410abb5f4b..37cfa29530 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -991,7 +991,6 @@ jobs: PRIOR_REVIEW_FILE: ${{ steps.prior-review.outputs.prior_review_file }} PRIOR_REVIEW_PROVENANCE: ${{ steps.prior-review.outputs.prior_review_provenance }} FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }} - HUMAN_RESOLVED_FILE: ${{ github.workspace }}/human-resolved-threads.json OTEL_EXPORTER_OTLP_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_ENDPOINT }} OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index d2bf6b38bc..2515a01526 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -25,10 +25,10 @@ type reusableWorkflow struct { } `yaml:"on"` } -// TestReviewWorkflowPassesHumanResolutionOutput verifies that the supported -// per-repo review workflow exposes the output location to the agent while the -// agent pre-script owns fetch orchestration. -func TestReviewWorkflowPassesHumanResolutionOutput(t *testing.T) { +// TestReviewWorkflowKeepsThreadFetchAgentOwned verifies that the supported +// per-repo review workflow passes app identity through while the agent owns +// thread-fetch output placement. +func TestReviewWorkflowKeepsThreadFetchAgentOwned(t *testing.T) { content, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "reusable-dispatch.yml")) require.NoError(t, err) workflow := string(content) @@ -40,7 +40,7 @@ func TestReviewWorkflowPassesHumanResolutionOutput(t *testing.T) { } assert.Contains(t, section, "FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET }}") - assert.Contains(t, section, "HUMAN_RESOLVED_FILE: ${{ github.workspace }}/human-resolved-threads.json") + assert.NotContains(t, section, "HUMAN_RESOLVED_FILE:") assert.NotContains(t, section, "HUMAN_RESOLVED_FETCH_SCRIPT:") } From 6b28b0c208def2e2a1b3f7fe2b7323c1edbd6ff6 Mon Sep 17 00:00:00 2001 From: csoceanu Date: Wed, 7 Oct 2026 11:07:17 +0300 Subject: [PATCH 18/18] fix(review): include verified actor roles Expose verified actor roles for review threads. Keep GitLab resolution attribution and documentation consistent. Co-authored-by: Codex Signed-off-by: csoceanu --- docs/guides/dev/cli-internals.md | 6 +- internal/forge/forge.go | 32 ++++--- internal/forge/github/github.go | 41 +++++++- internal/forge/github/review_threads_test.go | 40 +++++++- internal/forge/gitlab/methods_test.go | 76 ++++++++++++++- internal/forge/gitlab/mr.go | 98 ++++++++++++++++---- internal/normevent/event.go | 19 ++++ internal/normevent/event_test.go | 14 +++ internal/poll/convert.go | 16 +--- 9 files changed, 289 insertions(+), 53 deletions(-) diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 8d4a7120ee..b722b08183 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -216,7 +216,11 @@ fullsend `truncated` flag. GitHub review threads are capped at 20 pages; consumers must treat `truncated: true` as an incomplete result. GitLab merge-request discussions are mapped to the same thread model, including resolution state, -comments, positions, and resolver identity when GitLab provides it. +comments, positions, and resolver identity when GitLab provides it. Each comment +also includes `author_role` and `author_role_verified`; resolved threads include +`resolved_by_role` and `resolved_by_role_verified`. A role is `none` with +`verified: true` for an authoritative non-member result, and `verified: false` +when the actor is a bot/unknown or the permission lookup fails. The `mint`, `inference`, and `github` subcommands decompose setup into role-specific operations for organizations that separate GCP and GitHub responsibilities: diff --git a/internal/forge/forge.go b/internal/forge/forge.go index d40b0f0d5a..9e87d2d28a 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -12,6 +12,8 @@ import ( "os" "strings" "time" + + "github.com/fullsend-ai/fullsend/internal/normevent" ) // ConfigRepoName is the conventional name for the org-level fullsend @@ -469,25 +471,29 @@ type ReviewComment struct { // ReviewThreadComment is a comment belonging to a pull-request review thread. // AuthorType is the forge's actor type (for example, "Bot" or "User"). type ReviewThreadComment struct { - Author string `json:"author"` - AuthorType string `json:"author_type"` - Body string `json:"body"` - CreatedAt string `json:"created_at"` + Author string `json:"author"` + AuthorType string `json:"author_type"` + AuthorRole normevent.ActorRole `json:"author_role"` + AuthorRoleVerified bool `json:"author_role_verified"` + Body string `json:"body"` + CreatedAt string `json:"created_at"` } // ReviewThread represents the resolution state and comments of a pull-request // review thread. Forges that do not expose review threads return // ErrNotSupported. type ReviewThread struct { - ID string `json:"id"` - IsResolved bool `json:"is_resolved"` - Path string `json:"path"` - Line *int `json:"line"` - OriginalLine *int `json:"original_line"` - ResolvedBy string `json:"resolved_by"` - ResolvedByType string `json:"resolved_by_type"` - Comments []ReviewThreadComment `json:"comments"` - CommentsTruncated bool `json:"comments_truncated"` + ID string `json:"id"` + IsResolved bool `json:"is_resolved"` + Path string `json:"path"` + Line *int `json:"line"` + OriginalLine *int `json:"original_line"` + ResolvedBy string `json:"resolved_by"` + ResolvedByType string `json:"resolved_by_type"` + ResolvedByRole normevent.ActorRole `json:"resolved_by_role"` + ResolvedByRoleVerified bool `json:"resolved_by_role_verified"` + Comments []ReviewThreadComment `json:"comments"` + CommentsTruncated bool `json:"comments_truncated"` } // ReviewThreadPage contains a complete fetch of a pull request's review diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index 925dfd6bce..c0a1f59c3d 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -25,6 +25,7 @@ import ( "unicode/utf8" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" "golang.org/x/crypto/nacl/box" "golang.org/x/sync/singleflight" ) @@ -3714,6 +3715,33 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re result := forge.ReviewThreadPage{} var cursor *string + roleCache := make(map[string]struct { + role normevent.ActorRole + verified bool + }) + resolveRole := func(login, actorType string) (normevent.ActorRole, bool) { + if login == "" || actorType != "User" { + return normevent.RoleNone, false + } + if cached, ok := roleCache[login]; ok { + return cached.role, cached.verified + } + permission, err := c.GetCollaboratorPermission(ctx, owner, repo, login) + if err != nil { + verified := forge.IsNotFound(err) + roleCache[login] = struct { + role normevent.ActorRole + verified bool + }{normevent.RoleNone, verified} + return normevent.RoleNone, verified + } + role := normevent.MapGitHubPermission(permission) + roleCache[login] = struct { + role normevent.ActorRole + verified bool + }{role, true} + return role, true + } for page := 1; page <= 20; page++ { variables := map[string]any{ "owner": owner, @@ -3741,6 +3769,7 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re for _, thread := range threads.Nodes { converted := forge.ReviewThread{ ID: thread.ID, + ResolvedByRole: normevent.RoleNone, IsResolved: thread.IsResolved, Path: thread.Path, Line: thread.Line, @@ -3750,13 +3779,17 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re if thread.ResolvedBy != nil { converted.ResolvedBy = thread.ResolvedBy.Login converted.ResolvedByType = thread.ResolvedBy.Type + converted.ResolvedByRole, converted.ResolvedByRoleVerified = resolveRole(thread.ResolvedBy.Login, thread.ResolvedBy.Type) } for _, comment := range thread.Comments.Nodes { + role, roleVerified := resolveRole(comment.Author.Login, comment.Author.Type) converted.Comments = append(converted.Comments, forge.ReviewThreadComment{ - Author: comment.Author.Login, - AuthorType: comment.Author.Type, - Body: comment.Body, - CreatedAt: comment.CreatedAt, + Author: comment.Author.Login, + AuthorType: comment.Author.Type, + AuthorRole: role, + AuthorRoleVerified: roleVerified, + Body: comment.Body, + CreatedAt: comment.CreatedAt, }) } result.Threads = append(result.Threads, converted) diff --git a/internal/forge/github/review_threads_test.go b/internal/forge/github/review_threads_test.go index 9089c4afab..8187df95ac 100644 --- a/internal/forge/github/review_threads_test.go +++ b/internal/forge/github/review_threads_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -18,6 +19,11 @@ func TestListPullRequestReviewThreads(t *testing.T) { originalLine := 16 var request map[string]any srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + require.Equal(t, "/repos/owner/repo/collaborators/reviewer/permission", r.URL.Path) + json.NewEncoder(w).Encode(map[string]any{"role_name": "write"}) + return + } require.Equal(t, http.MethodPost, r.Method) require.Equal(t, "/graphql", r.URL.Path) require.Equal(t, "Bearer test-token", r.Header.Get("Authorization")) @@ -64,12 +70,15 @@ func TestListPullRequestReviewThreads(t *testing.T) { assert.Equal(t, forge.ReviewThread{ ID: "PRRT_1", IsResolved: true, Path: "main.go", Line: &line, OriginalLine: &originalLine, ResolvedBy: "reviewer", ResolvedByType: "User", + ResolvedByRole: normevent.RoleWrite, ResolvedByRoleVerified: true, Comments: []forge.ReviewThreadComment{{ - Author: "reviewer", AuthorType: "User", Body: "please update this", CreatedAt: "2026-10-04T10:00:00Z", + Author: "reviewer", AuthorType: "User", AuthorRole: normevent.RoleWrite, AuthorRoleVerified: true, + Body: "please update this", CreatedAt: "2026-10-04T10:00:00Z", }}, CommentsTruncated: true, }, got.Threads[0]) assert.Nil(t, got.Threads[1].Line) assert.Empty(t, got.Threads[1].ResolvedBy) + assert.Equal(t, normevent.RoleNone, got.Threads[1].ResolvedByRole) } func TestListPullRequestReviewThreads_GHESGraphQLEndpoint(t *testing.T) { @@ -84,6 +93,35 @@ func TestListPullRequestReviewThreads_GHESGraphQLEndpoint(t *testing.T) { require.NoError(t, err) } +func TestListPullRequestReviewThreads_RoleLookupFailures(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + switch r.URL.Path { + case "/repos/owner/repo/collaborators/missing/permission": + w.WriteHeader(http.StatusNotFound) + case "/repos/owner/repo/collaborators/failing/permission": + w.WriteHeader(http.StatusInternalServerError) + default: + t.Fatalf("unexpected permission path %s", r.URL.Path) + } + return + } + + _, _ = w.Write([]byte(`{"data":{"repository":{"pullRequest":{"reviewThreads":{"pageInfo":{"hasNextPage":false,"endCursor":""},"nodes":[{"id":"thread-1","isResolved":true,"resolvedBy":{"login":"missing","__typename":"User"},"comments":{"pageInfo":{"hasNextPage":false},"nodes":[{"author":{"login":"failing","__typename":"User"},"body":"comment","createdAt":"2026-10-06T10:00:00Z"},{"author":{"login":"review-bot","__typename":"Bot"},"body":"bot comment","createdAt":"2026-10-06T10:00:00Z"}]}}]}}}}}`)) + })) + defer srv.Close() + + got, err := newTestClient(t, srv).ListPullRequestReviewThreads(context.Background(), "owner", "repo", 1) + require.NoError(t, err) + require.Len(t, got.Threads, 1) + assert.Equal(t, normevent.RoleNone, got.Threads[0].ResolvedByRole) + assert.True(t, got.Threads[0].ResolvedByRoleVerified, "a confirmed non-member is authoritative RoleNone") + assert.Equal(t, normevent.RoleNone, got.Threads[0].Comments[0].AuthorRole) + assert.False(t, got.Threads[0].Comments[0].AuthorRoleVerified, "a failed lookup is not authoritative") + assert.Equal(t, normevent.RoleNone, got.Threads[0].Comments[1].AuthorRole) + assert.False(t, got.Threads[0].Comments[1].AuthorRoleVerified, "bots do not use human permission roles") +} + func TestListPullRequestReviewThreads_PaginatesAndCaps(t *testing.T) { var calls int srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index 132549c289..f93bb9f910 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -16,6 +16,7 @@ import ( "time" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -75,6 +76,7 @@ func TestCreateIssue(t *testing.T) { func TestListPullRequestReviewThreads(t *testing.T) { client, mux := setupTest(t) actorRequests := map[string]int{} + roleRequests := map[string]int{} mux.HandleFunc("/api/v4/users/", func(w http.ResponseWriter, r *http.Request) { actorID := strings.TrimPrefix(r.URL.Path, "/api/v4/users/") actorRequests[actorID]++ @@ -85,10 +87,27 @@ func TestListPullRequestReviewThreads(t *testing.T) { writeJSON(t, w, http.StatusOK, map[string]any{"id": 20, "username": "reviewer", "bot": false}) case "40": writeJSON(t, w, http.StatusOK, map[string]any{"id": 40, "username": "unknown", "bot": nil}) + case "50", "60": + writeJSON(t, w, http.StatusOK, map[string]any{"id": actorID, "username": "external-" + actorID, "bot": false}) default: writeJSON(t, w, http.StatusNotFound, map[string]string{"message": "404 User Not Found"}) } }) + for _, actorID := range []string{"20", "50", "60"} { + actorID := actorID + mux.HandleFunc("/api/v4/projects/myorg%2Fmyrepo/members/all/"+actorID, func(w http.ResponseWriter, _ *http.Request) { + roleRequests[actorID]++ + switch actorID { + case "20": + writeJSON(t, w, http.StatusOK, map[string]any{"access_level": 30}) + case "50": + writeJSON(t, w, http.StatusNotFound, map[string]string{"message": "404 Member Not Found"}) + case "60": + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("{")) + } + }) + } mux.HandleFunc("/api/v4/projects/myorg%2Fmyrepo/merge_requests/42/discussions", func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, "100", r.URL.Query().Get("per_page")) assert.Equal(t, "1", r.URL.Query().Get("page")) @@ -128,23 +147,58 @@ func TestListPullRequestReviewThreads(t *testing.T) { { "id": 11, "body": "resolved with unknown actors", "resolvable": true, "resolved": true, "resolved_by": map[string]any{"id": 40, "username": "unknown-resolver"}, - "position": map[string]any{"new_path": "", "old_path": "renamed.go", "old_line": 7}, + "position": map[string]any{"new_path": "new.go", "old_path": "renamed.go", "old_line": 7}, }, }, }, + { + "id": "discussion-5", + "notes": []map[string]any{ + { + "id": 12, "body": "resolved note", "resolvable": true, "resolved": true, + "resolved_by": map[string]any{"id": 20, "username": "reviewer"}, + }, + {"id": 13, "body": "still open", "resolvable": true, "resolved": false}, + }, + }, + { + "id": "discussion-6", + "notes": []map[string]any{ + {"id": 14, "body": "external author", "resolvable": false, "author": map[string]any{"id": 50, "username": "external-50"}}, + {"id": 15, "body": "unknown permission", "resolvable": false, "author": map[string]any{"id": 60, "username": "external-60"}}, + }, + }, + { + "id": "discussion-7", + "notes": []map[string]any{ + {"id": 16, "body": "older resolution", "resolvable": true, "resolved": true, "resolved_at": "2026-10-06T10:00:00Z", "resolved_by": map[string]any{"id": 20, "username": "older-resolver"}}, + {"id": 17, "body": "latest resolution", "resolvable": true, "resolved": true, "resolved_at": "2026-10-06T11:00:00Z", "resolved_by": map[string]any{"id": 40, "username": "latest-resolver"}}, + }, + }, + { + "id": "discussion-8", + "notes": []map[string]any{ + {"id": 18, "body": "older resolution", "resolvable": true, "resolved": true, "resolved_at": "2026-10-06T10:00:00Z", "resolved_by": map[string]any{"id": 20, "username": "older-resolver"}}, + {"id": 19, "body": "resolver unavailable", "resolvable": true, "resolved": true, "resolved_at": "2026-10-06T11:00:00Z", "resolved_by": nil}, + }, + }, }) }) got, err := client.ListPullRequestReviewThreads(context.Background(), "myorg", "myrepo", 42) require.NoError(t, err) - require.Len(t, got.Threads, 4) + require.Len(t, got.Threads, 8) assert.Equal(t, "discussion-1", got.Threads[0].ID) assert.True(t, got.Threads[0].IsResolved) assert.Equal(t, "reviewer", got.Threads[0].ResolvedBy) assert.Equal(t, "User", got.Threads[0].ResolvedByType) + assert.Equal(t, normevent.RoleWrite, got.Threads[0].ResolvedByRole) + assert.True(t, got.Threads[0].ResolvedByRoleVerified) assert.Equal(t, "main.go", got.Threads[0].Path) assert.Equal(t, 17, *got.Threads[0].Line) assert.Equal(t, "Bot", got.Threads[0].Comments[0].AuthorType) + assert.Equal(t, normevent.RoleNone, got.Threads[0].Comments[0].AuthorRole) + assert.False(t, got.Threads[0].Comments[0].AuthorRoleVerified) assert.False(t, got.Threads[1].IsResolved) assert.Equal(t, "unresolved.go", got.Threads[1].Path, "position data is retained before unresolved notes are skipped") require.NotNil(t, got.Threads[1].Line) @@ -156,10 +210,28 @@ func TestListPullRequestReviewThreads(t *testing.T) { require.Len(t, got.Threads[3].Comments, 1, "system notes must not be returned") assert.Equal(t, "Unknown", got.Threads[3].Comments[0].AuthorType) assert.Equal(t, "Unknown", got.Threads[3].ResolvedByType) + assert.Equal(t, normevent.RoleNone, got.Threads[3].ResolvedByRole) + assert.False(t, got.Threads[3].ResolvedByRoleVerified) + assert.False(t, got.Threads[4].IsResolved, "a discussion with an unresolved resolvable note is not resolved") + assert.Empty(t, got.Threads[4].ResolvedBy) + assert.Empty(t, got.Threads[4].ResolvedByType) assert.Equal(t, 1, actorRequests["10"]) assert.Equal(t, 1, actorRequests["20"], "the actor lookup should be cached per request") assert.Equal(t, 1, actorRequests["30"]) assert.Equal(t, 1, actorRequests["40"]) + assert.Equal(t, normevent.RoleWrite, got.Threads[1].Comments[0].AuthorRole) + assert.True(t, got.Threads[1].Comments[0].AuthorRoleVerified) + assert.Equal(t, normevent.RoleNone, got.Threads[5].Comments[0].AuthorRole) + assert.True(t, got.Threads[5].Comments[0].AuthorRoleVerified) + assert.Equal(t, normevent.RoleNone, got.Threads[5].Comments[1].AuthorRole) + assert.False(t, got.Threads[5].Comments[1].AuthorRoleVerified) + assert.Equal(t, 1, roleRequests["20"], "member lookups should be cached per request") + assert.Equal(t, 1, roleRequests["50"]) + assert.Equal(t, 1, roleRequests["60"]) + assert.Zero(t, roleRequests["10"], "bot actors must not be treated as human permission actors") + assert.Equal(t, "latest-resolver", got.Threads[6].ResolvedBy, "the latest resolved note is the discussion resolver") + assert.Empty(t, got.Threads[7].ResolvedBy, "a missing latest resolver must not retain an older resolver") + assert.Equal(t, normevent.RoleNone, got.Threads[7].ResolvedByRole) } func TestListPullRequestReviewThreads_DecodeError(t *testing.T) { diff --git a/internal/forge/gitlab/mr.go b/internal/forge/gitlab/mr.go index 25468ed251..fb052012a6 100644 --- a/internal/forge/gitlab/mr.go +++ b/internal/forge/gitlab/mr.go @@ -8,8 +8,10 @@ import ( "log" "net/http" "strings" + "time" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" ) // requestChangesMarker is the hidden HTML comment posted on GitLab @@ -776,13 +778,17 @@ type gitlabDiscussionActor struct { } // ListPullRequestReviewThreads maps GitLab merge-request discussions to the -// common review-thread model. A discussion is resolved when one of its -// resolvable notes is marked resolved; the resolver and note authors are -// preserved so consumers can distinguish human and bot resolutions. +// common review-thread model. A discussion is resolved when all of its +// resolvable notes are marked resolved; the latest resolver and note authors +// are preserved so consumers can distinguish human and bot resolutions. func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, repo string, number int) (forge.ReviewThreadPage, error) { proj := projectPath(owner, repo) result := forge.ReviewThreadPage{} actorTypes := make(map[int]string) + actorRoles := make(map[int]struct { + role normevent.ActorRole + verified bool + }) lookupActorType := func(actor *gitlabDiscussionActor) string { if actor == nil || actor.ID == 0 { return "Unknown" @@ -804,6 +810,30 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re actorTypes[actor.ID] = actorType return actorType } + lookupActorRole := func(actor *gitlabDiscussionActor, actorType string) (normevent.ActorRole, bool) { + if actor == nil || actor.ID == 0 || actorType != "User" { + return normevent.RoleNone, false + } + if cached, ok := actorRoles[actor.ID]; ok { + return cached.role, cached.verified + } + + level, err := c.GetProjectMemberAccessLevel(ctx, owner, repo, int64(actor.ID)) + if err != nil { + verified := forge.IsNotFound(err) + actorRoles[actor.ID] = struct { + role normevent.ActorRole + verified bool + }{normevent.RoleNone, verified} + return normevent.RoleNone, verified + } + role := normevent.MapGitLabAccessLevel(level) + actorRoles[actor.ID] = struct { + role normevent.ActorRole + verified bool + }{role, true} + return role, true + } for page := 1; page <= 20; page++ { path := fmt.Sprintf("/projects/%s/merge_requests/%d/discussions?per_page=100&page=%d", @@ -822,6 +852,7 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re CreatedAt string `json:"created_at"` Resolvable bool `json:"resolvable"` Resolved bool `json:"resolved"` + ResolvedAt *string `json:"resolved_at"` Author gitlabDiscussionActor `json:"author"` ResolvedBy *gitlabDiscussionActor `json:"resolved_by"` Position *struct { @@ -837,35 +868,66 @@ func (c *LiveClient) ListPullRequestReviewThreads(ctx context.Context, owner, re } for _, discussion := range discussions { - thread := forge.ReviewThread{ID: discussion.ID} + thread := forge.ReviewThread{ID: discussion.ID, ResolvedByRole: normevent.RoleNone} + hasResolvableNote := false + allResolvableNotesResolved := true + var resolvedBy *gitlabDiscussionActor + var resolvedAt time.Time + resolvedNoteID := 0 + resolvedNoteSelected := false + for _, note := range discussion.Notes { + if note.System || !note.Resolvable { + continue + } + hasResolvableNote = true + if !note.Resolved { + allResolvableNotesResolved = false + continue + } + noteResolvedAt := time.Time{} + if note.ResolvedAt != nil { + noteResolvedAt, _ = time.Parse(time.RFC3339Nano, *note.ResolvedAt) + } + if !resolvedNoteSelected || noteResolvedAt.After(resolvedAt) || + (noteResolvedAt.Equal(resolvedAt) && note.ID > resolvedNoteID) { + resolvedBy = note.ResolvedBy + resolvedAt = noteResolvedAt + resolvedNoteID = note.ID + resolvedNoteSelected = true + } + } + thread.IsResolved = hasResolvableNote && allResolvableNotesResolved + if thread.IsResolved && resolvedBy != nil { + thread.ResolvedBy = resolvedBy.Username + thread.ResolvedByType = lookupActorType(resolvedBy) + thread.ResolvedByRole, thread.ResolvedByRoleVerified = lookupActorRole(resolvedBy, thread.ResolvedByType) + } + for _, note := range discussion.Notes { if note.System { continue } + authorType := lookupActorType(¬e.Author) + authorRole, authorRoleVerified := lookupActorRole(¬e.Author, authorType) thread.Comments = append(thread.Comments, forge.ReviewThreadComment{ - Author: note.Author.Username, - AuthorType: lookupActorType(¬e.Author), - Body: note.Body, - CreatedAt: note.CreatedAt, + Author: note.Author.Username, + AuthorType: authorType, + AuthorRole: authorRole, + AuthorRoleVerified: authorRoleVerified, + Body: note.Body, + CreatedAt: note.CreatedAt, }) if note.Position != nil { thread.Path = note.Position.NewPath - if thread.Path == "" { + if note.Position.NewLine == nil && note.Position.OldLine != nil { + thread.Path = note.Position.OldPath + } else if thread.Path == "" { thread.Path = note.Position.OldPath } thread.Line = note.Position.NewLine thread.OriginalLine = note.Position.OldLine } - - if !note.Resolvable || !note.Resolved { - continue - } - thread.IsResolved = true - if note.ResolvedBy != nil { - thread.ResolvedBy = note.ResolvedBy.Username - thread.ResolvedByType = lookupActorType(note.ResolvedBy) - } } result.Threads = append(result.Threads, thread) } diff --git a/internal/normevent/event.go b/internal/normevent/event.go index eb65a095fc..0bd0593d28 100644 --- a/internal/normevent/event.go +++ b/internal/normevent/event.go @@ -322,6 +322,25 @@ func MapGitHubPermission(roleName string) ActorRole { } } +// MapGitLabAccessLevel maps a GitLab project membership access level to the +// normalized repository permission role used by the authorization contract. +func MapGitLabAccessLevel(accessLevel int) ActorRole { + switch accessLevel { + case 10: // Guest + return RoleRead + case 20: // Reporter + return RoleTriage + case 30: // Developer + return RoleWrite + case 40: // Maintainer + return RoleMaintain + case 50: // Owner + return RoleAdmin + default: + return RoleNone + } +} + // ComputeChangeProposalIsFork reports whether a change proposal is fork-based. // Missing head or base repo metadata is treated as fork (fail-closed) so CEL // guards like !event.state.change_proposal.is_fork stay trustworthy. diff --git a/internal/normevent/event_test.go b/internal/normevent/event_test.go index 8f4b4e9e4d..5aac6b4353 100644 --- a/internal/normevent/event_test.go +++ b/internal/normevent/event_test.go @@ -57,6 +57,20 @@ func TestMapGitHubPermission(t *testing.T) { assert.Equal(t, RoleNone, MapGitHubPermission("custom-docs-role")) } +func TestMapGitLabAccessLevel(t *testing.T) { + tests := map[int]ActorRole{ + 10: RoleRead, + 20: RoleTriage, + 30: RoleWrite, + 40: RoleMaintain, + 50: RoleAdmin, + 0: RoleNone, + } + for accessLevel, expected := range tests { + assert.Equal(t, expected, MapGitLabAccessLevel(accessLevel), accessLevel) + } +} + func TestComputeChangeProposalIsFork(t *testing.T) { assert.False(t, ComputeChangeProposalIsFork("o/r", "o/r")) assert.True(t, ComputeChangeProposalIsFork("fork/r", "o/r")) diff --git a/internal/poll/convert.go b/internal/poll/convert.go index 86aeb0a164..fdbf91b19e 100644 --- a/internal/poll/convert.go +++ b/internal/poll/convert.go @@ -10,6 +10,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/dispatch" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" ) // toNormalizedEvent converts a RoutableEvent into a dispatch.NormalizedEvent @@ -232,20 +233,7 @@ func (p *Poller) resolveActorRole(ctx context.Context, userID int) (string, erro return "", fmt.Errorf("resolve role for user %d: %w", userID, err) } - switch level { - case 10: // Guest - return "read", nil - case 20: // Reporter - return "triage", nil - case 30: // Developer - return "write", nil - case 40: // Maintainer - return "maintain", nil - case 50: // Owner - return "admin", nil - default: - return "none", nil - } + return string(normevent.MapGitLabAccessLevel(level)), nil } // extractCommand parses a note body for a /fs- slash command. It returns