From 55727056d811f4493a28421efb2413ee53b4d501 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 15:23:38 -0400 Subject: [PATCH 01/16] fix(#6966): flatten a rejected status before the generated post-script logs it The invalid-status rejection interpolated the model-supplied value into a stderr line as-is. jq -r turns JSON escapes into real CR/LF, so a crafted status could split the runner's log line and start a new one with a workflow-command prefix. Strip CR/LF and cap the shown value; a test feeds a status carrying a newline and a ::error:: prefix and asserts the rejection stays on one line. Goldens regenerated. Found by the review of fullsend-ai/agents#1167, whose example carries this script verbatim. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/agentnew/postscript_exec_test.go | 31 +++++++++++++++++++ internal/agentnew/templates/post.sh.tmpl | 9 +++++- internal/agentnew/testdata/golden/triage.txt | 9 +++++- .../testdata/golden/validation-loop.txt | 9 +++++- 4 files changed, 55 insertions(+), 3 deletions(-) diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index 0ad06c0acf..4c93a4bffc 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -130,3 +130,34 @@ func TestGeneratedPostScriptRunsFromTheRunDirectory(t *testing.T) { } }) } + +// TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging feeds a status +// that carries a newline and a workflow-command prefix. The rejection message +// must stay on one line and must not reproduce the injected line, because +// the script's stderr lands in the runner log where `::` at line start is +// interpreted as a command. +func TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging(t *testing.T) { + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{ + "status": "bogus\n::error::injected", + "summary": "s", + "comment": "c", + }, + }) + _, stderr, err := runPostScript(t, script, runDir) + if err == nil { + t.Fatal("expected the script to reject an invalid status") + } + if !strings.Contains(stderr, "status must be ok, findings or error") { + t.Fatalf("expected the status rejection, got stderr:\n%s", stderr) + } + for _, line := range strings.Split(strings.TrimSpace(stderr), "\n") { + if strings.HasPrefix(line, "::") { + t.Fatalf("model-supplied status reached the log as its own line: %q", line) + } + } + if strings.Count(strings.TrimSpace(stderr), "\n") != 0 { + t.Fatalf("rejection must be a single log line, got:\n%s", stderr) + } +} diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index 7a049dd895..3976d51985 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -81,7 +81,14 @@ comment=$(jq -r 'if (.comment | type) == "string" then .comment else empty end' case "${status}" in ok|findings|error) ;; - *) echo "post-__AGENT_NAME__: status must be ok, findings or error (got '${status}')" >&2; exit 1 ;; + *) + # status is model output: never echo it raw. A value carrying CR/LF would + # split the runner's log line (a workflow-command injection vector), so + # flatten it and cap it before it reaches stderr. + shown="${status//[$'\r\n']/ }" + echo "post-__AGENT_NAME__: status must be ok, findings or error (got '${shown:0:40}')" >&2 + exit 1 + ;; esac [[ -n "${summary}" ]] || { echo "post-__AGENT_NAME__: summary is required" >&2; exit 1; } if [[ "${summary}" == *$'\n'* || "${summary}" == *$'\r'* ]]; then diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index 8c518de616..a124f46ff4 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -233,7 +233,14 @@ comment=$(jq -r 'if (.comment | type) == "string" then .comment else empty end' case "${status}" in ok|findings|error) ;; - *) echo "post-lint-docs: status must be ok, findings or error (got '${status}')" >&2; exit 1 ;; + *) + # status is model output: never echo it raw. A value carrying CR/LF would + # split the runner's log line (a workflow-command injection vector), so + # flatten it and cap it before it reaches stderr. + shown="${status//[$'\r\n']/ }" + echo "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2 + exit 1 + ;; esac [[ -n "${summary}" ]] || { echo "post-lint-docs: summary is required" >&2; exit 1; } if [[ "${summary}" == *$'\n'* || "${summary}" == *$'\r'* ]]; then diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index 3253350e5b..aeb8cbb045 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -241,7 +241,14 @@ comment=$(jq -r 'if (.comment | type) == "string" then .comment else empty end' case "${status}" in ok|findings|error) ;; - *) echo "post-lint-docs: status must be ok, findings or error (got '${status}')" >&2; exit 1 ;; + *) + # status is model output: never echo it raw. A value carrying CR/LF would + # split the runner's log line (a workflow-command injection vector), so + # flatten it and cap it before it reaches stderr. + shown="${status//[$'\r\n']/ }" + echo "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2 + exit 1 + ;; esac [[ -n "${summary}" ]] || { echo "post-lint-docs: summary is required" >&2; exit 1; } if [[ "${summary}" == *$'\n'* || "${summary}" == *$'\r'* ]]; then From 7158fee01eebdac967b4f85c7d355ba828b711ae Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 15:39:50 -0400 Subject: [PATCH 02/16] test(#6966): skip the status-flattening exec test when jq is absent Matches the sibling exec test; without the guard a jq-less environment fails on the JSON-object check instead of exercising the flattening. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/agentnew/postscript_exec_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index 4c93a4bffc..e1f602d83d 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -137,6 +137,9 @@ func TestGeneratedPostScriptRunsFromTheRunDirectory(t *testing.T) { // the script's stderr lands in the runner log where `::` at line start is // interpreted as a command. func TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } script := renderPostScriptTo(t, t.TempDir()) runDir := writeRunDir(t, map[string]any{ "iteration-1": map[string]any{ From 637e8ccb8d5658604a64ccd70f01002d66a2ac9f Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 15:41:38 -0400 Subject: [PATCH 03/16] fix(#6966): log the rejected status with printf so xpg_echo cannot expand escapes Under bash's xpg_echo option echo interprets backslash escapes, so a status carrying a literal backslash-n would still forge a runner log line after the CR/LF flattening. printf '%s' never interprets its argument. A test runs the script with -O xpg_echo and asserts one line. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/agentnew/postscript_exec_test.go | 36 +++++++++++++++++++ internal/agentnew/templates/post.sh.tmpl | 4 ++- internal/agentnew/testdata/golden/triage.txt | 4 ++- .../testdata/golden/validation-loop.txt | 4 ++- 4 files changed, 45 insertions(+), 3 deletions(-) diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index e1f602d83d..49de3a62ff 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -164,3 +164,39 @@ func TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging(t *testing.T) { t.Fatalf("rejection must be a single log line, got:\n%s", stderr) } } + +// TestGeneratedPostScriptDoesNotExpandEscapesUnderXpgEcho runs the script +// with bash's xpg_echo option on, where `echo` interprets backslash escapes. +// A status carrying a literal backslash-n must still be logged on one line. +func TestGeneratedPostScriptDoesNotExpandEscapesUnderXpgEcho(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{ + "status": `bogus\n::error::injected`, + "summary": "s", + "comment": "c", + }, + }) + cmd := exec.Command("bash", "-O", "xpg_echo", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + DryRunEnvVar("lint-docs")+"=1", + ) + var stderr strings.Builder + cmd.Stderr = &stderr + if err := cmd.Run(); err == nil { + t.Fatal("expected the script to reject an invalid status") + } + out := strings.TrimSpace(stderr.String()) + if strings.Count(out, "\n") != 0 { + t.Fatalf("backslash escapes were expanded into a new log line:\n%s", out) + } + if !strings.Contains(out, `bogus\n::error::injected`) { + t.Fatalf("expected the literal value on the single line, got: %q", out) + } +} diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index 3976d51985..f2ff7bee8b 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -86,7 +86,9 @@ case "${status}" in # split the runner's log line (a workflow-command injection vector), so # flatten it and cap it before it reaches stderr. shown="${status//[$'\r\n']/ }" - echo "post-__AGENT_NAME__: status must be ok, findings or error (got '${shown:0:40}')" >&2 + # printf '%s' never interprets backslash escapes; echo does under xpg_echo, + # so a literal "\n" in the value could still forge a log line through echo. + printf '%s\n' "post-__AGENT_NAME__: status must be ok, findings or error (got '${shown:0:40}')" >&2 exit 1 ;; esac diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index a124f46ff4..caeeb2e4f3 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -238,7 +238,9 @@ case "${status}" in # split the runner's log line (a workflow-command injection vector), so # flatten it and cap it before it reaches stderr. shown="${status//[$'\r\n']/ }" - echo "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2 + # printf '%s' never interprets backslash escapes; echo does under xpg_echo, + # so a literal "\n" in the value could still forge a log line through echo. + printf '%s\n' "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2 exit 1 ;; esac diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index aeb8cbb045..8b47497613 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -246,7 +246,9 @@ case "${status}" in # split the runner's log line (a workflow-command injection vector), so # flatten it and cap it before it reaches stderr. shown="${status//[$'\r\n']/ }" - echo "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2 + # printf '%s' never interprets backslash escapes; echo does under xpg_echo, + # so a literal "\n" in the value could still forge a log line through echo. + printf '%s\n' "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2 exit 1 ;; esac From 1e96f48fbca9993507fdd3442f10ceb67b077dd3 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 16:12:29 -0400 Subject: [PATCH 04/16] feat(#6966): generate readonly_repo for the review role The fleet's review harness mounts the repository read-only so the prompt's "do not edit files" is enforcement rather than a request; the generated review harness now does the same. Found by the review of fullsend-ai/agents#1167, whose example is generated from this table. Assisted-by: Claude Signed-off-by: Wayne Sun --- docs/cli/agent.md | 2 ++ internal/agentnew/render.go | 1 + internal/agentnew/roles.go | 11 ++++++++--- internal/agentnew/roles_test.go | 13 +++++++++++++ 4 files changed, 24 insertions(+), 3 deletions(-) diff --git a/docs/cli/agent.md b/docs/cli/agent.md index e413df7220..09844bb8b0 100644 --- a/docs/cli/agent.md +++ b/docs/cli/agent.md @@ -146,6 +146,8 @@ command refuses an unknown one up front. The hosted mint serves these: | `retro` | `actions:read`, `contents:read`, `pull_requests:write`, `issues:write`, `metadata:read` | vertex-ai, github-ro, github-artifacts | | `prioritize` | `contents:read`, `issues:write`, `organization_projects:write`, `metadata:read` | vertex-ai, github-ro | +A `review` agent also gets `readonly_repo: true`, so the repository is mounted read-only in the sandbox: the prompt's "do not edit files" is enforced, not requested. That matches the review harness in fullsend-ai/agents. + Pick the role whose permissions fit what the agent does. An unknown role fails immediately with this table, rather than returning `403` from the mint the first time the agent runs. To use a role the hosted mint does not serve, you diff --git a/internal/agentnew/render.go b/internal/agentnew/render.go index 5e917bc0d8..ca0ed2935d 100644 --- a/internal/agentnew/render.go +++ b/internal/agentnew/render.go @@ -105,6 +105,7 @@ func buildHarness(opts Options, role Role) (*harness.Harness, error) { Effort: opts.Effort, PostScript: "scripts/post-" + opts.Name + ".sh", TimeoutMinutes: opts.TimeoutMinutes, + ReadonlyRepo: role.ReadonlyRepo, Trigger: opts.Trigger, Env: &harness.EnvConfig{ Runner: map[string]string{ diff --git a/internal/agentnew/roles.go b/internal/agentnew/roles.go index 461672b81b..81e2aaab2f 100644 --- a/internal/agentnew/roles.go +++ b/internal/agentnew/roles.go @@ -38,6 +38,10 @@ type Role struct { Profiles []string // Image is the sandbox image this role's agents run under. Image string + // ReadonlyRepo mirrors the fleet: the review harness mounts the target + // repository read-only so the prompt's "do not edit files" is enforced, + // not requested. Set for roles whose fleet harness sets `readonly_repo`. + ReadonlyRepo bool } // roleTable is the set of roles `agent new` will generate for. Excluded on @@ -60,9 +64,10 @@ var roleTable = map[string]Role{ "contents": "read", "pull_requests": "write", "issues": "write", "checks": "read", "metadata": "read", }, - Providers: []string{"providers/vertex-ai.yaml", "providers/github-ro.yaml"}, - Profiles: []string{"profiles/fullsend-vertex-ai.yaml", "profiles/fullsend-github-ro.yaml"}, - Image: config.DefaultCodeImage, + Providers: []string{"providers/vertex-ai.yaml", "providers/github-ro.yaml"}, + Profiles: []string{"profiles/fullsend-vertex-ai.yaml", "profiles/fullsend-github-ro.yaml"}, + Image: config.DefaultCodeImage, + ReadonlyRepo: true, }, "coder": { Name: "coder", diff --git a/internal/agentnew/roles_test.go b/internal/agentnew/roles_test.go index 0208526ac0..faaa741333 100644 --- a/internal/agentnew/roles_test.go +++ b/internal/agentnew/roles_test.go @@ -126,3 +126,16 @@ func TestCoderUsesEmbeddedGithubProvider(t *testing.T) { t.Errorf("coder should use providers/github.yaml, got %v", role.Providers) } } + +// TestReviewRoleMountsTheRepositoryReadOnly pins the fleet parity the +// authoring skill relies on: the review harness in fullsend-ai/agents sets +// readonly_repo, and the prompt's "do not edit files" is enforcement only if +// the generated harness does too. +func TestReviewRoleMountsTheRepositoryReadOnly(t *testing.T) { + for _, r := range roleTable { + want := r.Name == "review" + if r.ReadonlyRepo != want { + t.Errorf("role %s: ReadonlyRepo = %v, want %v", r.Name, r.ReadonlyRepo, want) + } + } +} From 5473296c92abbceae084227ea01c07d031702399 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 16:31:35 -0400 Subject: [PATCH 05/16] test(#6966): pin readonly_repo in the rendered review harness Extends the render round-trip so a regression that dropped the field from buildHarness fails, rather than only the in-memory role table. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/agentnew/render_test.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/internal/agentnew/render_test.go b/internal/agentnew/render_test.go index 64515f25be..6268f1b479 100644 --- a/internal/agentnew/render_test.go +++ b/internal/agentnew/render_test.go @@ -375,6 +375,12 @@ func TestRoleImageReachesTheHarness(t *testing.T) { if h.OpenShell == nil || !reflect.DeepEqual(h.OpenShell.Profiles, role.Profiles) { t.Errorf("role %q: profiles = %v, want %v", name, h.OpenShell, role.Profiles) } + // readonly_repo must survive into the emitted YAML, not only sit on + // the Role struct: a generated review harness that ships writable + // turns "do not edit files" back into a request. + if h.ReadonlyRepo != role.ReadonlyRepo || h.ReadonlyRepo != (name == "review") { + t.Errorf("role %q: readonly_repo = %v, want %v", name, h.ReadonlyRepo, name == "review") + } seen[role.Image] = true } // Both image constants must be reachable, or one is dead configuration. From cba63a7b9688591898cd516c72f184452b895d12 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 17:58:23 -0400 Subject: [PATCH 06/16] fix(#6966): on ok, replace an earlier findings comment with the all-clear The generated post-script posted nothing on status ok, so a findings comment from an earlier push stayed on the pull request after a later push fixed the problem (the trigger fires on synchronize). Now, when the status is ok and an earlier comment with this agent's marker exists, the sticky comment is replaced with the all-clear; with no earlier comment nothing is posted, as before. Dry run keeps the nothing-to-post notice so the documented local run output stays true. Found by the review of fullsend-ai/agents#1167. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/agentnew/postscript_exec_test.go | 25 +++++++++++++++++++ internal/agentnew/templates/post.sh.tmpl | 25 +++++++++++++++---- internal/agentnew/testdata/golden/triage.txt | 25 +++++++++++++++---- .../testdata/golden/validation-loop.txt | 25 +++++++++++++++---- 4 files changed, 85 insertions(+), 15 deletions(-) diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index 49de3a62ff..6929b0d8fb 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -200,3 +200,28 @@ func TestGeneratedPostScriptDoesNotExpandEscapesUnderXpgEcho(t *testing.T) { t.Fatalf("expected the literal value on the single line, got: %q", out) } } + +// TestGeneratedPostScriptOkPostsNothingWithoutAnEarlierComment pins the ok +// path under dry run: the script exits 0 and says nothing was posted. The +// live path additionally looks for an earlier marker comment and replaces it +// with the all-clear; that needs the forge, so it is exercised by the +// example's script test in fullsend-ai/agents, not here. +func TestGeneratedPostScriptOkPostsNothingWithoutAnEarlierComment(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + stdout, stderr, err := runPostScript(t, script, runDir) + if err != nil { + t.Fatalf("ok status must exit 0, got %v; stderr:\n%s", err, stderr) + } + if !strings.Contains(stderr, "nothing to post") { + t.Fatalf("expected the nothing-to-post notice, got stderr:\n%s", stderr) + } + if strings.TrimSpace(stdout) != "" { + t.Fatalf("ok under dry run must print no comment body, got:\n%s", stdout) + } +} diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index f2ff7bee8b..40519ae52b 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -111,11 +111,6 @@ if (( ${#comment} > MAX_COMMENT_CHARS )); then comment="${comment:0:${keep}}${TRUNCATION_MARKER}" fi -if [[ "${status}" == "ok" ]]; then - echo "post-__AGENT_NAME__: status=ok, nothing to post" >&2 - exit 0 -fi - # Derive the repo and number from the work item URL rather than trusting extra # environment. The pattern also rejects anything that is not a github.com URL. url_re='^https://github[.]com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)/(issues|pull)/([0-9]+)$' @@ -126,6 +121,26 @@ 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; replace +# that comment (same marker, edited in place) with the all-clear. +if [[ "${status}" == "ok" ]]; then + if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then + echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 + exit 0 + fi + earlier=0 + while read -r n; do earlier=$(( earlier + n )); done < <( + gh api --paginate "repos/${REPO}/issues/${NUMBER}/comments" \ + --jq --arg m "${MARKER}" '[.[] | select(.body | contains($m))] | length') + if (( earlier == 0 )); then + echo "post-__AGENT_NAME__: status=ok, nothing to post" >&2 + exit 0 + fi + echo "post-__AGENT_NAME__: status=ok, replacing the earlier findings comment with the all-clear" >&2 +fi + if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then printf '**%s**\n\n%s\n' "${summary}" "${comment}" echo "post-__AGENT_NAME__: dry run, not posting" >&2 diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index caeeb2e4f3..98e83e478f 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -263,11 +263,6 @@ if (( ${#comment} > MAX_COMMENT_CHARS )); then comment="${comment:0:${keep}}${TRUNCATION_MARKER}" fi -if [[ "${status}" == "ok" ]]; then - echo "post-lint-docs: status=ok, nothing to post" >&2 - exit 0 -fi - # Derive the repo and number from the work item URL rather than trusting extra # environment. The pattern also rejects anything that is not a github.com URL. url_re='^https://github[.]com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)/(issues|pull)/([0-9]+)$' @@ -278,6 +273,26 @@ 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; replace +# that comment (same marker, edited in place) with the all-clear. +if [[ "${status}" == "ok" ]]; then + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then + echo "post-lint-docs: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 + exit 0 + fi + earlier=0 + while read -r n; do earlier=$(( earlier + n )); done < <( + gh api --paginate "repos/${REPO}/issues/${NUMBER}/comments" \ + --jq --arg m "${MARKER}" '[.[] | select(.body | contains($m))] | length') + if (( earlier == 0 )); then + echo "post-lint-docs: status=ok, nothing to post" >&2 + exit 0 + fi + echo "post-lint-docs: status=ok, replacing the earlier findings comment with the all-clear" >&2 +fi + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then printf '**%s**\n\n%s\n' "${summary}" "${comment}" echo "post-lint-docs: dry run, not posting" >&2 diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index 8b47497613..38c512ccf2 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -271,11 +271,6 @@ if (( ${#comment} > MAX_COMMENT_CHARS )); then comment="${comment:0:${keep}}${TRUNCATION_MARKER}" fi -if [[ "${status}" == "ok" ]]; then - echo "post-lint-docs: status=ok, nothing to post" >&2 - exit 0 -fi - # Derive the repo and number from the work item URL rather than trusting extra # environment. The pattern also rejects anything that is not a github.com URL. url_re='^https://github[.]com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)/(issues|pull)/([0-9]+)$' @@ -286,6 +281,26 @@ 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; replace +# that comment (same marker, edited in place) with the all-clear. +if [[ "${status}" == "ok" ]]; then + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then + echo "post-lint-docs: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 + exit 0 + fi + earlier=0 + while read -r n; do earlier=$(( earlier + n )); done < <( + gh api --paginate "repos/${REPO}/issues/${NUMBER}/comments" \ + --jq --arg m "${MARKER}" '[.[] | select(.body | contains($m))] | length') + if (( earlier == 0 )); then + echo "post-lint-docs: status=ok, nothing to post" >&2 + exit 0 + fi + echo "post-lint-docs: status=ok, replacing the earlier findings comment with the all-clear" >&2 +fi + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then printf '**%s**\n\n%s\n' "${summary}" "${comment}" echo "post-lint-docs: dry run, not posting" >&2 From 10e0b762a5863add8582644085f8d65b9758ab10 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 18:24:24 -0400 Subject: [PATCH 07/16] feat(#6966): issues post-comment --only-if-exists; the generated ok path uses it The previous ok-path check called gh api --jq with a jq --arg it does not have, inside a process substitution that hid the failure, so it always concluded there was no earlier comment. Replace the shell check with a flag on the forge-backed primitive: --only-if-exists updates an existing marked comment and never creates one. The generated post-script now pipes the all-clear through fullsend issues post-comment --only-if-exists on ok. Tests: fake-client create-skipped and update cases, and an exec test with a stub fullsend on PATH proving the live ok path delegates to it. Goldens regenerated. Assisted-by: Claude Signed-off-by: Wayne Sun --- docs/guides/user/issues-commands.md | 1 + internal/agentnew/postscript_exec_test.go | 43 ++++++++++++++++ internal/agentnew/templates/post.sh.tmpl | 24 +++++---- internal/agentnew/testdata/golden/triage.txt | 24 +++++---- .../testdata/golden/validation-loop.txt | 24 +++++---- internal/cli/issues.go | 41 +++++++++------ internal/cli/issues_test.go | 50 +++++++++++++++++++ internal/sticky/sticky.go | 9 ++++ 8 files changed, 169 insertions(+), 47 deletions(-) diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index 0956c825d6..b751564e0e 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -87,6 +87,7 @@ echo "Triage complete. See PR #99." | fullsend issues post-comment \ | `--jira-email` | Jira only | Jira user email for auth (default: `$JIRA_USER_EMAIL`) | | `--dry-run` | No | Print what would be posted without making API calls | | `--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 replaced while a clean first run posts nothing. | | `--fullsend-dir` | No | Path to `.fullsend` config directory (sources defaults from its `config.yaml` when flags are omitted) | ### Jira marker storage diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index 6929b0d8fb..3bc5ffba6c 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -225,3 +225,46 @@ func TestGeneratedPostScriptOkPostsNothingWithoutAnEarlierComment(t *testing.T) t.Fatalf("ok under dry run must print no comment body, got:\n%s", stdout) } } + +// TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists runs the +// live ok path (no dry run) against a stub `fullsend` on PATH that records +// its arguments. The script must delegate the "is there an earlier findings +// comment" decision to `fullsend issues post-comment --only-if-exists` +// rather than reimplementing it with raw API calls in shell. +func TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + binDir := t.TempDir() + argsFile := filepath.Join(binDir, "args") + stub := "#!/usr/bin/env bash\nprintf '%s\\n' \"$@\" > " + argsFile + "\ncat >/dev/null\n" + if err := os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + cmd := exec.Command("bash", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH"), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + ) + var stderr strings.Builder + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + t.Fatalf("ok live path must exit 0, got %v; stderr:\n%s", err, stderr.String()) + } + got, err := os.ReadFile(argsFile) + if err != nil { + t.Fatalf("the script never invoked fullsend on the ok path: %v; stderr:\n%s", err, stderr.String()) + } + args := string(got) + for _, want := range []string{"issues\npost-comment\n", "--only-if-exists\n", "--marker\n", "fullsend-ai/demo\n", "99\n"} { + if !strings.Contains(args, want) { + t.Errorf("fullsend was called without %q; args:\n%s", strings.TrimSpace(want), args) + } + } +} diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index 40519ae52b..adbbc7193d 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -123,22 +123,24 @@ 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; replace -# that comment (same marker, edited in place) with the all-clear. +# problem the author has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend replace that comment (same marker, found +# through the forge client and the bot's own author) with the all-clear, +# and post nothing when there is no earlier comment. if [[ "${status}" == "ok" ]]; then if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 exit 0 fi - earlier=0 - while read -r n; do earlier=$(( earlier + n )); done < <( - gh api --paginate "repos/${REPO}/issues/${NUMBER}/comments" \ - --jq --arg m "${MARKER}" '[.[] | select(.body | contains($m))] | length') - if (( earlier == 0 )); then - echo "post-__AGENT_NAME__: status=ok, nothing to post" >&2 - exit 0 - fi - echo "post-__AGENT_NAME__: status=ok, replacing the earlier findings comment with the all-clear" >&2 + printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ + | fullsend issues post-comment \ + --tracker github \ + --project "${REPO}" \ + --number "${NUMBER}" \ + --marker "${MARKER}" \ + --only-if-exists \ + --result - + exit 0 fi if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index 98e83e478f..92322d251e 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -275,22 +275,24 @@ 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; replace -# that comment (same marker, edited in place) with the all-clear. +# problem the author has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend replace that comment (same marker, found +# through the forge client and the bot's own author) with the all-clear, +# and post nothing when there is no earlier comment. if [[ "${status}" == "ok" ]]; then if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then echo "post-lint-docs: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 exit 0 fi - earlier=0 - while read -r n; do earlier=$(( earlier + n )); done < <( - gh api --paginate "repos/${REPO}/issues/${NUMBER}/comments" \ - --jq --arg m "${MARKER}" '[.[] | select(.body | contains($m))] | length') - if (( earlier == 0 )); then - echo "post-lint-docs: status=ok, nothing to post" >&2 - exit 0 - fi - echo "post-lint-docs: status=ok, replacing the earlier findings comment with the all-clear" >&2 + printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ + | fullsend issues post-comment \ + --tracker github \ + --project "${REPO}" \ + --number "${NUMBER}" \ + --marker "${MARKER}" \ + --only-if-exists \ + --result - + exit 0 fi if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index 38c512ccf2..04061ec4ab 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -283,22 +283,24 @@ 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; replace -# that comment (same marker, edited in place) with the all-clear. +# problem the author has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend replace that comment (same marker, found +# through the forge client and the bot's own author) with the all-clear, +# and post nothing when there is no earlier comment. if [[ "${status}" == "ok" ]]; then if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then echo "post-lint-docs: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 exit 0 fi - earlier=0 - while read -r n; do earlier=$(( earlier + n )); done < <( - gh api --paginate "repos/${REPO}/issues/${NUMBER}/comments" \ - --jq --arg m "${MARKER}" '[.[] | select(.body | contains($m))] | length') - if (( earlier == 0 )); then - echo "post-lint-docs: status=ok, nothing to post" >&2 - exit 0 - fi - echo "post-lint-docs: status=ok, replacing the earlier findings comment with the all-clear" >&2 + printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ + | fullsend issues post-comment \ + --tracker github \ + --project "${REPO}" \ + --number "${NUMBER}" \ + --marker "${MARKER}" \ + --only-if-exists \ + --result - + exit 0 fi if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then diff --git a/internal/cli/issues.go b/internal/cli/issues.go index 928c1e8e27..4b9ed58696 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -169,17 +169,18 @@ func runIssuesGet(ctx context.Context, cfg *issuesGetConfig) error { // issuesPostCommentConfig holds the flags and test overrides for // "fullsend issues post-comment". type issuesPostCommentConfig struct { - trackerName string - project string - number int - marker string - result string - token string - jiraURL string - jiraEmail string - dryRun bool - keepHistory *bool // nil = resolve from config; non-nil = explicit flag - fullsendDir string + trackerName string + project string + number int + marker string + result string + token string + jiraURL string + jiraEmail string + dryRun bool + onlyIfExists bool + keepHistory *bool // nil = resolve from config; non-nil = explicit flag + fullsendDir string // Test overrides — when non-nil, used instead of creating a real // tracker client. Not set by CLI flag parsing. @@ -242,6 +243,7 @@ The --result flag accepts a file path or "-" for stdin.`, cmd.Flags().StringVar(&cfg.jiraURL, "jira-url", "", "Jira instance URL (default: $JIRA_BASE_URL)") cmd.Flags().StringVar(&cfg.jiraEmail, "jira-email", "", "Jira user email for Basic auth (default: $JIRA_USER_EMAIL)") cmd.Flags().BoolVar(&cfg.dryRun, "dry-run", false, "print what would be posted without making API calls") + cmd.Flags().BoolVar(&cfg.onlyIfExists, "only-if-exists", false, "update an existing comment with this marker but never create one (for an all-clear that should replace earlier findings)") cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "append previous content as collapsed history blocks (set false to replace in-place)") cmd.Flags().StringVar(&cfg.fullsendDir, "fullsend-dir", "", "path to .fullsend config directory (sources defaults from its config.yaml when flags are omitted)") _ = cmd.MarkFlagRequired("project") @@ -293,9 +295,10 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err } stickyCfg := sticky.Config{ - Marker: cfg.marker, - DryRun: cfg.dryRun, - KeepHistory: keepHistory, + Marker: cfg.marker, + DryRun: cfg.dryRun, + KeepHistory: keepHistory, + OnlyIfExists: cfg.onlyIfExists, } if trackerName == trackerJira { // The Jira write path routes every body through @@ -374,6 +377,11 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project return "", nil // Jira has no stable comment permalink } + if cfg.OnlyIfExists { + printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") + return "", nil + } + printer.StepStart("No existing comment found, creating new one") if cfg.DryRun { @@ -434,6 +442,11 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return existing.HTMLURL, nil } + if cfg.OnlyIfExists { + printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") + return "", nil + } + printer.StepStart("No existing comment found, creating new one") if cfg.DryRun { diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 066448f51d..74f9597320 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -1005,3 +1005,53 @@ func TestIssuesPostCommentCmd_TrackerNotRequired(t *testing.T) { assert.NotContains(t, err.Error(), `required flag(s) "tracker"`) assert.Contains(t, err.Error(), "--tracker is required") } + +func TestRunIssuesPostComment_OnlyIfExists_SkipsCreate(t *testing.T) { + fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" + tc := tracker.NewForgeClient(fc) + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: "", + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + + require.NoError(t, runIssuesPostComment(context.Background(), cfg)) + + comments, err := tc.ListComments(context.Background(), "acme/widgets", 42) + require.NoError(t, err) + assert.Empty(t, comments, "only-if-exists must not create a first comment") +} + +func TestRunIssuesPostComment_OnlyIfExists_ReplacesEarlierFindings(t *testing.T) { + fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" + tc := tracker.NewForgeClient(fc) + ctx := context.Background() + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: "", + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "2 broken links", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + cfg.onlyIfExists = true + cfg.testBody = "all clear" + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.Contains(t, string(comments[0].Body), "all clear") +} diff --git a/internal/sticky/sticky.go b/internal/sticky/sticky.go index 0b0a014862..a686bd70ed 100644 --- a/internal/sticky/sticky.go +++ b/internal/sticky/sticky.go @@ -21,6 +21,10 @@ type Config struct { MaxSize int // max comment body size (default 65000) DryRun bool KeepHistory bool // when false, updates replace the body in-place with no "Previous run" history + // OnlyIfExists updates an existing marked comment but never creates one: + // a post-script uses it on an all-clear result so an earlier findings + // comment is replaced while a clean first run stays silent. + OnlyIfExists bool } func (c Config) maxSize() int { @@ -72,6 +76,11 @@ func Post(ctx context.Context, client forge.Client, owner, repo string, number i return existing.HTMLURL, nil } + if cfg.OnlyIfExists { + printer.StepInfo("No existing comment with this marker; nothing to post (only-if-exists)") + return "", nil + } + printer.StepStart("No existing comment found, creating new one") if cfg.DryRun { From baaac7f89d1a6d45fa7e034c922db259edd01616 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 18:41:45 -0400 Subject: [PATCH 08/16] test(#6966): cover --only-if-exists on the forge-client and Jira paths Codecov flagged the OnlyIfExists branches in sticky.Post and the Jira sticky path as untested; both now have a skip-create and an update-existing case. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/cli/issues_test.go | 34 ++++++++++++++++++++++++++++++++++ internal/sticky/sticky_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 74f9597320..2715f6f5eb 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -1055,3 +1055,37 @@ func TestRunIssuesPostComment_OnlyIfExists_ReplacesEarlierFindings(t *testing.T) require.Len(t, comments, 1) assert.Contains(t, string(comments[0].Body), "all clear") } + +func TestRunIssuesPostComment_Jira_OnlyIfExists(t *testing.T) { + tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") + require.NoError(t, err) + ctx := context.Background() + + cfg := &issuesPostCommentConfig{ + trackerName: trackerJira, + project: "PROJ", + number: 42, + marker: "", + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + // No earlier comment: nothing is created. + require.NoError(t, runIssuesPostComment(ctx, cfg)) + comments, err := tc.ListComments(ctx, "PROJ", 42) + require.NoError(t, err) + assert.Empty(t, comments) + + // An earlier findings comment exists: it is replaced. + cfg.onlyIfExists = false + cfg.testBody = "2 broken links" + require.NoError(t, runIssuesPostComment(ctx, cfg)) + cfg.onlyIfExists = true + cfg.testBody = "all clear" + require.NoError(t, runIssuesPostComment(ctx, cfg)) + comments, err = tc.ListComments(ctx, "PROJ", 42) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.Contains(t, string(comments[0].Body), "all clear") +} diff --git a/internal/sticky/sticky_test.go b/internal/sticky/sticky_test.go index e65bf17b63..323c5e84f3 100644 --- a/internal/sticky/sticky_test.go +++ b/internal/sticky/sticky_test.go @@ -376,3 +376,30 @@ func TestPost_DryRunExisting(t *testing.T) { assert.Empty(t, client.UpdatedComments) } + +func TestPost_OnlyIfExists_SkipsCreate(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + cfg := Config{Marker: "", OnlyIfExists: true} + commentURL, err := Post(context.Background(), client, "o", "r", 1, "All clear.", cfg, printer) + require.NoError(t, err) + assert.Empty(t, commentURL) + assert.Empty(t, client.IssueComments["o/r/1"], "only-if-exists must not create a first comment") +} + +func TestPost_OnlyIfExists_UpdatesExisting(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: "\n2 broken links", Author: "bot"}}, + } + printer := ui.New(io.Discard) + + cfg := Config{Marker: "", OnlyIfExists: true} + commentURL, err := Post(context.Background(), client, "o", "r", 1, "All clear.", cfg, printer) + require.NoError(t, err) + assert.Equal(t, "https://github.com/o/r/issues/1#issuecomment-100", commentURL) + require.Len(t, client.UpdatedComments, 1) +} From 8a9628d7fd8be67d7f5ec1d3e241ccaaa9224ad0 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 18:47:11 -0400 Subject: [PATCH 09/16] fix(#6966): detect --only-if-exists before using it on the ok path The runner's fullsend is pinned by the repository's fullsend-ref, not by the CLI that generated the post-script, so an older runner would fail the common ok path on an unknown flag. The script now checks post-comment --help for the flag and, when absent, keeps the previous behaviour (post nothing) with a notice. Exec tests cover both a CLI that has the flag and one that does not. Assisted-by: Claude Signed-off-by: Wayne Sun --- internal/agentnew/postscript_exec_test.go | 43 ++++++++++++++++++- internal/agentnew/templates/post.sh.tmpl | 8 ++++ internal/agentnew/testdata/golden/triage.txt | 8 ++++ .../testdata/golden/validation-loop.txt | 8 ++++ 4 files changed, 66 insertions(+), 1 deletion(-) diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index 3bc5ffba6c..cfb205fd32 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -237,7 +237,7 @@ func TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists(t *testing. } binDir := t.TempDir() argsFile := filepath.Join(binDir, "args") - stub := "#!/usr/bin/env bash\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'; 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) } @@ -268,3 +268,44 @@ func TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists(t *testing. } } } + +// TestGeneratedPostScriptOkOnAnOlderFullsendPostsNothing pins the +// degradation path: the runner's fullsend is pinned by the repository, not +// by the CLI that generated the script, so when its post-comment has no +// --only-if-exists the ok path must post nothing and exit 0 rather than fail +// on an unknown flag. +func TestGeneratedPostScriptOkOnAnOlderFullsendPostsNothing(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + binDir := t.TempDir() + argsFile := filepath.Join(binDir, "args") + // An older CLI: --help lists no --only-if-exists, and any real call + // with that flag would fail — so the stub fails loudly if invoked to post. + stub := "#!/usr/bin/env bash\nif [[ \"$*\" == *--help* ]]; then echo ' --dry-run print what would be posted'; exit 0; fi\nprintf '%s\\n' \"$@\" > " + argsFile + "\necho 'Error: unknown flag: --only-if-exists' >&2; exit 1\n" + if err := os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + cmd := exec.Command("bash", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH"), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + ) + var stderr strings.Builder + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + t.Fatalf("ok on an older fullsend must exit 0, got %v; stderr:\n%s", err, stderr.String()) + } + if !strings.Contains(stderr.String(), "nothing to post") { + t.Fatalf("expected the nothing-to-post notice, got:\n%s", stderr.String()) + } + if _, err := os.Stat(argsFile); err == nil { + t.Fatalf("an older fullsend must not be asked to post on the ok path") + } +} diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index adbbc7193d..1d6fd64325 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -132,6 +132,14 @@ if [[ "${status}" == "ok" ]]; then echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 exit 0 fi + # The runner's fullsend may predate --only-if-exists (it is pinned by the + # repository's fullsend-ref, not by the CLI that generated this script). + # Detect the flag instead of assuming it: on an older CLI, keep the old + # behaviour — post nothing — rather than fail the common ok path. + if ! fullsend issues post-comment --help 2>&1 | grep -q -- '--only-if-exists'; then + echo "post-__AGENT_NAME__: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 + exit 0 + fi 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 92322d251e..cf688e801f 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -284,6 +284,14 @@ if [[ "${status}" == "ok" ]]; then echo "post-lint-docs: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 exit 0 fi + # The runner's fullsend may predate --only-if-exists (it is pinned by the + # repository's fullsend-ref, not by the CLI that generated this script). + # Detect the flag instead of assuming it: on an older CLI, keep the old + # behaviour — post nothing — rather than fail the common ok path. + if ! fullsend issues post-comment --help 2>&1 | grep -q -- '--only-if-exists'; then + echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 + exit 0 + fi 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 04061ec4ab..319f8e577c 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -292,6 +292,14 @@ if [[ "${status}" == "ok" ]]; then echo "post-lint-docs: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 exit 0 fi + # The runner's fullsend may predate --only-if-exists (it is pinned by the + # repository's fullsend-ref, not by the CLI that generated this script). + # Detect the flag instead of assuming it: on an older CLI, keep the old + # behaviour — post nothing — rather than fail the common ok path. + if ! fullsend issues post-comment --help 2>&1 | grep -q -- '--only-if-exists'; then + echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 + exit 0 + fi printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ From c08363131e1962e600aec1653b3577148bb742a2 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 11 Sep 2026 19:12:19 -0400 Subject: [PATCH 10/16] docs(#6966): list --only-if-exists in the CLI internals reference Assisted-by: Claude Signed-off-by: Wayne Sun --- docs/guides/dev/cli-internals.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index ccd70719fe..f9ceb475ca 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -155,6 +155,7 @@ fullsend │ ├── --number # Issue number │ ├── --marker # Sticky marker for idempotent updates (HTML comment or Jira property) │ ├── --keep-history # Append previous content as collapsed history (default true) +│ ├── --only-if-exists # Update an existing marked comment, never create one │ └── --fullsend-dir # .fullsend config directory (resolves keep_history default) ├── post-review # Post sticky PR/MR review comments (formal review is best-effort) │ ├── --forge # Forge backend: github (default) or gitlab From 9211ed973d35b3683f4cf749a145a4970e2926fb Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 30 Sep 2026 20:42:12 -0400 Subject: [PATCH 11/16] fix(#6966): match only the poster's own comment under --only-if-exists The tracker path looked up the earlier comment by marker text alone, so anyone could plant a comment carrying an agent's marker and every all-clear run would then target it. With --only-if-exists the lookup now requires the comment's author to be exactly the login the client posts as, resolved through forge.Client.GetAuthenticatedUser (which also handles App installation tokens via GraphQL viewer). When that login cannot be resolved, nothing is posted: an unverified comment is never edited. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- internal/cli/issues.go | 62 ++++++++++++++++++++++---- internal/cli/issues_test.go | 74 ++++++++++++++++++++++++++++++-- internal/tracker/forge_client.go | 7 +++ 3 files changed, 131 insertions(+), 12 deletions(-) diff --git a/internal/cli/issues.go b/internal/cli/issues.go index 4b9ed58696..146a9b4ab4 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -403,11 +403,17 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project // sticky.Post: find an existing comment bearing the marker, collapse // old content into history, and create or update in-place. // -// Unlike sticky.Post, this function does not perform bot-user -// verification for marker spoofing protection (tracker.Client has no -// GetAuthenticatedUser method). This is acceptable because the new -// command is used by agents in trusted CI environments, not by -// untrusted external callers. +// Unlike sticky.Post, this function does not by default perform +// bot-user verification for marker spoofing protection. This is +// acceptable because the command is used by agents in trusted CI +// environments, not by untrusted external callers. +// +// OnlyIfExists is the exception: it runs on every clean result, and the +// comment it edits must be the poster's own earlier findings, not one +// anyone could plant with the same marker. It therefore matches only +// comments whose author is exactly the login this client posts as. When +// that login cannot be resolved it posts nothing rather than fall back to +// marker-only matching: an unverified comment is never edited. func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project string, number int, body string, cfg sticky.Config, printer *ui.Printer) (string, error) { if strings.TrimSpace(body) == "" { return "", fmt.Errorf("comment body is empty") @@ -416,12 +422,22 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return "", fmt.Errorf("marker is empty") } + botUser := "" + if cfg.OnlyIfExists { + self, err := resolveTrackerSelf(ctx, tc) + if err != nil { + printer.StepWarn(fmt.Sprintf("Cannot verify who posted earlier comments (%v); nothing to post (--only-if-exists)", err)) + return "", nil + } + botUser = self + } + comments, err := tc.ListComments(ctx, project, number) if err != nil { return "", fmt.Errorf("listing comments: %w", err) } - existing := findMarkedTrackerComment(comments, cfg.Marker) + existing := findMarkedTrackerComment(comments, cfg.Marker, botUser) markedBody := cfg.Marker + "\n" + body if existing != nil { @@ -528,11 +544,39 @@ func resolveKeepHistory(flag *bool, fullsendDir string, testConfigReader config. return true, nil } +// authenticatedUserResolver is implemented by tracker clients that can +// report who they are authenticated as (tracker.ForgeClient). +type authenticatedUserResolver interface { + AuthenticatedUser(ctx context.Context) (string, error) +} + +// resolveTrackerSelf returns the exact login tc posts as. For GitHub this +// goes through forge.Client.GetAuthenticatedUser, which also resolves an +// App installation token (GraphQL viewer) where GET /user is refused. +func resolveTrackerSelf(ctx context.Context, tc tracker.Client) (string, error) { + ar, ok := tc.(authenticatedUserResolver) + if !ok { + return "", fmt.Errorf("this tracker cannot report the authenticated user") + } + self, err := ar.AuthenticatedUser(ctx) + if err != nil { + return "", err + } + if self == "" { + return "", fmt.Errorf("the authenticated user is empty") + } + return self, nil +} + // findMarkedTrackerComment returns the first tracker comment whose body -// contains the given marker string, or nil if none is found. This is -// the tracker.Comment equivalent of sticky.FindMarkedComment. -func findMarkedTrackerComment(comments []tracker.Comment, marker string) *tracker.Comment { +// contains the given marker string, or nil if none is found. When botUser +// is non-empty, only comments authored by botUser match. This is the +// tracker.Comment equivalent of sticky.FindMarkedComment. +func findMarkedTrackerComment(comments []tracker.Comment, marker, botUser string) *tracker.Comment { for i := range comments { + if botUser != "" && comments[i].Author != botUser { + continue + } if strings.Contains(string(comments[i].Body), marker) { return &comments[i] } diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 2715f6f5eb..68bac2a896 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -80,7 +81,7 @@ func TestFindMarkedTrackerComment(t *testing.T) { {ID: "3", Body: "another comment"}, } - found := findMarkedTrackerComment(comments, marker) + found := findMarkedTrackerComment(comments, marker, "") require.NotNil(t, found) assert.Equal(t, "2", found.ID) } @@ -90,12 +91,12 @@ func TestFindMarkedTrackerComment_NotFound(t *testing.T) { {ID: "1", Body: "no marker here"}, } - found := findMarkedTrackerComment(comments, "") + found := findMarkedTrackerComment(comments, "", "") assert.Nil(t, found) } func TestFindMarkedTrackerComment_Empty(t *testing.T) { - found := findMarkedTrackerComment(nil, "") + found := findMarkedTrackerComment(nil, "", "") assert.Nil(t, found) } @@ -1089,3 +1090,70 @@ func TestRunIssuesPostComment_Jira_OnlyIfExists(t *testing.T) { require.Len(t, comments, 1) assert.Contains(t, string(comments[0].Body), "all clear") } + +// runOnlyIfExistsAfterCommentBy seeds one marker comment as author, then runs an +// --only-if-exists all-clear as the bot "fullsend-ai-review[bot]". +func runOnlyIfExistsAfterCommentBy(t *testing.T, author string, botErr error) []tracker.Comment { + t.Helper() + ctx := context.Background() + fc := forge.NewFakeClient() + tc := tracker.NewForgeClient(fc) + const marker = "" + + fc.AuthenticatedUser = author + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nplanted findings")) + require.NoError(t, err) + + fc.AuthenticatedUser = "fullsend-ai-review[bot]" + if botErr != nil { + fc.Errors = map[string]error{"GetAuthenticatedUser": botErr} + } + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + return comments +} + +func TestRunIssuesPostComment_OnlyIfExists_IgnoresMarkerFromAnotherUser(t *testing.T) { + comments := runOnlyIfExistsAfterCommentBy(t, "mallory", nil) + require.Len(t, comments, 1, "only-if-exists must neither edit a planted comment nor create one") + assert.Contains(t, string(comments[0].Body), "planted findings") + assert.NotContains(t, string(comments[0].Body), "all clear") +} + +func TestRunIssuesPostComment_OnlyIfExists_IgnoresLookalikeBotLogin(t *testing.T) { + // Login shape is not identity: a different App whose login merely shares + // the "[bot]" suffix, or a prefix, must not match. + for _, author := range []string{"evil-review[bot]", "fullsend-ai-review", "x-fullsend-ai-review[bot]"} { + t.Run(author, func(t *testing.T) { + comments := runOnlyIfExistsAfterCommentBy(t, author, nil) + require.Len(t, comments, 1) + assert.NotContains(t, string(comments[0].Body), "all clear") + }) + } +} + +func TestRunIssuesPostComment_OnlyIfExists_EditsOwnComment(t *testing.T) { + comments := runOnlyIfExistsAfterCommentBy(t, "fullsend-ai-review[bot]", nil) + require.Len(t, comments, 1) + assert.Contains(t, string(comments[0].Body), "all clear") +} + +func TestRunIssuesPostComment_OnlyIfExists_UnresolvableSelfPostsNothing(t *testing.T) { + // Even the bot's own comment is left alone when the poster's login cannot + // be resolved: an unverified comment is never edited. + comments := runOnlyIfExistsAfterCommentBy(t, "fullsend-ai-review[bot]", errors.New("401 Bad credentials")) + require.Len(t, comments, 1) + assert.NotContains(t, string(comments[0].Body), "all clear") +} diff --git a/internal/tracker/forge_client.go b/internal/tracker/forge_client.go index 42e47b83e4..36de0e500e 100644 --- a/internal/tracker/forge_client.go +++ b/internal/tracker/forge_client.go @@ -24,6 +24,13 @@ func NewForgeClient(fc forge.Client) *ForgeClient { return &ForgeClient{forge: fc} } +// AuthenticatedUser returns the login the underlying forge client is +// authenticated as, so a caller can tell the bot's own comments from +// anyone else's. +func (c *ForgeClient) AuthenticatedUser(ctx context.Context) (string, error) { + return c.forge.GetAuthenticatedUser(ctx) +} + // GetIssue implements Client by splitting project into owner/repo for the // underlying forge call. func (c *ForgeClient) GetIssue(ctx context.Context, project string, number int) (*Issue, error) { From ab0d3f0d898213dfb3ff76b90dfc796e9f33eed1 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 30 Sep 2026 20:42:15 -0400 Subject: [PATCH 12/16] fix(#6966): tighten the generated ok path and its tests - Describe the author check the ok path now relies on accurately. - Read the whole help text when detecting --only-if-exists, so an early grep exit cannot SIGPIPE fullsend into a false "flag missing". - Say plainly that a dry run does not check for an earlier comment. - Cover CR-only and CRLF statuses in the flattening test, and name the dry-run ok test for what it pins. - Docs: an all-clear updates the earlier comment in place, keeping the old findings as history unless --keep-history=false. Goldens regenerated; the diff is the template change only. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- docs/guides/user/issues-commands.md | 2 +- internal/agentnew/postscript_exec_test.go | 65 ++++++++++--------- internal/agentnew/templates/post.sh.tmpl | 14 ++-- internal/agentnew/testdata/golden/triage.txt | 14 ++-- .../testdata/golden/validation-loop.txt | 14 ++-- 5 files changed, 62 insertions(+), 47 deletions(-) diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index b751564e0e..ed2c36fb42 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -87,7 +87,7 @@ echo "Triage complete. See PR #99." | fullsend issues post-comment \ | `--jira-email` | Jira only | Jira user email for auth (default: `$JIRA_USER_EMAIL`) | | `--dry-run` | No | Print what would be posted without making API calls | | `--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 replaced while a clean first run posts nothing. | +| `--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, nothing is posted. | | `--fullsend-dir` | No | Path to `.fullsend` config directory (sources defaults from its `config.yaml` when flags are omitted) | ### Jira marker storage diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index cfb205fd32..553c86fe2c 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -132,36 +132,40 @@ func TestGeneratedPostScriptRunsFromTheRunDirectory(t *testing.T) { } // TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging feeds a status -// that carries a newline and a workflow-command prefix. The rejection message -// must stay on one line and must not reproduce the injected line, because -// the script's stderr lands in the runner log where `::` at line start is -// interpreted as a command. +// that carries a line break (LF, CR alone, or CRLF) and a workflow-command +// prefix. The rejection message must stay on one line and must not reproduce +// the injected line, because the script's stderr lands in the runner log +// where `::` at line start is interpreted as a command. func TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging(t *testing.T) { if _, err := exec.LookPath("jq"); err != nil { t.Skip("jq not installed; the generated post-script needs it") } script := renderPostScriptTo(t, t.TempDir()) - runDir := writeRunDir(t, map[string]any{ - "iteration-1": map[string]any{ - "status": "bogus\n::error::injected", - "summary": "s", - "comment": "c", - }, - }) - _, stderr, err := runPostScript(t, script, runDir) - if err == nil { - t.Fatal("expected the script to reject an invalid status") - } - if !strings.Contains(stderr, "status must be ok, findings or error") { - t.Fatalf("expected the status rejection, got stderr:\n%s", stderr) - } - for _, line := range strings.Split(strings.TrimSpace(stderr), "\n") { - if strings.HasPrefix(line, "::") { - t.Fatalf("model-supplied status reached the log as its own line: %q", line) - } - } - if strings.Count(strings.TrimSpace(stderr), "\n") != 0 { - t.Fatalf("rejection must be a single log line, got:\n%s", stderr) + for name, brk := range map[string]string{"LF": "\n", "CR": "\r", "CRLF": "\r\n"} { + t.Run(name, func(t *testing.T) { + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{ + "status": "bogus" + brk + "::error::injected", + "summary": "s", + "comment": "c", + }, + }) + _, stderr, err := runPostScript(t, script, runDir) + if err == nil { + t.Fatal("expected the script to reject an invalid status") + } + if !strings.Contains(stderr, "status must be ok, findings or error") { + t.Fatalf("expected the status rejection, got stderr:\n%s", stderr) + } + for _, line := range strings.FieldsFunc(stderr, func(r rune) bool { return r == '\n' || r == '\r' }) { + if strings.HasPrefix(line, "::") { + t.Fatalf("model-supplied status reached the log as its own line: %q", line) + } + } + if strings.ContainsRune(stderr, '\r') || strings.Count(strings.TrimSpace(stderr), "\n") != 0 { + t.Fatalf("rejection must be a single log line, got: %q", stderr) + } + }) } } @@ -201,12 +205,11 @@ func TestGeneratedPostScriptDoesNotExpandEscapesUnderXpgEcho(t *testing.T) { } } -// TestGeneratedPostScriptOkPostsNothingWithoutAnEarlierComment pins the ok -// path under dry run: the script exits 0 and says nothing was posted. The -// live path additionally looks for an earlier marker comment and replaces it -// with the all-clear; that needs the forge, so it is exercised by the -// example's script test in fullsend-ai/agents, not here. -func TestGeneratedPostScriptOkPostsNothingWithoutAnEarlierComment(t *testing.T) { +// TestGeneratedPostScriptOkDryRunPostsNothing pins the ok path under dry +// run: the script exits 0 and says nothing was posted, without looking for +// an earlier comment. The live path is covered by the stubbed-fullsend tests +// below; the author check it relies on is tested in internal/cli. +func TestGeneratedPostScriptOkDryRunPostsNothing(t *testing.T) { if _, err := exec.LookPath("jq"); err != nil { t.Skip("jq not installed; the generated post-script needs it") } diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index 1d6fd64325..7fe1b844c0 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -124,19 +124,23 @@ 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 (same marker, found -# through the forge client and the bot's own author) with the all-clear, -# and post nothing when there is no earlier comment. +# --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; when that login cannot be resolved it posts nothing, so a +# comment anyone else planted with the marker is never edited. if [[ "${status}" == "ok" ]]; then if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then - echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 + echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 exit 0 fi # The runner's fullsend may predate --only-if-exists (it is pinned by the # repository's fullsend-ref, not by the CLI that generated this script). # Detect the flag instead of assuming it: on an older CLI, keep the old # behaviour — post nothing — rather than fail the common ok path. - if ! fullsend issues post-comment --help 2>&1 | grep -q -- '--only-if-exists'; then + # grep reads the whole help text (no -q): an early exit could SIGPIPE + # fullsend and, under pipefail, read as "flag missing". + if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; then echo "post-__AGENT_NAME__: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 exit 0 fi diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index cf688e801f..fee59c7f3d 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -276,19 +276,23 @@ 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 (same marker, found -# through the forge client and the bot's own author) with the all-clear, -# and post nothing when there is no earlier comment. +# --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; when that login cannot be resolved it posts nothing, so a +# comment anyone else planted with the marker is never edited. if [[ "${status}" == "ok" ]]; then if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then - echo "post-lint-docs: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 + echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 exit 0 fi # The runner's fullsend may predate --only-if-exists (it is pinned by the # repository's fullsend-ref, not by the CLI that generated this script). # Detect the flag instead of assuming it: on an older CLI, keep the old # behaviour — post nothing — rather than fail the common ok path. - if ! fullsend issues post-comment --help 2>&1 | grep -q -- '--only-if-exists'; then + # grep reads the whole help text (no -q): an early exit could SIGPIPE + # fullsend and, under pipefail, read as "flag missing". + if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; then echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 exit 0 fi diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index 319f8e577c..8ee7a5cba2 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -284,19 +284,23 @@ 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 (same marker, found -# through the forge client and the bot's own author) with the all-clear, -# and post nothing when there is no earlier comment. +# --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; when that login cannot be resolved it posts nothing, so a +# comment anyone else planted with the marker is never edited. if [[ "${status}" == "ok" ]]; then if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then - echo "post-lint-docs: status=ok, nothing to post (dry run: an earlier findings comment would be replaced with the all-clear)" >&2 + echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 exit 0 fi # The runner's fullsend may predate --only-if-exists (it is pinned by the # repository's fullsend-ref, not by the CLI that generated this script). # Detect the flag instead of assuming it: on an older CLI, keep the old # behaviour — post nothing — rather than fail the common ok path. - if ! fullsend issues post-comment --help 2>&1 | grep -q -- '--only-if-exists'; then + # grep reads the whole help text (no -q): an early exit could SIGPIPE + # fullsend and, under pipefail, read as "flag missing". + if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; then echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 exit 0 fi From f72f8bc3683ccc51714788fa964667d46be795a2 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 30 Sep 2026 20:52:00 -0400 Subject: [PATCH 13/16] fix(#6966)!: never edit a marker comment post-comment cannot verify as its own issues post-comment (GitHub, GitLab) edited the first comment carrying the marker, whoever wrote it. A planted marker comment therefore received the findings, and the --only-if-exists all-clear, which checks the author, could never replace them. The poster's identity is now always resolved, and an existing comment is edited only on an exact author and marker match; a planted one is ignored and a new comment posted. When the identity cannot be resolved, no comment is edited: a new one is posted with a warning naming the reason, or nothing under --only-if-exists. An empty identity matches nothing by construction. Jira, whose markers are comment properties, is unchanged. Help text and the user guide's trust model drop the "acceptable in trusted CI" caveat for the new rule. BREAKING CHANGE: issues post-comment (GitHub, GitLab) no longer edits a marker comment written by a different identity; after a token rotation or App migration the next run posts a new comment instead. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- docs/guides/user/issues-commands.md | 24 ++-- internal/cli/issues.go | 60 +++++----- internal/cli/issues_test.go | 169 ++++++++++++++++++++++++++-- 3 files changed, 202 insertions(+), 51 deletions(-) diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index ed2c36fb42..da7e4d0651 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -115,20 +115,18 @@ for how the `tracker` field resolves through the config overlay chain. ## Trust model -Marker-based comment lookup does not verify the comment author. In a -trusted CI environment (the intended deployment) this is safe because -only the bot writes marker-bearing comments. - For GitHub and GitLab, where markers are hidden HTML comments in the -body, an untrusted user who can post issue comments containing your -marker string could cause the bot to edit their comment instead of -creating its own. For Jira, markers are stored as comment entity -properties, which require comment-edit permissions to set — body-text -injection alone cannot spoof a marker. - -Do not use this command in environments where untrusted users can write -arbitrary issue comments bearing your marker (GitHub/GitLab) or have -comment-edit permissions (Jira). +body, an existing comment is edited only when it carries the marker +**and** its author is exactly the identity the command posts as. A +comment anyone else wrote with the same marker is ignored, never edited. +If that identity cannot be resolved, no existing comment is edited: the +command posts a new comment and logs a warning naming the reason, or +posts nothing with `--only-if-exists`. + +For Jira, markers are stored as comment entity properties, which require +comment-edit permissions to set — body-text injection alone cannot spoof +a marker. Do not use this command where untrusted users have +comment-edit permissions on your Jira project. ## Environment variables diff --git a/internal/cli/issues.go b/internal/cli/issues.go index 146a9b4ab4..7fde6bfbb6 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -212,14 +212,12 @@ 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: marker-based comment lookup does not verify the comment -author. In a trusted CI environment (the intended deployment) this -is safe because only the bot writes marker-bearing comments. If -untrusted users can post issue comments containing the marker -string, they could cause the bot to edit their comment instead of -creating its own. Do not use this command in environments where -untrusted users can write arbitrary issue comments bearing your -marker. +Trust model (GitHub, GitLab): an existing comment is edited only when +it carries the marker and its author is exactly the identity this +command posts as. A comment anyone else wrote with the same marker is +ignored, never edited. If that identity cannot be resolved, no existing +comment is edited: a new comment is posted instead, or nothing with +--only-if-exists. --tracker is required unless a default is supplied via config: set "tracker: github|gitlab|jira" in config.yaml and pass --fullsend-dir @@ -403,17 +401,12 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project // sticky.Post: find an existing comment bearing the marker, collapse // old content into history, and create or update in-place. // -// Unlike sticky.Post, this function does not by default perform -// bot-user verification for marker spoofing protection. This is -// acceptable because the command is used by agents in trusted CI -// environments, not by untrusted external callers. -// -// OnlyIfExists is the exception: it runs on every clean result, and the -// comment it edits must be the poster's own earlier findings, not one -// anyone could plant with the same marker. It therefore matches only -// comments whose author is exactly the login this client posts as. When -// that login cannot be resolved it posts nothing rather than fall back to -// marker-only matching: an unverified comment is never edited. +// 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, no +// existing comment is edited: a new comment is created instead, or, with +// OnlyIfExists, nothing is posted. func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project string, number int, body string, cfg sticky.Config, printer *ui.Printer) (string, error) { if strings.TrimSpace(body) == "" { return "", fmt.Errorf("comment body is empty") @@ -422,14 +415,16 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return "", fmt.Errorf("marker is empty") } - botUser := "" - if cfg.OnlyIfExists { - self, err := resolveTrackerSelf(ctx, tc) - if err != nil { - printer.StepWarn(fmt.Sprintf("Cannot verify who posted earlier comments (%v); nothing to post (--only-if-exists)", err)) + // An empty self matches nothing in findMarkedTrackerComment, so an + // unresolved identity can only lead to a new comment, never an edit. + self, selfErr := resolveTrackerSelf(ctx, tc) + if selfErr != nil { + if cfg.OnlyIfExists { + printer.StepWarn(fmt.Sprintf("Cannot verify who posted earlier comments (%v); nothing to post (--only-if-exists)", selfErr)) return "", nil } - botUser = self + printer.StepWarn(fmt.Sprintf("Cannot verify who posted earlier comments (%v); posting a new comment instead of editing one", selfErr)) + self = "" } comments, err := tc.ListComments(ctx, project, number) @@ -437,7 +432,7 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return "", fmt.Errorf("listing comments: %w", err) } - existing := findMarkedTrackerComment(comments, cfg.Marker, botUser) + existing := findMarkedTrackerComment(comments, cfg.Marker, self) markedBody := cfg.Marker + "\n" + body if existing != nil { @@ -569,12 +564,15 @@ func resolveTrackerSelf(ctx context.Context, tc tracker.Client) (string, error) } // findMarkedTrackerComment returns the first tracker comment whose body -// contains the given marker string, or nil if none is found. When botUser -// is non-empty, only comments authored by botUser match. This is the -// tracker.Comment equivalent of sticky.FindMarkedComment. -func findMarkedTrackerComment(comments []tracker.Comment, marker, botUser string) *tracker.Comment { +// contains the given marker string and whose author is exactly self, or nil +// if none is found. An empty self matches nothing: a comment whose author +// cannot be verified is never returned for editing. +func findMarkedTrackerComment(comments []tracker.Comment, marker, self string) *tracker.Comment { + if self == "" { + return nil + } for i := range comments { - if botUser != "" && comments[i].Author != botUser { + if comments[i].Author != self { continue } if strings.Contains(string(comments[i].Body), marker) { diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 68bac2a896..5dc59a1f45 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -76,14 +76,18 @@ func TestNewIssuesPostCommentCmd_DefaultFlags(t *testing.T) { func TestFindMarkedTrackerComment(t *testing.T) { marker := "" comments := []tracker.Comment{ - {ID: "1", Body: "irrelevant comment"}, - {ID: "2", Body: tracker.Body(marker + "\nsome content")}, - {ID: "3", Body: "another comment"}, + {ID: "1", Body: "irrelevant comment", Author: "bot"}, + {ID: "2", Body: tracker.Body(marker + "\nplanted"), Author: "mallory"}, + {ID: "3", Body: tracker.Body(marker + "\nsome content"), Author: "bot"}, + {ID: "4", Body: "another comment", Author: "bot"}, } - found := findMarkedTrackerComment(comments, marker, "") + found := findMarkedTrackerComment(comments, marker, "bot") require.NotNil(t, found) - assert.Equal(t, "2", found.ID) + assert.Equal(t, "3", found.ID) + + assert.Nil(t, findMarkedTrackerComment(comments, marker, ""), + "an unverified self must never match a comment for editing") } func TestFindMarkedTrackerComment_NotFound(t *testing.T) { @@ -91,12 +95,12 @@ func TestFindMarkedTrackerComment_NotFound(t *testing.T) { {ID: "1", Body: "no marker here"}, } - found := findMarkedTrackerComment(comments, "", "") + found := findMarkedTrackerComment(comments, "", "bot") assert.Nil(t, found) } func TestFindMarkedTrackerComment_Empty(t *testing.T) { - found := findMarkedTrackerComment(nil, "", "") + found := findMarkedTrackerComment(nil, "", "bot") assert.Nil(t, found) } @@ -1157,3 +1161,154 @@ func TestRunIssuesPostComment_OnlyIfExists_UnresolvableSelfPostsNothing(t *testi require.Len(t, comments, 1) assert.NotContains(t, string(comments[0].Body), "all clear") } + +func TestRunIssuesPostComment_OnlyIfExists_EmptySelfPostsNothing(t *testing.T) { + // An empty login with no error must not degrade to marker-only matching. + ctx := context.Background() + fc := forge.NewFakeClient() + tc := tracker.NewForgeClient(fc) + const marker = "" + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nplanted findings")) + require.NoError(t, err) + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.NotContains(t, string(comments[0].Body), "all clear") +} + +func TestRunIssuesPostComment_OnlyIfExists_SkipsPlantedCommentBeforeOwn(t *testing.T) { + // The realistic attack order: a planted marker comment listed first, the + // poster's own comment second. The planted one is skipped, the own one + // updated. + ctx := context.Background() + fc := forge.NewFakeClient() + tc := tracker.NewForgeClient(fc) + const marker = "" + + fc.AuthenticatedUser = "mallory" + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nplanted")) + require.NoError(t, err) + fc.AuthenticatedUser = "fullsend-ai-review[bot]" + _, err = tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\n2 broken links")) + require.NoError(t, err) + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + require.Len(t, comments, 2) + assert.Contains(t, string(comments[0].Body), "planted") + assert.NotContains(t, string(comments[0].Body), "all clear") + assert.Contains(t, string(comments[1].Body), "all clear") +} + +// runPostCommentAfterCommentBy seeds one marker comment as author, then runs +// a normal (create-or-update) post as "fullsend-ai-review[bot]". +func runPostCommentAfterCommentBy(t *testing.T, author string, botErr error) []tracker.Comment { + t.Helper() + ctx := context.Background() + fc := forge.NewFakeClient() + tc := tracker.NewForgeClient(fc) + const marker = "" + + fc.AuthenticatedUser = author + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nearlier")) + require.NoError(t, err) + + fc.AuthenticatedUser = "fullsend-ai-review[bot]" + if botErr != nil { + fc.Errors = map[string]error{"GetAuthenticatedUser": botErr} + } + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "2 broken links", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + return comments +} + +func TestRunIssuesPostComment_UpdatesOwnComment(t *testing.T) { + comments := runPostCommentAfterCommentBy(t, "fullsend-ai-review[bot]", nil) + require.Len(t, comments, 1) + assert.Contains(t, string(comments[0].Body), "2 broken links") +} + +func TestRunIssuesPostComment_PlantedMarkerGetsANewComment(t *testing.T) { + for _, author := range []string{"mallory", "evil-review[bot]", "x-fullsend-ai-review[bot]"} { + t.Run(author, func(t *testing.T) { + comments := runPostCommentAfterCommentBy(t, author, nil) + require.Len(t, comments, 2, "a planted marker comment must be left alone and a new one posted") + assert.NotContains(t, string(comments[0].Body), "2 broken links") + assert.Contains(t, string(comments[1].Body), "2 broken links") + }) + } +} + +func TestRunIssuesPostComment_UnresolvableSelfPostsNewComment(t *testing.T) { + // Even the poster's own earlier comment is not edited when the identity + // cannot be verified: a new comment is created instead. + comments := runPostCommentAfterCommentBy(t, "fullsend-ai-review[bot]", errors.New("401 Bad credentials")) + require.Len(t, comments, 2) + assert.NotContains(t, string(comments[0].Body), "2 broken links") + assert.Contains(t, string(comments[1].Body), "2 broken links") +} + +func TestRunIssuesPostComment_UnresolvableSelfWarnsWithTheReason(t *testing.T) { + for _, onlyIfExists := range []bool{false, true} { + t.Run(fmt.Sprintf("only-if-exists=%v", onlyIfExists), func(t *testing.T) { + ctx := context.Background() + fc := forge.NewFakeClient() + fc.Errors = map[string]error{"GetAuthenticatedUser": errors.New("401 Bad credentials")} + var out bytes.Buffer + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: "", + onlyIfExists: onlyIfExists, + testClient: tracker.NewForgeClient(fc), + testPrinter: ui.New(&out), + testBody: "body", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + assert.Contains(t, out.String(), "401 Bad credentials", "the warning must name why the identity is unverified") + if onlyIfExists { + assert.Contains(t, out.String(), "(401 Bad credentials); nothing to post (--only-if-exists)") + assert.NotContains(t, out.String(), "posting a new comment") + } else { + assert.Contains(t, out.String(), "(401 Bad credentials); posting a new comment instead of editing one") + } + }) + } +} From 842915698564842714559ffde03a8ea7b851830d Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 30 Sep 2026 20:56:31 -0400 Subject: [PATCH 14/16] test(#6966): pin that an unverified identity never edits an authorless comment A comment with no author and an unresolved (empty) identity must not match. The lookup's empty-identity guard was only covered indirectly. Help text, the user guide and the generated script's comment now say an existing comment is found by its marker and its own author. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- docs/guides/user/issues-commands.md | 3 +- internal/agentnew/templates/post.sh.tmpl | 4 +-- internal/agentnew/testdata/golden/triage.txt | 4 +-- .../testdata/golden/validation-loop.txt | 4 +-- internal/cli/issues.go | 3 +- internal/cli/issues_test.go | 30 +++++++++++++++++++ 6 files changed, 40 insertions(+), 8 deletions(-) diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index da7e4d0651..fd73d593e3 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -54,7 +54,8 @@ fullsend issues get \ ## `fullsend issues post-comment` Posts a comment with a sticky marker on an issue. On re-runs, finds -the existing comment by its marker and edits in-place. By default, +the existing comment by its marker and its own author (see +[Trust model](#trust-model)) and edits in-place. By default, old content is collapsed into `
` blocks to preserve history; set `keep_history: false` in config.yaml (or pass `--keep-history=false`) to replace the body with no history. diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index 7fe1b844c0..387d7379e9 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -162,8 +162,8 @@ if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then fi # fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and edits it in place, so -# re-runs do not flood the work item. +# finds this agent's previous comment by marker and its own author and edits +# it in place, so re-runs do not flood the work item. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index fee59c7f3d..29cc3d571d 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -314,8 +314,8 @@ if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then fi # fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and edits it in place, so -# re-runs do not flood the work item. +# finds this agent's previous comment by marker and its own author and edits +# it in place, so re-runs do not flood the work item. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index 8ee7a5cba2..27659c5bff 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -322,8 +322,8 @@ if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then fi # fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and edits it in place, so -# re-runs do not flood the work item. +# finds this agent's previous comment by marker and its own author and edits +# it in place, so re-runs do not flood the work item. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/cli/issues.go b/internal/cli/issues.go index 7fde6bfbb6..384316e755 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -201,7 +201,8 @@ func newIssuesPostCommentCmd() *cobra.Command { 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 edits in-place, collapsing old content into +by its marker and its own author and edits in-place, collapsing old +content into
blocks. This prevents comment flooding on re-runs. Works across GitHub, GitLab, and Jira via --tracker. diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 5dc59a1f45..0e93e149ca 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -1312,3 +1312,33 @@ func TestRunIssuesPostComment_UnresolvableSelfWarnsWithTheReason(t *testing.T) { }) } } + +func TestRunIssuesPostComment_UnresolvableSelfLeavesAuthorlessCommentAlone(t *testing.T) { + // GitHub can return a comment with no user; an unresolved self (also + // empty) must not "match" it and edit it. + ctx := context.Background() + fc := forge.NewFakeClient() + tc := tracker.NewForgeClient(fc) + const marker = "" + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nauthorless")) + require.NoError(t, err) + + fc.Errors = map[string]error{"GetAuthenticatedUser": errors.New("401 Bad credentials")} + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "2 broken links", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + require.Len(t, comments, 2) + require.Empty(t, comments[0].Author, "precondition: the seeded comment has no author") + assert.NotContains(t, string(comments[0].Body), "2 broken links") + assert.Contains(t, string(comments[1].Body), "2 broken links") +} From 33c3e4a17796fb66ad5d080fe22e2fc85336aff5 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 30 Sep 2026 21:08:17 -0400 Subject: [PATCH 15/16] fix(#6966)!: fail instead of posting when post-comment cannot verify its identity Posting a new comment when the poster's login could not be resolved avoided editing an unverified comment, but left the earlier comment behind: later runs keep updating the oldest own comment, so a findings comment orphaned by one transient failure would never be cleared. The identity lookup now retries briefly (two retries, context-aware) and, if it still fails, the command returns an error naming the cause and asking for a rerun, posting and editing nothing, with or without --only-if-exists. The generated post-script runs under set -e, so the run then fails visibly; its comment says so. BREAKING CHANGE: issues post-comment now fails, posting nothing, when it cannot resolve the identity it posts as. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- docs/guides/user/issues-commands.md | 9 +- internal/agentnew/templates/post.sh.tmpl | 6 +- internal/agentnew/testdata/golden/triage.txt | 6 +- .../testdata/golden/validation-loop.txt | 6 +- internal/cli/issues.go | 66 +++-- internal/cli/issues_test.go | 275 +++++++----------- 6 files changed, 163 insertions(+), 205 deletions(-) diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index fd73d593e3..d72e22a5bc 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -88,7 +88,7 @@ echo "Triage complete. See PR #99." | fullsend issues post-comment \ | `--jira-email` | Jira only | Jira user email for auth (default: `$JIRA_USER_EMAIL`) | | `--dry-run` | No | Print what would be posted without making API calls | | `--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, nothing is posted. | +| `--only-if-exists` | No | Update an existing comment with this marker but never create one. Use it for an all-clear result, so a findings comment from an earlier run is updated in place (the old findings are kept as collapsed history unless `--keep-history=false`) while a clean first run posts nothing. Only a comment whose author is exactly the identity posting matches; if that identity cannot be resolved, the command fails without posting. | | `--fullsend-dir` | No | Path to `.fullsend` config directory (sources defaults from its `config.yaml` when flags are omitted) | ### Jira marker storage @@ -120,9 +120,10 @@ For GitHub and GitLab, where markers are hidden HTML comments in the body, an existing comment is edited only when it carries the marker **and** its author is exactly the identity the command posts as. A comment anyone else wrote with the same marker is ignored, never edited. -If that identity cannot be resolved, no existing comment is edited: the -command posts a new comment and logs a warning naming the reason, or -posts nothing 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 or edits nothing, with or +without `--only-if-exists`; rerun it. Posting a new comment instead would +leave the earlier one behind with content no later run updates. For Jira, markers are stored as comment entity properties, which require comment-edit permissions to set — body-text injection alone cannot spoof diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index 387d7379e9..d1f53490a8 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -127,8 +127,10 @@ NUMBER="${BASH_REMATCH[3]}" # --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; when that login cannot be resolved it posts nothing, so a -# comment anyone else planted with the marker is never edited. +# posts as, so a comment anyone else planted with the marker is never +# edited. When that login cannot be resolved it exits non-zero without +# posting; under `set -e` this script, and so the run, then fails +# visibly — rerun it. if [[ "${status}" == "ok" ]]; then if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index 29cc3d571d..b53db91fee 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -279,8 +279,10 @@ NUMBER="${BASH_REMATCH[3]}" # --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; when that login cannot be resolved it posts nothing, so a -# comment anyone else planted with the marker is never edited. +# posts as, so a comment anyone else planted with the marker is never +# edited. When that login cannot be resolved it exits non-zero without +# posting; under `set -e` this script, and so the run, then fails +# visibly — rerun it. if [[ "${status}" == "ok" ]]; then if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index 27659c5bff..61cfa1480b 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -287,8 +287,10 @@ NUMBER="${BASH_REMATCH[3]}" # --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; when that login cannot be resolved it posts nothing, so a -# comment anyone else planted with the marker is never edited. +# posts as, so a comment anyone else planted with the marker is never +# edited. When that login cannot be resolved it exits non-zero without +# posting; under `set -e` this script, and so the run, then fails +# visibly — rerun it. if [[ "${status}" == "ok" ]]; then if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 diff --git a/internal/cli/issues.go b/internal/cli/issues.go index 384316e755..a1bf3c7e42 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -8,6 +8,7 @@ import ( "os" "slices" "strings" + "time" "github.com/spf13/cobra" @@ -216,9 +217,9 @@ so marker character restrictions do not apply. Trust model (GitHub, GitLab): an existing comment is edited only when it carries the marker and its author is exactly the identity this command posts as. A comment anyone else wrote with the same marker is -ignored, never edited. If that identity cannot be resolved, no existing -comment is edited: a new comment is posted instead, or nothing with ---only-if-exists. +ignored, never edited. If that identity cannot be resolved after a +short retry, the command fails without posting or editing anything; +rerun it. --tracker is required unless a default is supplied via config: set "tracker: github|gitlab|jira" in config.yaml and pass --fullsend-dir @@ -405,9 +406,9 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project // 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, no -// existing comment is edited: a new comment is created instead, or, with -// OnlyIfExists, nothing is posted. +// with the same marker is ignored. When that login cannot be resolved +// (after a short retry) it returns an error and posts nothing, with or +// without OnlyIfExists. func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project string, number int, body string, cfg sticky.Config, printer *ui.Printer) (string, error) { if strings.TrimSpace(body) == "" { return "", fmt.Errorf("comment body is empty") @@ -416,16 +417,12 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return "", fmt.Errorf("marker is empty") } - // An empty self matches nothing in findMarkedTrackerComment, so an - // unresolved identity can only lead to a new comment, never an edit. - self, selfErr := resolveTrackerSelf(ctx, tc) - if selfErr != nil { - if cfg.OnlyIfExists { - printer.StepWarn(fmt.Sprintf("Cannot verify who posted earlier comments (%v); nothing to post (--only-if-exists)", selfErr)) - return "", nil - } - printer.StepWarn(fmt.Sprintf("Cannot verify who posted earlier comments (%v); posting a new comment instead of editing one", selfErr)) - self = "" + // 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 "", fmt.Errorf("cannot verify which identity this command posts as, so no comment was posted or edited (rerun to retry): %w", err) } comments, err := tc.ListComments(ctx, project, number) @@ -546,22 +543,39 @@ type authenticatedUserResolver interface { AuthenticatedUser(ctx context.Context) (string, error) } -// resolveTrackerSelf returns the exact login tc posts as. For GitHub this -// goes through forge.Client.GetAuthenticatedUser, which also resolves an -// App installation token (GraphQL viewer) where GET /user is refused. +// selfLookupBackoff is the wait before each retry of the identity lookup; +// its length is the number of retries. Tests shorten it. +var selfLookupBackoff = []time.Duration{500 * time.Millisecond, time.Second} + +// resolveTrackerSelf returns the exact login tc posts as, retrying a failed +// lookup per selfLookupBackoff so a transient error does not fail the run. +// For GitHub this goes through forge.Client.GetAuthenticatedUser, which +// also resolves an App installation token (GraphQL viewer) where GET /user +// is refused. func resolveTrackerSelf(ctx context.Context, tc tracker.Client) (string, error) { ar, ok := tc.(authenticatedUserResolver) if !ok { return "", fmt.Errorf("this tracker cannot report the authenticated user") } - self, err := ar.AuthenticatedUser(ctx) - if err != nil { - return "", err - } - if self == "" { - return "", fmt.Errorf("the authenticated user is empty") + var lastErr error + for attempt := 0; ; attempt++ { + self, err := ar.AuthenticatedUser(ctx) + if err == nil && self == "" { + err = fmt.Errorf("the authenticated user is empty") + } + if err == nil { + return self, nil + } + lastErr = err + if attempt >= len(selfLookupBackoff) { + 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(selfLookupBackoff[attempt]): + } } - return self, nil } // findMarkedTrackerComment returns the first tracker comment whose body diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 0e93e149ca..1cf40d137c 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -11,6 +11,7 @@ import ( "path/filepath" "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -173,6 +174,7 @@ func TestPostTrackerStickyComment_EmptyMarker(t *testing.T) { func TestPostTrackerStickyComment_DryRun_Create(t *testing.T) { fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) printer := ui.New(io.Discard) cfg := sticky.Config{Marker: "", DryRun: true, KeepHistory: true} @@ -430,6 +432,7 @@ func TestRunIssuesPostComment_EmptyMarker(t *testing.T) { func TestRunIssuesPostComment_DryRun(t *testing.T) { fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) cfg := &issuesPostCommentConfig{ @@ -1095,98 +1098,151 @@ func TestRunIssuesPostComment_Jira_OnlyIfExists(t *testing.T) { assert.Contains(t, string(comments[0].Body), "all clear") } -// runOnlyIfExistsAfterCommentBy seeds one marker comment as author, then runs an -// --only-if-exists all-clear as the bot "fullsend-ai-review[bot]". -func runOnlyIfExistsAfterCommentBy(t *testing.T, author string, botErr error) []tracker.Comment { +// fastSelfLookup shortens the identity-lookup retry backoff for a test. +func fastSelfLookup(t *testing.T) { + t.Helper() + saved := selfLookupBackoff + selfLookupBackoff = []time.Duration{time.Millisecond, time.Millisecond} + t.Cleanup(func() { selfLookupBackoff = saved }) +} + +// flakySelfClient fails the identity lookup failures times, then defers to +// the wrapped ForgeClient. +type flakySelfClient struct { + *tracker.ForgeClient + failures int + calls int +} + +func (c *flakySelfClient) AuthenticatedUser(ctx context.Context) (string, error) { + c.calls++ + if c.calls <= c.failures { + return "", errors.New("502 Bad Gateway") + } + return c.ForgeClient.AuthenticatedUser(ctx) +} + +const testBot = "fullsend-ai-review[bot]" + +// postAfterCommentBy seeds one marker comment written by author, then runs +// post-comment as testBot through tc (a *flakySelfClient wrapping fc, so the +// identity lookup can be made to fail). It returns the run's error and the +// comments afterwards. +func postAfterCommentBy(t *testing.T, author string, onlyIfExists bool, failures int) (error, []tracker.Comment, *flakySelfClient) { t.Helper() + fastSelfLookup(t) ctx := context.Background() fc := forge.NewFakeClient() - tc := tracker.NewForgeClient(fc) + tc := &flakySelfClient{ForgeClient: tracker.NewForgeClient(fc), failures: failures} const marker = "" fc.AuthenticatedUser = author - _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nplanted findings")) + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nearlier findings")) require.NoError(t, err) - fc.AuthenticatedUser = "fullsend-ai-review[bot]" - if botErr != nil { - fc.Errors = map[string]error{"GetAuthenticatedUser": botErr} - } + fc.AuthenticatedUser = testBot cfg := &issuesPostCommentConfig{ trackerName: trackerGitHub, project: "acme/widgets", number: 42, marker: marker, - onlyIfExists: true, + onlyIfExists: onlyIfExists, testClient: tc, testPrinter: ui.New(io.Discard), - testBody: "all clear", + testBody: "new result", } - require.NoError(t, runIssuesPostComment(ctx, cfg)) + runErr := runIssuesPostComment(ctx, cfg) comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) - return comments + return runErr, comments, tc } -func TestRunIssuesPostComment_OnlyIfExists_IgnoresMarkerFromAnotherUser(t *testing.T) { - comments := runOnlyIfExistsAfterCommentBy(t, "mallory", nil) - require.Len(t, comments, 1, "only-if-exists must neither edit a planted comment nor create one") - assert.Contains(t, string(comments[0].Body), "planted findings") - assert.NotContains(t, string(comments[0].Body), "all clear") +func TestRunIssuesPostComment_EditsOwnComment(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") + }) + } } -func TestRunIssuesPostComment_OnlyIfExists_IgnoresLookalikeBotLogin(t *testing.T) { - // Login shape is not identity: a different App whose login merely shares - // the "[bot]" suffix, or a prefix, must not match. - for _, author := range []string{"evil-review[bot]", "fullsend-ai-review", "x-fullsend-ai-review[bot]"} { +func TestRunIssuesPostComment_IgnoresPlantedMarker(t *testing.T) { + // Login shape is not identity: another user, a different App whose login + // merely shares the "[bot]" suffix, the same name without it, or a prefix + // must not match. + for _, author := range []string{"mallory", "evil-review[bot]", "fullsend-ai-review", "x-fullsend-ai-review[bot]"} { t.Run(author, func(t *testing.T) { - comments := runOnlyIfExistsAfterCommentBy(t, author, nil) + // Normal path: the planted comment is left alone, a new one posted. + err, comments, _ := postAfterCommentBy(t, author, false, 0) + require.NoError(t, err) + require.Len(t, comments, 2) + assert.NotContains(t, string(comments[0].Body), "new result") + assert.Contains(t, string(comments[1].Body), "new result") + + // --only-if-exists: neither edited nor created. + err, comments, _ = postAfterCommentBy(t, author, true, 0) + require.NoError(t, err) require.Len(t, comments, 1) - assert.NotContains(t, string(comments[0].Body), "all clear") + assert.NotContains(t, string(comments[0].Body), "new result") }) } } -func TestRunIssuesPostComment_OnlyIfExists_EditsOwnComment(t *testing.T) { - comments := runOnlyIfExistsAfterCommentBy(t, "fullsend-ai-review[bot]", nil) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "all clear") +func TestRunIssuesPostComment_TransientSelfFailureRetriesThenEdits(t *testing.T) { + err, comments, tc := postAfterCommentBy(t, testBot, false, len(selfLookupBackoff)) + require.NoError(t, err) + assert.Equal(t, len(selfLookupBackoff)+1, tc.calls, "every retry is used before success") + require.Len(t, comments, 1, "a transient failure must not create a second comment") + assert.Contains(t, string(comments[0].Body), "new result") } -func TestRunIssuesPostComment_OnlyIfExists_UnresolvableSelfPostsNothing(t *testing.T) { - // Even the bot's own comment is left alone when the poster's login cannot - // be resolved: an unverified comment is never edited. - comments := runOnlyIfExistsAfterCommentBy(t, "fullsend-ai-review[bot]", errors.New("401 Bad credentials")) - require.Len(t, comments, 1) - assert.NotContains(t, string(comments[0].Body), "all clear") +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") + }) + } } -func TestRunIssuesPostComment_OnlyIfExists_EmptySelfPostsNothing(t *testing.T) { - // An empty login with no error must not degrade to marker-only matching. +func TestRunIssuesPostComment_EmptySelfErrors(t *testing.T) { + // An empty login with no error is unresolved too, never marker-only. + fastSelfLookup(t) ctx := context.Background() fc := forge.NewFakeClient() tc := tracker.NewForgeClient(fc) const marker = "" - _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nplanted findings")) + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nauthorless")) require.NoError(t, err) - cfg := &issuesPostCommentConfig{ - trackerName: trackerGitHub, - project: "acme/widgets", - number: 42, - marker: marker, - onlyIfExists: true, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "all clear", + 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") } - require.NoError(t, runIssuesPostComment(ctx, cfg)) - comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) require.Len(t, comments, 1) - assert.NotContains(t, string(comments[0].Body), "all clear") + assert.NotContains(t, string(comments[0].Body), "new result") } func TestRunIssuesPostComment_OnlyIfExists_SkipsPlantedCommentBeforeOwn(t *testing.T) { @@ -1201,7 +1257,7 @@ func TestRunIssuesPostComment_OnlyIfExists_SkipsPlantedCommentBeforeOwn(t *testi fc.AuthenticatedUser = "mallory" _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nplanted")) require.NoError(t, err) - fc.AuthenticatedUser = "fullsend-ai-review[bot]" + fc.AuthenticatedUser = testBot _, err = tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\n2 broken links")) require.NoError(t, err) @@ -1220,125 +1276,6 @@ func TestRunIssuesPostComment_OnlyIfExists_SkipsPlantedCommentBeforeOwn(t *testi comments, err := tc.ListComments(ctx, "acme/widgets", 42) require.NoError(t, err) require.Len(t, comments, 2) - assert.Contains(t, string(comments[0].Body), "planted") assert.NotContains(t, string(comments[0].Body), "all clear") assert.Contains(t, string(comments[1].Body), "all clear") } - -// runPostCommentAfterCommentBy seeds one marker comment as author, then runs -// a normal (create-or-update) post as "fullsend-ai-review[bot]". -func runPostCommentAfterCommentBy(t *testing.T, author string, botErr error) []tracker.Comment { - t.Helper() - ctx := context.Background() - fc := forge.NewFakeClient() - tc := tracker.NewForgeClient(fc) - const marker = "" - - fc.AuthenticatedUser = author - _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nearlier")) - require.NoError(t, err) - - fc.AuthenticatedUser = "fullsend-ai-review[bot]" - if botErr != nil { - fc.Errors = map[string]error{"GetAuthenticatedUser": botErr} - } - cfg := &issuesPostCommentConfig{ - trackerName: trackerGitHub, - project: "acme/widgets", - number: 42, - marker: marker, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "2 broken links", - } - require.NoError(t, runIssuesPostComment(ctx, cfg)) - - comments, err := tc.ListComments(ctx, "acme/widgets", 42) - require.NoError(t, err) - return comments -} - -func TestRunIssuesPostComment_UpdatesOwnComment(t *testing.T) { - comments := runPostCommentAfterCommentBy(t, "fullsend-ai-review[bot]", nil) - require.Len(t, comments, 1) - assert.Contains(t, string(comments[0].Body), "2 broken links") -} - -func TestRunIssuesPostComment_PlantedMarkerGetsANewComment(t *testing.T) { - for _, author := range []string{"mallory", "evil-review[bot]", "x-fullsend-ai-review[bot]"} { - t.Run(author, func(t *testing.T) { - comments := runPostCommentAfterCommentBy(t, author, nil) - require.Len(t, comments, 2, "a planted marker comment must be left alone and a new one posted") - assert.NotContains(t, string(comments[0].Body), "2 broken links") - assert.Contains(t, string(comments[1].Body), "2 broken links") - }) - } -} - -func TestRunIssuesPostComment_UnresolvableSelfPostsNewComment(t *testing.T) { - // Even the poster's own earlier comment is not edited when the identity - // cannot be verified: a new comment is created instead. - comments := runPostCommentAfterCommentBy(t, "fullsend-ai-review[bot]", errors.New("401 Bad credentials")) - require.Len(t, comments, 2) - assert.NotContains(t, string(comments[0].Body), "2 broken links") - assert.Contains(t, string(comments[1].Body), "2 broken links") -} - -func TestRunIssuesPostComment_UnresolvableSelfWarnsWithTheReason(t *testing.T) { - for _, onlyIfExists := range []bool{false, true} { - t.Run(fmt.Sprintf("only-if-exists=%v", onlyIfExists), func(t *testing.T) { - ctx := context.Background() - fc := forge.NewFakeClient() - fc.Errors = map[string]error{"GetAuthenticatedUser": errors.New("401 Bad credentials")} - var out bytes.Buffer - cfg := &issuesPostCommentConfig{ - trackerName: trackerGitHub, - project: "acme/widgets", - number: 42, - marker: "", - onlyIfExists: onlyIfExists, - testClient: tracker.NewForgeClient(fc), - testPrinter: ui.New(&out), - testBody: "body", - } - require.NoError(t, runIssuesPostComment(ctx, cfg)) - assert.Contains(t, out.String(), "401 Bad credentials", "the warning must name why the identity is unverified") - if onlyIfExists { - assert.Contains(t, out.String(), "(401 Bad credentials); nothing to post (--only-if-exists)") - assert.NotContains(t, out.String(), "posting a new comment") - } else { - assert.Contains(t, out.String(), "(401 Bad credentials); posting a new comment instead of editing one") - } - }) - } -} - -func TestRunIssuesPostComment_UnresolvableSelfLeavesAuthorlessCommentAlone(t *testing.T) { - // GitHub can return a comment with no user; an unresolved self (also - // empty) must not "match" it and edit it. - ctx := context.Background() - fc := forge.NewFakeClient() - tc := tracker.NewForgeClient(fc) - const marker = "" - _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nauthorless")) - require.NoError(t, err) - - fc.Errors = map[string]error{"GetAuthenticatedUser": errors.New("401 Bad credentials")} - cfg := &issuesPostCommentConfig{ - trackerName: trackerGitHub, - project: "acme/widgets", - number: 42, - marker: marker, - testClient: tc, - testPrinter: ui.New(io.Discard), - testBody: "2 broken links", - } - require.NoError(t, runIssuesPostComment(ctx, cfg)) - - comments, err := tc.ListComments(ctx, "acme/widgets", 42) - require.NoError(t, err) - require.Len(t, comments, 2) - require.Empty(t, comments[0].Author, "precondition: the seeded comment has no author") - assert.NotContains(t, string(comments[0].Body), "2 broken links") - assert.Contains(t, string(comments[1].Body), "2 broken links") -} From 069e28455ba97c9112791c227a327b69648a2ab0 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Wed, 30 Sep 2026 21:10:45 -0400 Subject: [PATCH 16/16] test(#6966): pin the identity lookup's cancellation and empty-identity guard A cancelled context stops the retry without waiting out the backoff, and an empty identity matches no comment, not even an authorless one. The --dry-run help now says it posts or edits nothing rather than "makes no API calls": it lists comments and resolves the poster's identity. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- docs/guides/user/issues-commands.md | 2 +- internal/cli/issues.go | 2 +- internal/cli/issues_test.go | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index d72e22a5bc..776a19169f 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -86,7 +86,7 @@ echo "Triage complete. See PR #99." | fullsend issues post-comment \ | `--token` | No | API token (default: env var per tracker) | | `--jira-url` | Jira only | Jira instance URL (default: `$JIRA_BASE_URL`) | | `--jira-email` | Jira only | Jira user email for auth (default: `$JIRA_USER_EMAIL`) | -| `--dry-run` | No | Print what would be posted without making API calls | +| `--dry-run` | No | Print what would be posted without posting or editing anything | | `--keep-history` | No | Append previous content as collapsed history blocks (default: `true`; set `false` to replace in-place) | | `--only-if-exists` | No | Update an existing comment with this marker but never create one. Use it for an all-clear result, so a findings comment from an earlier run is updated in place (the old findings are kept as collapsed history unless `--keep-history=false`) while a clean first run posts nothing. Only a comment whose author is exactly the identity posting matches; if that identity cannot be resolved, the command fails without posting. | | `--fullsend-dir` | No | Path to `.fullsend` config directory (sources defaults from its `config.yaml` when flags are omitted) | diff --git a/internal/cli/issues.go b/internal/cli/issues.go index a1bf3c7e42..ff4e9ef23a 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -242,7 +242,7 @@ The --result flag accepts a file path or "-" for stdin.`, cmd.Flags().StringVar(&cfg.token, "token", "", "API token (default: env var per tracker)") cmd.Flags().StringVar(&cfg.jiraURL, "jira-url", "", "Jira instance URL (default: $JIRA_BASE_URL)") cmd.Flags().StringVar(&cfg.jiraEmail, "jira-email", "", "Jira user email for Basic auth (default: $JIRA_USER_EMAIL)") - cmd.Flags().BoolVar(&cfg.dryRun, "dry-run", false, "print what would be posted without making API calls") + cmd.Flags().BoolVar(&cfg.dryRun, "dry-run", false, "print what would be posted without posting or editing anything") cmd.Flags().BoolVar(&cfg.onlyIfExists, "only-if-exists", false, "update an existing comment with this marker but never create one (for an all-clear that should replace earlier findings)") cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "append previous content as collapsed history blocks (set false to replace in-place)") cmd.Flags().StringVar(&cfg.fullsendDir, "fullsend-dir", "", "path to .fullsend config directory (sources defaults from its config.yaml when flags are omitted)") diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 1cf40d137c..86fe915b59 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -78,6 +78,7 @@ func TestFindMarkedTrackerComment(t *testing.T) { marker := "" comments := []tracker.Comment{ {ID: "1", Body: "irrelevant comment", Author: "bot"}, + {ID: "0", Body: tracker.Body(marker + "\nauthorless")}, {ID: "2", Body: tracker.Body(marker + "\nplanted"), Author: "mallory"}, {ID: "3", Body: tracker.Body(marker + "\nsome content"), Author: "bot"}, {ID: "4", Body: "another comment", Author: "bot"}, @@ -1279,3 +1280,18 @@ func TestRunIssuesPostComment_OnlyIfExists_SkipsPlantedCommentBeforeOwn(t *testi assert.NotContains(t, string(comments[0].Body), "all clear") assert.Contains(t, string(comments[1].Body), "all clear") } + +func TestResolveTrackerSelf_StopsRetryingWhenCancelled(t *testing.T) { + saved := selfLookupBackoff + selfLookupBackoff = []time.Duration{time.Hour, time.Hour} + t.Cleanup(func() { selfLookupBackoff = saved }) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + tc := &flakySelfClient{ForgeClient: tracker.NewForgeClient(forge.NewFakeClient()), failures: 1000} + + _, err := resolveTrackerSelf(ctx, tc) + require.Error(t, err) + assert.ErrorIs(t, err, context.Canceled) + assert.Equal(t, 1, tc.calls, "a cancelled context must not wait out the backoff") +}