From a1a9b31e60ae873df25c44822cd81cc767fb9332 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 1 Oct 2026 10:28:36 -0400 Subject: [PATCH 1/4] feat(#6966)!: replace stale findings on ok via issues post-comment --only-if-exists On status ok the generated post-script posted nothing, so a findings comment from an earlier push stayed on the pull request after a later push fixed the problem (the trigger fires again on synchronize). Add `issues post-comment --only-if-exists`: update the poster's own earlier marker comment, never create one. sticky.Config.OnlyIfExists carries it to the GitHub/GitLab and Jira paths, which honour it after the author check, so a comment someone else planted with the marker is never the target. sticky.Post does not read it. The generated ok path now pipes the all-clear through it. The runner's fullsend is pinned by fullsend-ref, not by the CLI that generated the script, so the script detects the flag from --help (reading the whole text, no grep -q, so an early exit cannot SIGPIPE it) and keeps the old "post nothing" on an older CLI. A failed post fails the run. Dry run calls nothing and says it did not check for an earlier comment. The ok path now runs after ISSUE_URL validation, so an ok result with a non-GitHub ISSUE_URL is rejected like any other. Tests: the flag on the forge-client and Jira paths (including a marker property planted by another account), and the generated ok path with stubbed fullsend binaries that do and do not know the flag, that fail the post, and that must not be called under dry run. Goldens regenerated; docs list the flag. BREAKING CHANGE: a regenerated post-script now fails the run on a status ok result when fullsend is missing, its --help fails, the posting identity cannot be resolved, or the post fails; previously the ok branch always exited 0. Existing generated scripts are unchanged until regenerated. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- docs/guides/dev/cli-internals.md | 1 + docs/guides/user/issues-commands.md | 7 +- internal/agentnew/postscript_exec_test.go | 147 +++++++++++ internal/agentnew/templates/post.sh.tmpl | 45 +++- internal/agentnew/testdata/golden/triage.txt | 45 +++- .../testdata/golden/validation-loop.txt | 45 +++- internal/cli/issues.go | 44 ++-- internal/cli/issues_test.go | 239 +++++++++++++++--- internal/sticky/sticky.go | 6 + 9 files changed, 505 insertions(+), 74 deletions(-) diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 5c59fa6732..74830f4ffb 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -156,6 +156,7 @@ fullsend │ ├── --number # Issue number │ ├── --marker # Sticky marker for idempotent updates (HTML comment or Jira property) │ ├── --keep-history # Append previous content as collapsed history (default true) +│ ├── --only-if-exists # Update an existing marked comment, never create one │ └── --fullsend-dir # .fullsend config directory (resolves keep_history default) ├── post-review # Post sticky PR/MR review comments (formal review is best-effort) │ ├── --forge # Forge backend: github (default) or gitlab diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index 2b995a6321..88bdb21611 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -88,6 +88,7 @@ echo "Triage complete. See PR #99." | fullsend issues post-comment \ | `--jira-email` | Jira only | Jira user email for auth (default: `$JIRA_USER_EMAIL`) | | `--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. | | `--fullsend-dir` | No | Path to `.fullsend` config directory (sources defaults from its `config.yaml` when flags are omitted) | ### Jira marker storage @@ -127,9 +128,9 @@ 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. Posting -a new comment instead would leave the earlier one behind with content no -later run updates. To recover: +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: 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/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index 0ad06c0acf..54dcbf346f 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -130,3 +130,150 @@ func TestGeneratedPostScriptRunsFromTheRunDirectory(t *testing.T) { } }) } + +// TestGeneratedPostScriptOkDryRunPostsNothing pins the ok path under dry +// run: the script exits 0 and says nothing was posted, without looking for +// an earlier comment. The live path is covered by the stubbed-fullsend tests +// below; the author check it relies on is tested in internal/cli. +func TestGeneratedPostScriptOkDryRunPostsNothing(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + // A fullsend that knows the flag sits first on PATH and records any + // call: a dry run must never reach it. + binDir := t.TempDir() + calledFile := filepath.Join(binDir, "called") + stub := "#!/usr/bin/env bash\ntouch " + calledFile + "\nif [[ \"$*\" == *--help* ]]; then echo ' --only-if-exists update an existing comment but never create one'; fi\nexit 0\n" + if err := os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + stdout, stderr, err := runPostScript(t, script, runDir, "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + if err != nil { + t.Fatalf("ok status must exit 0, got %v; stderr:\n%s", err, stderr) + } + if !strings.Contains(stderr, "dry run: did not check") { + t.Fatalf("expected the dry-run ok notice, got stderr:\n%s", stderr) + } + if strings.TrimSpace(stdout) != "" { + t.Fatalf("ok under dry run must print no comment body, got:\n%s", stdout) + } + if _, err := os.Stat(calledFile); err == nil { + t.Fatal("a dry run must not call fullsend") + } +} + +// TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists runs the +// live ok path (no dry run) against a stub `fullsend` on PATH that records +// its arguments. The script must delegate the "is there an earlier findings +// comment" decision to `fullsend issues post-comment --only-if-exists` +// rather than reimplementing it with raw API calls in shell. +func TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + binDir := t.TempDir() + argsFile := filepath.Join(binDir, "args") + stub := "#!/usr/bin/env bash\nif [[ \"$*\" == *--help* ]]; then echo ' --only-if-exists update an existing comment but never create one'; exit 0; fi\nprintf '%s\\n' \"$@\" > " + argsFile + "\ncat >/dev/null\n" + if err := os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + cmd := exec.Command("bash", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH"), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + ) + var stderr strings.Builder + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + t.Fatalf("ok live path must exit 0, got %v; stderr:\n%s", err, stderr.String()) + } + got, err := os.ReadFile(argsFile) + if err != nil { + t.Fatalf("the script never invoked fullsend on the ok path: %v; stderr:\n%s", err, stderr.String()) + } + args := string(got) + for _, want := range []string{"issues\npost-comment\n", "--only-if-exists\n", "--marker\n", "fullsend-ai/demo\n", "99\n"} { + if !strings.Contains(args, want) { + t.Errorf("fullsend was called without %q; args:\n%s", strings.TrimSpace(want), args) + } + } +} + +// TestGeneratedPostScriptOkOnAnOlderFullsendPostsNothing pins the +// degradation path: the runner's fullsend is pinned by the repository, not +// by the CLI that generated the script, so when its post-comment has no +// --only-if-exists the ok path must post nothing and exit 0 rather than fail +// on an unknown flag. +func TestGeneratedPostScriptOkOnAnOlderFullsendPostsNothing(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + binDir := t.TempDir() + argsFile := filepath.Join(binDir, "args") + // An older CLI: --help lists no --only-if-exists, and any real call + // with that flag would fail — so the stub fails loudly if invoked to post. + stub := "#!/usr/bin/env bash\nif [[ \"$*\" == *--help* ]]; then echo ' --dry-run print what would be posted'; exit 0; fi\nprintf '%s\\n' \"$@\" > " + argsFile + "\necho 'Error: unknown flag: --only-if-exists' >&2; exit 1\n" + if err := os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + cmd := exec.Command("bash", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH"), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + ) + var stderr strings.Builder + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + t.Fatalf("ok on an older fullsend must exit 0, got %v; stderr:\n%s", err, stderr.String()) + } + if !strings.Contains(stderr.String(), "nothing to post") { + t.Fatalf("expected the nothing-to-post notice, got:\n%s", stderr.String()) + } + if _, err := os.Stat(argsFile); err == nil { + t.Fatalf("an older fullsend must not be asked to post on the ok path") + } +} + +// TestGeneratedPostScriptOkFailsWhenThePostFails pins that the ok path does +// not swallow a failed post: when fullsend cannot verify its identity (or the +// API fails) it exits non-zero, and the run must fail visibly. +func TestGeneratedPostScriptOkFailsWhenThePostFails(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + binDir := t.TempDir() + stub := "#!/usr/bin/env bash\nif [[ \"$*\" == *--help* ]]; then echo ' --only-if-exists update an existing comment but never create one'; exit 0; fi\ncat >/dev/null\necho 'Error: cannot verify which identity this command posts as' >&2; exit 1\n" + if err := os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + cmd := exec.Command("bash", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH"), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + ) + if err := cmd.Run(); err == nil { + t.Fatal("ok must fail when fullsend issues post-comment fails") + } +} diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index e1252584a5..f54c30388d 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -111,11 +111,6 @@ if (( ${#comment} > MAX_COMMENT_CHARS )); then comment="${comment:0:${keep}}${TRUNCATION_MARKER}" fi -if [[ "${status}" == "ok" ]]; then - echo "post-__AGENT_NAME__: status=ok, nothing to post" >&2 - exit 0 -fi - # Derive the repo and number from the work item URL rather than trusting extra # environment. The pattern also rejects anything that is not a github.com URL. url_re='^https://github[.]com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)/(issues|pull)/([0-9]+)$' @@ -126,6 +121,42 @@ 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. +if [[ "${status}" == "ok" ]]; then + if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then + echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 + exit 0 + fi + # The runner's fullsend may predate --only-if-exists (it is pinned by the + # repository's fullsend-ref, not by the CLI that generated this script). + # Detect the flag instead of assuming it: on an older CLI, keep the old + # behaviour — post nothing — rather than fail the common ok path. + # grep reads the whole help text (no -q): an early exit could SIGPIPE + # fullsend and, under pipefail, read as "flag missing". + if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; 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 + printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ + | fullsend issues post-comment \ + --tracker github \ + --project "${REPO}" \ + --number "${NUMBER}" \ + --marker "${MARKER}" \ + --only-if-exists \ + --result - + exit 0 +fi + if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then # The preview prints model output. Under GitHub Actions a line starting # with "::" is a workflow command (the runner even trims leading spaces @@ -142,8 +173,8 @@ if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then fi # fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and edits it in place, so -# re-runs do not flood the work item. +# 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. 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 46e5c50a05..1f21814453 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -263,11 +263,6 @@ if (( ${#comment} > MAX_COMMENT_CHARS )); then comment="${comment:0:${keep}}${TRUNCATION_MARKER}" fi -if [[ "${status}" == "ok" ]]; then - echo "post-lint-docs: status=ok, nothing to post" >&2 - exit 0 -fi - # Derive the repo and number from the work item URL rather than trusting extra # environment. The pattern also rejects anything that is not a github.com URL. url_re='^https://github[.]com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)/(issues|pull)/([0-9]+)$' @@ -278,6 +273,42 @@ 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. +if [[ "${status}" == "ok" ]]; then + if [[ "${POST_LINT_DOCS_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 + exit 0 + fi + # The runner's fullsend may predate --only-if-exists (it is pinned by the + # repository's fullsend-ref, not by the CLI that generated this script). + # Detect the flag instead of assuming it: on an older CLI, keep the old + # behaviour — post nothing — rather than fail the common ok path. + # grep reads the whole help text (no -q): an early exit could SIGPIPE + # fullsend and, under pipefail, read as "flag missing". + if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; 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 + printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ + | fullsend issues post-comment \ + --tracker github \ + --project "${REPO}" \ + --number "${NUMBER}" \ + --marker "${MARKER}" \ + --only-if-exists \ + --result - + exit 0 +fi + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then # The preview prints model output. Under GitHub Actions a line starting # with "::" is a workflow command (the runner even trims leading spaces @@ -294,8 +325,8 @@ if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then fi # fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and edits it in place, so -# re-runs do not flood the work item. +# 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. 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 52032e6623..ced05cce7c 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -271,11 +271,6 @@ if (( ${#comment} > MAX_COMMENT_CHARS )); then comment="${comment:0:${keep}}${TRUNCATION_MARKER}" fi -if [[ "${status}" == "ok" ]]; then - echo "post-lint-docs: status=ok, nothing to post" >&2 - exit 0 -fi - # Derive the repo and number from the work item URL rather than trusting extra # environment. The pattern also rejects anything that is not a github.com URL. url_re='^https://github[.]com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)/(issues|pull)/([0-9]+)$' @@ -286,6 +281,42 @@ 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. +if [[ "${status}" == "ok" ]]; then + if [[ "${POST_LINT_DOCS_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 + exit 0 + fi + # The runner's fullsend may predate --only-if-exists (it is pinned by the + # repository's fullsend-ref, not by the CLI that generated this script). + # Detect the flag instead of assuming it: on an older CLI, keep the old + # behaviour — post nothing — rather than fail the common ok path. + # grep reads the whole help text (no -q): an early exit could SIGPIPE + # fullsend and, under pipefail, read as "flag missing". + if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; 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 + printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ + | fullsend issues post-comment \ + --tracker github \ + --project "${REPO}" \ + --number "${NUMBER}" \ + --marker "${MARKER}" \ + --only-if-exists \ + --result - + exit 0 +fi + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then # The preview prints model output. Under GitHub Actions a line starting # with "::" is a workflow command (the runner even trims leading spaces @@ -302,8 +333,8 @@ if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then fi # fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and edits it in place, so -# re-runs do not flood the work item. +# 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. 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 04434b5599..ef12293c33 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -170,17 +170,18 @@ func runIssuesGet(ctx context.Context, cfg *issuesGetConfig) error { // issuesPostCommentConfig holds the flags and test overrides for // "fullsend issues post-comment". type issuesPostCommentConfig struct { - trackerName string - project string - number int - marker string - result string - token string - jiraURL string - jiraEmail string - dryRun bool - keepHistory *bool // nil = resolve from config; non-nil = explicit flag - fullsendDir string + trackerName string + project string + number int + marker string + result string + token string + jiraURL string + jiraEmail string + dryRun bool + onlyIfExists bool + keepHistory *bool // nil = resolve from config; non-nil = explicit flag + fullsendDir string // Test overrides — when non-nil, used instead of creating a real // tracker client. Not set by CLI flag parsing. @@ -242,6 +243,7 @@ The --result flag accepts a file path or "-" for stdin.`, cmd.Flags().StringVar(&cfg.jiraURL, "jira-url", "", "Jira instance URL (default: $JIRA_BASE_URL)") cmd.Flags().StringVar(&cfg.jiraEmail, "jira-email", "", "Jira user email for Basic auth (default: $JIRA_USER_EMAIL)") 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().StringVar(&cfg.fullsendDir, "fullsend-dir", "", "path to .fullsend config directory (sources defaults from its config.yaml when flags are omitted)") _ = cmd.MarkFlagRequired("project") @@ -293,9 +295,10 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err } stickyCfg := sticky.Config{ - Marker: cfg.marker, - DryRun: cfg.dryRun, - KeepHistory: keepHistory, + Marker: cfg.marker, + DryRun: cfg.dryRun, + KeepHistory: keepHistory, + OnlyIfExists: cfg.onlyIfExists, } if trackerName == trackerJira { // The Jira write path routes every body through @@ -383,6 +386,11 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project return "", nil // Jira has no stable comment permalink } + if cfg.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") if cfg.DryRun { @@ -408,7 +416,8 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project // 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. +// (after a short retry) it returns an error and posts nothing, with or +// without OnlyIfExists. func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project string, number int, body string, cfg sticky.Config, printer *ui.Printer) (string, error) { if strings.TrimSpace(body) == "" { return "", fmt.Errorf("comment body is empty") @@ -451,6 +460,11 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return existing.HTMLURL, nil } + if cfg.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") if cfg.DryRun { diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 5ab1c757c4..5b6b4b7c5c 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -1015,6 +1015,90 @@ func TestIssuesPostCommentCmd_TrackerNotRequired(t *testing.T) { assert.Contains(t, err.Error(), "--tracker is required") } +func TestRunIssuesPostComment_OnlyIfExists_SkipsCreate(t *testing.T) { + fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" + tc := tracker.NewForgeClient(fc) + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: "", + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + + require.NoError(t, runIssuesPostComment(context.Background(), cfg)) + + comments, err := tc.ListComments(context.Background(), "acme/widgets", 42) + require.NoError(t, err) + assert.Empty(t, comments, "only-if-exists must not create a first comment") +} + +func TestRunIssuesPostComment_OnlyIfExists_ReplacesEarlierFindings(t *testing.T) { + fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" + tc := tracker.NewForgeClient(fc) + ctx := context.Background() + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: "", + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "2 broken links", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + cfg.onlyIfExists = true + cfg.testBody = "all clear" + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + 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") +} + +func TestRunIssuesPostComment_Jira_OnlyIfExists(t *testing.T) { + tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") + require.NoError(t, err) + ctx := context.Background() + + cfg := &issuesPostCommentConfig{ + trackerName: trackerJira, + project: "PROJ", + number: 42, + marker: "", + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + // No earlier comment: nothing is created. + require.NoError(t, runIssuesPostComment(ctx, cfg)) + comments, err := tc.ListComments(ctx, "PROJ", 42) + require.NoError(t, err) + assert.Empty(t, comments) + + // An earlier findings comment exists: it is replaced. + cfg.onlyIfExists = false + cfg.testBody = "2 broken links" + require.NoError(t, runIssuesPostComment(ctx, cfg)) + cfg.onlyIfExists = true + cfg.testBody = "all clear" + 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") +} + // fastSelfLookup shortens the identity-lookup retry backoff for a test. func fastSelfLookup(t *testing.T) { t.Helper() @@ -1045,7 +1129,7 @@ const testBot = "fullsend-ai-review[bot]" // post-comment as testBot through tc (a *flakySelfClient wrapping fc, so the // identity lookup can be made to fail). It returns the run's error and the // comments afterwards. -func postAfterCommentBy(t *testing.T, author string, failures int) (error, []tracker.Comment, *flakySelfClient) { +func postAfterCommentBy(t *testing.T, author string, onlyIfExists bool, failures int) (error, []tracker.Comment, *flakySelfClient) { t.Helper() fastSelfLookup(t) ctx := context.Background() @@ -1059,13 +1143,14 @@ func postAfterCommentBy(t *testing.T, author string, failures int) (error, []tra fc.AuthenticatedUser = testBot cfg := &issuesPostCommentConfig{ - trackerName: trackerGitHub, - project: "acme/widgets", - number: 42, - marker: marker, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "new result", + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + onlyIfExists: onlyIfExists, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "new result", } runErr := runIssuesPostComment(ctx, cfg) @@ -1075,10 +1160,14 @@ func postAfterCommentBy(t *testing.T, author string, failures int) (error, []tra } func TestRunIssuesPostComment_EditsOwnComment(t *testing.T) { - err, comments, _ := postAfterCommentBy(t, testBot, 0) - require.NoError(t, err) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "new result") + 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") + }) + } } func TestRunIssuesPostComment_IgnoresPlantedMarker(t *testing.T) { @@ -1087,17 +1176,24 @@ func TestRunIssuesPostComment_IgnoresPlantedMarker(t *testing.T) { // must not match. for _, author := range []string{"mallory", "evil-review[bot]", "fullsend-ai-review", "x-fullsend-ai-review[bot]"} { t.Run(author, func(t *testing.T) { - err, comments, _ := postAfterCommentBy(t, author, 0) + // Normal path: the planted comment is left alone, a new one posted. + err, comments, _ := postAfterCommentBy(t, author, false, 0) require.NoError(t, err) - require.Len(t, comments, 2, "the planted comment is left alone and a new one posted") + require.Len(t, comments, 2) assert.NotContains(t, string(comments[0].Body), "new result") assert.Contains(t, string(comments[1].Body), "new result") + + // --only-if-exists: neither edited nor created. + err, comments, _ = postAfterCommentBy(t, author, true, 0) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.NotContains(t, string(comments[0].Body), "new result") }) } } func TestRunIssuesPostComment_TransientSelfFailureRetriesThenEdits(t *testing.T) { - err, comments, tc := postAfterCommentBy(t, testBot, len(selfLookupBackoff)) + err, comments, tc := postAfterCommentBy(t, testBot, false, 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") @@ -1105,14 +1201,18 @@ func TestRunIssuesPostComment_TransientSelfFailureRetriesThenEdits(t *testing.T) } func TestRunIssuesPostComment_PersistentSelfFailureErrorsAndPostsNothing(t *testing.T) { - err, comments, tc := postAfterCommentBy(t, testBot, 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") + 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") + }) + } } func TestRunIssuesPostComment_EmptySelfErrors(t *testing.T) { @@ -1125,25 +1225,62 @@ func TestRunIssuesPostComment_EmptySelfErrors(t *testing.T) { _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nauthorless")) require.NoError(t, err) - cfg := &issuesPostCommentConfig{ - trackerName: trackerGitHub, - project: "acme/widgets", - number: 42, - marker: marker, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "new result", + 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") } - 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) assert.NotContains(t, string(comments[0].Body), "new result") } +func TestRunIssuesPostComment_OnlyIfExists_SkipsPlantedCommentBeforeOwn(t *testing.T) { + // The realistic attack order: a planted marker comment listed first, the + // poster's own comment second. The planted one is skipped, the own one + // updated. + ctx := context.Background() + fc := forge.NewFakeClient() + tc := tracker.NewForgeClient(fc) + const marker = "" + + fc.AuthenticatedUser = "mallory" + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nplanted")) + require.NoError(t, err) + fc.AuthenticatedUser = testBot + _, err = tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\n2 broken links")) + require.NoError(t, err) + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + 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") +} + func TestResolveTrackerSelf_StopsRetryingWhenCancelled(t *testing.T) { saved := selfLookupBackoff selfLookupBackoff = []time.Duration{time.Hour, time.Hour} @@ -1283,3 +1420,35 @@ func TestRunIssuesPostComment_DryRunStillVerifiesIdentity(t *testing.T) { }) } } + +func TestRunIssuesPostComment_Jira_OnlyIfExistsIgnoresPlantedMarker(t *testing.T) { + // The all-clear must not land on a comment whose marker property another + // account set, and must not create one either. + fastSelfLookup(t) + ctx := context.Background() + tc, fc, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") + require.NoError(t, err) + const marker = "" + + fc.Myself = jira.User{AccountID: "mallory-account-id", DisplayName: tracker.FakeJiraBot.DisplayName} + _, err = tc.CreateCommentWithMarker(ctx, "PROJ", 42, tracker.Body("planted findings"), marker) + require.NoError(t, err) + fc.Myself = tracker.FakeJiraBot + + cfg := &issuesPostCommentConfig{ + trackerName: trackerJira, + project: "PROJ", + number: 42, + marker: marker, + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + comments, err := tc.ListComments(ctx, "PROJ", 42) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.NotContains(t, string(comments[0].Body), "all clear") +} diff --git a/internal/sticky/sticky.go b/internal/sticky/sticky.go index 0b0a014862..152020bb9f 100644 --- a/internal/sticky/sticky.go +++ b/internal/sticky/sticky.go @@ -21,6 +21,12 @@ type Config struct { 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 + // OnlyIfExists updates an existing marked comment but never creates one: + // a post-script uses it on an all-clear result so an earlier findings + // comment is replaced while a clean first run stays silent. It is + // honoured by `fullsend issues post-comment` (internal/cli), which also + // verifies the comment author; Post here does not read it. + OnlyIfExists bool } func (c Config) maxSize() int { From 2254225564cc9314534949dc59c261f745dde107 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 1 Oct 2026 11:49:08 -0400 Subject: [PATCH 2/4] fix(#6966)!: fail on a broken fullsend, replace in place, keep --only-if-exists in cli - The generated ok path now fails when `fullsend issues post-comment --help` itself fails (fullsend missing or broken): that is a broken runner, not an older CLI. Only a working CLI without the flag still posts nothing. Capturing the help text also removes the grep pipeline. - The ok call passes --keep-history=false, so the all-clear replaces the comment in place and repeated clean runs do not stack identical "Previous run" blocks. - onlyIfExists is a parameter of the CLI's post functions instead of a sticky.Config field that sticky.Post never read; internal/sticky is unchanged. BREAKING CHANGE: a regenerated post-script now fails the run on a status ok result when fullsend is missing, its --help fails, the posting identity cannot be resolved, or the post fails; previously the ok branch always exited 0. Existing generated scripts are unchanged until regenerated. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- internal/agentnew/postscript_exec_test.go | 35 ++++++++++- internal/agentnew/templates/post.sh.tmpl | 18 ++++-- internal/agentnew/testdata/golden/triage.txt | 18 ++++-- .../testdata/golden/validation-loop.txt | 18 ++++-- internal/cli/issues.go | 22 +++---- internal/cli/issues_test.go | 62 +++++++++++++++---- internal/sticky/sticky.go | 6 -- 7 files changed, 133 insertions(+), 46 deletions(-) diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index 54dcbf346f..aed3c67b8f 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -202,7 +202,7 @@ func TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists(t *testing. t.Fatalf("the script never invoked fullsend on the ok path: %v; stderr:\n%s", err, stderr.String()) } args := string(got) - for _, want := range []string{"issues\npost-comment\n", "--only-if-exists\n", "--marker\n", "fullsend-ai/demo\n", "99\n"} { + for _, want := range []string{"issues\npost-comment\n", "--only-if-exists\n", "--keep-history=false\n", "--marker\n", "fullsend-ai/demo\n", "99\n"} { if !strings.Contains(args, want) { t.Errorf("fullsend was called without %q; args:\n%s", strings.TrimSpace(want), args) } @@ -277,3 +277,36 @@ func TestGeneratedPostScriptOkFailsWhenThePostFails(t *testing.T) { t.Fatal("ok must fail when fullsend issues post-comment fails") } } + +// TestGeneratedPostScriptOkFailsWhenFullsendHelpFails pins that a broken +// runner is not mistaken for an older CLI: a fullsend that is missing or +// whose --help fails must fail the ok path, not silently post nothing. +func TestGeneratedPostScriptOkFailsWhenFullsendHelpFails(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + binDir := t.TempDir() + stub := "#!/usr/bin/env bash\necho 'error: unable to load config' >&2\nexit 2\n" + if err := os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + cmd := exec.Command("bash", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH"), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + ) + var stderr strings.Builder + cmd.Stderr = &stderr + if err := cmd.Run(); err == nil { + t.Fatalf("ok must fail when fullsend --help fails; stderr:\n%s", stderr.String()) + } + if !strings.Contains(stderr.String(), "unable to load config") { + t.Fatalf("expected fullsend's own error in the log, got:\n%s", stderr.String()) + } +} diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index f54c30388d..ee2a089efa 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -138,14 +138,21 @@ if [[ "${status}" == "ok" ]]; then fi # The runner's fullsend may predate --only-if-exists (it is pinned by the # repository's fullsend-ref, not by the CLI that generated this script). - # Detect the flag instead of assuming it: on an older CLI, keep the old - # behaviour — post nothing — rather than fail the common ok path. - # grep reads the whole help text (no -q): an early exit could SIGPIPE - # fullsend and, under pipefail, read as "flag missing". - if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; then + # Detect the flag instead of assuming it. A fullsend that is missing or + # whose --help fails is a broken runner, not an older CLI: fail the run. + # 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' "${help_text}" >&2 + exit 1 + fi + if [[ "${help_text}" != *--only-if-exists* ]]; 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. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ @@ -153,6 +160,7 @@ if [[ "${status}" == "ok" ]]; then --number "${NUMBER}" \ --marker "${MARKER}" \ --only-if-exists \ + --keep-history=false \ --result - exit 0 fi diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index 1f21814453..11341920bf 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -290,14 +290,21 @@ if [[ "${status}" == "ok" ]]; then fi # The runner's fullsend may predate --only-if-exists (it is pinned by the # repository's fullsend-ref, not by the CLI that generated this script). - # Detect the flag instead of assuming it: on an older CLI, keep the old - # behaviour — post nothing — rather than fail the common ok path. - # grep reads the whole help text (no -q): an early exit could SIGPIPE - # fullsend and, under pipefail, read as "flag missing". - if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; then + # Detect the flag instead of assuming it. A fullsend that is missing or + # whose --help fails is a broken runner, not an older CLI: fail the run. + # 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' "${help_text}" >&2 + exit 1 + fi + if [[ "${help_text}" != *--only-if-exists* ]]; 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. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ @@ -305,6 +312,7 @@ if [[ "${status}" == "ok" ]]; then --number "${NUMBER}" \ --marker "${MARKER}" \ --only-if-exists \ + --keep-history=false \ --result - exit 0 fi diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index ced05cce7c..a78b499f8c 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -298,14 +298,21 @@ if [[ "${status}" == "ok" ]]; then fi # The runner's fullsend may predate --only-if-exists (it is pinned by the # repository's fullsend-ref, not by the CLI that generated this script). - # Detect the flag instead of assuming it: on an older CLI, keep the old - # behaviour — post nothing — rather than fail the common ok path. - # grep reads the whole help text (no -q): an early exit could SIGPIPE - # fullsend and, under pipefail, read as "flag missing". - if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; then + # Detect the flag instead of assuming it. A fullsend that is missing or + # whose --help fails is a broken runner, not an older CLI: fail the run. + # 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' "${help_text}" >&2 + exit 1 + fi + if [[ "${help_text}" != *--only-if-exists* ]]; 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. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ @@ -313,6 +320,7 @@ if [[ "${status}" == "ok" ]]; then --number "${NUMBER}" \ --marker "${MARKER}" \ --only-if-exists \ + --keep-history=false \ --result - exit 0 fi diff --git a/internal/cli/issues.go b/internal/cli/issues.go index ef12293c33..15871bcbf9 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -295,10 +295,9 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err } stickyCfg := sticky.Config{ - Marker: cfg.marker, - DryRun: cfg.dryRun, - KeepHistory: keepHistory, - OnlyIfExists: cfg.onlyIfExists, + Marker: cfg.marker, + DryRun: cfg.dryRun, + KeepHistory: keepHistory, } if trackerName == trackerJira { // The Jira write path routes every body through @@ -319,9 +318,9 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err // path; otherwise fall back to the body-embedded path used by // GitHub/GitLab. if jc, ok := tc.(*tracker.JiraClient); ok { - _, err = postJiraStickyComment(ctx, jc, cfg.project, cfg.number, body, stickyCfg, printer) + _, err = postJiraStickyComment(ctx, jc, cfg.project, cfg.number, body, stickyCfg, cfg.onlyIfExists, printer) } else { - _, err = postTrackerStickyComment(ctx, tc, cfg.project, cfg.number, body, stickyCfg, printer) + _, err = postTrackerStickyComment(ctx, tc, cfg.project, cfg.number, body, stickyCfg, cfg.onlyIfExists, printer) } return err } @@ -336,7 +335,7 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err // with ?expand=properties and matched by property value. On update, the // property is (re)set to handle legacy migration from body-embedded // markers. -func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project string, number int, body string, cfg sticky.Config, printer *ui.Printer) (string, error) { +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") } @@ -386,7 +385,7 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project return "", nil // Jira has no stable comment permalink } - if cfg.OnlyIfExists { + if onlyIfExists { printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") return "", nil } @@ -417,8 +416,9 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project // 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. -func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project string, number int, body string, cfg sticky.Config, printer *ui.Printer) (string, error) { +// without onlyIfExists, which updates an existing comment but never +// creates one. +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") } @@ -460,7 +460,7 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return existing.HTMLURL, nil } - if cfg.OnlyIfExists { + if onlyIfExists { printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") return "", nil } diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 5b6b4b7c5c..057d60060b 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -114,7 +114,7 @@ func TestPostTrackerStickyComment_Create(t *testing.T) { printer := ui.New(io.Discard) cfg := sticky.Config{Marker: "", KeepHistory: true} - url, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "hello world", cfg, printer) + url, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "hello world", cfg, false, printer) require.NoError(t, err) assert.NotEmpty(t, url) @@ -136,11 +136,11 @@ func TestPostTrackerStickyComment_Update(t *testing.T) { ctx := context.Background() // First post creates the comment. - _, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "first run", cfg, printer) + _, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "first run", cfg, false, printer) require.NoError(t, err) // Second post updates in-place. - _, err = postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "second run", cfg, printer) + _, err = postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "second run", cfg, false, printer) require.NoError(t, err) // Verify only one comment exists (updated, not duplicated). @@ -157,7 +157,7 @@ func TestPostTrackerStickyComment_EmptyBody(t *testing.T) { printer := ui.New(io.Discard) cfg := sticky.Config{Marker: "", KeepHistory: true} - _, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "", cfg, printer) + _, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "", cfg, false, printer) assert.Error(t, err) assert.Contains(t, err.Error(), "comment body is empty") } @@ -168,7 +168,7 @@ func TestPostTrackerStickyComment_EmptyMarker(t *testing.T) { printer := ui.New(io.Discard) cfg := sticky.Config{Marker: "", KeepHistory: true} - _, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "hello", cfg, printer) + _, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "hello", cfg, false, printer) assert.Error(t, err) assert.Contains(t, err.Error(), "marker is empty") } @@ -180,7 +180,7 @@ func TestPostTrackerStickyComment_DryRun_Create(t *testing.T) { printer := ui.New(io.Discard) cfg := sticky.Config{Marker: "", DryRun: true, KeepHistory: true} - url, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "hello", cfg, printer) + url, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "hello", cfg, false, printer) require.NoError(t, err) assert.Empty(t, url) // dry run returns empty URL @@ -199,12 +199,12 @@ func TestPostTrackerStickyComment_DryRun_Update(t *testing.T) { ctx := context.Background() // Create the initial comment (not dry run). - _, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "first", cfg, printer) + _, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "first", cfg, false, printer) require.NoError(t, err) // Dry run update should not modify the comment. cfg.DryRun = true - url, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "second", cfg, printer) + url, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, "second", cfg, false, printer) require.NoError(t, err) assert.Empty(t, url) @@ -721,7 +721,7 @@ func TestPostJiraStickyComment_DryRun_Create(t *testing.T) { printer := ui.New(io.Discard) cfg := sticky.Config{Marker: "", DryRun: true, KeepHistory: true} - url, err := postJiraStickyComment(context.Background(), tc, "PROJ", 42, "hello", cfg, printer) + url, err := postJiraStickyComment(context.Background(), tc, "PROJ", 42, "hello", cfg, false, printer) require.NoError(t, err) assert.Empty(t, url) @@ -740,12 +740,12 @@ func TestPostJiraStickyComment_DryRun_Update(t *testing.T) { ctx := context.Background() // Create the initial comment (not dry run). - _, err = postJiraStickyComment(ctx, tc, "PROJ", 42, "first", cfg, printer) + _, err = postJiraStickyComment(ctx, tc, "PROJ", 42, "first", cfg, false, printer) require.NoError(t, err) // Dry run update should not modify the comment. cfg.DryRun = true - url, err := postJiraStickyComment(ctx, tc, "PROJ", 42, "second", cfg, printer) + url, err := postJiraStickyComment(ctx, tc, "PROJ", 42, "second", cfg, false, printer) require.NoError(t, err) assert.Empty(t, url) @@ -761,7 +761,7 @@ func TestPostJiraStickyComment_EmptyBody(t *testing.T) { printer := ui.New(io.Discard) cfg := sticky.Config{Marker: "", KeepHistory: true} - _, err = postJiraStickyComment(context.Background(), tc, "PROJ", 42, " ", cfg, printer) + _, err = postJiraStickyComment(context.Background(), tc, "PROJ", 42, " ", cfg, false, printer) require.Error(t, err) assert.Contains(t, err.Error(), "comment body is empty") } @@ -772,7 +772,7 @@ func TestPostJiraStickyComment_EmptyMarker(t *testing.T) { printer := ui.New(io.Discard) cfg := sticky.Config{Marker: " ", KeepHistory: true} - _, err = postJiraStickyComment(context.Background(), tc, "PROJ", 42, "body", cfg, printer) + _, err = postJiraStickyComment(context.Background(), tc, "PROJ", 42, "body", cfg, false, printer) require.Error(t, err) assert.Contains(t, err.Error(), "marker is empty") } @@ -1452,3 +1452,39 @@ func TestRunIssuesPostComment_Jira_OnlyIfExistsIgnoresPlantedMarker(t *testing.T require.Len(t, comments, 1) 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. + ctx := context.Background() + fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" + tc := tracker.NewForgeClient(fc) + noHistory := false + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: "", + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "2 broken links", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + cfg.onlyIfExists = true + cfg.keepHistory = &noHistory + cfg.testBody = "all clear" + for i := 0; i < 3; i++ { + require.NoError(t, runIssuesPostComment(ctx, cfg)) + } + + 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") +} diff --git a/internal/sticky/sticky.go b/internal/sticky/sticky.go index 152020bb9f..0b0a014862 100644 --- a/internal/sticky/sticky.go +++ b/internal/sticky/sticky.go @@ -21,12 +21,6 @@ type Config struct { 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 - // OnlyIfExists updates an existing marked comment but never creates one: - // a post-script uses it on an all-clear result so an earlier findings - // comment is replaced while a clean first run stays silent. It is - // honoured by `fullsend issues post-comment` (internal/cli), which also - // verifies the comment author; Post here does not read it. - OnlyIfExists bool } func (c Config) maxSize() int { From e7e485ea8c6905f9eb198b4cb0756f008a4370bf Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 1 Oct 2026 12:38:56 -0400 Subject: [PATCH 3/4] test(#6966): pin that an ok result with a non-GitHub ISSUE_URL fails The ok path runs after the ISSUE_URL check, so an ok result is validated like any other. Moving the ok block back above the check fails the test. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- internal/agentnew/postscript_exec_test.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index aed3c67b8f..b615b7bc71 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -310,3 +310,23 @@ func TestGeneratedPostScriptOkFailsWhenFullsendHelpFails(t *testing.T) { t.Fatalf("expected fullsend's own error in the log, got:\n%s", stderr.String()) } } + +// TestGeneratedPostScriptOkRejectsANonGitHubIssueURL pins that an ok result +// is validated like any other: the ok path runs after the ISSUE_URL check, +// so a non-GitHub work-item URL fails the run instead of exiting 0 unseen. +func TestGeneratedPostScriptOkRejectsANonGitHubIssueURL(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + _, stderr, err := runPostScript(t, script, runDir, "ISSUE_URL=https://evil.example.com/fullsend-ai/demo/pull/99") + if err == nil { + t.Fatalf("ok with a non-GitHub ISSUE_URL must fail; stderr:\n%s", stderr) + } + if !strings.Contains(stderr, "ISSUE_URL is not a GitHub issue or pull request URL") { + t.Fatalf("expected the ISSUE_URL rejection, got:\n%s", stderr) + } +} From 93f9b47d0b699b690f54a699fe942fcc0b0bf4f6 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 1 Oct 2026 13:10:11 -0400 Subject: [PATCH 4/4] test(#6966): pin the --only-if-exists flag's registration and default Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- internal/cli/issues_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 057d60060b..ba4aae938c 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -72,6 +72,10 @@ func TestNewIssuesPostCommentCmd_DefaultFlags(t *testing.T) { dryRun := cmd.Flags().Lookup("dry-run") require.NotNil(t, dryRun) assert.Equal(t, "false", dryRun.DefValue) + + onlyIfExists := cmd.Flags().Lookup("only-if-exists") + require.NotNil(t, onlyIfExists) + assert.Equal(t, "false", onlyIfExists.DefValue) } func TestFindMarkedTrackerComment(t *testing.T) {