diff --git a/docs/agents/review.md b/docs/agents/review.md index 4a2719b620..bc4e9d6696 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. @@ -38,7 +38,7 @@ write or higher. The `/fs-review` command does not accept arguments and always forces a review. The review agent also runs automatically on a same-repository PR when it is opened, when its effective diff changes on a synchronize event, or when it is moved out of draft by a user with triage-level repository permission or higher. On GitHub, a fork PR is reviewed automatically under the same rules (a bot author is checked like any other author), through the managed `fullsend-fork-pr.yaml` workflow (see [Fork pull requests](../guides/getting-started/repo-management.md#fork-pull-requests)); the `ready-for-review` label does not start a fork PR review. Dependabot PRs are not reviewed automatically. On either, someone with triage access or higher (or an OWNERS approver or reviewer) can comment `/fs-review`. -For GitHub `pull_request` synchronize events (and `pull_request_target` from shims that have not been upgraded), the review is skipped when the complete effective diff matches the previous app-verified approved review. The guard posts or updates one PR-visible `fullsend:review-skip` status comment linking the previous approved review. GitLab diff metadata uses the same normalized model, but the GitLab poller does not consume this marker yet and continues to review synchronized merge requests. +For GitHub `pull_request` synchronize events (and `pull_request_target` from shims that have not been upgraded), the review is skipped when the complete effective diff matches the previous app-verified approved review. The guard posts a new PR-visible `fullsend:review-skip` status comment for each skip, linking the previous approved review, and never edits an earlier skip note in place on that publish path; a later full review supersedes each skip note once, in place, naming the commit that superseded it. GitLab diff metadata uses the same normalized model, but the GitLab poller does not consume this marker yet and continues to review synchronized merge requests. The deduplication check runs before final Bash/CEL stage selection, so CEL-selected review routes participate as well. File modes are part of the compared effective diff identity, so executable-bit changes cannot be hidden by an otherwise identical textual patch. The guard fails open and runs the review when there is no prior diff hash, the prior review cannot be verified, a required hash/head or base/head tree-mode API call fails, the file listing is incomplete or truncated, or any file has no representable patch (for example, a binary or rename-only change). 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..1fcac13128 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -424,6 +424,11 @@ 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 +382,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..688d827a61 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -532,11 +532,15 @@ 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), so a retried job posts a second copy of the comments its first + attempt already posted. The code-stage update and the triage comments use + fixed or run-scoped markers (`GITHUB_RUN_ID` or `CI_PIPELINE_ID`); the + run-scoped ones exist so a retried run can recognize its own earlier + comment, which find-and-edit turned into an update instead of a + duplicate. 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 +1748,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` 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..3ce0a39fd5 --- /dev/null +++ b/e2e/behaviour/features/triage/triage-re-run-append.feature @@ -0,0 +1,32 @@ +# 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 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." + And no comment on the issue contains "Previous run" 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/e2e/behaviour/github-emulator/shards.txt b/e2e/behaviour/github-emulator/shards.txt index d286b46a5e..6ccca8b9c5 100644 --- a/e2e/behaviour/github-emulator/shards.txt +++ b/e2e/behaviour/github-emulator/shards.txt @@ -12,7 +12,7 @@ d 2 4 features/dispatch/review-cel-route.feature:13 features/runtime/skill-overr e 2 4 features/dispatch/fork-bash-routing.feature:16 features/dispatch/dispatch.feature:68 features/platform/actor-authorization.feature:82 features/dispatch/fetch-allowlist-gate.feature:25 f 2 4 features/dispatch/owners-auth.feature:43 features/dispatch/base-dispatch.feature:7 features/dispatch/reaction-notifications.feature:10 features/dispatch/runner-secret-overlay-guard.feature:54 g 2 4 features/platform/bot-actor-authorization.feature:163 features/dispatch/fork-dispatch.feature:134 features/dispatch/url-dispatch.feature:64 features/dispatch/runner-secret-overlay-guard.feature:23 -h 2 4 features/code/branch-namespace.feature:31 features/triage/triage.feature:6 features/runtime/agent-settings.feature:13 features/dispatch/owners-auth.feature:55 +h 2 4 features/code/branch-namespace.feature:31 features/triage/triage.feature:6 features/triage/triage-re-run-append.feature:14 features/runtime/agent-settings.feature:13 features/dispatch/owners-auth.feature:55 i 2 4 features/dispatch/triage-prioritize-cel-route.feature:13 features/platform/actor-authorization.feature:55 features/platform/mint-status.feature:32 j 2 4 features/dispatch/retro-cel-route.feature:13 features/dispatch/dispatch.feature:31 features/dispatch/triage-prioritize-cel-route.feature:36 features/dispatch/retro-cel-route.feature:57 features/dispatch/jira-transport-bounds.feature:48 k 2 4 features/dispatch/fork-dispatch.feature:17 features/dispatch/dispatch.feature:6 features/dispatch/url-dispatch.feature:7 features/dispatch/retro-cel-route.feature:38 features/dispatch/jira-transport-bounds.feature:34 features/dispatch/jira-poll-dispatch.feature:40 diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index 5c0dd95f69..4360a0a9fb 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -166,18 +166,23 @@ func TestGeneratedPostScriptOkDryRunPostsNothing(t *testing.T) { } } -// 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 +// TestGeneratedPostScriptOkAppendsViaOnlyIfExists 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) { +// rather than reimplementing it with raw API calls in shell — and with +// this change's CLI the all-clear that follows is appended as a new +// comment (only a runner pinned between #6966 and this change still +// replaces in place). The stub's --help lists both --only-if-exists and +// --keep-history, a CLI of this change's generation: the deprecated flag +// is still listed, so it is passed (a pinned runner honours it). +func TestGeneratedPostScriptOkAppendsViaOnlyIfExists(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" + stub := "#!/usr/bin/env bash\nif [[ \"$*\" == *--help* ]]; then echo ' --only-if-exists update an existing comment but never create one'; echo ' --keep-history append previous content as collapsed history blocks'; 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) } @@ -209,6 +214,56 @@ func TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists(t *testing. } } +// TestGeneratedPostScriptOkWithoutKeepHistoryFlagStillPosts pins the +// forward-compatibility path: the generated script is rendered once into +// each repository and never regenerated, so a runner's CLI whose +// post-command has removed --keep-history (the cleanup #9517 schedules) +// must still get the all-clear posted. The script probes --help and passes +// the flag only when the CLI lists it. +func TestGeneratedPostScriptOkWithoutKeepHistoryFlagStillPosts(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") + // A post-cleanup CLI: --help lists --only-if-exists but no + // --keep-history, and any real call with the removed flag would fail — + // so the stub fails loudly if invoked with it. + stub := "#!/usr/bin/env bash\nif [[ \"$*\" == *--help* ]]; then echo ' --only-if-exists update an existing comment but never create one'; exit 0; fi\nif [[ \"$*\" == *--keep-history* ]]; then echo 'Error: unknown flag: --keep-history' >&2; exit 1; 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 on a CLI without --keep-history 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) + } + } + if strings.Contains(args, "--keep-history") { + t.Errorf("fullsend was called with the removed --keep-history flag; args:\n%s", 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 diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index 13ce33bca4..df64c0eadc 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,13 +172,25 @@ 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 is passed only + # when the runner's CLI still lists it: a fullsend pinned between #6966 + # and this change honours it (the all-clear replaces the earlier + # findings comment instead of stacking collapsed history blocks), while + # a CLI that has removed the flag must never see it — this script is + # rendered once into each repository and never regenerated, and an + # unknown flag would fail the run under `set -euo pipefail`. 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' - # shellcheck disable=SC2059 + keep_history_args='' + if [[ "${help_text}" == *--keep-history* ]]; then + keep_history_args='--keep-history=false' + fi + # shellcheck disable=SC2059,SC2086 + # (SC2086: an empty keep_history_args passes no flag at all) printf "${body_format}" "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ @@ -182,7 +198,7 @@ if [[ "${status}" == "ok" ]]; then --number "${NUMBER}" \ --marker "${MARKER}" \ --only-if-exists \ - --keep-history=false \ + ${keep_history_args} \ --result - exit 0 fi @@ -202,9 +218,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..016111f4aa 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,13 +323,25 @@ 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 is passed only + # when the runner's CLI still lists it: a fullsend pinned between #6966 + # and this change honours it (the all-clear replaces the earlier + # findings comment instead of stacking collapsed history blocks), while + # a CLI that has removed the flag must never see it — this script is + # rendered once into each repository and never regenerated, and an + # unknown flag would fail the run under `set -euo pipefail`. 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' - # shellcheck disable=SC2059 + keep_history_args='' + if [[ "${help_text}" == *--keep-history* ]]; then + keep_history_args='--keep-history=false' + fi + # shellcheck disable=SC2059,SC2086 + # (SC2086: an empty keep_history_args passes no flag at all) printf "${body_format}" "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ @@ -333,7 +349,7 @@ if [[ "${status}" == "ok" ]]; then --number "${NUMBER}" \ --marker "${MARKER}" \ --only-if-exists \ - --keep-history=false \ + ${keep_history_args} \ --result - exit 0 fi @@ -353,9 +369,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..5530721204 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,13 +341,25 @@ 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 is passed only + # when the runner's CLI still lists it: a fullsend pinned between #6966 + # and this change honours it (the all-clear replaces the earlier + # findings comment instead of stacking collapsed history blocks), while + # a CLI that has removed the flag must never see it — this script is + # rendered once into each repository and never regenerated, and an + # unknown flag would fail the run under `set -euo pipefail`. 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' - # shellcheck disable=SC2059 + keep_history_args='' + if [[ "${help_text}" == *--keep-history* ]]; then + keep_history_args='--keep-history=false' + fi + # shellcheck disable=SC2059,SC2086 + # (SC2086: an empty keep_history_args passes no flag at all) printf "${body_format}" "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ @@ -351,7 +367,7 @@ if [[ "${status}" == "ok" ]]; then --number "${NUMBER}" \ --marker "${MARKER}" \ --only-if-exists \ - --keep-history=false \ + ${keep_history_args} \ --result - exit 0 fi @@ -371,9 +387,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..4d1d70a7ba 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,13 +335,25 @@ 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 is passed only + # when the runner's CLI still lists it: a fullsend pinned between #6966 + # and this change honours it (the all-clear replaces the earlier + # findings comment instead of stacking collapsed history blocks), while + # a CLI that has removed the flag must never see it — this script is + # rendered once into each repository and never regenerated, and an + # unknown flag would fail the run under `set -euo pipefail`. 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' - # shellcheck disable=SC2059 + keep_history_args='' + if [[ "${help_text}" == *--keep-history* ]]; then + keep_history_args='--keep-history=false' + fi + # shellcheck disable=SC2059,SC2086 + # (SC2086: an empty keep_history_args passes no flag at all) printf "${body_format}" "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ @@ -345,7 +361,7 @@ if [[ "${status}" == "ok" ]]; then --number "${NUMBER}" \ --marker "${MARKER}" \ --only-if-exists \ - --keep-history=false \ + ${keep_history_args} \ --result - exit 0 fi @@ -365,9 +381,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..54dd968615 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,13 +343,25 @@ 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 is passed only + # when the runner's CLI still lists it: a fullsend pinned between #6966 + # and this change honours it (the all-clear replaces the earlier + # findings comment instead of stacking collapsed history blocks), while + # a CLI that has removed the flag must never see it — this script is + # rendered once into each repository and never regenerated, and an + # unknown flag would fail the run under `set -euo pipefail`. 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' - # shellcheck disable=SC2059 + keep_history_args='' + if [[ "${help_text}" == *--keep-history* ]]; then + keep_history_args='--keep-history=false' + fi + # shellcheck disable=SC2059,SC2086 + # (SC2086: an empty keep_history_args passes no flag at all) printf "${body_format}" "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ @@ -353,7 +369,7 @@ if [[ "${status}" == "ok" ]]; then --number "${NUMBER}" \ --marker "${MARKER}" \ --only-if-exists \ - --keep-history=false \ + ${keep_history_args} \ --result - exit 0 fi @@ -373,9 +389,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..451b7e7f4c 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,25 @@ 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 — fullsend's own 32 KiB parse cap, + // not a verified Jira Cloud limit. 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 the conversion. Capping here keeps the + // pre-create truncation under the locally enforced limit; a + // body over Jira's own server-side limit (unverified) fails + // at post time with Jira's API error. + 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 +545,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 +569,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 +605,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 +625,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 +888,25 @@ 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. The cap and +// its default live in sticky.Config.EffectiveMaxSize, so this door and +// sticky's own paths agree by construction. +func truncateForPost(body string, cfg sticky.Config) string { + return sticky.TruncateBody(body, cfg.EffectiveMaxSize()) +} + // 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..52d0b47889 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,55 +1033,31 @@ 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_JiraLeavesLegacyMarkerCommentUntouched(t *testing.T) { + // Criterion 4's Jira leg: a legacy marker comment (the marker in the + // visible body, from before markers moved to comment properties) is + // never migrated or edited — a new run appends beside it, so the + // append contract holds on the Jira door too. tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") require.NoError(t, err) ctx := context.Background() + const marker = "" - cfg := &issuesPostCommentConfig{ - trackerName: trackerJira, - project: "PROJ", - number: 42, - marker: "", - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "visible content only", - } - require.NoError(t, runIssuesPostComment(ctx, cfg)) - - comments, err := tc.ListComments(ctx, "PROJ", 42) + _, err = tc.CreateComment(ctx, "PROJ", 42, tracker.Body(marker+"\nearlier findings")) 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), "") -} - -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") + before, err := tc.ListComments(ctx, "PROJ", 42) require.NoError(t, err) - ctx := context.Background() + require.Len(t, before, 1) + seeded := string(before[0].Body) + assert.Contains(t, seeded, "earlier findings") - marker := "" - - // 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) - - // Run post-comment, which should find the legacy comment via body - // fallback, update it, and set the property. cfg := &issuesPostCommentConfig{ trackerName: trackerJira, project: "PROJ", @@ -1154,42 +1065,27 @@ func TestRunIssuesPostComment_JiraLegacyMigration(t *testing.T) { marker: marker, testClient: tc, testPrinter: ui.New(io.Discard), - testBody: "updated via property", + testBody: "new result", } 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, 2, "the new run appends a new comment") + assert.Equal(t, seeded, string(comments[0].Body), "the legacy marker comment is left untouched") + assert.Contains(t, string(comments[1].Body), "new result") } -// liveMarkerOpener matches a fullsend marker opener that would parse as a -// marker (case-insensitive, any whitespace around "fullsend"). -var liveMarkerOpener = regexp.MustCompile(`(?i)" cfg := &issuesPostCommentConfig{ trackerName: trackerJira, project: "PROJ", @@ -1197,138 +1093,113 @@ func TestRunIssuesPostComment_JiraNeutralizesInjectedMarkers(t *testing.T) { marker: "", testClient: tc, testPrinter: ui.New(io.Discard), - testBody: "first run\n\n" + sibling + "\n\n<!-- fullsend:agent-status:1 -->", + 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) - assert.NotRegexp(t, liveMarkerOpener, string(comments[0].Body), "create left a live marker opener") + assert.LessOrEqual(t, len(string(comments[0].Body)), jira.MaxMarkdownBytes, + "the created body must be truncated to the Jira markdown limit") +} - cfg.testBody = "second run \n\n" + sibling - require.NoError(t, runIssuesPostComment(ctx, cfg)) +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() - comments, err = tc.ListComments(ctx, "PROJ", 42) + cfg := sticky.Config{Marker: "", MaxSize: 500} + _, err := postTrackerStickyComment(ctx, tc, "acme/widgets", 42, strings.Repeat("a", 800), cfg, false, printer) require.NoError(t, err) - require.Len(t, comments, 1, "second run should update the existing comment in place") - body := string(comments[0].Body) - assert.NotRegexp(t, liveMarkerOpener, body, "update left a live marker opener") - assert.Contains(t, body, "second run") - assert.Contains(t, body, "Previous run") - assert.Contains(t, body, `\<!-- fullsend:review-agent -->`, "neutralized text should stay visible") - // Neither the quoted sibling marker nor the quoted status marker - // makes the comment discoverable as something it is not. - 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) + comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) - assert.False(t, isStatus) + 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_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. +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() - 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, + marker: "", testClient: tc, testPrinter: ui.New(io.Discard), - testBody: "new run", + 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) - 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 -->`) + // 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), "") } -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") +// liveMarkerOpener matches a fullsend marker opener that would parse as a +// marker (case-insensitive, any whitespace around "fullsend"). +var liveMarkerOpener = regexp.MustCompile(`(?i)" - - // First run creates the comment with the property set inline. + sibling := "" cfg := &issuesPostCommentConfig{ trackerName: trackerJira, project: "PROJ", number: 42, - marker: marker, + marker: "", testClient: tc, testPrinter: ui.New(io.Discard), - testBody: "first run", + testBody: "first run\n\n" + sibling + "\n\n<!-- fullsend:agent-status:1 -->", } 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") -} + assert.NotRegexp(t, liveMarkerOpener, string(comments[0].Body), "create left a live marker opener") -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() + cfg.testBody = "second run \n\n" + sibling + require.NoError(t, runIssuesPostComment(ctx, cfg)) - marker := "" - _, err = fc.CreateComment(ctx, "PROJ-42", marker+"\nlegacy content") + comments, err = tc.ListComments(ctx, "PROJ", 42) require.NoError(t, err) + require.Len(t, comments, 2, "second run should append a new comment") + body := string(comments[1].Body) + assert.NotRegexp(t, liveMarkerOpener, body, "the new comment left a live marker opener") + assert.Contains(t, body, "second run") + assert.Contains(t, body, `\<!-- fullsend:review-agent -->`, "neutralized text should stay visible") - 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) + // Neither the quoted sibling marker nor the quoted status marker + // makes the comment discoverable as something it is not. + raw, err := tc.ListJiraComments(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) + assert.Nil(t, tc.FindCommentByMarkerProperty(raw, sibling)) + isStatus, err := tc.IsStatusComment(ctx, "PROJ", 42, comments[1].ID) + require.NoError(t, err) + assert.False(t, isStatus) } func TestPostJiraStickyComment_DryRun_Create(t *testing.T) { @@ -1348,8 +1219,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 +1231,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 +1526,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 +1549,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 +1576,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 +1586,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 +1652,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 +1686,44 @@ 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_NormalPostIgnoresSelfLookupFailure(t *testing.T) { + // The other side of the narrowing: a post without --only-if-exists + // never resolves the posting identity, so an identity outage cannot + // block posting. A regression re-adding an unconditional + // GetAuthenticatedUser fails here (the lookup is down for this test). + err, comments, tc := postAfterCommentBy(t, testBot, false, 1000) + require.NoError(t, err) + assert.Zero(t, tc.calls, "a normal post never resolves the posting identity") + require.Len(t, comments, 2, "the result is appended with the identity lookup down") + assert.NotContains(t, string(comments[0].Body), "new result", "the earlier comment is left unchanged") + assert.Contains(t, string(comments[1].Body), "new result") } 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 +1732,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 +1781,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 +1806,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 +1825,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 +1841,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 +1859,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 +1869,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 +1890,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 +1915,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 +1964,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 +1993,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/keep_history_deprecation_test.go b/internal/cli/keep_history_deprecation_test.go new file mode 100644 index 0000000000..6d94df84d2 --- /dev/null +++ b/internal/cli/keep_history_deprecation_test.go @@ -0,0 +1,149 @@ +package cli + +import ( + "bytes" + "context" + "os" + "path/filepath" + "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/tracker" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// The keepHistoryDeprecationWarning snippet every door must print when +// --keep-history is passed explicitly. Shell scripts never read help text, +// so this stderr line is the only advance notice external automation gets +// before a cleanup PR removes the flag. +const keepHistoryDeprecationWarning = "warning: --keep-history is deprecated and has no effect" + +// The three doors that accept --keep-history (issues post-comment, +// post-comment and post-review) share warnKeepHistoryDeprecated, but its +// flag-Changed branch only runs through Cobra's flag parsing, so each door +// is driven at the command level: with the flag passed explicitly the +// warning must reach stderr, without it stderr must stay free of it. + +func TestIssuesPostCommentCmd_KeepHistoryWarnsOnExplicitFlag(t *testing.T) { + t.Setenv("GH_TOKEN", "") + t.Setenv("GITHUB_TOKEN", "") + t.Setenv("PATH", "/nonexistent") + + bodyFile := filepath.Join(t.TempDir(), "body.md") + require.NoError(t, os.WriteFile(bodyFile, []byte("comment body"), 0o644)) + + run := func(extra ...string) string { + cmd := newIssuesPostCommentCmd() + cmd.SilenceUsage = true + cmd.SilenceErrors = true + cmd.SetArgs(append([]string{ + "--tracker", "github", + "--project", "owner/repo", + "--number", "1", + "--marker", "", + "--result", bodyFile, + }, extra...)) + var stderr strings.Builder + cmd.SetErr(&stderr) + err := cmd.Execute() + // No token is available, so the run stops before posting; the + // warning is printed before that, at the top of RunE. + require.Error(t, err) + assert.Contains(t, err.Error(), "no GitHub token found") + return stderr.String() + } + + assert.Contains(t, run("--keep-history=false"), keepHistoryDeprecationWarning, + "an explicit --keep-history must warn on stderr") + assert.NotContains(t, run(), keepHistoryDeprecationWarning, + "the default flag value must not warn") +} + +func TestPostCommentCmd_KeepHistoryWarnsOnExplicitFlag(t *testing.T) { + t.Setenv("FULLSEND_DIR", "") + + bodyFile := filepath.Join(t.TempDir(), "body.md") + require.NoError(t, os.WriteFile(bodyFile, []byte("comment body"), 0o644)) + + run := func(extra ...string) string { + cmd := newPostCommentCmd() + cmd.SilenceUsage = true + cmd.SilenceErrors = true + cmd.SetArgs(append([]string{ + "--repo", "owner/repo", + "--number", "1", + "--marker", "", + "--result", bodyFile, + "--token", "test-token", + "--dry-run", + }, extra...)) + var stderr strings.Builder + cmd.SetErr(&stderr) + require.NoError(t, cmd.Execute()) + return stderr.String() + } + + assert.Contains(t, run("--keep-history=false"), keepHistoryDeprecationWarning, + "an explicit --keep-history must warn on stderr") + assert.NotContains(t, run(), keepHistoryDeprecationWarning, + "the default flag value must not warn") +} + +func TestPostReviewCmd_KeepHistoryWarnsOnExplicitFlag(t *testing.T) { + t.Setenv("FULLSEND_DIR", "") + + resultFile := filepath.Join(t.TempDir(), "result.json") + require.NoError(t, os.WriteFile(resultFile, []byte(`{"action":"comment","body":"ok"}`), 0o644)) + + run := func(extra ...string) string { + cmd := newPostReviewCmd() + cmd.SilenceUsage = true + cmd.SilenceErrors = true + cmd.SetArgs(append([]string{ + "--repo", "owner/repo", + "--pr", "1", + "--result", resultFile, + "--token", "test-token", + "--dry-run", + }, extra...)) + var stderr strings.Builder + cmd.SetErr(&stderr) + require.NoError(t, cmd.Execute()) + return stderr.String() + } + + assert.Contains(t, run("--keep-history=false"), keepHistoryDeprecationWarning, + "an explicit --keep-history must warn on stderr") + assert.NotContains(t, run(), keepHistoryDeprecationWarning, + "the default flag value must not warn") +} + +func TestRunIssuesPostComment_KeepHistoryWarnsOnConfigPath(t *testing.T) { + // The config route: with no explicit --keep-history, resolveKeepHistory + // reads config.yaml through --fullsend-dir, and every door prints the + // same shared notice when that resolution fails. The flag-path tests + // above pin warnKeepHistoryDeprecated; this pins the config leg, so a + // regression dropping the StepWarn (issues.go, postcomment.go and + // postreview.go carry the same branch) fails here. + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("{{{"), 0o644)) + + var out bytes.Buffer + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: "", + fullsendDir: dir, + testClient: tracker.NewForgeClient(forge.NewFakeClient()), + testPrinter: ui.New(&out), + testBody: "comment body", + } + require.NoError(t, runIssuesPostComment(context.Background(), cfg)) + assert.Contains(t, out.String(), "keep_history is deprecated and unused", + "a config.yaml that cannot load must still print the keep_history deprecation warning") +} 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..462c0e59e3 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 { @@ -388,23 +409,28 @@ func postReviewContent(ctx context.Context, client forge.Client, owner, repo str } else if !dryRun && strings.EqualFold(parsed.Action, "approve") { printer.StepWarn("Reviewed PR HEAD is unavailable; re-review deduplication will be unavailable") } - commentURL, err := sticky.Post(ctx, client, owner, repo, pr, parsed.Body, cfg, printer) + commentURL, commentID, err := sticky.PostComment(ctx, client, owner, repo, pr, parsed.Body, cfg, printer) if err != nil { return err } 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 // formal submission must never leave an approved-looking hash behind. + // The hash and head markers are added to the comment this run + // created (its ID from PostComment), so an approve run leaves + // exactly one review-agent comment: editing an earlier run's + // comment is the stickiness #9334 removed, and UpdateComment + // refuses a missing ID rather than guess one. hashBody := fmt.Sprintf("\n\n%s", diffHash, parsed.HeadSHA, parsed.Body) hashCfg := cfg hashCfg.TrustedLeadingLine = reviewTrustedLeadingLineReForHash(diffHash, parsed.HeadSHA) hashCfg.MaxTrustedLeadingLines = 3 - if _, hashErr := sticky.Post(ctx, client, owner, repo, pr, hashBody, hashCfg, printer); hashErr != nil { + if hashErr := sticky.UpdateComment(ctx, client, owner, repo, commentID, hashBody, hashCfg, printer); hashErr != nil { printer.StepWarn(fmt.Sprintf("Could not publish review diff hash after approval; re-review deduplication will be unavailable: %v", hashErr)) } } @@ -488,12 +514,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 +574,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 +606,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 +654,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 +669,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 +677,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..37efa917b3 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) { @@ -467,12 +472,19 @@ func TestPostReviewContent_IncludesDiffHashMarker(t *testing.T) { err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, cfg, false, printer) require.NoError(t, err) + // An approve run leaves exactly one review-agent comment: the review + // body is posted once, and the deduplication markers are added to + // that same comment once the formal approval succeeds. require.Len(t, fc.IssueComments["o/r/1"], 1) - assert.Regexp(t, reviewDiffHashMarkerRe, strings.SplitN(fc.IssueComments["o/r/1"][0].Body, "\n", 3)[1]) - assert.Contains(t, fc.IssueComments["o/r/1"][0].Body, "Previous run") + lines := strings.Split(fc.IssueComments["o/r/1"][0].Body, "\n") + require.GreaterOrEqual(t, len(lines), 3) + assert.Equal(t, reviewMarker, lines[0]) + assert.Regexp(t, reviewDiffHashMarkerRe, lines[1]) + assert.Equal(t, "", lines[2]) + assert.Contains(t, fc.IssueComments["o/r/1"][0].Body, "Looks good") } -func TestPostReviewContent_PreservesHistoryWhenPublishingDiffHash(t *testing.T) { +func TestPostReviewContent_LeavesPriorCommentUntouchedWhenPublishingDiffHash(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" fc.PullRequestHeadSHA = "abc123def456" @@ -503,11 +515,17 @@ Earlier review sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard)) require.NoError(t, err) - body := fc.IssueComments["o/r/1"][0].Body - assert.Contains(t, body, "Earlier review") - assert.Contains(t, body, "Prior review") - assert.Contains(t, body, "Looks good") - assert.Contains(t, body, "fullsend:review-diff-hash:") + // The prior comment stands exactly as it was (nothing is folded into + // history any more), and the hash is added to the comment this run + // created: one new comment per run, not one per publish. + require.Len(t, fc.IssueComments["o/r/1"], 2) + prior := fc.IssueComments["o/r/1"][0].Body + assert.Contains(t, prior, "Earlier review") + assert.Contains(t, prior, "Prior review") + assert.NotContains(t, prior, "Looks good") + reviewComment := fc.IssueComments["o/r/1"][1].Body + assert.Contains(t, reviewComment, "Looks good") + assert.Contains(t, reviewComment, "fullsend:review-diff-hash:") } func TestPostReviewContent_PublishesDiffHashOnlyAfterApproval(t *testing.T) { @@ -520,12 +538,16 @@ func TestPostReviewContent_PublishesDiffHashOnlyAfterApproval(t *testing.T) { requestChanges := ReviewResult{Body: "Needs changes", Action: "request-changes", HeadSHA: "abc123def456"} require.NoError(t, postReviewContent(context.Background(), fc, "o", "r", 1, requestChanges, sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard))) - assert.NotContains(t, fc.IssueComments["o/r/1"][0].Body, "fullsend:review-diff-hash:") + for _, comment := range fc.IssueComments["o/r/1"] { + assert.NotContains(t, comment.Body, "fullsend:review-diff-hash:") + } fc.Errors["CreatePullRequestReview"] = fmt.Errorf("approval API error") approval := ReviewResult{Body: "Looks good", Action: "approve", HeadSHA: "abc123def456"} require.NoError(t, postReviewContent(context.Background(), fc, "o", "r", 1, approval, sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard))) - assert.NotContains(t, fc.IssueComments["o/r/1"][0].Body, "fullsend:review-diff-hash:") + for _, comment := range fc.IssueComments["o/r/1"] { + assert.NotContains(t, comment.Body, "fullsend:review-diff-hash:") + } } func TestPostReviewContent_PreservesGeneratedHashAndProjectionMarkers(t *testing.T) { @@ -540,8 +562,11 @@ func TestPostReviewContent_PreservesGeneratedHashAndProjectionMarkers(t *testing err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard)) require.NoError(t, err) - body := fc.IssueComments["o/r/1"][0].Body - lines := strings.Split(body, "\n") + // One comment: the marker on the first line, then the generated hash, + // the reviewed head and the projection marker live and unescaped (the + // prior-review fetchers read the newest review-agent comment). + require.Len(t, fc.IssueComments["o/r/1"], 1) + lines := strings.Split(fc.IssueComments["o/r/1"][0].Body, "\n") require.GreaterOrEqual(t, len(lines), 4) assert.Equal(t, reviewMarker, lines[0]) assert.Regexp(t, reviewDiffHashMarkerRe, lines[1]) @@ -606,19 +631,6 @@ func TestPostReviewContent_DoesNotPublishHashWhenHeadLookupFails(t *testing.T) { assert.NotContains(t, fc.IssueComments["o/r/1"][0].Body, "fullsend:review-diff-hash:") } -type failSecondReviewCommentUpdateClient struct { - *forge.FakeClient - updates int -} - -func (c *failSecondReviewCommentUpdateClient) UpdateIssueComment(ctx context.Context, owner, repo string, id int, body string) error { - c.updates++ - if c.updates > 0 { - return fmt.Errorf("hash marker update failed") - } - return c.FakeClient.UpdateIssueComment(ctx, owner, repo, id, body) -} - func TestPostReviewContent_HashPublicationFailureIsBestEffort(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" @@ -626,13 +638,15 @@ func TestPostReviewContent_HashPublicationFailureIsBestEffort(t *testing.T) { fc.PRFileDiffs = map[string][]forge.PullRequestFileDiff{ "o/r/1": {{Path: "README.md", Patch: "@@ -1 +1 @@\n-old\n+new"}}, } - client := &failSecondReviewCommentUpdateClient{FakeClient: fc} + fc.Errors["UpdateIssueComment"] = fmt.Errorf("hash marker update failed") var buf bytes.Buffer - err := postReviewContent(context.Background(), client, "o", "r", 1, + err := postReviewContent(context.Background(), fc, "o", "r", 1, ReviewResult{Body: "Looks good", Action: "approve", HeadSHA: "abc123def456"}, sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(&buf)) require.NoError(t, err) + require.Len(t, fc.IssueComments["o/r/1"], 1) + assert.Contains(t, fc.IssueComments["o/r/1"][0].Body, "Looks good") assert.NotContains(t, fc.IssueComments["o/r/1"][0].Body, "fullsend:review-diff-hash:") assert.Contains(t, buf.String(), "Could not publish review diff hash after approval") } @@ -2578,5 +2592,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/cli/reviewdedup.go b/internal/cli/reviewdedup.go index 89af8a0653..7f41803522 100644 --- a/internal/cli/reviewdedup.go +++ b/internal/cli/reviewdedup.go @@ -15,6 +15,11 @@ import ( const reviewSkipMarker = "" +// supersededSkipPhrase appears in a skip note a full review already rewrote; a +// later full review leaves such a note alone so it keeps the commit that +// superseded it. +const supersededSkipPhrase = "was superseded by" + // newReviewDedupCmd owns the unchanged-synchronize review decision. It is // deliberately fail-open: a missing or unverifiable input prints skip=false // and exits successfully so routing can continue with a full review. @@ -60,7 +65,7 @@ func newReviewDedupCmd() *cobra.Command { result := decideReviewDedup(cmd.Context(), client, owner, repoName, pr, appSet, appClientID) writeReviewDedupOutput(cmd, result) if publish && result.Skip { - if err := publishReviewSkip(cmd.Context(), client, owner, repoName, pr, result.PriorURL, appClientID); err != nil { + if err := publishReviewSkip(cmd.Context(), client, owner, repoName, pr, result.PriorURL); err != nil { fmt.Fprintln(cmd.ErrOrStderr(), "::warning::Could not publish review skip note; running review") fmt.Fprintln(cmd.OutOrStdout(), "skipped=false") return nil @@ -78,7 +83,7 @@ func newReviewDedupCmd() *cobra.Command { cmd.Flags().StringVar(&baseURL, "base-url", "", "forge instance URL") cmd.Flags().StringVar(&appSet, "app-set", appsetup.DefaultAppSet, "review bot app-set name") cmd.Flags().StringVar(&appClientID, "app-client-id", "", "verified review GitHub App client ID") - cmd.Flags().BoolVar(&publish, "publish", false, "publish or update the skip note after a skip decision") + cmd.Flags().BoolVar(&publish, "publish", false, "publish a new skip note after a skip decision") cmd.Flags().BoolVar(&supersede, "supersede", false, "mark existing app-verified skip notes as superseded") cmd.Flags().StringVar(&headSHA, "head-sha", "", "head commit to include in a superseded skip note") _ = cmd.MarkFlagRequired("repo") @@ -261,42 +266,29 @@ func hasApprovedReview(reviews []forge.PullRequestReview, owner, appSet, head st return latest != nil && latest.State == "APPROVED" && latest.CommitID != "" && strings.EqualFold(latest.CommitID, head) } -func publishReviewSkip(ctx context.Context, client forge.Client, owner, repo string, pr int, priorURL, appClientID string) error { +// publishReviewSkip posts a new skip note at the end of the thread for every +// skipped review, like every other posting door; it never lists comments, +// resolves the posting identity, or updates an earlier note in place. +func publishReviewSkip(ctx context.Context, client forge.Client, owner, repo string, pr int, priorURL string) error { body := reviewSkipMarker + "\nFullsend skipped this synchronize review because the effective diff is unchanged from the previous approved review" if priorURL != "" { body += " (" + priorURL + ")" } body += ". No new review findings were generated." - comments, err := client.ListIssueComments(ctx, owner, repo, pr) - if err != nil { - return err - } - botUser, err := client.GetAuthenticatedUser(ctx) - if err != nil || botUser == "" { - return fmt.Errorf("cannot verify authenticated review bot") - } - var latest *forge.IssueComment - for i := range comments { - comment := &comments[i] - if comment.Author != botUser || comment.AppClientID != appClientID || !strings.HasPrefix(comment.Body, reviewSkipMarker) { - continue - } - if latest == nil || comment.CreatedAt > latest.CreatedAt || (comment.CreatedAt == latest.CreatedAt && comment.ID > latest.ID) { - latest = comment - } - } - if latest != nil { - return client.UpdateIssueComment(ctx, owner, repo, latest.ID, body) - } - _, err = client.CreateIssueComment(ctx, owner, repo, pr, body) + _, err := client.CreateIssueComment(ctx, owner, repo, pr, body) return err } +// supersedeReviewSkip edits the bot's earlier skip notes in place — unlike +// the append-only publishReviewSkip — because superseding marks history +// rather than reporting a new event: the thread keeps one skip note per app +// (each saying which commit it was superseded by) instead of a chain of +// them. func supersedeReviewSkip(ctx context.Context, client forge.Client, owner, repo string, pr int, headSHA, appSet, appClientID string) error { if !hexSHARe.MatchString(headSHA) { headSHA = "unknown head" } - body := reviewSkipMarker + "\nFullsend's earlier unchanged-diff skip note was superseded by a full review for commit " + headSHA + "." + body := reviewSkipMarker + "\nFullsend's earlier unchanged-diff skip note " + supersededSkipPhrase + " a full review for commit " + headSHA + "." if appClientID == "" { return nil } @@ -306,7 +298,7 @@ func supersedeReviewSkip(ctx context.Context, client forge.Client, owner, repo s } logins := reviewBotLogins(owner, appSet) for _, comment := range comments { - if logins[comment.Author] && comment.AppClientID == appClientID && strings.HasPrefix(comment.Body, reviewSkipMarker) { + if logins[comment.Author] && comment.AppClientID == appClientID && strings.HasPrefix(comment.Body, reviewSkipMarker) && !strings.Contains(comment.Body, supersededSkipPhrase) { if err := client.UpdateIssueComment(ctx, owner, repo, comment.ID, body); err != nil { return err } diff --git a/internal/cli/reviewdedup_test.go b/internal/cli/reviewdedup_test.go index de8d56023c..94c663330a 100644 --- a/internal/cli/reviewdedup_test.go +++ b/internal/cli/reviewdedup_test.go @@ -51,22 +51,26 @@ func TestReviewDedupCommandValidation(t *testing.T) { } } -func TestPublishReviewSkip_CreatesAndUpdatesVerifiedNote(t *testing.T) { +func TestPublishReviewSkip_EverySkipAppendsNewComment(t *testing.T) { ctx := context.Background() fc := forge.NewFakeClient() fc.AuthenticatedUser = "fullsend-ai-review[bot]" fc.IssueComments = map[string][]forge.IssueComment{} - require.NoError(t, publishReviewSkip(ctx, fc, "o", "r", 1, "https://example.test/review", "client")) + require.NoError(t, publishReviewSkip(ctx, fc, "o", "r", 1, "https://example.test/review")) require.Len(t, fc.IssueComments["o/r/1"], 1) assert.Contains(t, fc.IssueComments["o/r/1"][0].Body, "unchanged") + assert.Contains(t, fc.IssueComments["o/r/1"][0].Body, "https://example.test/review") fc.IssueComments["o/r/1"][0].AppClientID = "client" - require.NoError(t, publishReviewSkip(ctx, fc, "o", "r", 1, "", "client")) - require.Len(t, fc.IssueComments["o/r/1"], 1) - assert.NotContains(t, fc.IssueComments["o/r/1"][0].Body, "https://example.test/review") + require.NoError(t, publishReviewSkip(ctx, fc, "o", "r", 1, "")) + require.Len(t, fc.IssueComments["o/r/1"], 2) + assert.Contains(t, fc.IssueComments["o/r/1"][1].Body, "unchanged") + assert.NotContains(t, fc.IssueComments["o/r/1"][1].Body, "https://example.test/review") + assert.Contains(t, fc.IssueComments["o/r/1"][0].Body, "https://example.test/review") + assert.Empty(t, fc.UpdatedComments) } -func TestPublishReviewSkip_UpdatesNewestVerifiedNote(t *testing.T) { +func TestPublishReviewSkip_LeavesEarlierNotesUntouched(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "fullsend-ai-review[bot]" fc.IssueComments = map[string][]forge.IssueComment{ @@ -76,11 +80,12 @@ func TestPublishReviewSkip_UpdatesNewestVerifiedNote(t *testing.T) { }, } - require.NoError(t, publishReviewSkip(context.Background(), fc, "o", "r", 1, "", "client")) - require.Len(t, fc.UpdatedComments, 1) - assert.Equal(t, 11, fc.UpdatedComments[0].CommentID) - assert.Contains(t, fc.IssueComments["o/r/1"][1].Body, "unchanged") - assert.Contains(t, fc.IssueComments["o/r/1"][0].Body, "old") + require.NoError(t, publishReviewSkip(context.Background(), fc, "o", "r", 1, "")) + require.Empty(t, fc.UpdatedComments) + require.Len(t, fc.IssueComments["o/r/1"], 3) + assert.Contains(t, fc.IssueComments["o/r/1"][2].Body, "unchanged") + assert.Equal(t, reviewSkipMarker+"\nold", fc.IssueComments["o/r/1"][0].Body) + assert.Equal(t, reviewSkipMarker+"\nnewest", fc.IssueComments["o/r/1"][1].Body) } type reviewDedupInfoSequenceClient struct { @@ -225,12 +230,8 @@ func TestDecideReviewDedup_FailsOpenForIncompleteInputs(t *testing.T) { func TestPublishReviewSkip_FailsOpenOnPublicationErrors(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "fullsend-ai-review[bot]" - fc.Errors = map[string]error{"ListIssueComments": assert.AnError} - assert.Error(t, publishReviewSkip(context.Background(), fc, "o", "r", 1, "", "client")) - - fc.Errors = nil - fc.AuthenticatedUser = "" - assert.Error(t, publishReviewSkip(context.Background(), fc, "o", "r", 1, "", "client")) + fc.Errors = map[string]error{"CreateIssueComment": assert.AnError} + assert.Error(t, publishReviewSkip(context.Background(), fc, "o", "r", 1, "")) } func TestSupersedeReviewSkip_UpdatesOnlyVerifiedBotNotes(t *testing.T) { @@ -252,6 +253,27 @@ func TestSupersedeReviewSkip_UpdatesOnlyVerifiedBotNotes(t *testing.T) { assert.Equal(t, reviewSkipMarker+"\nleave me alone", comments[2].Body) } +func TestSupersedeReviewSkip_SkipsAlreadySupersededNotes(t *testing.T) { + fc := forge.NewFakeClient() + alreadySuperseded := reviewSkipMarker + "\nFullsend's earlier unchanged-diff skip note " + supersededSkipPhrase + + " a full review for commit 0000000000000000000000000000000000000000." + fc.IssueComments = map[string][]forge.IssueComment{ + "o/r/1": { + {ID: 1, Author: "o-review[bot]", AppClientID: "client", Body: reviewSkipMarker + "\nold"}, + {ID: 2, Author: "o-review[bot]", AppClientID: "client", Body: alreadySuperseded}, + }, + } + + require.NoError(t, supersedeReviewSkip(context.Background(), fc, "o", "r", 1, + "0123456789012345678901234567890123456789", "fullsend-ai", "client")) + + comments := fc.IssueComments["o/r/1"] + assert.Contains(t, comments[0].Body, "superseded by a full review for commit 012345678901") + assert.Equal(t, alreadySuperseded, comments[1].Body) + require.Len(t, fc.UpdatedComments, 1) + assert.Equal(t, 1, fc.UpdatedComments[0].CommentID) +} + func TestSupersedeReviewSkip_WithoutClientIDIsNoop(t *testing.T) { fc := forge.NewFakeClient() fc.Errors = map[string]error{"ListIssueComments": assert.AnError} diff --git a/internal/cli/truncate_for_post_test.go b/internal/cli/truncate_for_post_test.go new file mode 100644 index 0000000000..77ccd4b9c2 --- /dev/null +++ b/internal/cli/truncate_for_post_test.go @@ -0,0 +1,51 @@ +package cli + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/fullsend-ai/fullsend/internal/sticky" +) + +// truncateForPost caps a body at cfg's limit before the create. The edges +// are exercised directly here — an unset MaxSize falls back to +// sticky.DefaultMaxSize and a small budget truncates with the note — so +// the cap arithmetic is cheap to diagnose when the budget logic changes. +func TestTruncateForPost(t *testing.T) { + const note = "\n\n*Comment truncated due to comment size limits.*" + body := strings.Repeat("x", 100) + + t.Run("unset MaxSize falls back to the default and keeps a default-sized body", func(t *testing.T) { + got := truncateForPost(body, sticky.Config{}) + assert.Equal(t, body, got, "a body well under DefaultMaxSize passes unchanged") + }) + + t.Run("unset MaxSize falls back to the default and truncates an oversized body", func(t *testing.T) { + oversized := strings.Repeat("x", sticky.DefaultMaxSize+1000) + got := truncateForPost(oversized, sticky.Config{}) + assert.Len(t, got, sticky.DefaultMaxSize, "the body is capped at DefaultMaxSize") + assert.True(t, strings.HasSuffix(got, note), "the truncation note is appended") + }) + + t.Run("a set MaxSize is honoured", func(t *testing.T) { + // The cap must leave room for the truncation note itself. + got := truncateForPost(body, sticky.Config{MaxSize: 80}) + assert.Len(t, got, 80, "the body is capped at the configured MaxSize") + assert.True(t, strings.HasSuffix(got, note), "the truncation note is appended") + }) + + t.Run("a body within a small budget passes whole", func(t *testing.T) { + got := truncateForPost("short", sticky.Config{MaxSize: 80}) + assert.Equal(t, "short", got, "a body within the budget is not truncated") + }) +} + +// sticky.Config.EffectiveMaxSize owns the fallback the doors share: the +// table pins the unset, zero and set cases. +func TestEffectiveMaxSize(t *testing.T) { + assert.Equal(t, sticky.DefaultMaxSize, sticky.Config{}.EffectiveMaxSize(), "unset MaxSize falls back to the default") + assert.Equal(t, sticky.DefaultMaxSize, sticky.Config{MaxSize: 0}.EffectiveMaxSize(), "a zero MaxSize falls back to the default") + assert.Equal(t, 1234, sticky.Config{MaxSize: 1234}.EffectiveMaxSize(), "a set MaxSize is returned as is") +} 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..e85dd40fb3 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")) @@ -134,6 +134,18 @@ var trustedLineRe = regexp.MustCompile(`^" +// The review door's other two trusted leading lines (the diff-hash and +// head markers), and the anchored pattern that accepts any of the three, +// which the size-cap tests hand out as the caller's TrustedLeadingLine. +// They live here beside trustedLine/trustedLineRe so the marker +// vocabulary is defined once: a vocab change is one edit, not lockstep +// copies per test. +const hashLine = "" + +const headLine = "" + +var trustedLinesRe = regexp.MustCompile(`^(?:||)$`) + func TestNeutralizeBody_TrustedLeadingLine(t *testing.T) { cfg := Config{TrustedLeadingLine: trustedLineRe} escaped := "<!-- fullsend:review-findings-v2:eyJhIjoxfQ== -->" @@ -202,9 +214,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 +228,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/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") +} diff --git a/internal/sticky/post_size_cap_test.go b/internal/sticky/post_size_cap_test.go new file mode 100644 index 0000000000..731e331486 --- /dev/null +++ b/internal/sticky/post_size_cap_test.go @@ -0,0 +1,128 @@ +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") +} + +// The review door's approve update keeps three trusted leading lines +// (diff hash, head, then the findings projection), so the guard must +// cover all of them: a cut that lands inside the third line leaves a +// partial projection even though the first line is intact — the exact +// shape the first-line-only guard missed. +func TestPost_TrustedLeadingLinesThirdLineCutBySizeCapIsRefused(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + cfg := Config{ + Marker: "", + TrustedLeadingLine: trustedLinesRe, + MaxTrustedLeadingLines: 3, + // Room for the runner marker, the truncation note and the first + // two trusted lines plus most of the third: the cut lands inside + // the projection line, past the first line the old guard checked. + MaxSize: len("\n"+hashLine+"\n"+headLine+"\n"+trustedLine) + 20, + } + body := hashLine + "\n" + headLine + "\n" + 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 third 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") +} + +// The same three-line shape with room for all of them posts them +// intact and truncates only the untrusted rest. +func TestPost_TrustedLeadingLinesWithinSizeCapPostsIntact(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + cfg := Config{ + Marker: "", + TrustedLeadingLine: trustedLinesRe, + MaxTrustedLeadingLines: 3, + MaxSize: len("\n"+hashLine+"\n"+headLine+"\n"+trustedLine) + 80, + } + body := hashLine + "\n" + headLine + "\n" + 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"+hashLine+"\n"+headLine+"\n"+trustedLine), + "the runner marker and all three trusted leading lines stay intact") + assert.Contains(t, got, "*Comment truncated due to comment size limits.*", + "the oversized rest is truncated after the trusted lines") + assert.LessOrEqual(t, len(got), cfg.MaxSize, "the posted body respects the cap") +} diff --git a/internal/sticky/sticky.go b/internal/sticky/sticky.go index 067288b3ca..0d6c3f18da 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 @@ -34,116 +41,176 @@ type Config struct { MaxTrustedLeadingLines int } -func (c Config) maxSize() int { +// EffectiveMaxSize returns the size limit a comment body is capped at: +// cfg.MaxSize when set, DefaultMaxSize otherwise. It is the one place the +// fallback lives, so every door that caps a body — sticky's own create and +// update paths and the CLI's posting doors — agrees by construction. +func (c Config) EffectiveMaxSize() 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). +// 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. // -// 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. +// Callers that need to edit the comment they just created — the review +// door adding its diff hash once the formal approval succeeds — call +// PostComment for the created comment's ID and pass it to UpdateComment. 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") + url, _, err := PostComment(ctx, client, owner, repo, number, body, cfg, printer) + return url, err +} + +// PostComment publishes an agent result as a new comment at the end of +// the thread and returns the HTML URL and the ID of the created comment +// (empty and zero 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 PostComment(ctx context.Context, client forge.Client, owner, repo string, number int, body string, cfg Config, printer *ui.Printer) (string, int, error) { + markedBody, err := prepareBody(body, cfg) + if err != nil { + return "", 0, err } - if strings.TrimSpace(cfg.Marker) == "" { - return "", fmt.Errorf("marker is empty") + + printer.StepStart("Posting comment") + + if cfg.DryRun { + printer.StepInfo("Dry run — would create new comment") + printer.StepInfo("Body length: " + strconv.Itoa(len(markedBody))) + return "", 0, nil } - // 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) + created, err := client.CreateIssueComment(ctx, owner, repo, number, markedBody) if err != nil { - return "", unverifiedBotUserError(err) + return "", 0, fmt.Errorf("creating comment: %w", err) } + printer.StepDone("Comment created") + return created.HTMLURL, created.ID, nil +} - comments, err := client.ListIssueComments(ctx, owner, repo, number) +// UpdateComment replaces the body of a comment created in this same run +// (commentID from PostComment), never an earlier run's comment — that +// find-and-edit is the stickiness #9334 removed. The body is assembled +// exactly as on create: the runner's marker stays on the first line, +// marker syntax in the rest is escaped (trusted leading lines +// excepted), the size cap applies, and trusted leading lines the cap +// would cut refuse the update instead of posting it partial. +func UpdateComment(ctx context.Context, client forge.Client, owner, repo string, commentID int, body string, cfg Config, printer *ui.Printer) error { + if commentID == 0 { + return fmt.Errorf("comment ID is required") + } + markedBody, err := prepareBody(body, cfg) if err != nil { - return "", fmt.Errorf("listing comments: %w", err) + return 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) - - 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 + if cfg.DryRun { + printer.StepInfo("Dry run — would update comment " + strconv.Itoa(commentID)) + return nil } - printer.StepStart("No existing comment found, creating new one") + if err := client.UpdateIssueComment(ctx, owner, repo, commentID, markedBody); err != nil { + return fmt.Errorf("updating comment: %w", err) + } + printer.StepDone("Comment updated") + return nil +} - if cfg.DryRun { - printer.StepInfo("Dry run — would create new comment") - printer.StepInfo("Body length: " + strconv.Itoa(len(markedBody))) - return "", nil +// prepareBody assembles the comment body the same way for create and +// update: the runner's marker on the first line, the agent body with its +// marker syntax escaped (a trusted leading line excepted), the whole +// capped at the size limit. +func prepareBody(body string, cfg Config) (string, error) { + if strings.TrimSpace(body) == "" { + return "", fmt.Errorf("comment body is empty") + } + if strings.TrimSpace(cfg.Marker) == "" { + return "", fmt.Errorf("marker is empty") } - created, err := client.CreateIssueComment(ctx, owner, repo, number, markedBody) - if err != nil { - return "", fmt.Errorf("creating comment: %w", err) + // 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.EffectiveMaxSize()) + + // Trusted leading lines carry the projection payload the next run's + // prior-review fetch reads back, so the size cap must never cut any + // of them (nor the runner marker before them): TruncateBody cuts at + // a byte offset with no line awareness, and a projection line posted + // partial would break that fetch. The guard covers every trusted + // line the caller's limit keeps — not only the first; the review + // door keeps three (diff hash, head, then the findings projection) — + // reading the same split neutralizeBody kept, so what is kept + // unescaped is exactly what is refused cut. Refuse to post instead. + if prefix, _, trusted := splitTrusted(body, cfg); trusted > 0 && + !strings.HasPrefix(markedBody, cfg.Marker+"\n"+prefix) { + return "", fmt.Errorf("comment body exceeds the %d-byte size cap without room for the trusted leading line(s) intact; refusing to post a partial marker line", cfg.EffectiveMaxSize()) } - printer.StepDone("Comment created") - return created.HTMLURL, nil + return markedBody, nil } -// neutralizeBody escapes fullsend marker syntax in body. When -// cfg.TrustedLeadingLine matches the whole first line of body, that line is -// kept unescaped and only the text after the trusted leading lines is escaped. -// Escaping starts after the last trusted line, so it cannot join with it. +// neutralizeBody escapes fullsend marker syntax in body. The trusted +// leading lines splitTrusted keeps (see TrustedLeadingLine) are posted +// as-is and only the text after them is escaped. Escaping starts after +// the last trusted line, so it cannot join with it. func neutralizeBody(body string, cfg Config) string { - if cfg.TrustedLeadingLine != nil { - limit := cfg.MaxTrustedLeadingLines - if limit <= 0 { - limit = 1 - } - lines := strings.Split(body, "\n") - trusted := 0 - for trusted < len(lines) && trusted < limit && cfg.TrustedLeadingLine.MatchString(lines[trusted]) { - trusted++ - } - if trusted > 0 { - prefix := strings.Join(lines[:trusted], "\n") - if trusted == len(lines) { - return prefix - } - return prefix + "\n" + statuscomment.NeutralizeMarkers(strings.Join(lines[trusted:], "\n")) - } + prefix, rest, trusted := splitTrusted(body, cfg) + switch { + case trusted == 0: + return statuscomment.NeutralizeMarkers(body) + case rest == "": + return prefix + default: + return prefix + "\n" + statuscomment.NeutralizeMarkers(rest) } - return statuscomment.NeutralizeMarkers(body) +} + +// splitTrusted splits body into its trusted leading lines and the rest, +// with one set of rules for every reader: consecutive leading lines that +// whole-line match cfg.TrustedLeadingLine, at most +// cfg.MaxTrustedLeadingLines of them (default one). neutralizeBody keeps +// the prefix unescaped and the size-cap guard in prepareBody refuses any +// truncation that would cut it, so the two can never disagree about what +// is trusted. +func splitTrusted(body string, cfg Config) (prefix, rest string, trusted int) { + if cfg.TrustedLeadingLine == nil { + return "", body, 0 + } + limit := cfg.MaxTrustedLeadingLines + if limit <= 0 { + limit = 1 + } + lines := strings.Split(body, "\n") + for trusted < len(lines) && trusted < limit && cfg.TrustedLeadingLine.MatchString(lines[trusted]) { + trusted++ + } + if trusted == 0 { + return "", body, 0 + } + prefix = strings.Join(lines[:trusted], "\n") + if trusted == len(lines) { + return prefix, "", trusted + } + return prefix, strings.Join(lines[trusted:], "\n"), trusted } // 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 +226,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 +246,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 the cleanup deletes the history-folding machinery (#9517). 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. @@ -235,8 +266,8 @@ func BuildUpdatedBody(oldBody, newBody string, cfg Config) string { if footer != "" { result += "\n\n" + footer } - if len(result) > cfg.maxSize() { - result = TruncateBody(result, cfg.maxSize()) + if len(result) > cfg.EffectiveMaxSize() { + result = TruncateBody(result, cfg.EffectiveMaxSize()) } return result } @@ -320,27 +351,33 @@ func BuildUpdatedBody(oldBody, newBody string, cfg Config) string { combined := newBody + formatHistory(entries) + footerStr - for len(combined) > cfg.maxSize() && len(entries) > 0 { + for len(combined) > cfg.EffectiveMaxSize() && len(entries) > 0 { entries = entries[:len(entries)-1] combined = newBody + formatHistory(entries) + footerStr } - if len(combined) > cfg.maxSize() { - combined = TruncateBody(combined, cfg.maxSize()) + if len(combined) > cfg.EffectiveMaxSize() { + combined = TruncateBody(combined, cfg.EffectiveMaxSize()) } 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 size cap 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/sticky/update_comment_test.go b/internal/sticky/update_comment_test.go new file mode 100644 index 0000000000..dbe752fa4b --- /dev/null +++ b/internal/sticky/update_comment_test.go @@ -0,0 +1,137 @@ +package sticky + +import ( + "context" + "io" + "strconv" + "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" +) + +// UpdateComment replaces the body of a comment the same run created (the +// review door adding its diff hash after the formal approval succeeds), +// so an approve run leaves one review-agent comment. It assembles the +// body exactly as Post does: the runner's marker on the first line, the +// size cap applied, and a trusted leading line the cap would cut refused +// rather than written partial. + +func TestUpdateComment_ReplacesBodyOfCommentCreatedThisRun(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + created, err := client.CreateIssueComment(context.Background(), "o", "r", 1, "\nFirst.") + require.NoError(t, err) + + cfg := Config{Marker: ""} + err = UpdateComment(context.Background(), client, "o", "r", created.ID, "Second.", cfg, printer) + require.NoError(t, err) + + comments := client.IssueComments["o/r/1"] + require.Len(t, comments, 1, "the update adds no comment") + assert.Equal(t, "\nSecond.", comments[0].Body, "the marker stays on the first line") + require.Len(t, client.UpdatedComments, 1) + assert.Equal(t, created.ID, client.UpdatedComments[0].CommentID, "the comment created this run is the one updated") +} + +// TestUpdateComment_DryRunPrintsTheNoticeAndTouchesNothing pins the dry-run +// branch: it prints the notice naming the comment and returns nil without +// reaching the forge. The shipped doors call UpdateComment only outside dry +// run today, so this locks the branch down for future wiring. +func TestUpdateComment_DryRunPrintsTheNoticeAndTouchesNothing(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + var out strings.Builder + printer := ui.New(&out) + + created, err := client.CreateIssueComment(context.Background(), "o", "r", 1, "\nFirst.") + require.NoError(t, err) + + cfg := Config{Marker: "", DryRun: true} + err = UpdateComment(context.Background(), client, "o", "r", created.ID, "Second.", cfg, printer) + + require.NoError(t, err, "a dry run succeeds without touching the forge") + assert.Contains(t, out.String(), "Dry run", "the dry-run notice prints") + assert.Contains(t, out.String(), strconv.Itoa(created.ID), "the notice names the comment") + assert.Empty(t, client.UpdatedComments, "a dry run never edits a comment") + comments := client.IssueComments["o/r/1"] + require.Len(t, comments, 1) + assert.Equal(t, "\nFirst.", comments[0].Body, "the existing body stands untouched") +} + +func TestUpdateComment_RequiresTheCreatedCommentID(t *testing.T) { + client := forge.NewFakeClient() + printer := ui.New(io.Discard) + + err := UpdateComment(context.Background(), client, "o", "r", 0, "Second.", Config{Marker: ""}, printer) + + require.Error(t, err, "without the ID the update must not guess a comment to edit") + assert.Contains(t, err.Error(), "comment ID is required") + assert.Empty(t, client.UpdatedComments, "no comment is edited in place") +} + +func TestUpdateComment_TrustedLeadingLineTooLargeForSizeCapIsRefused(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + created, err := client.CreateIssueComment(context.Background(), "o", "r", 1, "\nFirst.") + require.NoError(t, err) + + // The same cap shape as the create path: room for the runner marker + // and the truncation note but not the whole trusted line, so the cut + // would land inside that line. + cfg := Config{ + Marker: "", + MaxSize: len("\n"+trustedLine) + 20, + TrustedLeadingLine: trustedLineRe, + } + body := trustedLine + "\n\n" + strings.Repeat("x", 200) + + err = UpdateComment(context.Background(), client, "o", "r", created.ID, body, cfg, printer) + + require.Error(t, err, "UpdateComment must refuse rather than write a partial trusted line") + assert.Contains(t, err.Error(), "size cap") + assert.Equal(t, "\nFirst.", client.IssueComments["o/r/1"][0].Body, + "the comment keeps the body it had: nothing partial is written") +} + +// TestUpdateComment_TrustedLeadingLinesThirdLineCutBySizeCapIsRefused +// mirrors Post's triple-line case (the review approve path passes +// MaxTrustedLeadingLines=3): a cut landing inside the third trusted line, +// past the first line the single-line guard checks, must refuse here too, +// so a regression in the shared splitTrusted handling breaks both doors' +// tests instead of staying green on the update path. +func TestUpdateComment_TrustedLeadingLinesThirdLineCutBySizeCapIsRefused(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + created, err := client.CreateIssueComment(context.Background(), "o", "r", 1, "\nFirst.") + require.NoError(t, err) + + // The same cap shape as the create path's triple-line case: room for + // the runner marker, the truncation note and the first two trusted + // lines plus most of the third, so the cut lands inside the + // projection line. + cfg := Config{ + Marker: "", + TrustedLeadingLine: trustedLinesRe, + MaxTrustedLeadingLines: 3, + MaxSize: len("\n"+hashLine+"\n"+headLine+"\n"+trustedLine) + 20, + } + body := hashLine + "\n" + headLine + "\n" + trustedLine + "\n\n" + strings.Repeat("x", 200) + + err = UpdateComment(context.Background(), client, "o", "r", created.ID, body, cfg, printer) + + require.Error(t, err, "UpdateComment must refuse rather than write a partial third trusted line") + assert.Contains(t, err.Error(), "size cap") + assert.Equal(t, "\nFirst.", client.IssueComments["o/r/1"][0].Body, + "the comment keeps the body it had: nothing partial is written") +} 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..9d0c968007 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" @@ -22,6 +23,18 @@ const ( // for use inside a step pattern's capture group. const targetAlternation = targetIssue + "|" + targetPullRequest +// The comment-assertion step patterns, bound by registerForgeStateSteps +// and compiled by the feature-wiring test (forge_state_feature_test.go), +// so the test checks the registered patterns themselves instead of a +// verbatim copy that can drift (thread 4586481481). +const ( + stepIssueCommentCountContains = `^the issue has (\d+) comments? containing "([^"]+)"$` + stepLastIssueCommentContains = `^the last comment on the issue contains "([^"]+)"$` + stepLastIssueCommentContainingContains = `^the last comment on the issue containing "([^"]+)" contains "([^"]+)"$` + stepIssueCommentOtherThanLastContains = `^a comment on the issue other than the last contains "([^"]+)"$` + stepNoTargetCommentContains = `^no comment on the (issue|pull request) contains "([^"]+)"$` +) + // registerForgeStateSteps binds Then steps that assert what agent // post-scripts leave on the forge: labels, issue and pull request state, // comments, the pull request body and agent-created issues. Each step is @@ -49,6 +62,25 @@ 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(stepNoTargetCommentContains, func(ctx context.Context, target, text string) (context.Context, error) { + return ctx, thenNoTargetCommentContains(world.FromContext(ctx), target, text) + }) + sc.Step(stepIssueCommentCountContains, 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(stepLastIssueCommentContains, func(ctx context.Context, text string) (context.Context, error) { + return ctx, thenLastIssueCommentContains(world.FromContext(ctx), text) + }) + sc.Step(stepLastIssueCommentContainingContains, func(ctx context.Context, marker, text string) (context.Context, error) { + return ctx, thenLastIssueCommentContainingContains(world.FromContext(ctx), marker, text) + }) + sc.Step(stepIssueCommentOtherThanLastContains, 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 +207,110 @@ 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)) } +// thenNoTargetCommentContains asserts that no comment on the scenario's +// issue or pull request contains text — the inverse of +// thenTargetCommentContains, pinning an absence (no folded "Previous run" +// sections beside the appended result). +func thenNoTargetCommentContains(w *world.World, target, text string) error { + comments, number, err := listTargetComments(w, target) + if err != nil { + return err + } + for _, c := range comments { + if strings.Contains(c.Body, text) { + return fmt.Errorf("a comment on %s #%d contains %q:\n%s", target, number, text, c.Body) + } + } + return nil +} + +// 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 +} + +// 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 +// 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_feature_test.go b/pkg/behaviourtest/steps/forge_state_feature_test.go new file mode 100644 index 0000000000..fa1da9dd0d --- /dev/null +++ b/pkg/behaviourtest/steps/forge_state_feature_test.go @@ -0,0 +1,69 @@ +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 test compiles the same +// package-level consts the registration binds), so a typo in the +// feature or a reworded 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(stepIssueCommentCountContains), + regexp.MustCompile(stepLastIssueCommentContains), + regexp.MustCompile(stepLastIssueCommentContainingContains), + regexp.MustCompile(stepIssueCommentOtherThanLastContains), + regexp.MustCompile(stepNoTargetCommentContains), + } + var commentAssertions []string + for _, step := range steps { + for _, p := range patterns { + if p.MatchString(step) { + commentAssertions = append(commentAssertions, step) + } + } + } + require.Len(t, commentAssertions, 5, "the scenario's five 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 0c9a584453..f9065cd87e 100644 --- a/pkg/behaviourtest/steps/forge_state_test.go +++ b/pkg/behaviourtest/steps/forge_state_test.go @@ -183,6 +183,139 @@ func TestThenTargetCommentContains(t *testing.T) { require.ErrorContains(t, thenTargetCommentContains(w, targetIssue, "x"), "listing comments on issue #7") } +func TestThenNoTargetCommentContains(t *testing.T) { + t.Parallel() + + f := &fakeForgeStateSCM{comments: map[int][]forge.IssueComment{ + 7: { + {Body: "unrelated"}, + {Body: "\nTriage finished"}, + }, + 8: {{Body: "\nLooks good"}}, + }} + w := forgeStateWorld(f) + + require.NoError(t, thenNoTargetCommentContains(w, targetIssue, "Looks good")) + require.NoError(t, thenNoTargetCommentContains(w, targetPullRequest, "Previous run")) + require.ErrorContains(t, thenNoTargetCommentContains(w, targetIssue, "Triage finished"), + `a comment on issue #7 contains "Triage finished"`) + + require.ErrorContains(t, thenNoTargetCommentContains(&world.World{}, targetIssue, "x"), "no issue created") + + f.err = errors.New("HTTP 403") + require.ErrorContains(t, thenNoTargetCommentContains(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 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() + + 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()