Files
stack/packages/mosaic/framework/tools/git/issue-comment.sh
Hermes Agent 10fdd49e32
All checks were successful
ci/woodpecker/pr/ci Pipeline was successful
fix(tools): bound Gitea read-back to this write; verify approve/reject state (#865)
Review remediation for two correctness holes in the #865 fix:

BLOCKER 1 — issue-comment.sh read-back was body-only across all history:
if `tea comment` silently no-opped (the #865 bug) while an identically
bodied comment already existed from a prior run, the read-back matched the
OLD comment and falsely reported success. Now record the pre-write maximum
comment id as a boundary and require a comment with id > boundary AND exact
body match; monotonic Gitea ids make id > boundary mean "created by this
write". Fails closed otherwise.

BLOCKER 2 — pr-review.sh approve/reject trusted tea's exit code for the
review STATE (same never-trust-exit-zero defect class as #865). Removed the
TODO deferral and added a real bounded read-back: record the max review id
before `tea pr approve`/`reject`, then require a review with id > boundary,
the expected state (APPROVED / REQUEST_CHANGES), and commit_id equal to the
PR's current head. Fails closed if absent.

Tests: extended test-pr-review-gitea-comment.sh to model and assert the new
review-state read-back (guardrails preserved, assertions added). Added
test-issue-comment-readback.sh proving the pre-existing-identical-body
false positive now fails closed and a genuinely new comment verifies.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 18:21:02 -05:00

232 lines
8.9 KiB
Bash
Executable File

#!/bin/bash
# issue-comment.sh - Add a comment to an issue on GitHub or Gitea
# Usage: issue-comment.sh -i <issue_number> -c <comment> [--login <name>]
#
# tea v0.11.1 defines no `comment` subcommand under `tea issue` (or `tea pr`);
# the correct invocation is the TOP-LEVEL `tea comment <index> <body>` form.
# Calling the non-existent `tea issue comment ...` form does not error — tea
# silently falls through to a no-op and still exits 0, so a caller trusting
# the exit code alone believes a comment was posted when it was not (#865).
# Because that failure mode is silent, this script never trusts tea's exit
# code alone: after posting, it independently re-fetches the issue's comments
# via the Gitea REST API (curl — urllib is blocked by Cloudflare on this
# host) and fails closed if the posted body cannot be found.
#
# --login override: the default `--login` is resolved from the local `tea`
# login list for this repo's host (get_gitea_login). Pass --login <name> to
# override that default for this invocation only. The override is appended
# to the tea command line AFTER the detected default, because tea honors
# only the LAST `--login` flag on the command line — a flag placed before
# the default would be silently clobbered by it.
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/detect-platform.sh"
# Parse arguments
ISSUE_NUMBER=""
COMMENT=""
LOGIN_OVERRIDE=""
while [[ $# -gt 0 ]]; do
case $1 in
-i|--issue)
ISSUE_NUMBER="$2"
shift 2
;;
-c|--comment)
COMMENT="$2"
shift 2
;;
-l|--login)
LOGIN_OVERRIDE="$2"
shift 2
;;
-h|--help)
echo "Usage: issue-comment.sh -i <issue_number> -c <comment> [--login <name>]"
echo ""
echo "Options:"
echo " -i, --issue Issue number (required)"
echo " -c, --comment Comment text (required)"
echo " -l, --login Override the detected Gitea tea login for this call"
echo " -h, --help Show this help"
exit 0
;;
*)
echo "Unknown option: $1"
exit 1
;;
esac
done
if [[ -z "$ISSUE_NUMBER" ]]; then
echo "Error: Issue number is required (-i)"
exit 1
fi
if [[ -z "$COMMENT" ]]; then
echo "Error: Comment is required (-c)"
exit 1
fi
detect_platform >/dev/null
# Resolve and cache the Gitea REST endpoint + token for the current remote.
# Populates GITEA_API_BASE and GITEA_API_TOKEN. Returns non-zero (with a
# clear stderr message) if any part of the resolution fails.
gitea_resolve_api() {
local host configured_url repo
host=$(get_remote_host)
GITEA_API_TOKEN=$(get_gitea_token "$host") || {
echo "Error: Gitea token not found for comment read-back verification" >&2
return 1
}
configured_url=$(get_gitea_url_for_host "$host") || {
echo "Error: Configured Gitea URL not found for comment read-back verification" >&2
return 1
}
repo=$(get_gitea_repo_slug_for_url "$configured_url") || {
echo "Error: Could not resolve Gitea owner/repository relative to configured URL" >&2
return 1
}
GITEA_API_BASE="${configured_url%/}/api/v1/repos/$repo"
return 0
}
# Print the maximum existing comment id on an issue (0 if none). This is the
# pre-write BOUNDARY: Gitea comment ids are monotonic, so any comment created
# by a subsequent write has an id strictly greater than this value. Bounding
# the read-back this way is what distinguishes a genuine fresh write from a
# pre-existing comment that merely happens to share the same body — the exact
# false-positive a body-only, whole-history match would miss when `tea
# comment` silently no-ops (#865).
gitea_max_comment_id() {
local issue_number="$1" response_file status
response_file=$(mktemp "${TMPDIR:-/tmp}/mosaic-issue-comment-boundary.XXXXXX")
trap 'rm -f "$response_file"' RETURN
if ! status=$(curl -sS -o "$response_file" -w '%{http_code}' \
-H "Authorization: token $GITEA_API_TOKEN" \
"$GITEA_API_BASE/issues/$issue_number/comments"); then
echo "Error: Gitea comment boundary read transport failed" >&2
return 1
fi
if [[ "$status" != "200" ]]; then
echo "Error: Gitea comment boundary read failed with HTTP $status" >&2
return 1
fi
python3 - "$response_file" <<'PY'
import json
import sys
try:
with open(sys.argv[1], encoding="utf-8") as response:
comments = json.load(response)
if not isinstance(comments, list):
raise ValueError("response is not a comment list")
ids = [c.get("id") for c in comments if isinstance(c, dict) and isinstance(c.get("id"), int)]
print(max(ids) if ids else 0)
except (OSError, json.JSONDecodeError, TypeError, ValueError) as error:
print(f"Error: could not compute Gitea comment boundary: {error}", file=sys.stderr)
raise SystemExit(1)
PY
}
# Independently re-fetch the issue's comments via the Gitea REST API and
# require a comment that was created by THIS write: its id must be strictly
# greater than the pre-write boundary AND its body must exactly match what we
# submitted (see header comment: tea's exit code is not trustworthy evidence
# of a durable write on its own). Prints the matched comment ID on success.
gitea_verify_comment_posted() {
local issue_number="$1" comment_body="$2" boundary="$3"
local readback_response_file status
readback_response_file=$(mktemp "${TMPDIR:-/tmp}/mosaic-issue-comment-readback.XXXXXX")
trap 'rm -f "$readback_response_file"' RETURN
if ! status=$(curl -sS -o "$readback_response_file" -w '%{http_code}' \
-H "Authorization: token $GITEA_API_TOKEN" \
"$GITEA_API_BASE/issues/$issue_number/comments"); then
echo "Error: Gitea comment read-back transport failed" >&2
return 1
fi
if [[ "$status" != "200" ]]; then
echo "Error: Gitea comment read-back failed with HTTP $status" >&2
return 1
fi
EXPECTED_COMMENT_BODY="$comment_body" BOUNDARY_COMMENT_ID="$boundary" \
python3 - "$readback_response_file" <<'PY'
import json
import os
import sys
try:
with open(sys.argv[1], encoding="utf-8") as response:
comments = json.load(response)
if not isinstance(comments, list):
raise ValueError("response is not a comment list")
expected_body = os.environ["EXPECTED_COMMENT_BODY"]
boundary = int(os.environ["BOUNDARY_COMMENT_ID"])
# Require both: created-after-boundary (fresh write) AND exact body match.
matches = [
c for c in comments
if isinstance(c, dict)
and isinstance(c.get("id"), int)
and c.get("id") > boundary
and c.get("body") == expected_body
]
if not matches:
raise ValueError(
"no comment created by this write matched (id > boundary and exact body); "
"tea may have silently no-opped (#865)"
)
comment_id = max(c["id"] for c in matches)
except (OSError, json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
print(f"Error: Gitea comment persistence verification failed: {error}", file=sys.stderr)
raise SystemExit(1)
print(comment_id)
PY
}
if [[ "$PLATFORM" == "github" ]]; then
gh issue comment "$ISSUE_NUMBER" --body "$COMMENT"
echo "Added comment to GitHub issue #$ISSUE_NUMBER"
elif [[ "$PLATFORM" == "gitea" ]]; then
# Build the invocation as an argv array (not unquoted $(get_gitea_repo_args)
# word-splitting) so the comment body — including Markdown backticks, $(...),
# and quotes — is passed verbatim and never re-split or shell-evaluated.
REPO_SLUG=$(get_repo_slug)
GITEA_LOGIN_NAME=$(get_gitea_login) || {
echo "Error: could not resolve a Gitea login for this repo; cannot comment on issue #$ISSUE_NUMBER." >&2
exit 1
}
# Resolve the REST endpoint and record the pre-write boundary BEFORE the
# write, so the read-back can require a strictly-newer comment id.
gitea_resolve_api || exit 1
boundary=$(gitea_max_comment_id "$ISSUE_NUMBER") || exit 1
TEA_ARGS=(comment "$ISSUE_NUMBER" "$COMMENT" --repo "$REPO_SLUG" --login "$GITEA_LOGIN_NAME")
# --login override goes LAST: tea honors only the final --login on its
# command line, so an override placed before the detected default above
# would be silently clobbered by it.
if [[ -n "$LOGIN_OVERRIDE" ]]; then
TEA_ARGS+=(--login "$LOGIN_OVERRIDE")
fi
tea "${TEA_ARGS[@]}"
comment_id=$(gitea_verify_comment_posted "$ISSUE_NUMBER" "$COMMENT" "$boundary") || {
echo "Error: could not verify comment landed on Gitea issue #$ISSUE_NUMBER via bounded read-back; treating tea's exit code as untrustworthy (#865)." >&2
exit 1
}
echo "Added and verified comment on Gitea issue #$ISSUE_NUMBER (comment ID $comment_id)"
else
echo "Error: Unknown platform"
exit 1
fi