From 0f8322ed87428a82c170bda63caec5bf5b7cc192 Mon Sep 17 00:00:00 2001 From: Tim Pouyer Date: Wed, 11 Nov 2026 14:12:36 -0500 Subject: [PATCH 01/25] test(#9334): add reproduction test for Remove sticky comments: post Reproduction test for https://github.com/fullsend-ai/fullsend/issues/9334 (reproduced). Evidence: TestPost_SecondRunAddsNewCommentAtEnd and TestPost_EveryRunAppendsNewComment fail: sticky.Post updates the marked comment in place and folds the previous result into a "Previous run"
section instead of adding a new comment at the end of the thread Signed-off-by: Tim Pouyer --- internal/sticky/post_new_comment_test.go | 63 ++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 internal/sticky/post_new_comment_test.go diff --git a/internal/sticky/post_new_comment_test.go b/internal/sticky/post_new_comment_test.go new file mode 100644 index 0000000000..d0acad598b --- /dev/null +++ b/internal/sticky/post_new_comment_test.go @@ -0,0 +1,63 @@ +package sticky + +import ( + "context" + "io" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// Issue #9334: sticky comments are removed. Every agent result is posted +// as a new comment at the end of the thread. Nothing is edited in place, +// there are no "Previous run" sections, and the thread itself is the +// history. + +func TestPost_SecondRunAddsNewCommentAtEnd(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + client.IssueComments = map[string][]forge.IssueComment{ + "o/r/1": { + {ID: 100, HTMLURL: "https://github.com/o/r/issues/1#issuecomment-100", Body: "\nFirst result.", Author: "bot"}, + }, + } + printer := ui.New(io.Discard) + + cfg := Config{Marker: "", KeepHistory: true} + commentURL, err := Post(context.Background(), client, "o", "r", 1, "Second result.", cfg, printer) + require.NoError(t, err) + + comments := client.IssueComments["o/r/1"] + require.Len(t, comments, 2, "a second run must add a new comment at the end of the thread") + assert.Equal(t, "\nFirst result.", comments[0].Body, "the earlier comment must be left unchanged") + assert.Contains(t, comments[1].Body, "Second result.") + assert.Contains(t, comments[1].Body, "", "the new comment keeps the hidden marker") + assert.NotContains(t, comments[1].Body, "Previous run", "no Previous run section is produced") + assert.Empty(t, client.UpdatedComments, "no comment is edited in place") + assert.Contains(t, commentURL, "issuecomment-", "the result is the newly created comment") + assert.NotEqual(t, "https://github.com/o/r/issues/1#issuecomment-100", commentURL, "the returned URL is not the earlier comment's") +} + +func TestPost_EveryRunAppendsNewComment(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + cfg := Config{Marker: "", KeepHistory: true} + for _, body := range []string{"Run 1.", "Run 2.", "Run 3."} { + _, err := Post(context.Background(), client, "o", "r", 1, body, cfg, printer) + require.NoError(t, err) + } + + comments := client.IssueComments["o/r/1"] + require.Len(t, comments, 3, "three runs leave three comments; the thread itself is the history") + for i, want := range []string{"Run 1.", "Run 2.", "Run 3."} { + assert.Contains(t, comments[i].Body, want) + assert.NotContains(t, comments[i].Body, "Previous run") + } + assert.Empty(t, client.UpdatedComments, "no comment is edited in place") +} From 635b640083d95d1161b64aa647ccf81b7f0fd113 Mon Sep 17 00:00:00 2001 From: Tim Pouyer Date: Thu, 12 Nov 2026 16:01:51 -0500 Subject: [PATCH 02/25] fix(#9334): post every agent result as a new comment Fixes https://github.com/fullsend-ai/fullsend/issues/9334 Reproduction: see the test(#9334) commit in this branch. Test rounds used: 11/100. PR review: round 13, verdict approve (17 nitpick(s), 0 advisory(ies), 0 unresolved blocking). Signed-off-by: Tim Pouyer --- .../triage/triage-re-run-append.feature | 31 ++ .../fixtures/triage/sufficient-recheck.json | 24 + internal/agentnew/templates/post.sh.tmpl | 44 +- internal/agentnew/testdata/golden/codex.txt | 44 +- .../agentnew/testdata/golden/pi-openai.txt | 44 +- internal/agentnew/testdata/golden/triage.txt | 44 +- .../testdata/golden/validation-loop.txt | 44 +- internal/cli/issues.go | 237 ++++----- internal/cli/issues_test.go | 500 ++++++------------ internal/cli/postcomment.go | 16 +- internal/cli/postcomment_test.go | 15 +- internal/cli/postreview.go | 73 ++- internal/cli/postreview_test.go | 9 +- internal/config/config.go | 9 +- internal/config/defaults.go | 7 +- internal/config/interfaces.go | 16 +- internal/forge/gitlab/mr.go | 2 +- .../scripts/pre-fetch-prior-review-test.sh | 25 + internal/statuscomment/statuscomment.go | 2 - internal/sticky/markers_test.go | 40 +- internal/sticky/sticky.go | 136 ++--- internal/sticky/sticky_test.go | 172 +----- internal/tracker/jira_client.go | 34 -- internal/tracker/jira_client_test.go | 201 ------- pkg/behaviourtest/steps/forge_state.go | 75 +++ pkg/behaviourtest/steps/forge_state_test.go | 76 +++ 26 files changed, 798 insertions(+), 1122 deletions(-) create mode 100644 e2e/behaviour/features/triage/triage-re-run-append.feature create mode 100644 e2e/behaviour/fixtures/triage/sufficient-recheck.json diff --git a/e2e/behaviour/features/triage/triage-re-run-append.feature b/e2e/behaviour/features/triage/triage-re-run-append.feature new file mode 100644 index 0000000000..0d0ede2192 --- /dev/null +++ b/e2e/behaviour/features/triage/triage-re-run-append.feature @@ -0,0 +1,31 @@ +# Sticky comments were removed (#9334): every agent run appends its +# result as a new comment at the end of the thread instead of editing +# the comment the first run created. This scenario re-runs triage on the +# same issue (first on the ready-for-triage label, then on a /fs-triage +# comment) and asserts the second result is a new comment behind the +# first, so a regression to edit-in-place fails the comment count. +# @skip:gitlab because the GitLab posting door for triage lives in the +# agents repo's post-triage.sh, whose GitLab notes path still edits in +# place until the companion change lands there; the GitHub door is the +# one this repository owns. +@skip:gitlab +Feature: Re-running triage appends a new comment + + Scenario: A second triage run posts a new comment and leaves the first unchanged + Given the enrolled test repository + And a dummy agent that would: + | description | op | args | + | Emit triage JSON | write_fixture | output/agent-result.json, fixtures/triage/sufficient.json | + And an issue + When the issue is labeled "ready-for-triage" + Then the triage agent completes successfully + And the issue has label "ready-to-code" + And the issue has 1 comment containing "" + When a dummy agent that would: + | description | op | args | + | Emit triage JSON | write_fixture | output/agent-result.json, fixtures/triage/sufficient-recheck.json | + And the write actor posts "/fs-triage" on the issue + Then the triage agent completes successfully + And the issue has 2 comments containing "" + And the last comment on the issue contains "Re-triage on the second run" + And a comment on the issue other than the last contains "This issue is ready for implementation." diff --git a/e2e/behaviour/fixtures/triage/sufficient-recheck.json b/e2e/behaviour/fixtures/triage/sufficient-recheck.json new file mode 100644 index 0000000000..a6cca7d67c --- /dev/null +++ b/e2e/behaviour/fixtures/triage/sufficient-recheck.json @@ -0,0 +1,24 @@ +{ + "action": "sufficient", + "reasoning": "Re-triage on a second run: the reproduction steps still hold and no new information changes the outcome.", + "clarity_scores": { + "symptom": 0.9, + "cause": 0.85, + "reproduction": 0.9, + "impact": 0.8, + "overall": 0.87 + }, + "triage_summary": { + "title": "Login fails", + "severity": "high", + "category": "bug", + "problem": "Application crashes on login", + "root_cause_hypothesis": "Session handling regression", + "reproduction_steps": ["Open app", "Enter credentials", "Click login"], + "environment": "Linux", + "impact": "Users cannot authenticate", + "recommended_fix": "Fix session token validation", + "proposed_test_case": "test_login_success" + }, + "comment": "## Triage Summary\n\nRe-triage on the second run: the issue is still ready for implementation." +} diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index 13ce33bca4..be840a8de0 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -27,7 +27,8 @@ # Treat the result file as untrusted: it is model output. Only the three # fields below are ever read, each must be a string, and the comment body is # piped on stdin rather than interpolated into a command. comment may be -# missing or empty when status is ok, because nothing new is posted then. +# missing or empty when status is ok, because the all-clear is the summary +# alone. set -euo pipefail @@ -138,19 +139,22 @@ fi REPO="${BASH_REMATCH[1]}" NUMBER="${BASH_REMATCH[3]}" -# On ok, post nothing — unless an earlier run left a findings comment on -# this work item. The harness trigger fires again on later pushes, so a -# problem the author has since fixed would otherwise stay reported. -# --only-if-exists makes fullsend replace that comment with the all-clear, -# and post nothing when there is no earlier comment. It matches only a -# comment carrying this marker whose author is exactly the login fullsend -# posts as, so a comment anyone else planted with the marker is never -# edited. When that login cannot be resolved it exits non-zero without -# posting; under `set -e` this script, and so the run, then fails -# visibly — rerun it. +# On ok, post nothing — unless an earlier comment with this marker exists +# on this work item, from findings or a previous all-clear alike (the gate +# is marker-only, so it stays open once the first all-clear is posted). +# The harness trigger fires again on later pushes, so a problem the author +# has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend post the all-clear as a new comment at +# the end of the thread, but only when an earlier comment with this +# marker exists; with none, nothing is posted. It matches only a comment +# carrying this marker whose author is exactly the login fullsend posts +# as, so a comment anyone else planted with the marker never counts. +# When that login cannot be resolved it exits non-zero without posting; +# under `set -e` this script, and so the run, then fails visibly — +# rerun it. if [[ "${status}" == "ok" ]]; then if [[ "${dry_run}" == "1" ]]; then - echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 + echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: did not check for an earlier findings comment)" >&2 exit 0 fi # The runner's fullsend may predate --only-if-exists (it is pinned by the @@ -160,7 +164,7 @@ if [[ "${status}" == "ok" ]]; then # Only a working CLI without the flag keeps the old behaviour — post # nothing. if ! help_text=$(fullsend issues post-comment --help 2>&1); then - printf '%s\n' "post-__AGENT_NAME__: 'fullsend issues post-comment --help' failed; cannot replace an earlier findings comment" >&2 + printf '%s\n' "post-__AGENT_NAME__: 'fullsend issues post-comment --help' failed; cannot check for an earlier findings comment" >&2 printf '%s\n' "${help_text}" >&2 exit 1 fi @@ -168,9 +172,11 @@ if [[ "${status}" == "ok" ]]; then echo "post-__AGENT_NAME__: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 exit 0 fi - # --keep-history=false: the all-clear replaces the comment in place, so - # repeated clean runs do not stack identical "Previous run" blocks. With - # no comment the all-clear is the summary alone. + # --keep-history=false is deprecated and, on a fullsend that has this + # change, has no effect: the all-clear is posted as a new comment at the + # end of the thread, following any earlier findings. It stays for + # runners pinned to an older CLI by the repository's fullsend-ref. With + # no comment in the result the all-clear is the summary alone. # The format is chosen here, never taken from the result file. body_format='**%s**\n\n%s\n' [[ -n "${comment}" ]] || body_format='**%s**\n%s' @@ -202,9 +208,9 @@ if [[ "${dry_run}" == "1" ]]; then exit 0 fi -# fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and its own author and edits -# it in place, so re-runs do not flood the work item. +# fullsend issues post-comment posts the result as a new comment at the +# end of the thread, carrying this agent's marker so later steps can find +# it; the thread itself is the history. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/agentnew/testdata/golden/codex.txt b/internal/agentnew/testdata/golden/codex.txt index b5e8309cf1..e2eed63977 100644 --- a/internal/agentnew/testdata/golden/codex.txt +++ b/internal/agentnew/testdata/golden/codex.txt @@ -178,7 +178,8 @@ trigger: | # Treat the result file as untrusted: it is model output. Only the three # fields below are ever read, each must be a string, and the comment body is # piped on stdin rather than interpolated into a command. comment may be -# missing or empty when status is ok, because nothing new is posted then. +# missing or empty when status is ok, because the all-clear is the summary +# alone. set -euo pipefail @@ -289,19 +290,22 @@ fi REPO="${BASH_REMATCH[1]}" NUMBER="${BASH_REMATCH[3]}" -# On ok, post nothing — unless an earlier run left a findings comment on -# this work item. The harness trigger fires again on later pushes, so a -# problem the author has since fixed would otherwise stay reported. -# --only-if-exists makes fullsend replace that comment with the all-clear, -# and post nothing when there is no earlier comment. It matches only a -# comment carrying this marker whose author is exactly the login fullsend -# posts as, so a comment anyone else planted with the marker is never -# edited. When that login cannot be resolved it exits non-zero without -# posting; under `set -e` this script, and so the run, then fails -# visibly — rerun it. +# On ok, post nothing — unless an earlier comment with this marker exists +# on this work item, from findings or a previous all-clear alike (the gate +# is marker-only, so it stays open once the first all-clear is posted). +# The harness trigger fires again on later pushes, so a problem the author +# has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend post the all-clear as a new comment at +# the end of the thread, but only when an earlier comment with this +# marker exists; with none, nothing is posted. It matches only a comment +# carrying this marker whose author is exactly the login fullsend posts +# as, so a comment anyone else planted with the marker never counts. +# When that login cannot be resolved it exits non-zero without posting; +# under `set -e` this script, and so the run, then fails visibly — +# rerun it. if [[ "${status}" == "ok" ]]; then if [[ "${dry_run}" == "1" ]]; then - echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 + echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment)" >&2 exit 0 fi # The runner's fullsend may predate --only-if-exists (it is pinned by the @@ -311,7 +315,7 @@ if [[ "${status}" == "ok" ]]; then # Only a working CLI without the flag keeps the old behaviour — post # nothing. if ! help_text=$(fullsend issues post-comment --help 2>&1); then - printf '%s\n' "post-lint-docs: 'fullsend issues post-comment --help' failed; cannot replace an earlier findings comment" >&2 + printf '%s\n' "post-lint-docs: 'fullsend issues post-comment --help' failed; cannot check for an earlier findings comment" >&2 printf '%s\n' "${help_text}" >&2 exit 1 fi @@ -319,9 +323,11 @@ if [[ "${status}" == "ok" ]]; then echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 exit 0 fi - # --keep-history=false: the all-clear replaces the comment in place, so - # repeated clean runs do not stack identical "Previous run" blocks. With - # no comment the all-clear is the summary alone. + # --keep-history=false is deprecated and, on a fullsend that has this + # change, has no effect: the all-clear is posted as a new comment at the + # end of the thread, following any earlier findings. It stays for + # runners pinned to an older CLI by the repository's fullsend-ref. With + # no comment in the result the all-clear is the summary alone. # The format is chosen here, never taken from the result file. body_format='**%s**\n\n%s\n' [[ -n "${comment}" ]] || body_format='**%s**\n%s' @@ -353,9 +359,9 @@ if [[ "${dry_run}" == "1" ]]; then exit 0 fi -# fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and its own author and edits -# it in place, so re-runs do not flood the work item. +# fullsend issues post-comment posts the result as a new comment at the +# end of the thread, carrying this agent's marker so later steps can find +# it; the thread itself is the history. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/agentnew/testdata/golden/pi-openai.txt b/internal/agentnew/testdata/golden/pi-openai.txt index 42d9977cc4..8aece61945 100644 --- a/internal/agentnew/testdata/golden/pi-openai.txt +++ b/internal/agentnew/testdata/golden/pi-openai.txt @@ -196,7 +196,8 @@ trigger: | # Treat the result file as untrusted: it is model output. Only the three # fields below are ever read, each must be a string, and the comment body is # piped on stdin rather than interpolated into a command. comment may be -# missing or empty when status is ok, because nothing new is posted then. +# missing or empty when status is ok, because the all-clear is the summary +# alone. set -euo pipefail @@ -307,19 +308,22 @@ fi REPO="${BASH_REMATCH[1]}" NUMBER="${BASH_REMATCH[3]}" -# On ok, post nothing — unless an earlier run left a findings comment on -# this work item. The harness trigger fires again on later pushes, so a -# problem the author has since fixed would otherwise stay reported. -# --only-if-exists makes fullsend replace that comment with the all-clear, -# and post nothing when there is no earlier comment. It matches only a -# comment carrying this marker whose author is exactly the login fullsend -# posts as, so a comment anyone else planted with the marker is never -# edited. When that login cannot be resolved it exits non-zero without -# posting; under `set -e` this script, and so the run, then fails -# visibly — rerun it. +# On ok, post nothing — unless an earlier comment with this marker exists +# on this work item, from findings or a previous all-clear alike (the gate +# is marker-only, so it stays open once the first all-clear is posted). +# The harness trigger fires again on later pushes, so a problem the author +# has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend post the all-clear as a new comment at +# the end of the thread, but only when an earlier comment with this +# marker exists; with none, nothing is posted. It matches only a comment +# carrying this marker whose author is exactly the login fullsend posts +# as, so a comment anyone else planted with the marker never counts. +# When that login cannot be resolved it exits non-zero without posting; +# under `set -e` this script, and so the run, then fails visibly — +# rerun it. if [[ "${status}" == "ok" ]]; then if [[ "${dry_run}" == "1" ]]; then - echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 + echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment)" >&2 exit 0 fi # The runner's fullsend may predate --only-if-exists (it is pinned by the @@ -329,7 +333,7 @@ if [[ "${status}" == "ok" ]]; then # Only a working CLI without the flag keeps the old behaviour — post # nothing. if ! help_text=$(fullsend issues post-comment --help 2>&1); then - printf '%s\n' "post-lint-docs: 'fullsend issues post-comment --help' failed; cannot replace an earlier findings comment" >&2 + printf '%s\n' "post-lint-docs: 'fullsend issues post-comment --help' failed; cannot check for an earlier findings comment" >&2 printf '%s\n' "${help_text}" >&2 exit 1 fi @@ -337,9 +341,11 @@ if [[ "${status}" == "ok" ]]; then echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 exit 0 fi - # --keep-history=false: the all-clear replaces the comment in place, so - # repeated clean runs do not stack identical "Previous run" blocks. With - # no comment the all-clear is the summary alone. + # --keep-history=false is deprecated and, on a fullsend that has this + # change, has no effect: the all-clear is posted as a new comment at the + # end of the thread, following any earlier findings. It stays for + # runners pinned to an older CLI by the repository's fullsend-ref. With + # no comment in the result the all-clear is the summary alone. # The format is chosen here, never taken from the result file. body_format='**%s**\n\n%s\n' [[ -n "${comment}" ]] || body_format='**%s**\n%s' @@ -371,9 +377,9 @@ if [[ "${dry_run}" == "1" ]]; then exit 0 fi -# fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and its own author and edits -# it in place, so re-runs do not flood the work item. +# fullsend issues post-comment posts the result as a new comment at the +# end of the thread, carrying this agent's marker so later steps can find +# it; the thread itself is the history. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index 51e77e6031..a4ddde3410 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -190,7 +190,8 @@ trigger: | # Treat the result file as untrusted: it is model output. Only the three # fields below are ever read, each must be a string, and the comment body is # piped on stdin rather than interpolated into a command. comment may be -# missing or empty when status is ok, because nothing new is posted then. +# missing or empty when status is ok, because the all-clear is the summary +# alone. set -euo pipefail @@ -301,19 +302,22 @@ fi REPO="${BASH_REMATCH[1]}" NUMBER="${BASH_REMATCH[3]}" -# On ok, post nothing — unless an earlier run left a findings comment on -# this work item. The harness trigger fires again on later pushes, so a -# problem the author has since fixed would otherwise stay reported. -# --only-if-exists makes fullsend replace that comment with the all-clear, -# and post nothing when there is no earlier comment. It matches only a -# comment carrying this marker whose author is exactly the login fullsend -# posts as, so a comment anyone else planted with the marker is never -# edited. When that login cannot be resolved it exits non-zero without -# posting; under `set -e` this script, and so the run, then fails -# visibly — rerun it. +# On ok, post nothing — unless an earlier comment with this marker exists +# on this work item, from findings or a previous all-clear alike (the gate +# is marker-only, so it stays open once the first all-clear is posted). +# The harness trigger fires again on later pushes, so a problem the author +# has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend post the all-clear as a new comment at +# the end of the thread, but only when an earlier comment with this +# marker exists; with none, nothing is posted. It matches only a comment +# carrying this marker whose author is exactly the login fullsend posts +# as, so a comment anyone else planted with the marker never counts. +# When that login cannot be resolved it exits non-zero without posting; +# under `set -e` this script, and so the run, then fails visibly — +# rerun it. if [[ "${status}" == "ok" ]]; then if [[ "${dry_run}" == "1" ]]; then - echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 + echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment)" >&2 exit 0 fi # The runner's fullsend may predate --only-if-exists (it is pinned by the @@ -323,7 +327,7 @@ if [[ "${status}" == "ok" ]]; then # Only a working CLI without the flag keeps the old behaviour — post # nothing. if ! help_text=$(fullsend issues post-comment --help 2>&1); then - printf '%s\n' "post-lint-docs: 'fullsend issues post-comment --help' failed; cannot replace an earlier findings comment" >&2 + printf '%s\n' "post-lint-docs: 'fullsend issues post-comment --help' failed; cannot check for an earlier findings comment" >&2 printf '%s\n' "${help_text}" >&2 exit 1 fi @@ -331,9 +335,11 @@ if [[ "${status}" == "ok" ]]; then echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 exit 0 fi - # --keep-history=false: the all-clear replaces the comment in place, so - # repeated clean runs do not stack identical "Previous run" blocks. With - # no comment the all-clear is the summary alone. + # --keep-history=false is deprecated and, on a fullsend that has this + # change, has no effect: the all-clear is posted as a new comment at the + # end of the thread, following any earlier findings. It stays for + # runners pinned to an older CLI by the repository's fullsend-ref. With + # no comment in the result the all-clear is the summary alone. # The format is chosen here, never taken from the result file. body_format='**%s**\n\n%s\n' [[ -n "${comment}" ]] || body_format='**%s**\n%s' @@ -365,9 +371,9 @@ if [[ "${dry_run}" == "1" ]]; then exit 0 fi -# fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and its own author and edits -# it in place, so re-runs do not flood the work item. +# fullsend issues post-comment posts the result as a new comment at the +# end of the thread, carrying this agent's marker so later steps can find +# it; the thread itself is the history. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index b2a2d9a1f3..cb82bc20ad 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -198,7 +198,8 @@ trigger: | # Treat the result file as untrusted: it is model output. Only the three # fields below are ever read, each must be a string, and the comment body is # piped on stdin rather than interpolated into a command. comment may be -# missing or empty when status is ok, because nothing new is posted then. +# missing or empty when status is ok, because the all-clear is the summary +# alone. set -euo pipefail @@ -309,19 +310,22 @@ fi REPO="${BASH_REMATCH[1]}" NUMBER="${BASH_REMATCH[3]}" -# On ok, post nothing — unless an earlier run left a findings comment on -# this work item. The harness trigger fires again on later pushes, so a -# problem the author has since fixed would otherwise stay reported. -# --only-if-exists makes fullsend replace that comment with the all-clear, -# and post nothing when there is no earlier comment. It matches only a -# comment carrying this marker whose author is exactly the login fullsend -# posts as, so a comment anyone else planted with the marker is never -# edited. When that login cannot be resolved it exits non-zero without -# posting; under `set -e` this script, and so the run, then fails -# visibly — rerun it. +# On ok, post nothing — unless an earlier comment with this marker exists +# on this work item, from findings or a previous all-clear alike (the gate +# is marker-only, so it stays open once the first all-clear is posted). +# The harness trigger fires again on later pushes, so a problem the author +# has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend post the all-clear as a new comment at +# the end of the thread, but only when an earlier comment with this +# marker exists; with none, nothing is posted. It matches only a comment +# carrying this marker whose author is exactly the login fullsend posts +# as, so a comment anyone else planted with the marker never counts. +# When that login cannot be resolved it exits non-zero without posting; +# under `set -e` this script, and so the run, then fails visibly — +# rerun it. if [[ "${status}" == "ok" ]]; then if [[ "${dry_run}" == "1" ]]; then - echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 + echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment)" >&2 exit 0 fi # The runner's fullsend may predate --only-if-exists (it is pinned by the @@ -331,7 +335,7 @@ if [[ "${status}" == "ok" ]]; then # Only a working CLI without the flag keeps the old behaviour — post # nothing. if ! help_text=$(fullsend issues post-comment --help 2>&1); then - printf '%s\n' "post-lint-docs: 'fullsend issues post-comment --help' failed; cannot replace an earlier findings comment" >&2 + printf '%s\n' "post-lint-docs: 'fullsend issues post-comment --help' failed; cannot check for an earlier findings comment" >&2 printf '%s\n' "${help_text}" >&2 exit 1 fi @@ -339,9 +343,11 @@ if [[ "${status}" == "ok" ]]; then echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 exit 0 fi - # --keep-history=false: the all-clear replaces the comment in place, so - # repeated clean runs do not stack identical "Previous run" blocks. With - # no comment the all-clear is the summary alone. + # --keep-history=false is deprecated and, on a fullsend that has this + # change, has no effect: the all-clear is posted as a new comment at the + # end of the thread, following any earlier findings. It stays for + # runners pinned to an older CLI by the repository's fullsend-ref. With + # no comment in the result the all-clear is the summary alone. # The format is chosen here, never taken from the result file. body_format='**%s**\n\n%s\n' [[ -n "${comment}" ]] || body_format='**%s**\n%s' @@ -373,9 +379,9 @@ if [[ "${dry_run}" == "1" ]]; then exit 0 fi -# fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and its own author and edits -# it in place, so re-runs do not flood the work item. +# fullsend issues post-comment posts the result as a new comment at the +# end of the thread, carrying this agent's marker so later steps can find +# it; the thread itself is the history. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/cli/issues.go b/internal/cli/issues.go index fc368c3c74..8818ffb19a 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -416,12 +416,11 @@ func newIssuesPostCommentCmd() *cobra.Command { cmd := &cobra.Command{ Use: "post-comment", - Short: "Post or update a sticky comment on an issue", - Long: `Posts a comment with a sticky marker on an issue. On first -run, creates a new comment. On re-runs, finds the existing comment -by its marker and its own author and edits in-place, collapsing old -content into
blocks. This prevents comment flooding on -re-runs. + Short: "Post a marked comment on an issue", + Long: `Posts a comment carrying a hidden marker on an issue. Every run +adds a new comment at the end of the thread: nothing is edited in +place and there are no collapsed "Previous run" sections — the thread +itself is the history. Works across GitHub, GitLab, and Jira via --tracker. @@ -431,12 +430,13 @@ For --tracker jira, the marker is stored as an invisible comment entity property rather than embedded in the visible comment body, so marker character restrictions do not apply. -Trust model: an existing comment is edited only when it carries the -marker and its author is exactly the identity this command posts as -(the login on GitHub and GitLab, the account ID on Jira). A comment -anyone else wrote with the same marker is ignored, never edited. If -that identity cannot be resolved after a short retry, the command fails -without posting or editing anything; rerun it. +With --only-if-exists, the comment is posted only when an earlier +comment with this marker exists (written by the identity this +command posts as — the login on GitHub and GitLab, the account ID on +Jira), so an all-clear follows earlier findings instead of arriving +unannounced. A comment anyone else wrote with the same marker is +ignored. If that identity cannot be resolved after a short retry, +the command fails without posting anything; rerun it. --tracker is required unless a default is supplied via config: set "tracker: {jira: {...}}" (or github/gitlab) in config.yaml and pass --fullsend-dir @@ -447,6 +447,7 @@ The --result flag accepts a file path or "-" for stdin.`, RunE: func(cmd *cobra.Command, args []string) error { if cmd.Flags().Changed("keep-history") { cfg.keepHistory = &keepHistory + warnKeepHistoryDeprecated(cmd) } return runIssuesPostComment(cmd.Context(), &cfg) }, @@ -455,12 +456,12 @@ The --result flag accepts a file path or "-" for stdin.`, cmd.Flags().StringVar(&cfg.trackerName, "tracker", "", "tracker backend: github, gitlab, or jira (required unless a default is set via config)") cmd.Flags().StringVar(&cfg.project, "project", "", projectFlagUsage) cmd.Flags().IntVar(&cfg.number, "number", 0, "issue number (required)") - cmd.Flags().StringVar(&cfg.marker, "marker", "", "sticky marker to identify this agent's comments (required)") + cmd.Flags().StringVar(&cfg.marker, "marker", "", "marker identifying this agent's comments (required)") cmd.Flags().StringVar(&cfg.result, "result", "-", "path to comment body file, or '-' for stdin") cmd.Flags().StringVar(&cfg.token, "token", "", tokenFlagUsage) - cmd.Flags().BoolVar(&cfg.dryRun, "dry-run", false, "print what would be posted without posting or editing anything") - cmd.Flags().BoolVar(&cfg.onlyIfExists, "only-if-exists", false, "update an existing comment with this marker but never create one (for an all-clear that should replace earlier findings)") - cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "append previous content as collapsed history blocks (set false to replace in-place)") + cmd.Flags().BoolVar(&cfg.dryRun, "dry-run", false, "print what would be posted without posting anything") + cmd.Flags().BoolVar(&cfg.onlyIfExists, "only-if-exists", false, "post only when an earlier comment with this marker exists (for an all-clear that follows earlier findings)") + cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "deprecated: no effect (every result is posted as a new comment; sticky comments were removed)") cmd.Flags().StringVar(&cfg.fullsendDir, "fullsend-dir", "", "path to .fullsend config directory (sources defaults, including the tracker.jira connection settings, from its config.yaml when flags are omitted)") _ = cmd.MarkFlagRequired("number") _ = cmd.MarkFlagRequired("marker") @@ -510,7 +511,7 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err keepHistory, err := resolveKeepHistory(cfg.keepHistory, cfg.fullsendDir, cfg.testConfigReader) if err != nil { - printer.StepWarn(fmt.Sprintf("Warning: %v; defaulting to keep_history=true", err)) + printer.StepWarn(fmt.Sprintf("Warning: %v (keep_history is deprecated and unused; every result is posted as a new comment)", err)) } stickyCfg := sticky.Config{ @@ -518,25 +519,22 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err DryRun: cfg.dryRun, KeepHistory: keepHistory, } - if trackerName == trackerJira { - // The Jira write path routes every body through - // jira.MarkdownToADF, which hard-rejects input over - // jira.MaxMarkdownBytes. Sticky's default max size (65000, - // derived from GitHub's comment cap) is well over that, so an - // accumulated sticky body that grows past the Jira limit would - // otherwise pass sticky's trim and only fail once it reaches - // Jira. Capping here keeps sticky's own trimming in charge of - // staying under the limit that will actually be enforced. - stickyCfg.MaxSize = jira.MaxMarkdownBytes - } - // Jira stores sticky markers as comment entity properties instead + // Jira stores markers as comment entity properties instead // of embedding them in the visible ADF body (Jira has no HTML // comments — the marker would be visible to users). When the // tracker.Client is a *tracker.JiraClient, use the property-based // path; otherwise fall back to the body-embedded path used by // GitHub/GitLab. if jc, ok := tc.(*tracker.JiraClient); ok { + // The Jira write path routes every body through + // jira.MarkdownToADF, which hard-rejects input over + // jira.MaxMarkdownBytes. Sticky's default max size (65000, + // derived from GitHub's comment cap) is well over that, so a + // body capped at the default would only fail once it reaches + // Jira. Capping here keeps the pre-create truncation under the + // limit that will actually be enforced. + stickyCfg.MaxSize = jira.MaxMarkdownBytes _, err = postJiraStickyComment(ctx, jc, project, cfg.number, body, stickyCfg, cfg.onlyIfExists, printer) } else { _, err = postTrackerStickyComment(ctx, tc, project, cfg.number, body, stickyCfg, cfg.onlyIfExists, printer) @@ -544,16 +542,18 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err return err } -// postJiraStickyComment implements the sticky comment lifecycle for Jira -// using comment entity properties to store the marker, keeping it out -// of the visible ADF body. Jira has no HTML comment equivalent, so -// without this the marker would be visible to users. +// postJiraStickyComment posts an agent result as a new Jira comment, +// storing the marker as a comment entity property so it stays out of the +// visible ADF body (Jira has no HTML comment equivalent, so an embedded +// marker would be visible to users). Nothing is edited in place: sticky +// comments were removed (#9334), every run appends a comment, and the +// thread itself is the history. // -// On create, the marker is stored as a comment property via the Jira -// comment-create API's properties array. On lookup, comments are fetched -// with ?expand=properties and matched by property value. On update, the -// property is set only for a legacy comment matched by its body-embedded -// marker, migrating it; a comment matched by property is left as is. +// onlyIfExists gates the post on an earlier comment with this marker: an +// all-clear then follows earlier findings at the end of the thread +// instead of replacing them. The gate considers only the poster's own +// comments, matched by exact account ID, so a marker another account +// planted never controls it. func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project string, number int, body string, cfg sticky.Config, onlyIfExists bool, printer *ui.Printer) (string, error) { if strings.TrimSpace(body) == "" { return "", fmt.Errorf("comment body is empty") @@ -566,63 +566,27 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project // GitHub/GitLab path does, in the form that stays escaped through // the Markdown -> ADF -> Markdown round trip. body = statuscomment.NeutralizeMarkersADF(body) + // The create path has no history trimming, so cap the body at the + // configured size before creating: an oversized single result would + // otherwise fail the post. + body = truncateForPost(body, cfg) - // Same rule as the GitHub/GitLab path: only the poster's own comments - // are candidates, matched by exact account ID. Filtering before the - // lookup covers both the marker property and the legacy body-text - // fallback, either of which another account can plant. - self, err := resolveTrackerSelf(ctx, jc) - if err != nil { - return "", unverifiedSelfError(err) - } - - jiraComments, err := jc.ListJiraComments(ctx, project, number) - if err != nil { - return "", fmt.Errorf("listing comments: %w", err) - } - - existing := jc.FindCommentByMarkerProperty(ownJiraComments(jiraComments, self), cfg.Marker) - - if existing != nil { - printer.StepStart("Found existing comment, updating in-place") - - // Build the updated body using sticky's history-collapsing - // logic. The old body is read from Jira as Markdown (via - // ADFToMarkdown). A legacy body-embedded marker is cut from the - // front of oldBody (the property-based path has none). The new - // body is passed without the marker prefix because the marker - // lives in a property, not the visible body. - // - // ADFToMarkdown decodes any escaped marker in the stored text - // back into a live one, so the old body is neutralized again - // after it is read back. The legacy marker is cut first so it - // is dropped rather than kept as escaped text in history. - // BuildUpdatedBody's own escaping uses "<", which Jira would - // decode, so its result is neutralized once more as well. - oldBody := jira.ADFToMarkdown(existing.Body) - oldBody, _ = strings.CutPrefix(oldBody, cfg.Marker) - oldBody = statuscomment.NeutralizeMarkersADF(oldBody) - newBody := statuscomment.NeutralizeMarkersADF(sticky.BuildUpdatedBody(oldBody, body, cfg)) - - if cfg.DryRun { - printer.StepInfo("Dry run — would update comment " + existing.ID) - printer.StepInfo(fmt.Sprintf("Body length: %d", len(newBody))) - return "", nil + if onlyIfExists { + self, err := resolveTrackerSelf(ctx, jc) + if err != nil { + return "", unverifiedSelfError(err) } - - if err := jc.MigrateAndUpdateComment(ctx, project, number, *existing, tracker.Body(newBody), cfg.Marker); err != nil { - return "", fmt.Errorf("updating comment: %w", err) + jiraComments, err := jc.ListJiraComments(ctx, project, number) + if err != nil { + return "", fmt.Errorf("listing comments: %w", err) + } + if jc.FindCommentByMarkerProperty(ownJiraComments(jiraComments, self), cfg.Marker) == nil { + printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") + return "", nil } - printer.StepDone("Comment updated") - return "", nil // Jira has no stable comment permalink - } - - if onlyIfExists { - printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") - return "", nil } - printer.StepStart("No existing comment found, creating new one") + printer.StepStart("Posting comment") if cfg.DryRun { printer.StepInfo("Dry run — would create new comment") @@ -638,18 +602,18 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project return created.HTMLURL, nil } -// postTrackerStickyComment implements the sticky comment lifecycle using -// tracker.Client instead of forge.Client. It mirrors the behavior of -// sticky.Post: find an existing comment bearing the marker, collapse -// old content into history, and create or update in-place. +// postTrackerStickyComment posts an agent result as a new comment using +// tracker.Client instead of forge.Client. It mirrors sticky.Post: nothing +// is edited in place — sticky comments were removed (#9334), every run +// appends a comment, and the thread itself is the history. // -// It never edits a comment it cannot verify as its own: an existing -// comment matches only when it carries the marker and its author is -// exactly the login this client posts as, so a comment anyone could plant -// with the same marker is ignored. When that login cannot be resolved -// (after a short retry) it returns an error and posts nothing, with or -// without onlyIfExists, which updates an existing comment but never -// creates one. +// onlyIfExists gates the post on an earlier comment with this marker, so +// an all-clear follows earlier findings at the end of the thread instead +// of replacing them. The gate matches only the poster's own comments (the +// author must be exactly the login this client posts as, so a comment +// anyone could plant with the same marker is ignored). When that login +// cannot be resolved (after a short retry) it returns an error and posts +// nothing. func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project string, number int, body string, cfg sticky.Config, onlyIfExists bool, printer *ui.Printer) (string, error) { if strings.TrimSpace(body) == "" { return "", fmt.Errorf("comment body is empty") @@ -658,48 +622,30 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return "", fmt.Errorf("marker is empty") } - // Without a verified identity nothing is posted at all: editing would - // trust an unverified comment, and creating a new one would orphan the - // earlier comment, whose stale content later runs would never update. - self, err := resolveTrackerSelf(ctx, tc) - if err != nil { - return "", unverifiedSelfError(err) - } - - comments, err := tc.ListComments(ctx, project, number) - if err != nil { - return "", fmt.Errorf("listing comments: %w", err) - } - - existing := findMarkedTrackerComment(comments, cfg.Marker, self) // Escape marker syntax in the agent-written body before the runner's // own marker is prepended, so the runner's marker is the only live one. markedBody := cfg.Marker + "\n" + statuscomment.NeutralizeMarkers(body) + // The create path has no history trimming, so cap the body at the + // configured size before creating: an oversized single result would + // otherwise fail the post. + markedBody = truncateForPost(markedBody, cfg) - if existing != nil { - printer.StepStart("Found existing comment, updating in-place") - - newBody := sticky.BuildUpdatedBody(string(existing.Body), markedBody, cfg) - - if cfg.DryRun { - printer.StepInfo("Dry run — would update comment " + existing.ID) - printer.StepInfo(fmt.Sprintf("Body length: %d", len(newBody))) - return "", nil + if onlyIfExists { + self, err := resolveTrackerSelf(ctx, tc) + if err != nil { + return "", unverifiedSelfError(err) } - - if err := tc.UpdateComment(ctx, project, number, existing.ID, tracker.Body(newBody)); err != nil { - return "", fmt.Errorf("updating comment: %w", err) + comments, err := tc.ListComments(ctx, project, number) + if err != nil { + return "", fmt.Errorf("listing comments: %w", err) + } + if findMarkedTrackerComment(comments, cfg.Marker, self) == nil { + printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") + return "", nil } - printer.StepDone("Comment updated") - return existing.HTMLURL, nil - } - - if onlyIfExists { - printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") - return "", nil } - printer.StepStart("No existing comment found, creating new one") + printer.StepStart("Posting comment") if cfg.DryRun { printer.StepInfo("Dry run — would create new comment") @@ -939,6 +885,27 @@ func resolveKeepHistory(flag *bool, fullsendDir string, testConfigReader config. return true, nil } +// warnKeepHistoryDeprecated prints a one-line warning when --keep-history is +// explicitly passed: the flag is accepted but has no effect (sticky comments +// were removed, #9334). Shell scripts never read help text, so the warning +// is the only advance notice external automation gets before a cleanup +// removes the flag (mirroring --vendor-fullsend-binary). +func warnKeepHistoryDeprecated(cmd *cobra.Command) { + fmt.Fprintln(cmd.ErrOrStderr(), "warning: --keep-history is deprecated and has no effect; every result is posted as a new comment") +} + +// truncateForPost caps a comment body at cfg's size limit before it is +// created. The create path has no history trimming (the update path that +// used to cap the assembled body is gone with sticky comments, #9334), so +// an oversized single result would otherwise fail the post. +func truncateForPost(body string, cfg sticky.Config) string { + maxSize := cfg.MaxSize + if maxSize <= 0 { + maxSize = sticky.DefaultMaxSize + } + return sticky.TruncateBody(body, maxSize) +} + // ownJiraComments returns the comments whose author account ID is exactly // self. An empty self returns none. func ownJiraComments(comments []jira.Comment, self string) []jira.Comment { diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 23e3ccb3f8..58576a6825 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -452,7 +452,7 @@ func TestPostTrackerStickyComment_Create(t *testing.T) { assert.Contains(t, string(comments[0].Body), "hello world") } -func TestPostTrackerStickyComment_Update(t *testing.T) { +func TestPostTrackerStickyComment_SecondRunAppends(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) @@ -465,16 +465,18 @@ func TestPostTrackerStickyComment_Update(t *testing.T) { _, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "first run", cfg, false, printer) require.NoError(t, err) - // Second post updates in-place. + // Second run adds a new comment at the end of the thread. _, err = postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "second run", cfg, false, printer) require.NoError(t, err) - // Verify only one comment exists (updated, not duplicated). comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "second run") - assert.Contains(t, string(comments[0].Body), "Previous run") + require.Len(t, comments, 2, "a second run must add a new comment") + assert.Contains(t, string(comments[0].Body), "first run") + assert.NotContains(t, string(comments[0].Body), "second run", "the earlier comment is left unchanged") + assert.Contains(t, string(comments[1].Body), "second run") + assert.Contains(t, string(comments[1].Body), "") + assert.NotContains(t, string(comments[1].Body), "Previous run") } func TestPostTrackerStickyComment_NeutralizesMarkersInBody(t *testing.T) { @@ -494,18 +496,20 @@ func TestPostTrackerStickyComment_NeutralizesMarkersInBody(t *testing.T) { comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) - require.Len(t, comments, 1) - got := string(comments[0].Body) + require.Len(t, comments, 3, "every run adds its own comment") - assert.True(t, strings.HasPrefix(got, cfg.Marker+"\n")) - assert.Equal(t, 1, strings.Count(got, cfg.Marker), "exactly one runner marker") - assert.Equal(t, 1, strings.Count(got, "fullsend:triage-agent"), "no escaped copy of the runner's marker lands in history") - assert.Equal(t, 1, strings.Count(strings.ToLower(got), ""), "current body and both history entries") - assert.Equal(t, 3, strings.Count(got, "<!--FULLSEND\t:review-agent-->")) - assert.Equal(t, 3, strings.Count(got, "already <!-- fullsend:x -->"), "pre-escaped text is unchanged") - assert.NotContains(t, got, "&lt;") + for i, c := range comments { + got := string(c.Body) + assert.True(t, strings.HasPrefix(got, cfg.Marker+"\n"), "comment %d: marker at the start", i) + assert.Equal(t, 1, strings.Count(got, cfg.Marker), "comment %d: exactly one runner marker", i) + assert.Equal(t, 1, strings.Count(got, "fullsend:triage-agent"), "comment %d: no escaped copy of the runner's marker", i) + assert.Equal(t, 1, strings.Count(strings.ToLower(got), ""), "comment %d: agent marker escaped once", i) + assert.Equal(t, 1, strings.Count(got, "<!--FULLSEND\t:review-agent-->"), "comment %d", i) + assert.Equal(t, 1, strings.Count(got, "already <!-- fullsend:x -->"), "comment %d: pre-escaped text is unchanged", i) + assert.NotContains(t, got, "&lt;") + } } func TestPostTrackerStickyComment_EmptyBody(t *testing.T) { @@ -547,7 +551,7 @@ func TestPostTrackerStickyComment_DryRun_Create(t *testing.T) { assert.Empty(t, comments) } -func TestPostTrackerStickyComment_DryRun_Update(t *testing.T) { +func TestPostTrackerStickyComment_DryRun_WithExistingComment(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) @@ -559,7 +563,7 @@ func TestPostTrackerStickyComment_DryRun_Update(t *testing.T) { _, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "first", cfg, false, printer) require.NoError(t, err) - // Dry run update should not modify the comment. + // A dry run posts nothing, so the existing comment is unchanged. cfg.DryRun = true url, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "second", cfg, false, printer) require.NoError(t, err) @@ -833,7 +837,7 @@ func TestRunIssuesPostComment_Create(t *testing.T) { assert.Contains(t, string(comments[0].Body), "automated comment body") } -func TestRunIssuesPostComment_Update(t *testing.T) { +func TestRunIssuesPostComment_SecondRunAppends(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) @@ -853,15 +857,17 @@ func TestRunIssuesPostComment_Update(t *testing.T) { err := runIssuesPostComment(ctx, cfg) require.NoError(t, err) - // Second run updates. + // Second run adds a new comment at the end of the thread. cfg.testBody = "second run" err = runIssuesPostComment(ctx, cfg) require.NoError(t, err) comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "second run") + require.Len(t, comments, 2) + assert.Contains(t, string(comments[0].Body), "first run") + assert.NotContains(t, string(comments[0].Body), "second run", "the earlier comment is left unchanged") + assert.Contains(t, string(comments[1].Body), "second run") } func TestRunIssuesPostComment_InvalidNumber(t *testing.T) { @@ -945,76 +951,6 @@ func TestRunIssuesPostComment_FromFile(t *testing.T) { assert.Contains(t, string(comments[0].Body), "comment from file") } -func TestRunIssuesPostComment_JiraCapsStickyMaxSize(t *testing.T) { - tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") - require.NoError(t, err) - ctx := context.Background() - - // Under jira.MaxMarkdownBytes individually (so MarkdownToADF accepts - // it on the first run), but large enough that the second-run body — - // "second run" plus a
wrapper around this history — exceeds - // jira.MaxMarkdownBytes, forcing the Jira-aware MaxSize cap to trim - // the history rather than assembling a body that would fail once it - // reaches Jira's MarkdownToADF. - firstBody := strings.Repeat("a", 32700) - - cfg := &issuesPostCommentConfig{ - trackerName: trackerJira, - project: "PROJ", - number: 42, - marker: "", - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: firstBody, - } - require.NoError(t, runIssuesPostComment(ctx, cfg)) - - cfg.testBody = "second run" - require.NoError(t, runIssuesPostComment(ctx, cfg)) - - comments, err := tc.ListComments(ctx, "PROJ", 42) - require.NoError(t, err) - require.Len(t, comments, 1) - - // The collapsed ~32 KB history plus "second run" and its
- // wrapper exceeds jira.MaxMarkdownBytes, so the Jira path must - // trim the history rather than assembling a body that would fail - // once it reaches Jira's MarkdownToADF. - assert.LessOrEqual(t, len(comments[0].Body), jira.MaxMarkdownBytes) - assert.Contains(t, string(comments[0].Body), "second run") -} - -func TestRunIssuesPostComment_NonJiraKeepsDefaultStickyMaxSize(t *testing.T) { - fc := forge.NewFakeClient() - fc.AuthenticatedUser = "bot" - tc := tracker.NewForgeClient(fc) - ctx := context.Background() - - firstBody := strings.Repeat("a", 40000) - - cfg := &issuesPostCommentConfig{ - trackerName: trackerGitHub, - project: "acme/widgets", - number: 42, - marker: "", - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: firstBody, - } - require.NoError(t, runIssuesPostComment(ctx, cfg)) - - cfg.testBody = "second run" - require.NoError(t, runIssuesPostComment(ctx, cfg)) - - comments, err := tc.ListComments(ctx, "acme/widgets", 42) - require.NoError(t, err) - require.Len(t, comments, 1) - - // Non-Jira trackers keep sticky's default 65000-byte cap, so the same - // accumulated body (well under 65000) keeps its history intact. - assert.Contains(t, string(comments[0].Body), "Previous run") -} - func TestRunIssuesPostComment_JiraAcceptsMarkerWithSpecialChars(t *testing.T) { // Jira now stores markers in comment entity properties instead of // the visible body, so marker character restrictions no longer @@ -1071,13 +1007,12 @@ func TestRunIssuesPostComment_JiraProjectWithoutConfig(t *testing.T) { assert.Contains(t, err.Error(), "no default Jira project is configured") } -func TestRunIssuesPostComment_JiraRoundTripUpdatesInPlace(t *testing.T) { - // Drives the Jira property-based sticky comment path twice through +func TestRunIssuesPostComment_JiraSecondRunAppends(t *testing.T) { + // Drives the Jira property-based comment path twice through // tracker.JiraClient (via NewFakeJiraClientWithFake) so comment // bodies round-trip through real jira.MarkdownToADF/ADFToMarkdown. // The marker is stored in a comment entity property, not in the - // visible ADF body, and must be matched via property on the second - // run to update in place instead of flooding a new comment. + // visible ADF body, and the second run appends a new comment. tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") require.NoError(t, err) ctx := context.Background() @@ -1098,14 +1033,19 @@ func TestRunIssuesPostComment_JiraRoundTripUpdatesInPlace(t *testing.T) { comments, err := tc.ListComments(ctx, "PROJ", 42) require.NoError(t, err) - require.Len(t, comments, 1, "second run should update the existing comment in place, not flood a new one") - assert.Contains(t, string(comments[0].Body), "second run") - assert.Contains(t, string(comments[0].Body), "Previous run") + require.Len(t, comments, 2, "second run should append a new comment") + assert.Contains(t, string(comments[0].Body), "first run") + assert.NotContains(t, string(comments[0].Body), "second run", "the earlier comment is left unchanged") + assert.Contains(t, string(comments[1].Body), "second run") + assert.NotContains(t, string(comments[1].Body), "Previous run") } -func TestRunIssuesPostComment_JiraMarkerNotInVisibleBody(t *testing.T) { - // The marker must be stored only in the comment entity property, - // not in the visible ADF body that Jira renders to users. +func TestRunIssuesPostComment_JiraTruncatesOversizedBody(t *testing.T) { + // Pins the Jira door's create-path size cap: runIssuesPostComment + // caps stickyCfg.MaxSize at jira.MaxMarkdownBytes, and the fake + // client runs the real jira.MarkdownToADF, which hard-rejects input + // over that limit — so an oversized single result must be truncated + // before it is created instead of failing the post. tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") require.NoError(t, err) ctx := context.Background() @@ -1117,63 +1057,62 @@ func TestRunIssuesPostComment_JiraMarkerNotInVisibleBody(t *testing.T) { marker: "", testClient: tc, testPrinter: ui.New(io.Discard), - testBody: "visible content only", + testBody: strings.Repeat("a", jira.MaxMarkdownBytes+5000), } require.NoError(t, runIssuesPostComment(ctx, cfg)) comments, err := tc.ListComments(ctx, "PROJ", 42) require.NoError(t, err) require.Len(t, comments, 1) - // The visible body must contain the content but NOT the marker. - assert.Contains(t, string(comments[0].Body), "visible content only") - assert.NotContains(t, string(comments[0].Body), "") + assert.LessOrEqual(t, len(string(comments[0].Body)), jira.MaxMarkdownBytes, + "the created body must be truncated to the Jira markdown limit") } -func TestRunIssuesPostComment_JiraLegacyMigration(t *testing.T) { - // A legacy Jira comment has the marker embedded in the visible ADF - // body (old behavior). On the next run, the property-based path - // should find it via body-text fallback, set the property, and - // strip the marker from the body on update. - tc, fc, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") - require.NoError(t, err) +func TestPostTrackerStickyComment_TruncatesOversizedBodyBeforeCreate(t *testing.T) { + // Mirrors TestPost_TruncatesOversizedBodyBeforeCreate for the + // tracker door: a single result over the configured size limit is + // truncated before it is created instead of failing the post. + fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" + tc := tracker.NewForgeClient(fc) + printer := ui.New(io.Discard) ctx := context.Background() - marker := "" + cfg := sticky.Config{Marker: "", MaxSize: 500} + _, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, strings.Repeat("a", 800), cfg, false, printer) + require.NoError(t, err) - // Simulate a legacy comment: marker embedded in body, no property. - legacyBody := marker + "\nlegacy content" - _, createErr := fc.CreateComment(ctx, "PROJ-42", legacyBody) - require.NoError(t, createErr) + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.LessOrEqual(t, len(string(comments[0].Body)), 500, "the created body must fit the configured size") + assert.Contains(t, string(comments[0].Body), "") +} + +func TestRunIssuesPostComment_JiraMarkerNotInVisibleBody(t *testing.T) { + // The marker must be stored only in the comment entity property, + // not in the visible ADF body that Jira renders to users. + tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") + require.NoError(t, err) + ctx := context.Background() - // Run post-comment, which should find the legacy comment via body - // fallback, update it, and set the property. cfg := &issuesPostCommentConfig{ trackerName: trackerJira, project: "PROJ", number: 42, - marker: marker, + marker: "", testClient: tc, testPrinter: ui.New(io.Discard), - testBody: "updated via property", + testBody: "visible content only", } require.NoError(t, runIssuesPostComment(ctx, cfg)) comments, err := tc.ListComments(ctx, "PROJ", 42) require.NoError(t, err) - require.Len(t, comments, 1, "should update the legacy comment in place") - assert.Contains(t, string(comments[0].Body), "updated via property") - // After migration, marker should not be in the visible body. - assert.NotContains(t, string(comments[0].Body), marker) - - // Third run: should find the now-migrated comment via property, - // not via body, confirming property was set during migration. - cfg.testBody = "third run" - require.NoError(t, runIssuesPostComment(ctx, cfg)) - - comments, err = tc.ListComments(ctx, "PROJ", 42) - require.NoError(t, err) - require.Len(t, comments, 1, "third run should still update the same comment") - assert.Contains(t, string(comments[0].Body), "third run") + require.Len(t, comments, 1) + // The visible body must contain the content but NOT the marker. + assert.Contains(t, string(comments[0].Body), "visible content only") + assert.NotContains(t, string(comments[0].Body), "") } // liveMarkerOpener matches a fullsend marker opener that would parse as a @@ -1183,8 +1122,8 @@ var liveMarkerOpener = regexp.MustCompile(`(?i)`, "neutralized text should stay visible") // Neither the quoted sibling marker nor the quoted status marker @@ -1223,114 +1161,11 @@ func TestRunIssuesPostComment_JiraNeutralizesInjectedMarkers(t *testing.T) { raw, err := tc.ListJiraComments(ctx, "PROJ", 42) require.NoError(t, err) assert.Nil(t, tc.FindCommentByMarkerProperty(raw, sibling)) - isStatus, err := tc.IsStatusComment(ctx, "PROJ", 42, comments[0].ID) + isStatus, err := tc.IsStatusComment(ctx, "PROJ", 42, comments[1].ID) require.NoError(t, err) assert.False(t, isStatus) } -func TestRunIssuesPostComment_JiraNeutralizesStoredMarkersInHistory(t *testing.T) { - // A sticky comment stored before neutralization holds live marker - // text. On update, the old body read back from ADF must be - // neutralized before it is folded into history. - tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") - require.NoError(t, err) - ctx := context.Background() - - marker := "" - _, err = tc.CreateCommentWithMarker(ctx, "PROJ", 42, "old run\n\n", marker) - require.NoError(t, err) - - cfg := &issuesPostCommentConfig{ - trackerName: trackerJira, - project: "PROJ", - number: 42, - marker: marker, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "new run", - } - require.NoError(t, runIssuesPostComment(ctx, cfg)) - - comments, err := tc.ListComments(ctx, "PROJ", 42) - require.NoError(t, err) - require.Len(t, comments, 1) - body := string(comments[0].Body) - assert.NotRegexp(t, liveMarkerOpener, body) - assert.Contains(t, body, "new run") - assert.Contains(t, body, "old run") - assert.Contains(t, body, `\<!-- fullsend:review-agent -->`) -} - -func TestRunIssuesPostComment_JiraPropertyMarkedSkipsPropertyWrite(t *testing.T) { - // An existing comment whose marker property already matches is - // updated without rewriting the property, so a Jira rejection of - // property writes (e.g. 403) does not block the body update. - tc, fc, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") - require.NoError(t, err) - ctx := context.Background() - - marker := "" - - // First run creates the comment with the property set inline. - cfg := &issuesPostCommentConfig{ - trackerName: trackerJira, - project: "PROJ", - number: 42, - marker: marker, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "first run", - } - require.NoError(t, runIssuesPostComment(ctx, cfg)) - assert.Zero(t, fc.PropertyWrites, "creation sets the property inline, not via a separate write") - - fc.PropertyError = fmt.Errorf("set comment property: %w", forge.ErrForbidden) - - cfg.testBody = "second run" - require.NoError(t, runIssuesPostComment(ctx, cfg)) - assert.Zero(t, fc.PropertyWrites, "an exact property match must not rewrite the property") - - comments, err := tc.ListComments(ctx, "PROJ", 42) - require.NoError(t, err) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "second run") -} - -func TestRunIssuesPostComment_JiraLegacyPropertyPermissionFailure(t *testing.T) { - // When the Jira API rejects the property write that migrates a - // legacy comment, the update fails with an actionable error and the - // body keeps its legacy marker rather than losing it. - tc, fc, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") - require.NoError(t, err) - ctx := context.Background() - - marker := "" - _, err = fc.CreateComment(ctx, "PROJ-42", marker+"\nlegacy content") - require.NoError(t, err) - - fc.PropertyError = fmt.Errorf("set comment property: %w", forge.ErrForbidden) - - cfg := &issuesPostCommentConfig{ - trackerName: trackerJira, - project: "PROJ", - number: 42, - marker: marker, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "second run", - } - err = runIssuesPostComment(ctx, cfg) - require.Error(t, err) - assert.Contains(t, err.Error(), "sticky marker property") - assert.Equal(t, 1, fc.PropertyWrites) - - comments, err := tc.ListComments(ctx, "PROJ", 42) - require.NoError(t, err) - require.Len(t, comments, 1) - assert.NotContains(t, string(comments[0].Body), "second run") - assert.Contains(t, string(comments[0].Body), marker) -} - func TestPostJiraStickyComment_DryRun_Create(t *testing.T) { // Dry-run create should not create a comment. tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") @@ -1348,8 +1183,8 @@ func TestPostJiraStickyComment_DryRun_Create(t *testing.T) { assert.Empty(t, comments) } -func TestPostJiraStickyComment_DryRun_Update(t *testing.T) { - // Dry-run update should not modify the existing comment. +func TestPostJiraStickyComment_DryRun_WithExistingComment(t *testing.T) { + // A dry run posts nothing, so the existing comment is unchanged. tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") require.NoError(t, err) printer := ui.New(io.Discard) @@ -1360,7 +1195,7 @@ func TestPostJiraStickyComment_DryRun_Update(t *testing.T) { _, err = postJiraStickyComment(ctx, tc, "PROJ", 42, "first", cfg, false, printer) require.NoError(t, err) - // Dry run update should not modify the comment. + // A dry run posts nothing, so the existing comment is unchanged. cfg.DryRun = true url, err := postJiraStickyComment(ctx, tc, "PROJ", 42, "second", cfg, false, printer) require.NoError(t, err) @@ -1655,7 +1490,7 @@ func TestRunIssuesPostComment_OnlyIfExists_SkipsCreate(t *testing.T) { assert.Empty(t, comments, "only-if-exists must not create a first comment") } -func TestRunIssuesPostComment_OnlyIfExists_ReplacesEarlierFindings(t *testing.T) { +func TestRunIssuesPostComment_OnlyIfExists_AppendsAllClearAfterEarlierFindings(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) @@ -1678,8 +1513,10 @@ func TestRunIssuesPostComment_OnlyIfExists_ReplacesEarlierFindings(t *testing.T) comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "all clear") + require.Len(t, comments, 2, "the all-clear is a new comment at the end of the thread") + assert.Contains(t, string(comments[0].Body), "2 broken links") + assert.NotContains(t, string(comments[0].Body), "all clear", "the earlier findings are left unchanged") + assert.Contains(t, string(comments[1].Body), "all clear") } func TestRunIssuesPostComment_Jira_OnlyIfExists(t *testing.T) { @@ -1703,7 +1540,8 @@ func TestRunIssuesPostComment_Jira_OnlyIfExists(t *testing.T) { require.NoError(t, err) assert.Empty(t, comments) - // An earlier findings comment exists: it is replaced. + // An earlier findings comment exists: the all-clear follows it as a + // new comment. cfg.onlyIfExists = false cfg.testBody = "2 broken links" require.NoError(t, runIssuesPostComment(ctx, cfg)) @@ -1712,8 +1550,10 @@ func TestRunIssuesPostComment_Jira_OnlyIfExists(t *testing.T) { require.NoError(t, runIssuesPostComment(ctx, cfg)) comments, err = tc.ListComments(ctx, "PROJ", 42) require.NoError(t, err) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "all clear") + require.Len(t, comments, 2) + assert.Contains(t, string(comments[0].Body), "2 broken links") + assert.NotContains(t, string(comments[0].Body), "all clear", "the earlier findings are left unchanged") + assert.Contains(t, string(comments[1].Body), "all clear") } // fastSelfLookup shortens the identity-lookup retry backoff for a test. @@ -1776,13 +1616,14 @@ func postAfterCommentBy(t *testing.T, author string, onlyIfExists bool, failures return runErr, comments, tc } -func TestRunIssuesPostComment_EditsOwnComment(t *testing.T) { +func TestRunIssuesPostComment_AppendsAfterOwnComment(t *testing.T) { for _, onlyIfExists := range []bool{false, true} { t.Run(fmt.Sprintf("only-if-exists=%v", onlyIfExists), func(t *testing.T) { err, comments, _ := postAfterCommentBy(t, testBot, onlyIfExists, 0) require.NoError(t, err) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "new result") + require.Len(t, comments, 2, "the result is a new comment at the end of the thread") + assert.NotContains(t, string(comments[0].Body), "new result", "the earlier comment is left unchanged") + assert.Contains(t, string(comments[1].Body), "new result") }) } } @@ -1809,31 +1650,31 @@ func TestRunIssuesPostComment_IgnoresPlantedMarker(t *testing.T) { } } -func TestRunIssuesPostComment_TransientSelfFailureRetriesThenEdits(t *testing.T) { - err, comments, tc := postAfterCommentBy(t, testBot, false, len(selfLookupBackoff)) +func TestRunIssuesPostComment_TransientSelfFailureRetriesThenPosts(t *testing.T) { + // Only --only-if-exists resolves the posting identity (to gate on the + // poster's own earlier comment); a transient failure there is retried. + err, comments, tc := postAfterCommentBy(t, testBot, true, len(selfLookupBackoff)) require.NoError(t, err) assert.Equal(t, len(selfLookupBackoff)+1, tc.calls, "every retry is used before success") - require.Len(t, comments, 1, "a transient failure must not create a second comment") - assert.Contains(t, string(comments[0].Body), "new result") + require.Len(t, comments, 2) + assert.Contains(t, string(comments[1].Body), "new result") } func TestRunIssuesPostComment_PersistentSelfFailureErrorsAndPostsNothing(t *testing.T) { - for _, onlyIfExists := range []bool{false, true} { - t.Run(fmt.Sprintf("only-if-exists=%v", onlyIfExists), func(t *testing.T) { - err, comments, tc := postAfterCommentBy(t, testBot, onlyIfExists, 1000) - require.Error(t, err) - assert.Contains(t, err.Error(), "cannot verify which identity") - assert.Contains(t, err.Error(), "rerun") - assert.Contains(t, err.Error(), "502 Bad Gateway", "the error must name the cause") - assert.Equal(t, len(selfLookupBackoff)+1, tc.calls) - require.Len(t, comments, 1, "no comment may be created") - assert.NotContains(t, string(comments[0].Body), "new result", "no comment may be edited") - }) - } + // Only --only-if-exists resolves the posting identity, so only that + // path fails when it cannot be verified. + err, comments, tc := postAfterCommentBy(t, testBot, true, 1000) + require.Error(t, err) + assert.Contains(t, err.Error(), "cannot verify which identity") + assert.Contains(t, err.Error(), "rerun") + assert.Contains(t, err.Error(), "502 Bad Gateway", "the error must name the cause") + assert.Equal(t, len(selfLookupBackoff)+1, tc.calls) + require.Len(t, comments, 1, "no comment may be created") } func TestRunIssuesPostComment_EmptySelfErrors(t *testing.T) { // An empty login with no error is unresolved too, never marker-only. + // Only --only-if-exists resolves the posting identity. fastSelfLookup(t) ctx := context.Background() fc := forge.NewFakeClient() @@ -1842,21 +1683,19 @@ func TestRunIssuesPostComment_EmptySelfErrors(t *testing.T) { _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nauthorless")) require.NoError(t, err) - for _, onlyIfExists := range []bool{false, true} { - cfg := &issuesPostCommentConfig{ - trackerName: trackerGitHub, - project: "acme/widgets", - number: 42, - marker: marker, - onlyIfExists: onlyIfExists, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "new result", - } - err := runIssuesPostComment(ctx, cfg) - require.Error(t, err) - assert.Contains(t, err.Error(), "authenticated user is empty") + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "new result", } + err = runIssuesPostComment(ctx, cfg) + require.Error(t, err) + assert.Contains(t, err.Error(), "authenticated user is empty") comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) require.Len(t, comments, 1) @@ -1893,9 +1732,10 @@ func TestRunIssuesPostComment_OnlyIfExists_SkipsPlantedCommentBeforeOwn(t *testi comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) - require.Len(t, comments, 2) - assert.NotContains(t, string(comments[0].Body), "all clear") - assert.Contains(t, string(comments[1].Body), "all clear") + require.Len(t, comments, 3, "the all-clear is a new comment at the end of the thread") + assert.NotContains(t, string(comments[0].Body), "all clear", "the planted comment must be untouched") + assert.NotContains(t, string(comments[1].Body), "all clear", "the own earlier comment is left unchanged") + assert.Contains(t, string(comments[2].Body), "all clear") } func TestResolveTrackerSelf_StopsRetryingWhenCancelled(t *testing.T) { @@ -1917,7 +1757,7 @@ func TestResolveTrackerSelf_StopsRetryingWhenCancelled(t *testing.T) { // author (with the marker as a comment property, or, when legacy is set, // embedded in the body the way pre-property comments stored it), then // runs post-comment as tracker.FakeJiraBot. -func postJiraAfterCommentBy(t *testing.T, author jira.User, legacy bool, myselfErr error) (error, []tracker.Comment) { +func postJiraAfterCommentBy(t *testing.T, author jira.User, legacy bool, myselfErr error, onlyIfExists bool) (error, []tracker.Comment) { t.Helper() fastSelfLookup(t) ctx := context.Background() @@ -1936,13 +1776,14 @@ func postJiraAfterCommentBy(t *testing.T, author jira.User, legacy bool, myselfE fc.Myself = tracker.FakeJiraBot fc.MyselfError = myselfErr cfg := &issuesPostCommentConfig{ - trackerName: trackerJira, - project: "PROJ", - number: 42, - marker: marker, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "new result", + trackerName: trackerJira, + project: "PROJ", + number: 42, + marker: marker, + onlyIfExists: onlyIfExists, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "new result", } runErr := runIssuesPostComment(ctx, cfg) @@ -1951,13 +1792,14 @@ func postJiraAfterCommentBy(t *testing.T, author jira.User, legacy bool, myselfE return runErr, comments } -func TestRunIssuesPostComment_Jira_EditsOwnComment(t *testing.T) { +func TestRunIssuesPostComment_Jira_AppendsAfterOwnComment(t *testing.T) { for _, legacy := range []bool{false, true} { t.Run(fmt.Sprintf("legacy=%v", legacy), func(t *testing.T) { - err, comments := postJiraAfterCommentBy(t, tracker.FakeJiraBot, legacy, nil) + err, comments := postJiraAfterCommentBy(t, tracker.FakeJiraBot, legacy, nil, false) require.NoError(t, err) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "new result") + require.Len(t, comments, 2, "the result is a new comment at the end of the thread") + assert.NotContains(t, string(comments[0].Body), "new result", "the earlier comment is left unchanged") + assert.Contains(t, string(comments[1].Body), "new result") }) } } @@ -1968,7 +1810,7 @@ func TestRunIssuesPostComment_Jira_IgnoresPlantedMarker(t *testing.T) { mallory := jira.User{AccountID: "mallory-account-id", DisplayName: tracker.FakeJiraBot.DisplayName} for _, legacy := range []bool{false, true} { t.Run(fmt.Sprintf("legacy=%v", legacy), func(t *testing.T) { - err, comments := postJiraAfterCommentBy(t, mallory, legacy, nil) + err, comments := postJiraAfterCommentBy(t, mallory, legacy, nil, false) require.NoError(t, err) require.Len(t, comments, 2, "the planted comment is left alone and a new one posted") assert.NotContains(t, string(comments[0].Body), "new result") @@ -1978,12 +1820,13 @@ func TestRunIssuesPostComment_Jira_IgnoresPlantedMarker(t *testing.T) { } func TestRunIssuesPostComment_Jira_UnresolvableSelfErrorsAndPostsNothing(t *testing.T) { - err, comments := postJiraAfterCommentBy(t, tracker.FakeJiraBot, false, errors.New("401 Unauthorized")) + // Only --only-if-exists resolves the posting identity, so only that + // path fails when it cannot be verified. + err, comments := postJiraAfterCommentBy(t, tracker.FakeJiraBot, false, errors.New("401 Unauthorized"), true) require.Error(t, err) assert.Contains(t, err.Error(), "cannot verify which identity") assert.Contains(t, err.Error(), "401 Unauthorized") require.Len(t, comments, 1, "no comment may be created") - assert.NotContains(t, string(comments[0].Body), "new result", "no comment may be edited") } func TestOwnJiraComments(t *testing.T) { @@ -1998,9 +1841,10 @@ func TestOwnJiraComments(t *testing.T) { assert.Empty(t, ownJiraComments(comments, ""), "an unverified self owns nothing, not even authorless comments") } -func TestRunIssuesPostComment_DryRunStillVerifiesIdentity(t *testing.T) { - // --dry-run resolves the posting identity too: a dry run that cannot - // verify it fails rather than silently previewing an edit. +func TestRunIssuesPostComment_DryRunOnlyIfExistsStillVerifiesIdentity(t *testing.T) { + // --dry-run --only-if-exists resolves the posting identity too: a dry + // run that cannot verify it fails rather than silently previewing a + // post gated on the poster's own earlier comment. fastSelfLookup(t) ctx := context.Background() const marker = "" @@ -2022,14 +1866,15 @@ func TestRunIssuesPostComment_DryRunStillVerifiesIdentity(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { cfg := &issuesPostCommentConfig{ - trackerName: tc.tracker, - project: tc.project, - number: 42, - marker: marker, - dryRun: true, - testClient: tc.client, - testPrinter: ui.New(io.Discard), - testBody: "preview", + trackerName: tc.tracker, + project: tc.project, + number: 42, + marker: marker, + dryRun: true, + onlyIfExists: true, + testClient: tc.client, + testPrinter: ui.New(io.Discard), + testBody: "preview", } err := runIssuesPostComment(ctx, cfg) require.Error(t, err) @@ -2070,10 +1915,10 @@ func TestRunIssuesPostComment_Jira_OnlyIfExistsIgnoresPlantedMarker(t *testing.T assert.NotContains(t, string(comments[0].Body), "all clear") } -func TestRunIssuesPostComment_OnlyIfExistsWithoutHistoryReplacesInPlace(t *testing.T) { - // The generated ok path passes --keep-history=false: the all-clear - // replaces the earlier findings, and repeated clean runs leave one - // all-clear rather than stacking identical "Previous run" blocks. +func TestRunIssuesPostComment_OnlyIfExistsAppendsAllClear(t *testing.T) { + // The generated ok path passes --keep-history=false, which no longer + // has an effect: the all-clear follows the earlier findings as a new + // comment, and repeated clean runs each add their own. ctx := context.Background() fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" @@ -2099,9 +1944,10 @@ func TestRunIssuesPostComment_OnlyIfExistsWithoutHistoryReplacesInPlace(t *testi comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) - require.Len(t, comments, 1) - body := string(comments[0].Body) - assert.Equal(t, 1, strings.Count(body, "all clear"), "the all-clear replaces in place; got:\n%s", body) - assert.NotContains(t, body, "2 broken links") - assert.NotContains(t, body, "Previous run") + require.Len(t, comments, 4, "the findings comment plus one all-clear per clean run") + assert.Contains(t, string(comments[0].Body), "2 broken links") + for _, c := range comments[1:] { + assert.Contains(t, string(c.Body), "all clear") + assert.NotContains(t, string(c.Body), "Previous run") + } } diff --git a/internal/cli/postcomment.go b/internal/cli/postcomment.go index dd96d0dd73..d6bdb3c68f 100644 --- a/internal/cli/postcomment.go +++ b/internal/cli/postcomment.go @@ -26,7 +26,7 @@ func newPostCommentCmd() *cobra.Command { cmd := &cobra.Command{ Use: "post-comment", - Short: "Post or update a sticky comment on an issue or PR (deprecated: use 'fullsend issues post-comment')", + Short: "Post a marked comment on an issue or PR (deprecated: use 'fullsend issues post-comment')", Deprecated: "use 'fullsend issues post-comment --tracker github' instead", Long: `Posts a comment with a hidden HTML marker on an issue or pull request. @@ -34,9 +34,9 @@ DEPRECATED: This command targets GitHub only. Use 'fullsend issues post-comment --tracker github' for GitHub, GitLab, or Jira support. -On first run, creates a new comment. On re-runs, finds the existing -comment by its marker and edits in-place, collapsing old content into -
blocks. This prevents comment flooding on re-runs. +Every run adds a new comment at the end of the thread: nothing is +edited in place and there are no collapsed "Previous run" sections — +the thread itself is the history. The --marker flag identifies this agent's comments. Each agent should use a unique marker (e.g. ""). @@ -75,11 +75,13 @@ The --result flag accepts a file path or "-" for stdin.`, // --fullsend-dir (matching the pattern in issues post-comment // and post-review). resolvedKeepHistory := keepHistory - if !cmd.Flags().Changed("keep-history") { + if cmd.Flags().Changed("keep-history") { + warnKeepHistoryDeprecated(cmd) + } else { var khFlag *bool // nil = not explicitly set resolved, resolveErr := resolveKeepHistory(khFlag, fullsendDir, nil) if resolveErr != nil { - printer.StepWarn(fmt.Sprintf("Warning: %v; defaulting to keep_history=true", resolveErr)) + printer.StepWarn(fmt.Sprintf("Warning: %v (keep_history is deprecated and unused; every result is posted as a new comment)", resolveErr)) } resolvedKeepHistory = resolved } @@ -100,7 +102,7 @@ The --result flag accepts a file path or "-" for stdin.`, cmd.Flags().StringVar(&result, "result", "-", "path to comment body file, or '-' for stdin") cmd.Flags().StringVar(&token, "token", "", "GitHub token (default: GH_TOKEN, GITHUB_TOKEN, or gh auth token)") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "print what would be posted without making API calls") - cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "append previous content as collapsed history blocks (set false to replace in-place)") + cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "deprecated: no effect (every result is posted as a new comment; sticky comments were removed)") cmd.Flags().StringVar(&fullsendDir, "fullsend-dir", os.Getenv("FULLSEND_DIR"), "path to .fullsend config directory (default: $FULLSEND_DIR; sources defaults from its config.yaml when flags are omitted)") _ = cmd.MarkFlagRequired("repo") _ = cmd.MarkFlagRequired("number") diff --git a/internal/cli/postcomment_test.go b/internal/cli/postcomment_test.go index 14f91d0b9e..e51057cc96 100644 --- a/internal/cli/postcomment_test.go +++ b/internal/cli/postcomment_test.go @@ -71,10 +71,16 @@ func TestPostCommentCmd_AcceptsGHToken(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sawAuth = r.Header.Get("Authorization") switch { - case r.URL.Path == "/user": - _ = json.NewEncoder(w).Encode(map[string]string{"login": "octocat"}) - case strings.Contains(r.URL.Path, "/issues/1/comments"): - _, _ = io.WriteString(w, "[]") + // A dry run makes no API call (nothing is edited in place + // anymore, so no identity needs resolving), so the token is + // observed on the comment it posts. + case r.Method == http.MethodPost && r.URL.Path == "/repos/owner/repo/issues/1/comments": + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 1, + "html_url": "https://github.com/owner/repo/issues/1#issuecomment-1", + "body": "comment body", + "user": map[string]string{"login": "octocat"}, + }) default: http.NotFound(w, r) } @@ -97,7 +103,6 @@ func TestPostCommentCmd_AcceptsGHToken(t *testing.T) { "--number", "1", "--marker", "", "--result", bodyFile, - "--dry-run", }) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) diff --git a/internal/cli/postreview.go b/internal/cli/postreview.go index 5525b26450..2a47fc3287 100644 --- a/internal/cli/postreview.go +++ b/internal/cli/postreview.go @@ -29,6 +29,14 @@ import ( const reviewMarker = "" +// reviewNoticeMarker marks stale-head and failure notices. It is +// deliberately distinct from reviewMarker: the prior-review fetchers +// (pre-fetch-prior-review.sh and the GitLab run-agent-job.sh) select the +// newest comment carrying reviewMarker as the previous review, so a +// notice posted with the review marker would be read as the prior +// review and hide the real review content the next re-review needs. +const reviewNoticeMarker = "" + // StaleHeadExitCode is the process exit code used when a review is // discarded because the PR HEAD moved after the agent reviewed it. // post-review.sh uses this to detect stale-head outcomes and @@ -84,19 +92,20 @@ func newPostReviewCmd() *cobra.Command { cmd := &cobra.Command{ Use: "post-review", - Short: "Post or update a sticky review comment on a PR/MR", - Long: `Posts review findings as a sticky issue comment on a pull request + Short: "Post a review comment on a PR/MR", + Long: `Posts review findings as an issue comment on a pull request or merge request, then submits a formal review with the disposition. -The sticky comment is the success criterion. If it is posted, the +The review comment is the success criterion. If it is posted, the command exits 0 even when the subsequent formal review submission fails; that failure is logged as a warning so a posted verdict is not reported as a workflow Failure. -On first run, creates a new comment with a hidden HTML marker. -On re-runs, finds the existing comment, collapses old content into -a
block, and edits in-place. Stale formal reviews by the -same user are minimized before submitting a new one. +Every run adds a new comment with a hidden HTML marker at the end of +the thread: nothing is edited in place and there are no collapsed +"Previous run" sections — the thread itself is the history. Stale +formal reviews by the same user are minimized before submitting a +new one. The --result flag accepts a file path containing a JSON review result (with action, body, and optionally head_sha fields), or reads from @@ -162,11 +171,13 @@ GITLAB_TOKEN for GitLab and GH_TOKEN / GITHUB_TOKEN for GitHub.`, // precedence, otherwise fall back to config.yaml via // --fullsend-dir (matching the pattern in issues post-comment). resolvedKeepHistory := keepHistory - if !cmd.Flags().Changed("keep-history") { + if cmd.Flags().Changed("keep-history") { + warnKeepHistoryDeprecated(cmd) + } else { var khFlag *bool // nil = not explicitly set resolved, resolveErr := resolveKeepHistory(khFlag, fullsendDir, nil) if resolveErr != nil { - printer.StepWarn(fmt.Sprintf("Warning: %v; defaulting to keep_history=true", resolveErr)) + printer.StepWarn(fmt.Sprintf("Warning: %v (keep_history is deprecated and unused; every result is posted as a new comment)", resolveErr)) } resolvedKeepHistory = resolved } @@ -189,7 +200,7 @@ GITLAB_TOKEN for GitLab and GH_TOKEN / GITHUB_TOKEN for GitHub.`, } } - // Failure action: post a failure notice as a sticky comment, + // Failure action: post a failure notice comment, // skip formal review. if strings.ToLower(parsed.Action) == "failure" { return postFailureNotice(cmd.Context(), client, owner, repoName, pr, parsed, cfg, printer) @@ -205,7 +216,7 @@ GITLAB_TOKEN for GitLab and GH_TOKEN / GITHUB_TOKEN for GitHub.`, cmd.Flags().StringVar(&token, "token", "", "forge token (default: $GH_TOKEN / $GITHUB_TOKEN for GitHub, $GITLAB_TOKEN for GitLab)") cmd.Flags().StringVar(&headSHA, "head-sha", "", "expected PR HEAD SHA (skips review if HEAD has moved)") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "print what would be posted without making API calls") - cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "append previous content as collapsed history blocks (set false to replace in-place)") + cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "deprecated: no effect (every result is posted as a new comment; sticky comments were removed)") cmd.Flags().StringVar(&fullsendDir, "fullsend-dir", os.Getenv("FULLSEND_DIR"), "path to .fullsend config directory (default: $FULLSEND_DIR; sources defaults from its config.yaml when flags are omitted)") cmd.Flags().StringVar(&forgeName, "forge", "", "forge backend: github (default) or gitlab") cmd.Flags().StringVar(&baseURL, "base-url", "", "forge instance URL (e.g. https://gitlab.example.com)") @@ -320,6 +331,11 @@ func (e *staleHeadError) ExitCode() int { return StaleHeadExitCode } // since the review was generated. Returns a *staleHeadError so the CLI // exits with StaleHeadExitCode, enabling post-review.sh to re-dispatch. func postStaleHeadNotice(ctx context.Context, client forge.Client, owner, repo string, pr int, reviewedSHA, currentSHA string, cfg sticky.Config, printer *ui.Printer) error { + // The notice carries its own marker, not the review marker, so the + // prior-review fetchers keep selecting the last real review instead + // of this notice (see reviewNoticeMarker). + cfg.Marker = reviewNoticeMarker + body := fmt.Sprintf(`## Review **Reason:** stale-head @@ -332,10 +348,15 @@ The review agent reviewed commit `+"`%s`"+` but the PR HEAD is now `+"`%s`"+`. T return &staleHeadError{reviewedSHA: reviewedSHA, currentSHA: currentSHA} } -// postFailureNotice posts a failure comment as a sticky comment. +// postFailureNotice posts a failure comment. func postFailureNotice(ctx context.Context, client forge.Client, owner, repo string, pr int, parsed ReviewResult, cfg sticky.Config, printer *ui.Printer) error { printer.StepStart("Review agent reported failure, posting notice") + // The notice carries its own marker, not the review marker, so the + // prior-review fetchers keep selecting the last real review instead + // of this notice (see reviewNoticeMarker). + cfg.Marker = reviewNoticeMarker + reason := parsed.Reason if reason == "" { reason = "unknown" @@ -361,8 +382,8 @@ This PR was NOT reviewed. Do not count this as an approval.`, reason) return nil } -// postReviewContent posts the sticky review comment, then attempts a -// formal PR/MR review. Once the sticky comment is on the PR, formal +// postReviewContent posts the review comment, then attempts a +// formal PR/MR review. Once the review comment is on the PR, formal // review submission is best-effort: a forge API failure must not turn // a posted verdict into a workflow Failure (#3548). func postReviewContent(ctx context.Context, client forge.Client, owner, repo string, pr int, parsed ReviewResult, cfg sticky.Config, dryRun bool, printer *ui.Printer) error { @@ -395,7 +416,7 @@ func postReviewContent(ctx context.Context, client forge.Client, owner, repo str formalReviewErr := submitFormalReviewWithDiffs(ctx, client, owner, repo, pr, parsed.Action, parsed.HeadSHA, commentURL, parsed.Findings, dryRun, printer, diffListing) if formalReviewErr != nil { - printer.StepWarn(fmt.Sprintf("Formal review submission failed (%v); sticky review comment was posted", formalReviewErr)) + printer.StepWarn(fmt.Sprintf("Formal review submission failed (%v); review comment was posted", formalReviewErr)) } else if !dryRun && diffHash != "" && strings.EqualFold(parsed.Action, "approve") { // Publish the deduplication marker only after the matching formal // approval succeeds. A request-changes/comment result or a failed @@ -488,12 +509,12 @@ func pullRequestDiffHashFromDiffs(diffs []forge.PullRequestFileDiff, err error) // The review body varies by event type to balance notification noise // against GitHub API requirements: // - APPROVE: empty body (avoids duplicate notification) -// - REQUEST_CHANGES: includes a link to the sticky comment (API +// - REQUEST_CHANGES: includes a link to the review comment (API // requires a non-empty body for this event); when inline comments // are attached, the body references them instead -// - COMMENT: skipped when no inline-eligible findings exist (sticky -// comment already covers it); when inline comments are present, a -// COMMENT review is submitted with a body linking to the sticky +// - COMMENT: skipped when no inline-eligible findings exist (the +// review comment already covers it); when inline comments are present, a +// COMMENT review is submitted with a body linking to the review // comment so findings appear on the relevant code lines func submitFormalReview(ctx context.Context, client forge.Client, owner, repo string, pr int, action, commitSHA, commentURL string, findings []ReviewFinding, dryRun bool, printer *ui.Printer) error { return submitFormalReviewWithDiffs(ctx, client, owner, repo, pr, action, commitSHA, commentURL, findings, dryRun, printer, nil) @@ -548,7 +569,7 @@ func submitFormalReviewWithDiffs(ctx context.Context, client forge.Client, owner // We filter inline comments here because the GitHub API cannot // accept review comments on lines outside the PR diff. The - // findings themselves remain in the sticky comment body and + // findings themselves remain in the review comment body and // continue to influence the review verdict. // // Findings whose file is in the PR diff but whose line falls @@ -580,9 +601,9 @@ func submitFormalReviewWithDiffs(ctx context.Context, client forge.Client, owner // relevant code lines. if event == "COMMENT" && len(inlineComments) == 0 { // There is no replacement formal review to succeed, so remove stale - // approvals after the sticky verdict has been prepared. + // approvals after the review comment has been prepared. dismissStaleApprovals(ctx, client, owner, repo, pr, user, priorReviews, printer) - printer.StepInfo("Skipping formal COMMENT review (sticky comment already updated)") + printer.StepInfo("Skipping formal COMMENT review (review comment already posted)") return nil } @@ -628,7 +649,7 @@ func submitFormalReviewWithDiffs(ctx context.Context, client forge.Client, owner // every failure path logs and returns so the caller's main review still // proceeds. On a 422 the comment bodies are retried inside a plain review // body — mirroring the main review's fallback — so the findings stay -// visible on the review itself rather than only in the sticky comment. +// visible on the review itself rather than only in the review comment. func postFileLevelComments(ctx context.Context, client forge.Client, owner, repo string, pr int, commitSHA string, comments []forge.ReviewComment, printer *ui.Printer) { err := client.CreatePullRequestReview(ctx, owner, repo, pr, "COMMENT", "", commitSHA, comments) if err == nil { @@ -643,7 +664,7 @@ func postFileLevelComments(ctx context.Context, client forge.Client, owner, repo fallbackBody := buildFallbackReviewBody("", comments) if retryErr := client.CreatePullRequestReview(ctx, owner, repo, pr, "COMMENT", fallbackBody, commitSHA, nil); retryErr != nil { logAPIErrorDetails(retryErr, printer) - printer.StepWarn(fmt.Sprintf("File-level comments failed (%v), findings remain in sticky comment", retryErr)) + printer.StepWarn(fmt.Sprintf("File-level comments failed (%v), findings remain in review comment", retryErr)) return } printer.StepDone("File-level comments posted in review body (comments omitted due to 422)") @@ -651,12 +672,12 @@ func postFileLevelComments(ctx context.Context, client forge.Client, owner, repo } logAPIErrorDetails(err, printer) - printer.StepWarn(fmt.Sprintf("File-level comments failed (%v), findings remain in sticky comment", err)) + printer.StepWarn(fmt.Sprintf("File-level comments failed (%v), findings remain in review comment", err)) } // findingsToReviewComments converts review findings with file and line // locations into inline review comments. Findings without a file path -// or line number are omitted — they remain in the sticky comment body. +// or line number are omitted — they remain in the review comment body. // // When diffHunks is non-nil, findings referencing files outside the PR // diff are omitted to avoid GitHub 422 errors. Findings whose file is diff --git a/internal/cli/postreview_test.go b/internal/cli/postreview_test.go index 730189bc88..9ec5147af1 100644 --- a/internal/cli/postreview_test.go +++ b/internal/cli/postreview_test.go @@ -178,6 +178,10 @@ func TestPostStaleHeadNotice(t *testing.T) { require.Len(t, comments, 1) assert.Contains(t, comments[0].Body, "stale-head") assert.Contains(t, comments[0].Body, "old_sha_123") + // The notice must not carry the review marker: prior-review fetchers + // select the newest review-marker comment as the previous review. + assert.Contains(t, comments[0].Body, reviewNoticeMarker) + assert.NotContains(t, comments[0].Body, reviewMarker) // Verify the error carries StaleHeadExitCode for post-review.sh. var she *staleHeadError @@ -205,6 +209,7 @@ func TestPostFailureNotice_WithBody(t *testing.T) { comments := fc.IssueComments["o/r/1"] require.Len(t, comments, 1) assert.Contains(t, comments[0].Body, "Custom failure message") + assert.Contains(t, comments[0].Body, reviewNoticeMarker) } func TestPostFailureNotice_WithoutBody(t *testing.T) { @@ -257,7 +262,7 @@ func TestPostReviewContent_FormalReviewFailureDoesNotFailCommand(t *testing.T) { assert.Contains(t, comments[0].Body, "Looks good") assert.Empty(t, fc.CreatedReviews) assert.Contains(t, buf.String(), "Formal review submission failed") - assert.Contains(t, buf.String(), "sticky review comment was posted") + assert.Contains(t, buf.String(), "review comment was posted") } func TestPostReviewContent_RequestChangesFormalReviewFailureDoesNotFailCommand(t *testing.T) { @@ -2578,5 +2583,5 @@ func TestPostFailureNotice_EscapesProjectionMarker(t *testing.T) { comments := fc.IssueComments["o/r/1"] require.Len(t, comments, 1) - assert.Equal(t, reviewMarker+"\n<!-- fullsend:review-findings-v2:eyJ9 -->\nFailed", comments[0].Body) + assert.Equal(t, reviewNoticeMarker+"\n<!-- fullsend:review-findings-v2:eyJ9 -->\nFailed", comments[0].Body) } diff --git a/internal/config/config.go b/internal/config/config.go index f612dd939c..1765464ecf 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1138,11 +1138,10 @@ type perRepoConfig struct { KillSwitch *bool `yaml:"kill_switch,omitempty"` Runtime string `yaml:"runtime,omitempty"` - // KeepHistory controls whether sticky comment updates append the - // previous body as a collapsed "Previous run"
block. When - // nil (omitted), falls through to parent (code default true — - // history appended). When explicitly false, updates replace the body - // in-place with no history. + // KeepHistory is deprecated and has no effect: sticky comments were + // removed (#9334); every result is a new comment. Kept until a + // cleanup removes the field. When nil (omitted), falls through to + // parent (code default true). KeepHistory *bool `yaml:"keep_history,omitempty"` Roles []string `yaml:"roles,omitempty"` diff --git a/internal/config/defaults.go b/internal/config/defaults.go index bf031116f2..d478215f2c 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -98,9 +98,10 @@ func (d *perRepoDefaults) ConfigInferenceWIFAudience() string { return "" } // impersonate (empty — direct federated identity, no impersonation). func (d *perRepoDefaults) ConfigInferenceServiceAccount() string { return "" } -// ConfigKeepHistory returns the default keep-history state (true — -// sticky comment updates append previous content as "Previous run" -// blocks, preserving the pre-existing behavior). +// ConfigKeepHistory returns the default keep-history state (true). +// Deprecated: the setting has no effect — sticky comments were removed +// (#9334); every result is a new comment. Kept until a cleanup removes +// the field. func (d *perRepoDefaults) ConfigKeepHistory() bool { return true } // ConfigInferenceOpenAI returns the default OpenAI WIF identifiers (none — diff --git a/internal/config/interfaces.go b/internal/config/interfaces.go index 32ff2bbf77..573fc08aab 100644 --- a/internal/config/interfaces.go +++ b/internal/config/interfaces.go @@ -465,11 +465,11 @@ func (c *perRepoConfig) ConfigForge() string { return "" } -// ConfigKeepHistory reports whether sticky comment updates should -// append previous content as a collapsed "Previous run" block. -// KeepHistory is a *bool: nil falls through to parent, non-nil -// (including explicit false) is the local decision. Code default -// is true (history appended). +// ConfigKeepHistory reports the keep_history setting, which is deprecated +// and has no effect on posting: sticky comments were removed (#9334); +// every result is a new comment. The field stays until a cleanup removes +// it. KeepHistory is a *bool: nil falls through to parent, non-nil is the +// local decision. Code default is true. func (c *perRepoConfig) ConfigKeepHistory() bool { if c.KeepHistory != nil { return *c.KeepHistory @@ -697,9 +697,9 @@ func (c *perRepoConfig) SetRoles(roles []string) { c.Roles = roles } // SetRuntime replaces the configured agent runtime. func (c *perRepoConfig) SetRuntime(runtime string) { c.Runtime = runtime } -// SetKeepHistory sets whether sticky comment updates append history. -// Stores a *bool so that an explicit false is distinguishable from -// unset (nil) across layers. +// SetKeepHistory stores the deprecated keep_history setting, which has +// no effect on posting (see ConfigKeepHistory). Stores a *bool so that +// an explicit false is distinguishable from unset (nil) across layers. func (c *perRepoConfig) SetKeepHistory(v bool) { c.KeepHistory = &v } // SetMintURL sets the token mint URL. diff --git a/internal/forge/gitlab/mr.go b/internal/forge/gitlab/mr.go index 5e05db4445..4c949ebb8a 100644 --- a/internal/forge/gitlab/mr.go +++ b/internal/forge/gitlab/mr.go @@ -458,7 +458,7 @@ func (c *LiveClient) UpdatePullRequestBranch(ctx context.Context, owner, repo st // verdict. A post-hoc 401 handler remains as a safety net for edge // cases (e.g., a future per-role PAT where the pre-call identity // check doesn't apply but project settings still block approval). -// The sticky review comment remains the authoritative record either +// The review comment remains the authoritative record either // way. // - REQUEST_CHANGES or COMMENT: POST a note with the review body, // plus inline comments (see below). diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh index bdd0707e3d..127b84475e 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh @@ -325,6 +325,31 @@ run_test "html-comment-sha-with-history" \ "5429609dce9a122a2721107edb51551c8d73cc6f" \ 0 +# 14. Several marked comments by the same review bot — the newest wins. +# Every re-review run appends its own comment now that sticky comments +# are gone (#9334), so multiple matches are the norm; a regression to +# first-match would silently degrade every re-review to considering +# the oldest review. +BODY_OLDER_REVIEW=" +## Review + +**Head SHA:** aaaa111 + +Older review content." + +BODY_NEWER_REVIEW=" +## Review + +**Head SHA:** bbbb222 + +Newer review content." + +run_test "multiple-marked-comments-newest-wins" \ + "$(make_comment_json "${BODY_OLDER_REVIEW}") +$(make_comment_json "${BODY_NEWER_REVIEW}")" \ + "bbbb222" \ + 0 + # --- Summary --- echo "" diff --git a/internal/statuscomment/statuscomment.go b/internal/statuscomment/statuscomment.go index c1d5ba8bc7..bc57fd1a3e 100644 --- a/internal/statuscomment/statuscomment.go +++ b/internal/statuscomment/statuscomment.go @@ -1,8 +1,6 @@ // Package statuscomment posts agent start/completion status comments // on issues and pull requests via the tracker abstraction. // -// Unlike internal/sticky, which manages persistent bot comments that -// accumulate history across multiple runs (e.g. review output), // statuscomment manages transient lifecycle markers: a start comment // created when the agent begins, then updated or replaced on // completion (including cancellation). GitHub and GitLab use invisible HTML diff --git a/internal/sticky/markers_test.go b/internal/sticky/markers_test.go index 0a08e81183..9fa086b0c1 100644 --- a/internal/sticky/markers_test.go +++ b/internal/sticky/markers_test.go @@ -18,12 +18,12 @@ import ( // a marker (case-insensitive, any whitespace). var liveMarkerRe = regexp.MustCompile(`(?i)"), - "run %s: agent marker text is escaped once per run, not re-escaped", run) + assert.Equal(t, 1, strings.Count(body, "<!-- fullsend:agent-status:999 -->"), + "run %s: agent marker text is escaped once, not re-escaped", run) assert.NotContains(t, body, "&lt;", "run %s: pre-escaped text must be unchanged", run) assert.NotContains(t, body, "<<", "run %s: escaping must not stack", run) assert.Contains(t, body, "Run "+run+" ") } - // The comment cannot be confused with a sibling's sticky comment. + // The comments cannot be confused with a sibling's comments. comments := client.IssueComments["o/r/1"] assert.Nil(t, FindMarkedComment(comments, "", "bot")) assert.Nil(t, FindMarkedComment(comments, "", "bot")) @@ -202,9 +202,9 @@ func TestNeutralizeBody_TrustedLeadingLines(t *testing.T) { assert.Equal(t, trustedLine+"\n"+second+"\n\nReview <!-- fullsend:agent-status:1 -->", neutralizeBody(body, cfg)) } -// A trusted leading line stays live in the current body across updates, -// while each earlier copy is escaped as it moves into history. -func TestPost_TrustedLeadingLine_AcrossUpdates(t *testing.T) { +// A trusted leading line stays live in every posted comment; nothing is +// folded into history, so no earlier copy is ever re-escaped. +func TestPost_TrustedLeadingLine_AcrossRuns(t *testing.T) { client := forge.NewFakeClient() client.AuthenticatedUser = "bot" printer := ui.New(io.Discard) @@ -216,13 +216,13 @@ func TestPost_TrustedLeadingLine_AcrossUpdates(t *testing.T) { require.NoError(t, err) comments := client.IssueComments["o/r/1"] - require.Len(t, comments, 1) - got := comments[0].Body + require.Len(t, comments, i) + got := comments[i-1].Body assert.True(t, strings.HasPrefix(got, cfg.Marker+"\n"+trustedLine+"\n\nReview <!-- fullsend:triage-agent -->"), "run %d: trusted line follows the runner marker unescaped", i) assert.Len(t, liveMarkerRe.FindAllString(got, -1), 2, "run %d: only the runner marker and trusted line are live", i) - assert.Equal(t, i-1, strings.Count(got, "<!-- fullsend:review-findings-v2:"), - "run %d: earlier trusted lines are escaped in history", i) + assert.Zero(t, strings.Count(got, "<!-- fullsend:review-findings-v2:"), + "run %d: the trusted line is never escaped", i) } } diff --git a/internal/sticky/sticky.go b/internal/sticky/sticky.go index 067288b3ca..508fac8530 100644 --- a/internal/sticky/sticky.go +++ b/internal/sticky/sticky.go @@ -6,7 +6,6 @@ import ( "regexp" "strconv" "strings" - "time" "unicode/utf8" "github.com/fullsend-ai/fullsend/internal/forge" @@ -14,15 +13,23 @@ import ( "github.com/fullsend-ai/fullsend/internal/ui" ) -const defaultMaxSize = 65000 +// DefaultMaxSize is the default maximum comment body size in bytes. +const DefaultMaxSize = 65000 -// Config controls how a sticky comment is identified and managed. +// Config controls how an agent result comment is marked and posted. type Config struct { Marker string // hidden HTML comment, e.g. "" FooterMarker string // optional footer delimiter, stripped before collapsing history MaxSize int // max comment body size (default 65000) DryRun bool - KeepHistory bool // when false, updates replace the body in-place with no "Previous run" history + + // KeepHistory is deprecated and has no effect on posting: sticky + // comments were removed (#9334), so every result is a new comment and + // nothing is folded into "Previous run" blocks. It is still read by + // BuildUpdatedBody, which no posting path calls anymore; the flag and + // config field that set it stay accepted so existing callers keep + // working until a cleanup removes them. + KeepHistory bool // TrustedLeadingLine, when set, matches a marker line that the trusted // caller places at the start of the body. Matching leading lines are @@ -38,20 +45,16 @@ func (c Config) maxSize() int { if c.MaxSize > 0 { return c.MaxSize } - return defaultMaxSize + return DefaultMaxSize } -// Post implements the sticky comment lifecycle: find an existing comment -// bearing the marker, collapse old content into history, and create or -// update in-place. Returns the HTML URL of the comment (empty on dry run). -// -// It never edits a comment it cannot verify as its own: an existing -// comment matches only when it carries the marker and its author is -// exactly the login this client posts as, so a comment anyone could plant -// with the same marker is ignored. When that login cannot be resolved -// (after a short retry) it returns an error and posts nothing — not even -// on dry run, since dry run should not claim an edit would occur when none -// safely could. +// Post publishes an agent result as a new comment at the end of the +// thread and returns the HTML URL of the created comment (empty on dry +// run). It never edits an existing comment: sticky comments were removed +// (#9334), so every run appends its own comment and the thread itself is +// the history. The marker is still prepended so other steps can find this +// agent's comments; readers looking for the newest result find it at the +// bottom, where new activity is expected. func Post(ctx context.Context, client forge.Client, owner, repo string, number int, body string, cfg Config, printer *ui.Printer) (string, error) { if strings.TrimSpace(body) == "" { return "", fmt.Errorf("comment body is empty") @@ -60,44 +63,16 @@ func Post(ctx context.Context, client forge.Client, owner, repo string, number i return "", fmt.Errorf("marker is empty") } - // Without a verified identity nothing is posted at all: editing would - // trust an unverified comment, and creating a new one would orphan the - // earlier comment, whose stale content later runs would never update. - botUser, err := resolveBotUser(ctx, client) - if err != nil { - return "", unverifiedBotUserError(err) - } - - comments, err := client.ListIssueComments(ctx, owner, repo, number) - if err != nil { - return "", fmt.Errorf("listing comments: %w", err) - } - - existing := FindMarkedComment(comments, cfg.Marker, botUser) // Escape marker syntax in the agent-written body before the runner's // own marker is prepended, so the runner's marker is the only live one // (apart from a validated trusted leading line, see neutralizeBody). markedBody := cfg.Marker + "\n" + neutralizeBody(body, cfg) + // The create path has no history trimming (the update path that used + // to cap the assembled body is gone), so cap the body before + // creating: an oversized single result would otherwise fail the post. + markedBody = TruncateBody(markedBody, cfg.maxSize()) - if existing != nil { - printer.StepStart("Found existing comment, updating in-place") - - newBody := BuildUpdatedBody(existing.Body, markedBody, cfg) - - if cfg.DryRun { - printer.StepInfo("Dry run — would update comment " + strconv.Itoa(existing.ID)) - printer.StepInfo("Body length: " + strconv.Itoa(len(newBody))) - return "", nil - } - - if err := client.UpdateIssueComment(ctx, owner, repo, existing.ID, newBody); err != nil { - return "", fmt.Errorf("updating comment: %w", err) - } - printer.StepDone("Comment updated") - return existing.HTMLURL, nil - } - - printer.StepStart("No existing comment found, creating new one") + printer.StepStart("Posting comment") if cfg.DryRun { printer.StepInfo("Dry run — would create new comment") @@ -141,9 +116,8 @@ func neutralizeBody(body string, cfg Config) string { // FindMarkedComment returns the first comment whose body contains the given // marker string and whose author is exactly botUser, or nil if none is -// found. An empty botUser matches nothing: callers pass it only when -// identity resolution failed, and matching on the marker alone would let -// anyone's comment be treated as the bot's own and edited in-place. +// found. An empty botUser matches nothing: matching on the marker alone +// would let anyone's comment be treated as the bot's own. func FindMarkedComment(comments []forge.IssueComment, marker, botUser string) *forge.IssueComment { if botUser == "" { return nil @@ -159,46 +133,6 @@ func FindMarkedComment(comments []forge.IssueComment, marker, botUser string) *f return nil } -// botUserLookupBackoff is the wait before each retry of the bot identity -// lookup; its length is the number of retries. Tests shorten it. -var botUserLookupBackoff = []time.Duration{500 * time.Millisecond, time.Second} - -// resolveBotUser returns the exact login client posts as, retrying a failed -// or empty lookup per botUserLookupBackoff so a transient error does not -// degrade marker spoofing protection. This mirrors resolveTrackerSelf in -// internal/cli/issues.go, but internal/cli imports this package, so the -// retry logic is kept local here rather than shared, to avoid an import -// cycle. -func resolveBotUser(ctx context.Context, client forge.Client) (string, error) { - var lastErr error - for attempt := 0; ; attempt++ { - botUser, err := client.GetAuthenticatedUser(ctx) - if err == nil && botUser == "" { - err = fmt.Errorf("the authenticated user is empty") - } - if err == nil { - return botUser, nil - } - lastErr = err - if attempt >= len(botUserLookupBackoff) { - return "", fmt.Errorf("after %d attempts: %w", attempt+1, lastErr) - } - select { - case <-ctx.Done(): - return "", fmt.Errorf("%w (last lookup error: %v)", ctx.Err(), lastErr) - case <-time.After(botUserLookupBackoff[attempt]): - } - } -} - -// unverifiedBotUserError reports that the posting identity could not be -// resolved, so nothing was posted or edited. -func unverifiedBotUserError(err error) error { - return fmt.Errorf("cannot verify which identity this posts as, so no comment was posted or edited; "+ - "rerun if the failure was transient, otherwise check that the token can read its own identity "+ - "(the authenticated user): %w", err) -} - // History blocks are wrapped with sentinel comments so extraction is safe // even when review content contains nested
tags. const ( @@ -219,6 +153,10 @@ var legacyDetailsRe = regexp.MustCompile(`(?s)
\s*Previous [^<] // When cfg.KeepHistory is false, the old body is discarded entirely and // the new body is returned with footer re-appended (no "Previous run" // blocks). +// +// Deprecated: no posting path calls this anymore — sticky comments were +// removed (#9334) and every result is posted as a new comment. It is kept +// only until a cleanup deletes the history-folding machinery. func BuildUpdatedBody(oldBody, newBody string, cfg Config) string { // When history is disabled, replace the body entirely. We still // need to preserve the footer from the old body if configured. @@ -332,15 +270,21 @@ func BuildUpdatedBody(oldBody, newBody string, cfg Config) string { return combined } -// TruncateBody trims body to fit within maxSize, keeping the current -// content at the top and trimming history from the end. The truncation -// point is aligned to a valid UTF-8 boundary. +// TruncateBody trims body to fit within maxSize, keeping the content at +// the top and cutting the end. The truncation point is aligned to a valid +// UTF-8 boundary. func TruncateBody(body string, maxSize int) string { if len(body) <= maxSize { return body } - truncationMsg := "\n\n---\n*Previous history truncated due to comment size limits.*" + // No thematic break ("---") before the note: the Jira door round-trips + // the body through MarkdownToADF/ADFToMarkdown, and that renders a + // thematic break with a following blank line — one byte longer than + // the markdown that was posted. Without the break the round trip is + // byte-stable, so a body truncated to the Jira limit stays within it + // as the stored comment's markdown rendering too. + truncationMsg := "\n\n*Comment truncated due to comment size limits.*" budget := maxSize - len(truncationMsg) if budget < 0 { budget = 0 diff --git a/internal/sticky/sticky_test.go b/internal/sticky/sticky_test.go index 6475ad6cf6..c66fe927fb 100644 --- a/internal/sticky/sticky_test.go +++ b/internal/sticky/sticky_test.go @@ -2,11 +2,9 @@ package sticky import ( "context" - "errors" "io" "strings" "testing" - "time" "unicode/utf8" "github.com/stretchr/testify/assert" @@ -225,13 +223,13 @@ func TestBuildUpdatedBody_NoHistory_MultipleRuns(t *testing.T) { func TestTruncateBody_UnderLimit(t *testing.T) { body := "short body" - assert.Equal(t, body, TruncateBody(body, defaultMaxSize)) + assert.Equal(t, body, TruncateBody(body, DefaultMaxSize)) } func TestTruncateBody_OverLimit(t *testing.T) { - body := strings.Repeat("a", defaultMaxSize+1000) - result := TruncateBody(body, defaultMaxSize) - assert.LessOrEqual(t, len(result), defaultMaxSize+100) + body := strings.Repeat("a", DefaultMaxSize+1000) + result := TruncateBody(body, DefaultMaxSize) + assert.LessOrEqual(t, len(result), DefaultMaxSize+100) assert.Contains(t, result, "truncated") } @@ -258,7 +256,7 @@ func TestTruncateBody_RuneSafe(t *testing.T) { // at a naive byte boundary. prefix := strings.Repeat("a", 100) multibyte := strings.Repeat("é", 50) // é is 2 bytes in UTF-8 - body := prefix + multibyte + strings.Repeat("b", defaultMaxSize) + body := prefix + multibyte + strings.Repeat("b", DefaultMaxSize) result := TruncateBody(body, 200) @@ -283,24 +281,24 @@ func TestPost_CreateNew(t *testing.T) { assert.Contains(t, comments[0].Body, "Body.") } -func TestPost_UpdateExisting(t *testing.T) { +func TestPost_TruncatesOversizedBodyBeforeCreate(t *testing.T) { + // Every run creates a new comment now (#9334), and the create path + // has no history trimming, so a single result over the size limit + // must be truncated before it is created instead of failing the post + // at the forge's own limit. client := forge.NewFakeClient() client.AuthenticatedUser = "bot" - client.IssueComments = map[string][]forge.IssueComment{ - "o/r/1": {{ID: 100, HTMLURL: "https://github.com/o/r/issues/1#issuecomment-100", Body: "\nOld.", Author: "bot"}}, - } printer := ui.New(io.Discard) - cfg := Config{Marker: "", KeepHistory: true} - commentURL, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer) + cfg := Config{Marker: "", MaxSize: 500} + commentURL, err := Post(context.Background(), client, "o", "r", 1, strings.Repeat("a", 800), cfg, printer) require.NoError(t, err) - assert.Equal(t, "https://github.com/o/r/issues/1#issuecomment-100", commentURL) + assert.Contains(t, commentURL, "issuecomment-") - require.Len(t, client.UpdatedComments, 1) - assert.Equal(t, 100, client.UpdatedComments[0].CommentID) - assert.Contains(t, client.UpdatedComments[0].Body, "New.") - assert.Contains(t, client.UpdatedComments[0].Body, "
") - assert.Contains(t, client.UpdatedComments[0].Body, "Old.") + comments := client.IssueComments["o/r/1"] + require.Len(t, comments, 1) + assert.LessOrEqual(t, len(comments[0].Body), 500, "the created body must fit the configured size") + assert.Contains(t, comments[0].Body, "") } func TestPost_DryRun(t *testing.T) { @@ -347,126 +345,6 @@ func TestPost_EmptyMarker(t *testing.T) { assert.Contains(t, err.Error(), "marker") } -func TestPost_UpdateExisting_EmptyHTMLURL(t *testing.T) { - client := forge.NewFakeClient() - client.AuthenticatedUser = "bot" - client.IssueComments = map[string][]forge.IssueComment{ - "o/r/1": {{ID: 100, Body: "\nOld.", Author: "bot"}}, - } - printer := ui.New(io.Discard) - - cfg := Config{Marker: "", KeepHistory: true} - commentURL, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer) - require.NoError(t, err) - assert.Empty(t, commentURL, "should return empty URL when existing comment has no HTMLURL") - - require.Len(t, client.UpdatedComments, 1) - assert.Contains(t, client.UpdatedComments[0].Body, "New.") -} - -func TestPost_DryRunExisting(t *testing.T) { - client := forge.NewFakeClient() - client.AuthenticatedUser = "bot" - client.IssueComments = map[string][]forge.IssueComment{ - "o/r/1": {{ID: 100, Body: "\nOld.", Author: "bot"}}, - } - printer := ui.New(io.Discard) - - cfg := Config{Marker: "", DryRun: true} - commentURL, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer) - require.NoError(t, err) - assert.Empty(t, commentURL) - - assert.Empty(t, client.UpdatedComments) -} - -// fastBotUserLookup shortens the identity-lookup retry backoff for a test. -func fastBotUserLookup(t *testing.T) { - t.Helper() - saved := botUserLookupBackoff - botUserLookupBackoff = []time.Duration{time.Millisecond, time.Millisecond} - t.Cleanup(func() { botUserLookupBackoff = saved }) -} - -// flakyAuthClient fails GetAuthenticatedUser failures times, then defers to -// the wrapped forge.Client. -type flakyAuthClient struct { - forge.Client - failures int - calls int -} - -func (c *flakyAuthClient) GetAuthenticatedUser(ctx context.Context) (string, error) { - c.calls++ - if c.calls <= c.failures { - return "", errors.New("502 Bad Gateway") - } - return c.Client.GetAuthenticatedUser(ctx) -} - -func TestPost_PersistentIdentityFailure_ErrorsAndPostsNothing(t *testing.T) { - fastBotUserLookup(t) - fc := forge.NewFakeClient() - fc.AuthenticatedUser = "bot" - fc.IssueComments = map[string][]forge.IssueComment{ - "o/r/1": {{ID: 100, Body: "\nOld.", Author: "bot"}}, - } - client := &flakyAuthClient{Client: fc, failures: 1000} - printer := ui.New(io.Discard) - - cfg := Config{Marker: "", KeepHistory: true} - _, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer) - require.Error(t, err) - assert.Contains(t, err.Error(), "cannot verify which identity") - assert.Contains(t, err.Error(), "502 Bad Gateway", "the error must name the cause") - assert.Equal(t, len(botUserLookupBackoff)+1, client.calls) - - assert.Empty(t, fc.UpdatedComments, "no comment may be edited") - require.Len(t, fc.IssueComments["o/r/1"], 1, "no comment may be created") -} - -func TestPost_TransientIdentityFailure_RetriesThenEdits(t *testing.T) { - fastBotUserLookup(t) - fc := forge.NewFakeClient() - fc.AuthenticatedUser = "bot" - fc.IssueComments = map[string][]forge.IssueComment{ - "o/r/1": {{ID: 100, Body: "\nOld.", Author: "bot"}}, - } - client := &flakyAuthClient{Client: fc, failures: len(botUserLookupBackoff)} - printer := ui.New(io.Discard) - - cfg := Config{Marker: "", KeepHistory: true} - _, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer) - require.NoError(t, err) - assert.Equal(t, len(botUserLookupBackoff)+1, client.calls, "every retry is used before success") - - require.Len(t, fc.UpdatedComments, 1) - assert.Equal(t, 100, fc.UpdatedComments[0].CommentID) - assert.Contains(t, fc.UpdatedComments[0].Body, "New.") -} - -func TestPost_IgnoresPlantedMarker_EditsOnlyOwnComment(t *testing.T) { - client := forge.NewFakeClient() - client.AuthenticatedUser = "bot" - client.IssueComments = map[string][]forge.IssueComment{ - "o/r/1": { - {ID: 100, Body: "\nplanted by attacker", Author: "attacker"}, - {ID: 101, Body: "\nOld.", Author: "bot"}, - }, - } - printer := ui.New(io.Discard) - - cfg := Config{Marker: "", KeepHistory: true} - _, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer) - require.NoError(t, err) - - require.Len(t, client.UpdatedComments, 1) - assert.Equal(t, 101, client.UpdatedComments[0].CommentID, "only the bot's own comment may be edited") - - comments := client.IssueComments["o/r/1"] - assert.NotContains(t, comments[0].Body, "New.", "the planted comment must be left untouched") -} - func TestPost_OnlyPlantedMarker_CreatesNewCommentWithoutTouchingPlanted(t *testing.T) { client := forge.NewFakeClient() client.AuthenticatedUser = "bot" @@ -486,19 +364,3 @@ func TestPost_OnlyPlantedMarker_CreatesNewCommentWithoutTouchingPlanted(t *testi assert.Contains(t, comments[1].Body, "New.") assert.Empty(t, client.UpdatedComments) } - -func TestPost_DryRun_UnresolvedIdentity_Errors(t *testing.T) { - fastBotUserLookup(t) - client := forge.NewFakeClient() - client.IssueComments = map[string][]forge.IssueComment{ - "o/r/1": {{ID: 100, Body: "\nOld.", Author: "bot"}}, - } - printer := ui.New(io.Discard) - - cfg := Config{Marker: "", DryRun: true} - commentURL, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer) - require.Error(t, err, "dry run must not imply an edit would occur when identity is unresolved") - assert.Contains(t, err.Error(), "cannot verify which identity") - assert.Empty(t, commentURL) - assert.Empty(t, client.UpdatedComments) -} diff --git a/internal/tracker/jira_client.go b/internal/tracker/jira_client.go index 156e1b4d9b..8af7497a4c 100644 --- a/internal/tracker/jira_client.go +++ b/internal/tracker/jira_client.go @@ -363,8 +363,6 @@ func (c *JiraClient) CreateCommentWithMarker(ctx context.Context, project string // It only matches a comment that carries no fullsend property and whose // body opens with the marker, the layout legacy comments were written in, // so another comment that quotes the marker is never picked. -// This allows transparent migration: the first update to a legacy -// comment will set the property and strip the marker from the body. func (c *JiraClient) FindCommentByMarkerProperty(comments []jira.Comment, marker string) *jira.Comment { // Primary: match by entity property. for i := range comments { @@ -424,38 +422,6 @@ func hasLegacyMarker(md, marker string) bool { return marker != "" && strings.HasPrefix(md, marker) } -// MigrateAndUpdateComment updates the body of comment, the sticky -// comment FindCommentByMarkerProperty matched, and ensures the sticky -// marker is stored as a comment entity property. -// -// A comment that already carries a property exactly matching marker is -// updated without rewriting the property: the write would be redundant, -// and a Jira rejection of it would otherwise block the body update. A -// comment found via the legacy body-text path has the property set -// first, transparently migrating it to the property-based scheme. -// -// The body written to Jira has the marker stripped (unlike -// GitHub/GitLab where the marker is an invisible HTML comment). The -// caller should pass the body without the marker prefix. -func (c *JiraClient) MigrateAndUpdateComment(ctx context.Context, project string, number int, comment jira.Comment, body Body, marker string) error { - key := issueKey(project, number) - if !hasStickyMarkerProperty(comment, marker) { - // Property-before-body ordering is intentional: if the property - // write succeeds but the body update fails, the next run will - // still find the comment via its property and can retry. The - // reverse order risks losing the marker from both the body - // (which was just stripped) and the property (which was never - // set). - if err := c.jira.SetCommentProperty(ctx, key, comment.ID, stickyPropertyKey, stickyMarkerProperty{Marker: marker}); err != nil { - return fmt.Errorf("setting sticky marker property on comment %s of %s: %w", comment.ID, key, err) - } - } - if err := c.jira.UpdateComment(ctx, key, comment.ID, string(body)); err != nil { - return wrapNotFound(err) - } - return nil -} - // UpdateComment implements Client. Unlike GitHub/GitLab, Jira's // update-comment endpoint needs the issue key, which is why number is // part of the signature here. diff --git a/internal/tracker/jira_client_test.go b/internal/tracker/jira_client_test.go index c1f718b7e0..139e89eb72 100644 --- a/internal/tracker/jira_client_test.go +++ b/internal/tracker/jira_client_test.go @@ -721,207 +721,6 @@ func TestJiraClient_FindStatusComment_IgnoresQuotedMarker(t *testing.T) { } } -// listedComment returns the comment with id as ListJiraComments reports -// it, properties included, failing the test if it is absent. -func listedComment(t *testing.T, c *JiraClient, id string) jira.Comment { - t.Helper() - comments, err := c.ListJiraComments(context.Background(), "PROJ", 42) - if err != nil { - t.Fatalf("ListJiraComments: %v", err) - } - for _, jc := range comments { - if jc.ID == id { - return jc - } - } - t.Fatalf("comment %s not found", id) - return jira.Comment{} -} - -func TestJiraClient_MigrateAndUpdateComment(t *testing.T) { - fc := &FakeJiraClient{} - c := newTestJiraClient(t, fc, "https://acme.atlassian.net") - ctx := context.Background() - marker := "" - - // Create a legacy comment: marker in body, no property. - legacyBody := marker + "\nlegacy content" - _, err := fc.CreateComment(ctx, "PROJ-42", legacyBody) - if err != nil { - t.Fatalf("CreateComment: %v", err) - } - - // Migrate: update body and set property. - err = c.MigrateAndUpdateComment(ctx, "PROJ", 42, listedComment(t, c, "1"), "migrated content", marker) - if err != nil { - t.Fatalf("MigrateAndUpdateComment: %v", err) - } - - // Verify body was updated. - if fc.UpdatedBody != "migrated content" { - t.Errorf("UpdatedBody = %q, want %q", fc.UpdatedBody, "migrated content") - } - if fc.PropertyWrites != 1 { - t.Errorf("PropertyWrites = %d, want 1 for a legacy migration", fc.PropertyWrites) - } - - // Verify property was set. - propKey := "PROJ-42/1" - props, ok := fc.CommentProperties[propKey] - if !ok { - t.Fatal("expected comment properties to be set after migration") - } - var stored stickyMarkerProperty - if err := json.Unmarshal(props[stickyPropertyKey], &stored); err != nil { - t.Fatalf("unmarshal property value: %v", err) - } - if stored.Marker != marker { - t.Errorf("stored marker = %q, want %q", stored.Marker, marker) - } -} - -// A comment already carrying an exactly matching marker property is -// updated without any property write, so a Jira rejection of property -// writes cannot block the body update. -func TestJiraClient_MigrateAndUpdateComment_ExactPropertySkipsPropertyWrite(t *testing.T) { - fc := &FakeJiraClient{} - c := newTestJiraClient(t, fc, "https://acme.atlassian.net") - ctx := context.Background() - marker := "" - - created, err := c.CreateCommentWithMarker(ctx, "PROJ", 42, "first run", marker) - if err != nil { - t.Fatalf("CreateCommentWithMarker: %v", err) - } - fc.PropertyError = errors.New("403 forbidden") - - if err := c.MigrateAndUpdateComment(ctx, "PROJ", 42, listedComment(t, c, created.ID), "second run", marker); err != nil { - t.Fatalf("MigrateAndUpdateComment: %v", err) - } - if fc.PropertyWrites != 0 { - t.Errorf("PropertyWrites = %d, want 0 for an exact property match", fc.PropertyWrites) - } - if fc.UpdatedCommentID != created.ID || fc.UpdatedBody != "second run" { - t.Errorf("UpdateComment(%q, %q), want (%q, %q)", fc.UpdatedCommentID, fc.UpdatedBody, created.ID, "second run") - } -} - -// Only a decodable property whose marker equals the requested marker -// counts as an exact match; anything else is (re)written before the body. -func TestJiraClient_MigrateAndUpdateComment_InexactPropertyIsWritten(t *testing.T) { - marker := "" - for _, tc := range []struct { - name string - value string - }{ - {"malformed value", `not json`}, - {"different marker", `{"marker":""}`}, - {"key without marker", `{}`}, - {"wrong value shape", `"` + marker + `"`}, - } { - t.Run(tc.name, func(t *testing.T) { - fc := &FakeJiraClient{ - CommentProperties: map[string]map[string]json.RawMessage{ - "PROJ-42/1": {stickyPropertyKey: json.RawMessage(tc.value)}, - }, - } - c := newTestJiraClient(t, fc, "https://acme.atlassian.net") - ctx := context.Background() - if _, err := fc.CreateComment(ctx, "PROJ-42", "content"); err != nil { - t.Fatalf("CreateComment: %v", err) - } - comment := listedComment(t, c, "1") - if hasStickyMarkerProperty(comment, marker) { - t.Fatalf("hasStickyMarkerProperty(%s) = true, want false", tc.value) - } - - if err := c.MigrateAndUpdateComment(ctx, "PROJ", 42, comment, "updated", marker); err != nil { - t.Fatalf("MigrateAndUpdateComment: %v", err) - } - if fc.PropertyWrites != 1 { - t.Errorf("PropertyWrites = %d, want 1", fc.PropertyWrites) - } - if !hasStickyMarkerProperty(listedComment(t, c, "1"), marker) { - t.Error("property should hold the requested marker after the update") - } - }) - } -} - -func TestJiraClient_MigrateAndUpdateComment_SetPropertyError(t *testing.T) { - fc := &FakeJiraClient{} - c := newTestJiraClient(t, fc, "https://acme.atlassian.net") - ctx := context.Background() - marker := "" - - // Create a legacy comment to migrate. - _, err := fc.CreateComment(ctx, "PROJ-42", marker+"\nlegacy content") - if err != nil { - t.Fatalf("CreateComment: %v", err) - } - - // Simulate a property write failure. - fc.PropertyError = errors.New("403 forbidden") - - err = c.MigrateAndUpdateComment(ctx, "PROJ", 42, listedComment(t, c, "1"), "updated", marker) - if err == nil { - t.Fatal("expected error from MigrateAndUpdateComment when SetCommentProperty fails") - } - if !errors.Is(err, fc.PropertyError) { - t.Errorf("error should wrap PropertyError, got: %v", err) - } - - // The body must be untouched, so the legacy marker still identifies - // the comment on the next run. - if fc.UpdatedCommentID != "" { - t.Errorf("UpdateComment called for comment %q after the property write failed", fc.UpdatedCommentID) - } - comments, err := c.ListJiraComments(ctx, "PROJ", 42) - if err != nil { - t.Fatalf("ListJiraComments: %v", err) - } - if found := c.FindCommentByMarkerProperty(comments, marker); found == nil || found.ID != "1" { - t.Errorf("FindCommentByMarkerProperty = %+v, want legacy comment 1", found) - } -} - -func TestJiraClient_MigrateAndUpdateComment_UpdateCommentError(t *testing.T) { - fc := &FakeJiraClient{} - c := newTestJiraClient(t, fc, "https://acme.atlassian.net") - ctx := context.Background() - marker := "" - - // Create a legacy comment to migrate. - _, err := fc.CreateComment(ctx, "PROJ-42", marker+"\nlegacy content") - if err != nil { - t.Fatalf("CreateComment: %v", err) - } - - // Simulate an update failure (property write succeeds, body update fails). - fc.UpdateError = forge.ErrNotFound - - err = c.MigrateAndUpdateComment(ctx, "PROJ", 42, listedComment(t, c, "1"), "updated", marker) - if err == nil { - t.Fatal("expected error from MigrateAndUpdateComment when UpdateComment fails") - } - if !errors.Is(err, forge.ErrNotFound) { - t.Errorf("error should wrap forge.ErrNotFound, got: %v", err) - } - - // The migrated property keeps the comment discoverable for a retry. - comments, err := c.ListJiraComments(ctx, "PROJ", 42) - if err != nil { - t.Fatalf("ListJiraComments: %v", err) - } - found := c.FindCommentByMarkerProperty(comments, marker) - if found == nil || found.ID != "1" { - t.Fatalf("FindCommentByMarkerProperty = %+v, want comment 1", found) - } - if !hasStickyMarkerProperty(*found, marker) { - t.Error("comment should be found via its migrated property") - } -} - func TestNewFakeJiraClient(t *testing.T) { c, err := NewFakeJiraClient("https://acme.atlassian.net") if err != nil { diff --git a/pkg/behaviourtest/steps/forge_state.go b/pkg/behaviourtest/steps/forge_state.go index aa6a589137..f9f24d48c2 100644 --- a/pkg/behaviourtest/steps/forge_state.go +++ b/pkg/behaviourtest/steps/forge_state.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "slices" + "strconv" "strings" "github.com/cucumber/godog" @@ -49,6 +50,19 @@ func registerForgeStateSteps(sc *godog.ScenarioContext) { sc.Step(`^a comment on the (`+targetAlternation+`) contains "([^"]+)"$`, func(ctx context.Context, target, text string) (context.Context, error) { return ctx, thenTargetCommentContains(world.FromContext(ctx), target, text) }) + sc.Step(`^the issue has (\d+) comments? containing "([^"]+)"$`, func(ctx context.Context, count, text string) (context.Context, error) { + n, err := strconv.Atoi(count) + if err != nil { + return ctx, fmt.Errorf("parsing comment count %q: %w", count, err) + } + return ctx, thenIssueCommentCountContains(world.FromContext(ctx), n, text) + }) + sc.Step(`^the last comment on the issue contains "([^"]+)"$`, func(ctx context.Context, text string) (context.Context, error) { + return ctx, thenLastIssueCommentContains(world.FromContext(ctx), text) + }) + sc.Step(`^a comment on the issue other than the last contains "([^"]+)"$`, func(ctx context.Context, text string) (context.Context, error) { + return ctx, thenIssueCommentOtherThanLastContains(world.FromContext(ctx), text) + }) sc.Step(`^the pull request body contains "([^"]+)"$`, func(ctx context.Context, text string) (context.Context, error) { return ctx, thenPullRequestBodyContains(world.FromContext(ctx), text) }) @@ -175,6 +189,67 @@ func thenTargetCommentContains(w *world.World, target, text string) error { return fmt.Errorf("no comment on %s #%d contains %q (%d comments checked)", target, number, text, len(comments)) } +// thenIssueCommentCountContains asserts that exactly count comments on +// the scenario's issue contain text. Sticky comments were removed +// (#9334): a re-run must append its result as a new comment, so the +// number of comments carrying the agent's marker is what separates +// append-on-every-run from a regression to edit-in-place, which keeps +// the count at one. +func thenIssueCommentCountContains(w *world.World, count int, text string) error { + comments, number, err := listTargetComments(w, targetIssue) + if err != nil { + return err + } + matched := 0 + for _, c := range comments { + if strings.Contains(c.Body, text) { + matched++ + } + } + if matched != count { + return fmt.Errorf("issue #%d has %d comments containing %q, want %d (%d comments checked)", number, matched, text, count, len(comments)) + } + return nil +} + +// thenLastIssueCommentContains asserts that the last comment on the +// scenario's issue contains text: the newest result sits at the end of +// the thread, where readers look for new activity. +func thenLastIssueCommentContains(w *world.World, text string) error { + comments, number, err := listTargetComments(w, targetIssue) + if err != nil { + return err + } + if len(comments) == 0 { + return fmt.Errorf("issue #%d has no comments", number) + } + last := comments[len(comments)-1] + if !strings.Contains(last.Body, text) { + return fmt.Errorf("the last comment on issue #%d does not contain %q:\n%s", number, text, last.Body) + } + return nil +} + +// thenIssueCommentOtherThanLastContains asserts that a comment before +// the last on the scenario's issue contains text: an earlier result +// stays where it was posted instead of being folded into the newest +// comment. +func thenIssueCommentOtherThanLastContains(w *world.World, text string) error { + comments, number, err := listTargetComments(w, targetIssue) + if err != nil { + return err + } + if len(comments) < 2 { + return fmt.Errorf("issue #%d has %d comments, need at least 2", number, len(comments)) + } + for _, c := range comments[:len(comments)-1] { + if strings.Contains(c.Body, text) { + return nil + } + } + return fmt.Errorf("no comment before the last on issue #%d contains %q (%d comments checked)", number, text, len(comments)-1) +} + // thenPullRequestBodyContains asserts that the scenario's pull request // body contains text. The placeholder expands to the scenario's // issue number, so "Closes #" checks the closing reference. diff --git a/pkg/behaviourtest/steps/forge_state_test.go b/pkg/behaviourtest/steps/forge_state_test.go index 0c9a584453..0ddfa9d2f5 100644 --- a/pkg/behaviourtest/steps/forge_state_test.go +++ b/pkg/behaviourtest/steps/forge_state_test.go @@ -183,6 +183,82 @@ func TestThenTargetCommentContains(t *testing.T) { require.ErrorContains(t, thenTargetCommentContains(w, targetIssue, "x"), "listing comments on issue #7") } +func TestThenIssueCommentCountContains(t *testing.T) { + t.Parallel() + + f := &fakeForgeStateSCM{comments: map[int][]forge.IssueComment{ + 7: { + {Body: "\nThis issue is ready for implementation."}, + {Body: "unrelated"}, + {Body: "\nRe-triage on the second run"}, + }, + }} + w := forgeStateWorld(f) + + require.NoError(t, thenIssueCommentCountContains(w, 2, "")) + require.NoError(t, thenIssueCommentCountContains(w, 1, "Re-triage on the second run")) + require.ErrorContains(t, thenIssueCommentCountContains(w, 1, ""), + `issue #7 has 2 comments containing "", want 1 (3 comments checked)`) + require.ErrorContains(t, thenIssueCommentCountContains(w, 2, "Re-triage on the second run"), + `issue #7 has 1 comments containing "Re-triage on the second run", want 2 (3 comments checked)`) + + require.ErrorContains(t, thenIssueCommentCountContains(&world.World{}, 1, "x"), "no issue created") + + f.err = errors.New("HTTP 403") + require.ErrorContains(t, thenIssueCommentCountContains(w, 1, "x"), "listing comments on issue #7") +} + +func TestThenLastIssueCommentContains(t *testing.T) { + t.Parallel() + + f := &fakeForgeStateSCM{comments: map[int][]forge.IssueComment{ + 7: { + {Body: "\nThis issue is ready for implementation."}, + {Body: "\nRe-triage on the second run"}, + }, + 8: {}, + }} + w := forgeStateWorld(f) + + require.NoError(t, thenLastIssueCommentContains(w, "Re-triage on the second run")) + require.ErrorContains(t, thenLastIssueCommentContains(w, "This issue is ready for implementation."), + `the last comment on issue #7 does not contain "This issue is ready for implementation."`) + + // An issue with no comments has no last comment to assert on. + f2 := &fakeForgeStateSCM{comments: map[int][]forge.IssueComment{7: {}}} + require.ErrorContains(t, thenLastIssueCommentContains(forgeStateWorld(f2), "x"), "issue #7 has no comments") + + f.err = errors.New("HTTP 403") + require.ErrorContains(t, thenLastIssueCommentContains(w, "x"), "listing comments on issue #7") +} + +func TestThenIssueCommentOtherThanLastContains(t *testing.T) { + t.Parallel() + + f := &fakeForgeStateSCM{comments: map[int][]forge.IssueComment{ + 7: { + {Body: "\nThis issue is ready for implementation."}, + {Body: "\nRe-triage on the second run"}, + }, + }} + w := forgeStateWorld(f) + + require.NoError(t, thenIssueCommentOtherThanLastContains(w, "This issue is ready for implementation.")) + // The last comment's text must not satisfy the step: it checks the + // comments before the last only. + require.ErrorContains(t, thenIssueCommentOtherThanLastContains(w, "Re-triage on the second run"), + `no comment before the last on issue #7 contains "Re-triage on the second run" (1 comments checked)`) + require.ErrorContains(t, thenIssueCommentOtherThanLastContains(w, "missing"), "no comment before the last on issue #7") + + // A single comment leaves nothing before the last to assert on. + f2 := &fakeForgeStateSCM{comments: map[int][]forge.IssueComment{7: {}}} + require.ErrorContains(t, thenIssueCommentOtherThanLastContains(forgeStateWorld(f2), "x"), + "issue #7 has 0 comments, need at least 2") + + f.err = errors.New("HTTP 403") + require.ErrorContains(t, thenIssueCommentOtherThanLastContains(w, "x"), "listing comments on issue #7") +} + func TestThenPullRequestBodyContains(t *testing.T) { t.Parallel() From c9231c84244349e15fcf04e8499ec5eaccc50b75 Mon Sep 17 00:00:00 2001 From: Tim Pouyer Date: Thu, 12 Nov 2026 16:01:59 -0500 Subject: [PATCH 03/25] docs(#9334): post every agent result as a new comment The doc edits for https://github.com/fullsend-ai/fullsend/issues/9334, kept out of the fix(#9334) commit so its size reads on its own. Signed-off-by: Tim Pouyer --- docs/agents/review.md | 2 +- docs/contributing/config-source-inventory.md | 2 +- docs/guides/dev/behaviour-testing.md | 3 ++ docs/guides/dev/cli-internals.md | 12 ++--- .../layered-config-reference.md | 26 ++++------ docs/guides/user/customizing-overview.md | 2 +- docs/guides/user/issues-commands.md | 52 +++++++++---------- docs/guides/user/jira-integration.md | 14 ++--- docs/reference/config-reference.md | 12 ++--- 9 files changed, 60 insertions(+), 65 deletions(-) diff --git a/docs/agents/review.md b/docs/agents/review.md index 4a2719b620..0cd0ad4fc0 100644 --- a/docs/agents/review.md +++ b/docs/agents/review.md @@ -15,7 +15,7 @@ The review agent is triggered when a PR is opened or updated, subject to the syn 1. **Pre-script** validates inputs and fetches PR metadata. 2. **Sandbox** — the agent runs the `pr-review` orchestrator skill. The orchestrator triages the change, then dispatches specialized sub-agents in parallel — each covering a distinct review dimension (correctness, security, intent & coherence, style & conventions, docs currency, and optionally cross-repo contracts). Sub-agents run concurrently and return structured findings. The orchestrator collects, deduplicates, and synthesizes findings across dimensions, runs PR-level checks (scope authorization, protected paths), and produces a structured JSON review result. The agent cannot push files, edit code, or push — it is strictly read-only. 3. **Validation loop** — the output is checked against a schema, with up to 2 retry iterations if the output is malformed. -4. **Post-script** posts the review on the PR. Findings that include a file path and a line in the change diff are also posted as inline comments on that line (GitHub review comments; GitLab merge-request discussions). Findings that cannot be positioned — file-level notes, lines outside the diff, or a GitLab diff version whose `head_sha` no longer matches the reviewed commit — stay in the sticky review comment, and on GitLab as general MR notes. Once the sticky review comment is posted, a failure to submit the forge's native review (GitHub PR review or GitLab approval) is logged as a warning and does not fail the run — the sticky comment is the authoritative record of the verdict. +4. **Post-script** posts the review on the PR. Findings that include a file path and a line in the change diff are also posted as inline comments on that line (GitHub review comments; GitLab merge-request discussions). Findings that cannot be positioned — file-level notes, lines outside the diff, or a GitLab diff version whose `head_sha` no longer matches the reviewed commit — stay in the review comment, and on GitLab as general MR notes. Every run posts a new review comment at the end of the thread. Once the review comment is posted, a failure to submit the forge's native review (GitHub PR review or GitLab approval) is logged as a warning and does not fail the run — the review comment is the authoritative record of the verdict. If a prior review exists (e.g., re-review after fixes), it is injected into the sandbox so the agent can assess whether previous findings were addressed. diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index 59c7bcb612..9c11bd8fdf 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -74,7 +74,7 @@ These fields live on `perRepoConfig` in `internal/config/config.go`. Unset means |---|---|---|---|---|---|---| | `version` | Config schema version | Overlay, base, compiled `"1"` | Overlay, then base, then `"1"` | Config loader | Already layered | No. It is the schema version, not an admin policy. | | `forge` | Hosting platform (`github` or `gitlab`) | `--forge`, overlay, base, compiled empty (GitHub) | `--forge`, then overlay, then base. If still empty, CI detection (`GITHUB_ACTIONS`/`GITLAB_CI`) fills it; outside CI it can stay empty | CLI | Already layered. The flag is a one-shot override and stays first. | Yes, when a fleet is single-forge. | -| `keep_history` | Whether sticky comments keep a collapsed previous body | `--keep-history`, overlay, base, compiled `true` | `--keep-history` (when the flag was explicitly passed), then overlay, then base, then `true` | Comment updaters | Already layered. The flag is a one-shot override and stays first. | Yes, when a fleet wants one comment style. | +| `keep_history` | Deprecated: no effect (sticky comments were removed; every result is a new comment) | `--keep-history`, overlay, base, compiled `true` | `--keep-history` (when the flag was explicitly passed), then overlay, then base, then `true` | Nothing; accepted until a cleanup removes it | Already layered. The flag is a one-shot override and stays first. | No. It no longer changes behaviour. | | `allowed_remote_resources` | URL prefixes agents may fetch | Overlay, base, compiled fullsend and agents prefixes | Accessor-level: overlay union or deny-all, then base, then the compiled prefixes. Commands (`run`/`lint`/`lock`, harness dispatch, `dispatch --route`, Jira poll, agent set/add/update/remove) ensure fullsend's default prefixes on top of a non-empty result; `Validate()` callers (`github setup` re-runs, `repos install`) and managed `repos.yaml` validation admit the same shapes through `perRepoConfig.Validate`/`ValidateMergedManaged` (`config_base` preset validation parses the preset standalone — preset list plus the defaults, no overlay — so it is stricter than the read for overlay-only prefixes and for a preset `[]`, and looser over a runtime overlay `[]`; merged managed validation sees only the managed blocks plus the defaults, so a prefix declared only in `config.base.yaml` or a `config_base` preset makes it stricter than the read); a resolved `[]` stays deny-all | Resource fetch, agent-source validation | Already layered. Accessor-level and command-level resolution are two steps of one rule. | Yes. This is the shared fetch allowlist. | | `tracker` | Issue tracker provider block (`github`, `gitlab`, or `jira`): the default for `fullsend issues --tracker` and the provider's `allowed_targets`, where agents may open issues | Overlay, base, compiled unset (flag required, no extra targets) | `--tracker`, then the layered file; the whole object replaces the parent when set | `fullsend issues`, issue creation | Already layered. The flag is a one-shot override and stays first. | Yes for a shared allowlist. A repository overlay replaces the whole object. | | `status_notifications` | Start and completion comments and reactions | Overlay, base, compiled unset | Whole object replaces the parent when set | Status posting | Already layered | Yes, when a fleet wants one notification policy. | diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index 0d87aae70f..248ea30d62 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -424,6 +424,9 @@ once `the pull request head branch matches` has found it. | `the pull request has been closed` | The pull request is closed, merged or not | | `a comment on the issue contains ""` | Some issue comment contains the text, such as a sticky marker like ``). GitHub/GitLab: hidden HTML comment in body. Jira: comment entity property. | +| `--marker` | Yes | Marker identifying this agent's comments (e.g. ``). GitHub/GitLab: hidden HTML comment in body. Jira: comment entity property. | | `--result` | No | Path to comment body file, or `-` for stdin (default: `-`) | | `--token` | No | GitHub/GitLab API token (default: env var per tracker). Rejected for Jira | -| `--dry-run` | No | Print what would be posted without posting or editing anything | -| `--keep-history` | No | Append previous content as collapsed history blocks (default: `true`; set `false` to replace in-place) | -| `--only-if-exists` | No | Update an existing comment with this marker but never create one. Use it for an all-clear result, so a findings comment from an earlier run is updated in place (the old findings are kept as collapsed history unless `--keep-history=false`) while a clean first run posts nothing. Only a comment whose author is exactly the identity posting matches; if that identity cannot be resolved, the command fails without posting. | +| `--dry-run` | No | Print what would be posted without posting anything | +| `--keep-history` | No | Deprecated: no effect. Every result is posted as a new comment; the flag stays accepted so existing callers keep working | +| `--only-if-exists` | No | Post only when an earlier comment with this marker exists, so a run with no earlier comment posts nothing. Use it for an all-clear result, so it follows earlier findings at the end of the thread while a clean first run posts nothing. Only a comment whose author is exactly the identity posting matches; if that identity cannot be resolved, the command fails without posting. | | `--fullsend-dir` | Jira | Path to `.fullsend` config directory. Supplies defaults from its `config.yaml` when flags are omitted, including the [Jira connection settings](#jira-connection-settings) | ### Jira marker storage @@ -383,21 +380,20 @@ for how the `tracker` field resolves through the config overlay chain. ## Trust model -An existing comment is edited only when it carries the marker **and** -its author is exactly the identity the command posts as: the login on -GitHub and GitLab, where markers are hidden HTML comments in the body, -and the account ID (from `GET /myself`) on Jira, where markers are -comment entity properties. Display names and login shapes are never -trusted. A comment anyone else wrote with the same marker, as body text -or as a comment property on their own comment, is ignored, never edited. -Anyone who can edit the command's own comments (a repository maintainer, -or a Jira user with Edit All Comments) is still trusted: their edits are -kept as history when the comment is next updated. - -If that identity cannot be resolved after a short retry, the command -fails with an error naming the cause and posts or edits nothing, with or -without `--only-if-exists`. Posting a new comment instead would leave the -earlier one behind with content no later run updates. To recover: +A comment counts as this command's own only when it carries the marker +**and** its author is exactly the identity the command posts as: the +login on GitHub and GitLab, where markers are hidden HTML comments in +the body, and the account ID (from `GET /myself`) on Jira, where +markers are comment entity properties. Display names and login shapes +are never trusted. A comment anyone else wrote with the same marker, as +body text or as a comment property on their own comment, never counts, +so it cannot gate `--only-if-exists` and it is never edited. + +Every run posts a new comment, so a plain post resolves no identity. +With `--only-if-exists`, if that identity cannot be resolved after a +short retry the command fails with an error naming the cause and posts +nothing — otherwise a planted marker could decide whether the comment +is posted. To recover: 1. Rerun the command. A transient API failure clears on its own. 2. If it fails again, check that the token can read its own identity: diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 860200fab6..0f55af5523 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -532,11 +532,13 @@ explicit `FULLSEND_TRACKER` or `ISSUE_URL` points somewhere else. Code stops if a label not used anywhere on the Jira site (triage does not create new labels), and component changes skipped because the issue's current components could not be read. -- **Retries:** comments are not duplicated. The code-stage update and the - sticky triage comments use fixed markers. Other triage comments use a marker - scoped to the CI run (`GITHUB_RUN_ID` or `CI_PIPELINE_ID`). A re-run of the - same workflow or pipeline edits its earlier comment, while a new triage run - posts a new one. +- **Retries:** on GitHub and Jira a re-run posts a new comment at the end of + the thread instead of editing the earlier one (sticky comments were + removed). The code-stage update and the triage comments use fixed or + run-scoped markers (`GITHUB_RUN_ID` or `CI_PIPELINE_ID`), so later steps + still find the relevant comment. On GitLab, the triage scripts from the + agents repo keep their find-and-edit behaviour on a re-run of the same + pipeline. - **Write failures:** a failed Jira write fails the step, so it is never reported as a success. For triage this covers label adds and removals, component updates, comments, and transitions. For code the step fails even @@ -1744,7 +1746,7 @@ However, more pollers against the same Jira project means more API calls per cyc | Triage or code results do not appear on the Jira issue | The built-in agents are pinned to a release that predates Jira result writes | Use built-in agents from the agents release that follows v0.52.0, or later. Re-pin a harness registered with `source:` or composed with `base:` with `fullsend agent update `. See [Where built-in agent results appear](#where-built-in-agent-results-appear) | | Code run skipped; the Jira issue has a comment starting `An open pull request already addresses — skipping automated implementation.` | An open pull request written by a person names the issue key in its title or description. Bot pull requests do not count | GitHub: comment `/fs-code --force` on the Jira issue. GitLab: close the merge request, then comment `/fs-code`. See [If the code agent skips the run](#if-the-code-agent-skips-the-run) | | Code run skipped; the Jira issue has a comment starting ` has child issues — skipping automated implementation.` | The issue has child issues, open or closed. Subtasks do not count | Run the code agent on the child issues. On GitHub you can also comment `/fs-code --force` to implement the parent issue. See [If the code agent skips the run](#if-the-code-agent-skips-the-run) | -| Code step fails after the PR or MR was created | The Jira write of the code-stage update failed | Check the step log for the Jira error, and confirm the Jira credentials reach the agent job, that `tracker.jira.base_url` is set (a missing or invalid setting stops a Jira-sourced run before the sandbox, with a `jira-sourced run:` error in the run log), and that the account can comment on the issue. A re-run edits the existing update rather than posting a second one | +| Code step fails after the PR or MR was created | The Jira write of the code-stage update failed | Check the step log for the Jira error, and confirm the Jira credentials reach the agent job, that `tracker.jira.base_url` is set (a missing or invalid setting stops a Jira-sourced run before the sandbox, with a `jira-sourced run:` error in the run log), and that the account can comment on the issue. A re-run posts a new update comment rather than editing the earlier one | ## See also diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index c69e96b7b8..9cd57af2f8 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -25,7 +25,7 @@ forge: github # Hosting platform: github, gitlab (auto-de # ── Operations ─────────────────────────────────────────────── kill_switch: false # Emergency stop — disables all agent dispatch when true -keep_history: true # Append previous sticky-comment content as collapsed "Previous run" blocks +keep_history: true # Deprecated: no effect (every result is posted as a new comment) # ── Runtime ────────────────────────────────────────────────── runtime: claude # Default agent runtime: claude, pi, codex, opencode @@ -197,11 +197,11 @@ that does not fall through. ### `keep_history` -Controls whether sticky comment updates (from post-review, post-comment, and -issues post-comment) append the previous comment body as a collapsed "Previous -run" `
` block. Default is `true` (history appended). Set to `false` -when accumulated "Previous run" blocks add unwanted noise — for example, when -comments are synced to Jira where `
` does not render as collapsible. +Deprecated: no effect. Sticky comments were removed, so every result from +post-review, post-comment, and issues post-comment is posted as a new +comment at the end of the thread and nothing is folded into "Previous +run" blocks. The field stays accepted (and `--keep-history` with it) so +existing configs keep working until a cleanup removes it. ### `runtime` From 8f62aa0ec34059be7ae4fe523331c00218a0abc6 Mon Sep 17 00:00:00 2001 From: Tim Pouyer Date: Thu, 12 Nov 2026 21:37:05 -0500 Subject: [PATCH 04/25] test(#9334): refuse when the size cap cuts the trusted line Land round 1: the test a review thread asked for. Signed-off-by: Tim Pouyer --- internal/sticky/post_size_cap_test.go | 71 +++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 internal/sticky/post_size_cap_test.go diff --git a/internal/sticky/post_size_cap_test.go b/internal/sticky/post_size_cap_test.go new file mode 100644 index 0000000000..2a9d8d7fdf --- /dev/null +++ b/internal/sticky/post_size_cap_test.go @@ -0,0 +1,71 @@ +package sticky + +import ( + "context" + "io" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// The trusted leading line carries the projection payload the next run's +// prior-review fetch reads back (it selects the newest marked comment and +// copies its body), so the create-path size cap must never cut it: Post +// refuses rather than creating a comment whose marker line is partial. + +func TestPost_TrustedLeadingLineTooLargeForSizeCapIsRefused(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + // A cap with room for the runner marker and the truncation note but + // not the whole trusted line cuts inside that line: the marker stays + // intact while the projection line is partial — the thread's defect + // shape, so the refusal cannot be a marker-only guard. + cfg := Config{ + Marker: "", + MaxSize: len("\n"+trustedLine) + 20, + TrustedLeadingLine: trustedLineRe, + } + body := trustedLine + "\n\n" + strings.Repeat("x", 200) + + _, err := Post(context.Background(), client, "o", "r", 1, body, cfg, printer) + + require.Error(t, err, "Post must refuse rather than post a partial trusted line") + assert.Contains(t, err.Error(), "size cap") + assert.Empty(t, client.IssueComments["o/r/1"], "no comment is created") + assert.Empty(t, client.UpdatedComments, "no comment is edited in place") +} + +func TestPost_TrustedLeadingLineWithinSizeCapPostsIntact(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + // The cap leaves room for the runner marker and the trusted line + // (plus the truncation note), so an oversized rest of the body is + // truncated after them, not through them. + cfg := Config{ + Marker: "", + MaxSize: len("\n"+trustedLine) + 80, + TrustedLeadingLine: trustedLineRe, + } + body := trustedLine + "\n\n" + strings.Repeat("x", 500) + + _, err := Post(context.Background(), client, "o", "r", 1, body, cfg, printer) + require.NoError(t, err) + + comments := client.IssueComments["o/r/1"] + require.Len(t, comments, 1, "the comment is created") + got := comments[0].Body + assert.True(t, strings.HasPrefix(got, cfg.Marker+"\n"+trustedLine), + "the runner marker and the trusted leading line stay intact") + assert.Contains(t, got, "*Comment truncated due to comment size limits.*", + "the oversized rest is truncated after the trusted line") + assert.LessOrEqual(t, len(got), cfg.MaxSize, "the posted body respects the cap") +} From c1da73c03832d9b448a7ae08b8a92df714e070d0 Mon Sep 17 00:00:00 2001 From: Tim Pouyer Date: Thu, 12 Nov 2026 21:37:12 -0500 Subject: [PATCH 05/25] fix(#9334): refuse when the size cap cuts the trusted line Land round 1 of https://github.com/fullsend-ai/fullsend/issues/9334: review threads answered in this commit. PR review: round 15, verdict approve (7 nitpick(s), 0 advisory(ies)). Signed-off-by: Tim Pouyer --- internal/sticky/sticky.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/internal/sticky/sticky.go b/internal/sticky/sticky.go index 508fac8530..a8a54cbad0 100644 --- a/internal/sticky/sticky.go +++ b/internal/sticky/sticky.go @@ -72,6 +72,18 @@ func Post(ctx context.Context, client forge.Client, owner, repo string, number i // creating: an oversized single result would otherwise fail the post. markedBody = TruncateBody(markedBody, cfg.maxSize()) + // A trusted leading line carries the projection payload the next + // run's prior-review fetch reads back, so the size cap must never + // cut it (nor the runner marker before it): TruncateBody cuts at a + // byte offset with no line awareness, and a projection line posted + // partial would break that fetch. Refuse to post instead. + if cfg.TrustedLeadingLine != nil { + if first, _, _ := strings.Cut(body, "\n"); cfg.TrustedLeadingLine.MatchString(first) && + !strings.HasPrefix(markedBody, cfg.Marker+"\n"+first) { + return "", fmt.Errorf("comment body exceeds the %d-byte size cap without room for the trusted leading line intact; refusing to post a partial marker line", cfg.maxSize()) + } + } + printer.StepStart("Posting comment") if cfg.DryRun { From cf3b983be0128b8b1b026cf1870c11aa823309c1 Mon Sep 17 00:00:00 2001 From: Tim Pouyer Date: Fri, 13 Nov 2026 11:55:43 -0500 Subject: [PATCH 06/25] fix(#9334): scope the re-run assertion to the marker comment Scope the re-run assertion to the marker comment. Addresses review feedback on https://github.com/fullsend- ai/fullsend/pull/9399. Signed-off-by: Tim Pouyer --- .../triage/triage-re-run-append.feature | 2 +- pkg/behaviourtest/steps/forge_state.go | 29 ++++++++ .../steps/forge_state_feature_test.go | 67 +++++++++++++++++++ pkg/behaviourtest/steps/forge_state_test.go | 34 ++++++++++ 4 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 pkg/behaviourtest/steps/forge_state_feature_test.go diff --git a/e2e/behaviour/features/triage/triage-re-run-append.feature b/e2e/behaviour/features/triage/triage-re-run-append.feature index 0d0ede2192..89feea6f12 100644 --- a/e2e/behaviour/features/triage/triage-re-run-append.feature +++ b/e2e/behaviour/features/triage/triage-re-run-append.feature @@ -27,5 +27,5 @@ Feature: Re-running triage appends a new comment And the write actor posts "/fs-triage" on the issue Then the triage agent completes successfully And the issue has 2 comments containing "" - And the last comment on the issue contains "Re-triage on the second run" + And the last comment on the issue containing "" contains "Re-triage on the second run" And a comment on the issue other than the last contains "This issue is ready for implementation." diff --git a/pkg/behaviourtest/steps/forge_state.go b/pkg/behaviourtest/steps/forge_state.go index f9f24d48c2..997808df90 100644 --- a/pkg/behaviourtest/steps/forge_state.go +++ b/pkg/behaviourtest/steps/forge_state.go @@ -60,6 +60,9 @@ func registerForgeStateSteps(sc *godog.ScenarioContext) { sc.Step(`^the last comment on the issue contains "([^"]+)"$`, func(ctx context.Context, text string) (context.Context, error) { return ctx, thenLastIssueCommentContains(world.FromContext(ctx), text) }) + sc.Step(`^the last comment on the issue containing "([^"]+)" contains "([^"]+)"$`, func(ctx context.Context, marker, text string) (context.Context, error) { + return ctx, thenLastIssueCommentContainingContains(world.FromContext(ctx), marker, text) + }) sc.Step(`^a comment on the issue other than the last contains "([^"]+)"$`, func(ctx context.Context, text string) (context.Context, error) { return ctx, thenIssueCommentOtherThanLastContains(world.FromContext(ctx), text) }) @@ -230,6 +233,32 @@ func thenLastIssueCommentContains(w *world.World, text string) error { return nil } +// thenLastIssueCommentContainingContains asserts that the last comment +// on the scenario's issue carrying marker (an agent's result marker) +// also contains text: the newest of an agent's results is the one +// readers look for, whatever other comments — a status completion, a +// command — were posted behind it. Unlike thenLastIssueCommentContains +// it does not depend on which comment the run left last of any kind. +func thenLastIssueCommentContainingContains(w *world.World, marker, text string) error { + comments, number, err := listTargetComments(w, targetIssue) + if err != nil { + return err + } + last := -1 + for i, c := range comments { + if strings.Contains(c.Body, marker) { + last = i + } + } + if last < 0 { + return fmt.Errorf("no comment on issue #%d contains %q (%d comments checked)", number, marker, len(comments)) + } + if !strings.Contains(comments[last].Body, text) { + return fmt.Errorf("the last comment on issue #%d containing %q does not contain %q:\n%s", number, marker, text, comments[last].Body) + } + return nil +} + // thenIssueCommentOtherThanLastContains asserts that a comment before // the last on the scenario's issue contains text: an earlier result // stays where it was posted instead of being folded into the newest diff --git a/pkg/behaviourtest/steps/forge_state_feature_test.go b/pkg/behaviourtest/steps/forge_state_feature_test.go new file mode 100644 index 0000000000..7616925225 --- /dev/null +++ b/pkg/behaviourtest/steps/forge_state_feature_test.go @@ -0,0 +1,67 @@ +package steps + +import ( + "bufio" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestTriageReRunAppendFeature_StepsMatchPatterns checks that every +// comment assertion of the triage re-run scenario matches a pattern +// registerForgeStateSteps registers (the patterns are repeated here +// verbatim), so a typo in the feature or the step text fails here +// rather than after a lease: the scenario's behaviour job skips on +// fork PRs, so its wiring is otherwise only checked live. +func TestTriageReRunAppendFeature_StepsMatchPatterns(t *testing.T) { + t.Parallel() + + f, err := os.Open(filepath.Join("..", "..", "..", "e2e", "behaviour", "features", "triage", "triage-re-run-append.feature")) + require.NoError(t, err) + defer f.Close() + + var steps []string + scanner := bufio.NewScanner(f) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if strings.HasPrefix(line, "Given ") || strings.HasPrefix(line, "When ") || + strings.HasPrefix(line, "Then ") || strings.HasPrefix(line, "And ") { + steps = append(steps, line[strings.Index(line, " ")+1:]) + } + } + require.NoError(t, scanner.Err()) + + patterns := []*regexp.Regexp{ + regexp.MustCompile(`^the issue has (\d+) comments? containing "([^"]+)"$`), + regexp.MustCompile(`^the last comment on the issue contains "([^"]+)"$`), + regexp.MustCompile(`^the last comment on the issue containing "([^"]+)" contains "([^"]+)"$`), + regexp.MustCompile(`^a comment on the issue other than the last contains "([^"]+)"$`), + } + var commentAssertions []string + for _, step := range steps { + for _, p := range patterns { + if p.MatchString(step) { + commentAssertions = append(commentAssertions, step) + } + } + } + require.Len(t, commentAssertions, 4, "the scenario's four comment assertions, each matching exactly one pattern") + + // The marker-scoped assertion matches its own pattern, never the + // any-kind last-comment one. + markerScoped := 0 + for _, step := range steps { + if !strings.HasPrefix(step, `the last comment on the issue containing "`) { + continue + } + markerScoped++ + assert.True(t, patterns[2].MatchString(step), "step does not match the registered pattern: %s", step) + assert.False(t, patterns[1].MatchString(step), "step also matches the any-kind pattern: %s", step) + } + assert.Equal(t, 1, markerScoped, "exactly one marker-scoped last-comment assertion") +} diff --git a/pkg/behaviourtest/steps/forge_state_test.go b/pkg/behaviourtest/steps/forge_state_test.go index 0ddfa9d2f5..6438a8092f 100644 --- a/pkg/behaviourtest/steps/forge_state_test.go +++ b/pkg/behaviourtest/steps/forge_state_test.go @@ -232,6 +232,40 @@ func TestThenLastIssueCommentContains(t *testing.T) { require.ErrorContains(t, thenLastIssueCommentContains(w, "x"), "listing comments on issue #7") } +func TestThenLastIssueCommentContainingContains(t *testing.T) { + t.Parallel() + + f := &fakeForgeStateSCM{comments: map[int][]forge.IssueComment{ + 7: { + {Body: "\nThis issue is ready for implementation."}, + {Body: "\nRe-triage on the second run"}, + // A status completion appended behind the result: the + // marker-scoped step must ignore it, where the + // any-kind last-comment step would read it instead. + {Body: "🤖 Triage · Completed"}, + }, + }} + w := forgeStateWorld(f) + + require.NoError(t, thenLastIssueCommentContainingContains(w, "", "Re-triage on the second run")) + // Only the last marker comment satisfies the step, not an earlier one. + require.ErrorContains(t, thenLastIssueCommentContainingContains(w, "", "This issue is ready for implementation."), + `the last comment on issue #7 containing "" does not contain "This issue is ready for implementation."`) + // The comment behind the last marker comment is not the one asserted on. + require.ErrorContains(t, thenLastIssueCommentContainingContains(w, "", "Completed"), + `does not contain "Completed"`) + + // No comment carries the marker. + f2 := &fakeForgeStateSCM{comments: map[int][]forge.IssueComment{7: {{Body: "unrelated"}}}} + require.ErrorContains(t, thenLastIssueCommentContainingContains(forgeStateWorld(f2), "", "x"), + `no comment on issue #7 contains "" (1 comments checked)`) + + require.ErrorContains(t, thenLastIssueCommentContainingContains(&world.World{}, "m", "x"), "no issue created") + + f.err = errors.New("HTTP 403") + require.ErrorContains(t, thenLastIssueCommentContainingContains(w, "m", "x"), "listing comments on issue #7") +} + func TestThenIssueCommentOtherThanLastContains(t *testing.T) { t.Parallel() From a0a9522e4ed0bf32f3804e1c68bee023cd2adfec Mon Sep 17 00:00:00 2001 From: Tim Pouyer Date: Fri, 13 Nov 2026 11:55:49 -0500 Subject: [PATCH 07/25] docs(#9334): scope the re-run assertion to the marker comment The doc edits this change needs. Signed-off-by: Tim Pouyer --- docs/guides/dev/behaviour-testing.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index 248ea30d62..d0aff1d76e 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -426,6 +426,7 @@ once `the pull request head branch matches` has found it. | `a comment on the pull request contains ""` | Some pull request comment contains the text | | `the issue has comments containing ""` | Exactly comments on the issue contain the text | | `the last comment on the issue contains ""` | The last (newest) comment on the issue contains the text | +| `the last comment on the issue containing "" contains ""` | The newest comment on the issue carrying the marker (an agent's result marker) contains the text | | `a comment on the issue other than the last contains ""` | Some comment before the last on the issue contains the text | | `the pull request body contains ""` | The PR body contains the text. `` expands, so `"Closes #"` checks the closing reference | | `an issue with label "