diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index 9e46c4fb8c..3750d795ec 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -74,7 +74,6 @@ These fields live on `perRepoConfig` in `internal/config/config.go`. Unset means |---|---|---|---|---|---|---| | `version` | Config schema version | Overlay, base, compiled `"1"` | Overlay, then base, then `"1"` | Config loader | Already layered | No. It is the schema version, not an admin policy. | | `forge` | Hosting platform (`github`, `gitlab`, or `forgejo`) | `--forge`, overlay, base, compiled empty (GitHub) | `--forge`, then overlay, then base. If still empty, CI detection (`FORGEJO_ACTIONS`/`GITEA_ACTIONS`, then `GITHUB_ACTIONS`, then `GITLAB_CI`) fills it; outside CI it can stay empty | CLI | Already layered. The flag is a one-shot override and stays first. | Yes, when a fleet is single-forge. | -| `keep_history` | Deprecated: no effect (sticky comments were removed; every result is a new comment) | `--keep-history`, overlay, base, compiled `true` | `--keep-history` (when the flag was explicitly passed), then overlay, then base, then `true` | Nothing; accepted until a cleanup removes it | Already layered. The flag is a one-shot override and stays first. | No. It no longer changes behaviour. | | `allowed_remote_resources` | URL prefixes agents may fetch | Overlay, base, compiled fullsend and agents prefixes | Accessor-level: overlay union or deny-all, then base, then the compiled prefixes. Commands (`run`/`lint`/`lock`, harness dispatch, `dispatch --route`, Jira poll, agent set/add/update/remove) ensure fullsend's default prefixes on top of a non-empty result; `Validate()` callers (`github setup` re-runs, `repos install`) and managed `repos.yaml` validation admit the same shapes through `perRepoConfig.Validate`/`ValidateMergedManaged` (`config_base` preset validation parses the preset standalone — preset list plus the defaults, no overlay — so it is stricter than the read for overlay-only prefixes and for a preset `[]`, and looser over a runtime overlay `[]`; merged managed validation sees only the managed blocks plus the defaults, so a prefix declared only in `config.base.yaml` or a `config_base` preset makes it stricter than the read); a resolved `[]` stays deny-all | Resource fetch, agent-source validation | Already layered. Accessor-level and command-level resolution are two steps of one rule. | Yes. This is the shared fetch allowlist. | | `tracker` | Issue tracker provider block (`github`, `gitlab`, or `jira`): the default for `fullsend issues --tracker` and the provider's `allowed_targets`, where agents may open issues | Overlay, base, compiled unset (flag required, no extra targets) | `--tracker`, then the layered file; the whole object replaces the parent when set | `fullsend issues`, issue creation | Already layered. The flag is a one-shot override and stays first. | Yes for a shared allowlist. A repository overlay replaces the whole object. | | `status_notifications` | Start and completion comments and reactions | Overlay, base, compiled unset | Whole object replaces the parent when set | Status posting | Already layered | Yes, when a fleet wants one notification policy. | diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 7e0f3c787f..ec020dc1c4 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -183,7 +183,6 @@ fullsend │ │ ├── --project # Project: owner/repo (GitHub/GitLab) or key (Jira) │ │ ├── --number # Issue number │ │ ├── --marker # Marker identifying this agent's comments (HTML comment or Jira property) -│ │ ├── --keep-history # Deprecated: no effect (every result is a new comment) │ │ ├── --only-if-exists # Post only when an earlier marked comment exists │ │ └── --fullsend-dir # .fullsend config directory │ ├── link # Create a typed link between two issues (Jira only) @@ -212,9 +211,7 @@ fullsend │ ├── --result # Path to review result file, or '-' for stdin │ ├── --token # Forge token (default: $GH_TOKEN / $GITHUB_TOKEN / gh auth token, or $GITLAB_TOKEN) │ ├── --head-sha # Expected PR HEAD SHA (skips review if HEAD moved) -│ ├── --dry-run # Print what would be posted without API calls -│ ├── --keep-history # Deprecated: no effect (every result is a new comment) -│ └── --fullsend-dir # .fullsend config directory (default: $FULLSEND_DIR) +│ └── --dry-run # Print what would be posted without API calls ├── review-dedup # Skip unchanged synchronize reviews or supersede prior skip notes │ ├── --repo # Repository in owner/repo format (required) │ ├── --pr # Pull request number (required) diff --git a/docs/guides/infrastructure/layered-config-reference.md b/docs/guides/infrastructure/layered-config-reference.md index 4b6f9ad01f..47728a5f7d 100644 --- a/docs/guides/infrastructure/layered-config-reference.md +++ b/docs/guides/infrastructure/layered-config-reference.md @@ -135,7 +135,6 @@ the overlay → base → code defaults chain. | `version` | `string` | Scalar override | `"1"` | | `runtime` | `string` | Scalar override | `"claude"` | | `kill_switch` | `*bool` | Scalar override | `false` (inactive) | -| `keep_history` | `*bool` | Scalar override | `true` (deprecated: no effect) | | `roles` | `[]string` | Replace if set | `PerRepoDefaultRoles()` | | `agents` | `[]AgentEntry` | Keyed merge by `DerivedName()` | `nil` (none) | | `allowed_remote_resources` | `[]string` | Union with deny-all | `DefaultAllowedRemoteResources()` | @@ -246,14 +245,6 @@ unset, the accessor falls through to the base layer, then to code defaults. - `*false` (explicit `kill_switch: false`) — locally set to inactive. Does **not** fall through. - `*true` (explicit `kill_switch: true`) — locally set to active. -- **`keep_history`**: Pointer to bool (`*bool`). Deprecated: no effect. - Sticky comments were removed, so every result from `post-review`, - `post-comment`, and `issues post-comment` is posted as a new comment - and nothing is folded into "Previous run" blocks. The field keeps the - same three-state pointer semantics as `kill_switch` (`nil` falls - through to parent, an explicit value is a local decision) and stays - accepted so existing layered configs keep resolving until a cleanup - removes it. ### `mint_url` and `inference` — scalar override @@ -597,7 +588,6 @@ compiled-in defaults apply: | `version` | `"1"` | | `runtime` | `"claude"` | | `kill_switch` | `false` (inactive) | -| `keep_history` | `true` (deprecated: no effect) | | `roles` | `["triage", "coder", "review", "fix", "retro", "prioritize"]` | | `agents` | `nil` (none configured) | | `allowed_remote_resources` | `["https://raw.githubusercontent.com/fullsend-ai/fullsend/", "https://raw.githubusercontent.com/fullsend-ai/agents/"]`, plus `https:///fullsend-ai/fullsend/raw/` and `https:///fullsend-ai/agents/raw/` when `GITHUB_SERVER_URL` names a host other than `github.com`. A Forgejo agent source (`FULLSEND_FORGEJO_URL`) is never added; list `///raw/` explicitly | diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index 7e006cab4b..138983f6a7 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -272,7 +272,6 @@ echo "Triage complete. See PR #99." | fullsend issues post-comment \ | `--result` | No | Path to comment body file, or `-` for stdin (default: `-`) | | `--token` | No | GitHub/GitLab API token (default: env var per tracker). Rejected for Jira | | `--dry-run` | No | Print what would be posted without posting anything | -| `--keep-history` | No | Deprecated: no effect. Every result is posted as a new comment; the flag stays accepted so existing callers keep working | | `--only-if-exists` | No | Post only when an earlier comment with this marker exists, so a run with no earlier comment posts nothing. Use it for an all-clear result, so it follows earlier findings at the end of the thread while a clean first run posts nothing. Only a comment whose author is exactly the identity posting matches; if that identity cannot be resolved, the command fails without posting. | | `--fullsend-dir` | Jira | Path to `.fullsend` config directory. Supplies defaults from its `config.yaml` when flags are omitted, including the [Jira connection settings](#jira-connection-settings) | diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 502b7d4ea2..a58a7528e0 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -25,7 +25,6 @@ forge: github # Hosting platform: github, gitlab, forgejo # ── Operations ─────────────────────────────────────────────── kill_switch: false # Emergency stop — disables all agent dispatch when true -keep_history: true # Deprecated: no effect (every result is posted as a new comment) # ── Runtime ────────────────────────────────────────────────── runtime: claude # Default agent runtime: claude, pi, codex, opencode @@ -209,13 +208,17 @@ repository. Uses pointer semantics in the layered config system — `nil` (omitted) falls through to parent; an explicit `false` is a local decision that does not fall through. -### `keep_history` - -Deprecated: no effect. Sticky comments were removed, so every result from -post-review, post-comment, and issues post-comment is posted as a new -comment at the end of the thread and nothing is folded into "Previous -run" blocks. The field stays accepted (and `--keep-history` with it) so -existing configs keep working until a cleanup removes it. +**Migration from `keep_history`:** the top-level `keep_history` key is +removed. A repository's own `.fullsend/config.yaml` (and +`config.base.yaml`) still loads with the key present — the layered loader +ignores unknown keys — but managed `repos.yaml` `config:` blocks now reject +it through strict validation with an `unknown field "keep_history"` error: +delete the key from managed blocks. The key has had no effect since sticky +comments were removed (#9334); every result is posted as a new comment. The +`--keep-history` flag on the posting commands (`issues post-comment`, +`fullsend post-comment`, `fullsend post-review`) stays as a hidden no-op so +pre-cleanup post-scripts keep working; it is not listed in `--help` and no +removal release is scheduled yet. ### `runtime` diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index df64c0eadc..e264d8cb8f 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -176,9 +176,10 @@ if [[ "${status}" == "ok" ]]; then # change, has no effect: the all-clear is posted as a new comment at the # end of the thread, following any earlier findings. It is passed only # when the runner's CLI still lists it: a fullsend pinned between #6966 - # and this change honours it (the all-clear replaces the earlier - # findings comment instead of stacking collapsed history blocks), while - # a CLI that has removed the flag must never see it — this script is + # and #9399 honours it (the all-clear replaces the earlier findings + # comment instead of stacking collapsed history blocks); from #9399 until + # this change it is still listed but a warned no-op. A CLI that has + # removed the flag must never see it — this script is # rendered once into each repository and never regenerated, and an # unknown flag would fail the run under `set -euo pipefail`. With no # comment in the result the all-clear is the summary alone. diff --git a/internal/agentnew/testdata/golden/codex.txt b/internal/agentnew/testdata/golden/codex.txt index 016111f4aa..d9c9868755 100644 --- a/internal/agentnew/testdata/golden/codex.txt +++ b/internal/agentnew/testdata/golden/codex.txt @@ -327,9 +327,10 @@ if [[ "${status}" == "ok" ]]; then # change, has no effect: the all-clear is posted as a new comment at the # end of the thread, following any earlier findings. It is passed only # when the runner's CLI still lists it: a fullsend pinned between #6966 - # and this change honours it (the all-clear replaces the earlier - # findings comment instead of stacking collapsed history blocks), while - # a CLI that has removed the flag must never see it — this script is + # and #9399 honours it (the all-clear replaces the earlier findings + # comment instead of stacking collapsed history blocks); from #9399 until + # this change it is still listed but a warned no-op. A CLI that has + # removed the flag must never see it — this script is # rendered once into each repository and never regenerated, and an # unknown flag would fail the run under `set -euo pipefail`. With no # comment in the result the all-clear is the summary alone. diff --git a/internal/agentnew/testdata/golden/pi-openai.txt b/internal/agentnew/testdata/golden/pi-openai.txt index 5530721204..18c98daa20 100644 --- a/internal/agentnew/testdata/golden/pi-openai.txt +++ b/internal/agentnew/testdata/golden/pi-openai.txt @@ -345,9 +345,10 @@ if [[ "${status}" == "ok" ]]; then # change, has no effect: the all-clear is posted as a new comment at the # end of the thread, following any earlier findings. It is passed only # when the runner's CLI still lists it: a fullsend pinned between #6966 - # and this change honours it (the all-clear replaces the earlier - # findings comment instead of stacking collapsed history blocks), while - # a CLI that has removed the flag must never see it — this script is + # and #9399 honours it (the all-clear replaces the earlier findings + # comment instead of stacking collapsed history blocks); from #9399 until + # this change it is still listed but a warned no-op. A CLI that has + # removed the flag must never see it — this script is # rendered once into each repository and never regenerated, and an # unknown flag would fail the run under `set -euo pipefail`. With no # comment in the result the all-clear is the summary alone. diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index 4d1d70a7ba..79fed0f41a 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -339,9 +339,10 @@ if [[ "${status}" == "ok" ]]; then # change, has no effect: the all-clear is posted as a new comment at the # end of the thread, following any earlier findings. It is passed only # when the runner's CLI still lists it: a fullsend pinned between #6966 - # and this change honours it (the all-clear replaces the earlier - # findings comment instead of stacking collapsed history blocks), while - # a CLI that has removed the flag must never see it — this script is + # and #9399 honours it (the all-clear replaces the earlier findings + # comment instead of stacking collapsed history blocks); from #9399 until + # this change it is still listed but a warned no-op. A CLI that has + # removed the flag must never see it — this script is # rendered once into each repository and never regenerated, and an # unknown flag would fail the run under `set -euo pipefail`. With no # comment in the result the all-clear is the summary alone. diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index cd19b425fc..52e4049e23 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -347,9 +347,10 @@ if [[ "${status}" == "ok" ]]; then # change, has no effect: the all-clear is posted as a new comment at the # end of the thread, following any earlier findings. It is passed only # when the runner's CLI still lists it: a fullsend pinned between #6966 - # and this change honours it (the all-clear replaces the earlier - # findings comment instead of stacking collapsed history blocks), while - # a CLI that has removed the flag must never see it — this script is + # and #9399 honours it (the all-clear replaces the earlier findings + # comment instead of stacking collapsed history blocks); from #9399 until + # this change it is still listed but a warned no-op. A CLI that has + # removed the flag must never see it — this script is # rendered once into each repository and never regenerated, and an # unknown flag would fail the run under `set -euo pipefail`. With no # comment in the result the all-clear is the summary alone. diff --git a/internal/cli/issues.go b/internal/cli/issues.go index c62f53970a..c618ca79ff 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -397,7 +397,6 @@ type issuesPostCommentConfig struct { token 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 @@ -409,10 +408,7 @@ type issuesPostCommentConfig struct { } func newIssuesPostCommentCmd() *cobra.Command { - var ( - cfg issuesPostCommentConfig - keepHistory bool - ) + var cfg issuesPostCommentConfig cmd := &cobra.Command{ Use: "post-comment", @@ -445,10 +441,6 @@ to tracker.jira.project. The --result flag accepts a file path or "-" for stdin.`, RunE: func(cmd *cobra.Command, args []string) error { - if cmd.Flags().Changed("keep-history") { - cfg.keepHistory = &keepHistory - warnKeepHistoryDeprecated(cmd) - } return runIssuesPostComment(cmd.Context(), &cfg) }, } @@ -461,7 +453,7 @@ The --result flag accepts a file path or "-" for stdin.`, cmd.Flags().StringVar(&cfg.token, "token", "", tokenFlagUsage) cmd.Flags().BoolVar(&cfg.dryRun, "dry-run", false, "print what would be posted without posting anything") cmd.Flags().BoolVar(&cfg.onlyIfExists, "only-if-exists", false, "post only when an earlier comment with this marker exists (for an all-clear that follows earlier findings)") - cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "deprecated: no effect (every result is posted as a new comment; sticky comments were removed)") + addLegacyHistoryFlag(cmd) cmd.Flags().StringVar(&cfg.fullsendDir, "fullsend-dir", "", "path to .fullsend config directory (sources defaults, including the tracker.jira connection settings, from its config.yaml when flags are omitted)") _ = cmd.MarkFlagRequired("number") _ = cmd.MarkFlagRequired("marker") @@ -509,15 +501,9 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err printer.Header("Post Comment") - keepHistory, err := resolveKeepHistory(cfg.keepHistory, cfg.fullsendDir, cfg.testConfigReader) - if err != nil { - printer.StepWarn(fmt.Sprintf("Warning: %v (keep_history is deprecated and unused; every result is posted as a new comment)", err)) - } - stickyCfg := sticky.Config{ - Marker: cfg.marker, - DryRun: cfg.dryRun, - KeepHistory: keepHistory, + Marker: cfg.marker, + DryRun: cfg.dryRun, } // Jira stores markers as comment entity properties instead @@ -863,36 +849,30 @@ func validateTrackerName(name string) (string, error) { return normalized, nil } -// resolveKeepHistory returns the explicit flag value if non-nil, otherwise -// resolves the keep_history setting from config.yaml via fullsendDir. If -// neither source provides a value, defaults to true (current behavior). -// Returns an error when config loading fails so callers can surface it -// (matching the pattern in resolveTracker). -func resolveKeepHistory(flag *bool, fullsendDir string, testConfigReader config.PerRepoConfigReader) (bool, error) { - if flag != nil { - return *flag, nil - } - prc := testConfigReader - if prc == nil && fullsendDir != "" { - reader, err := config.LoadConfig(fullsendDir, config.LoadOpts{MissingOK: true}) - if err != nil { - return true, fmt.Errorf("loading config for keep_history: %w", err) - } - prc, _ = reader.(config.PerRepoConfigReader) - } - if prc != nil { - return prc.ConfigKeepHistory(), nil - } - return true, nil +// addLegacyHistoryFlag registers the removed --keep-history flag as a +// hidden no-op on a posting command. Sticky comments were removed (#9334) +// and the history folding with them (#9517); the flag stays accepted for a +// release because post-scripts generated before #9334 pass +// --keep-history=false unconditionally and are rendered once into each +// repository, never regenerated — cobra would reject the unknown flag and +// fail those runs under `set -euo pipefail`. Hidden, so --help (and the +// generated scripts' probe) no longer lists it; delete it once those +// scripts have aged out. +func addLegacyHistoryFlag(cmd *cobra.Command) { + var legacy bool + cmd.Flags().BoolVar(&legacy, "keep-history", false, "deprecated: no effect (accepted so pre-cleanup post-scripts keep working)") + _ = cmd.Flags().MarkHidden("keep-history") } -// warnKeepHistoryDeprecated prints a one-line warning when --keep-history is -// explicitly passed: the flag is accepted but has no effect (sticky comments -// were removed, #9334). Shell scripts never read help text, so the warning -// is the only advance notice external automation gets before a cleanup -// removes the flag (mirroring --vendor-fullsend-binary). -func warnKeepHistoryDeprecated(cmd *cobra.Command) { - fmt.Fprintln(cmd.ErrOrStderr(), "warning: --keep-history is deprecated and has no effect; every result is posted as a new comment") +// addLegacyFullsendDirFlag registers --fullsend-dir as a hidden no-op on +// a posting command. The only default it ever sourced there was the +// keep-history setting, which #9517 removed. It stays accepted (and +// hidden) so external callers passing it are not rejected; delete it +// once those callers have moved off it. +func addLegacyFullsendDirFlag(cmd *cobra.Command) { + var fullsendDir string + cmd.Flags().StringVar(&fullsendDir, "fullsend-dir", os.Getenv("FULLSEND_DIR"), "deprecated: no effect on this command (accepted for compatibility)") + _ = cmd.Flags().MarkHidden("fullsend-dir") } // truncateForPost caps a comment body at cfg's size limit before it is diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 52d0b47889..effada5e86 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -438,7 +438,7 @@ func TestPostTrackerStickyComment_Create(t *testing.T) { tc := tracker.NewForgeClient(fc) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} url, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "hello world", cfg, false, printer) require.NoError(t, err) @@ -458,7 +458,7 @@ func TestPostTrackerStickyComment_SecondRunAppends(t *testing.T) { tc := tracker.NewForgeClient(fc) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} ctx := context.Background() // First post creates the comment. @@ -485,7 +485,7 @@ func TestPostTrackerStickyComment_NeutralizesMarkersInBody(t *testing.T) { tc := tracker.NewForgeClient(fc) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} ctx := context.Background() body := "result already <!-- fullsend:x -->" @@ -516,7 +516,7 @@ func TestPostTrackerStickyComment_EmptyBody(t *testing.T) { fc := forge.NewFakeClient() tc := tracker.NewForgeClient(fc) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} _, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "", cfg, false, printer) assert.Error(t, err) @@ -527,7 +527,7 @@ func TestPostTrackerStickyComment_EmptyMarker(t *testing.T) { fc := forge.NewFakeClient() tc := tracker.NewForgeClient(fc) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} _, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "hello", cfg, false, printer) assert.Error(t, err) @@ -539,7 +539,7 @@ func TestPostTrackerStickyComment_DryRun_Create(t *testing.T) { fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", DryRun: true, KeepHistory: true} + cfg := sticky.Config{Marker: "", DryRun: true} url, err := postTrackerStickyComment(context.Background(), tc, "acme/widgets", 42, "hello", cfg, false, printer) require.NoError(t, err) @@ -556,7 +556,7 @@ func TestPostTrackerStickyComment_DryRun_WithExistingComment(t *testing.T) { fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} ctx := context.Background() // Create the initial comment (not dry run). @@ -1207,7 +1207,7 @@ func TestPostJiraStickyComment_DryRun_Create(t *testing.T) { tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") require.NoError(t, err) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", DryRun: true, KeepHistory: true} + cfg := sticky.Config{Marker: "", DryRun: true} url, err := postJiraStickyComment(context.Background(), tc, "PROJ", 42, "hello", cfg, false, printer) require.NoError(t, err) @@ -1224,7 +1224,7 @@ func TestPostJiraStickyComment_DryRun_WithExistingComment(t *testing.T) { tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") require.NoError(t, err) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} ctx := context.Background() // Create the initial comment (not dry run). @@ -1247,7 +1247,7 @@ func TestPostJiraStickyComment_EmptyBody(t *testing.T) { tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") require.NoError(t, err) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} _, err = postJiraStickyComment(context.Background(), tc, "PROJ", 42, " ", cfg, false, printer) require.Error(t, err) @@ -1258,7 +1258,7 @@ func TestPostJiraStickyComment_EmptyMarker(t *testing.T) { tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") require.NoError(t, err) printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: " ", KeepHistory: true} + cfg := sticky.Config{Marker: " "} _, err = postJiraStickyComment(context.Background(), tc, "PROJ", 42, "body", cfg, false, printer) require.Error(t, err) @@ -1355,58 +1355,6 @@ func TestResolveTracker_FullsendDirWithoutTrackerSet_Errors(t *testing.T) { assert.Contains(t, err.Error(), "--tracker is required") } -// --- resolveKeepHistory tests --- -// -// Mirrors the resolveTracker test suite. resolveKeepHistory resolves -// the keep_history setting from: (1) explicit flag, (2) config -// reader, (3) fullsend-dir config.yaml, (4) default true. - -func TestResolveKeepHistory_FlagOverridesConfig(t *testing.T) { - reader, err := config.ParsePerRepoConfig([]byte("keep_history: true\n")) - require.NoError(t, err) - - flagVal := false - got, err := resolveKeepHistory(&flagVal, "", reader) - require.NoError(t, err) - assert.False(t, got, "explicit flag=false should override config=true") -} - -func TestResolveKeepHistory_FallsBackToConfigReader(t *testing.T) { - reader, err := config.ParsePerRepoConfig([]byte("keep_history: false\n")) - require.NoError(t, err) - - got, err := resolveKeepHistory(nil, "", reader) - require.NoError(t, err) - assert.False(t, got, "nil flag should fall back to config reader value") -} - -func TestResolveKeepHistory_FallsBackToFullsendDirConfig(t *testing.T) { - dir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("keep_history: false\n"), 0o644)) - - got, err := resolveKeepHistory(nil, dir, nil) - require.NoError(t, err) - assert.False(t, got, "nil flag + nil reader should fall back to fullsend-dir config") -} - -func TestResolveKeepHistory_NilEverythingDefaultsTrue(t *testing.T) { - got, err := resolveKeepHistory(nil, "", nil) - require.NoError(t, err) - assert.True(t, got, "nil flag + no config + no fullsend-dir should default to true") -} - -func TestResolveKeepHistory_ConfigLoadErrorReturnsTrueWithError(t *testing.T) { - // Point at a directory with an invalid config.yaml to trigger a load error. - dir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(":\tinvalid yaml\n"), 0o644)) - - got, err := resolveKeepHistory(nil, dir, nil) - require.Error(t, err, "should propagate config load error") - assert.True(t, got, "should default to true on config load error") -} - -// --- config-default --tracker integration tests --- - func TestRunIssuesPostComment_TrackerFromConfig(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" @@ -1965,14 +1913,12 @@ func TestRunIssuesPostComment_Jira_OnlyIfExistsIgnoresPlantedMarker(t *testing.T } func TestRunIssuesPostComment_OnlyIfExistsAppendsAllClear(t *testing.T) { - // The generated ok path passes --keep-history=false, which no longer - // has an effect: the all-clear follows the earlier findings as a new - // comment, and repeated clean runs each add their own. + // The all-clear follows the earlier findings as a new comment, and + // repeated clean runs each add their own. ctx := context.Background() fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) - noHistory := false cfg := &issuesPostCommentConfig{ trackerName: trackerGitHub, project: "acme/widgets", @@ -1985,7 +1931,6 @@ func TestRunIssuesPostComment_OnlyIfExistsAppendsAllClear(t *testing.T) { require.NoError(t, runIssuesPostComment(ctx, cfg)) cfg.onlyIfExists = true - cfg.keepHistory = &noHistory cfg.testBody = "all clear" for i := 0; i < 3; i++ { require.NoError(t, runIssuesPostComment(ctx, cfg)) diff --git a/internal/cli/keep_history_deprecation_test.go b/internal/cli/keep_history_deprecation_test.go deleted file mode 100644 index 6d94df84d2..0000000000 --- a/internal/cli/keep_history_deprecation_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package cli - -import ( - "bytes" - "context" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/fullsend-ai/fullsend/internal/forge" - "github.com/fullsend-ai/fullsend/internal/tracker" - "github.com/fullsend-ai/fullsend/internal/ui" -) - -// The keepHistoryDeprecationWarning snippet every door must print when -// --keep-history is passed explicitly. Shell scripts never read help text, -// so this stderr line is the only advance notice external automation gets -// before a cleanup PR removes the flag. -const keepHistoryDeprecationWarning = "warning: --keep-history is deprecated and has no effect" - -// The three doors that accept --keep-history (issues post-comment, -// post-comment and post-review) share warnKeepHistoryDeprecated, but its -// flag-Changed branch only runs through Cobra's flag parsing, so each door -// is driven at the command level: with the flag passed explicitly the -// warning must reach stderr, without it stderr must stay free of it. - -func TestIssuesPostCommentCmd_KeepHistoryWarnsOnExplicitFlag(t *testing.T) { - t.Setenv("GH_TOKEN", "") - t.Setenv("GITHUB_TOKEN", "") - t.Setenv("PATH", "/nonexistent") - - bodyFile := filepath.Join(t.TempDir(), "body.md") - require.NoError(t, os.WriteFile(bodyFile, []byte("comment body"), 0o644)) - - run := func(extra ...string) string { - cmd := newIssuesPostCommentCmd() - cmd.SilenceUsage = true - cmd.SilenceErrors = true - cmd.SetArgs(append([]string{ - "--tracker", "github", - "--project", "owner/repo", - "--number", "1", - "--marker", "", - "--result", bodyFile, - }, extra...)) - var stderr strings.Builder - cmd.SetErr(&stderr) - err := cmd.Execute() - // No token is available, so the run stops before posting; the - // warning is printed before that, at the top of RunE. - require.Error(t, err) - assert.Contains(t, err.Error(), "no GitHub token found") - return stderr.String() - } - - assert.Contains(t, run("--keep-history=false"), keepHistoryDeprecationWarning, - "an explicit --keep-history must warn on stderr") - assert.NotContains(t, run(), keepHistoryDeprecationWarning, - "the default flag value must not warn") -} - -func TestPostCommentCmd_KeepHistoryWarnsOnExplicitFlag(t *testing.T) { - t.Setenv("FULLSEND_DIR", "") - - bodyFile := filepath.Join(t.TempDir(), "body.md") - require.NoError(t, os.WriteFile(bodyFile, []byte("comment body"), 0o644)) - - run := func(extra ...string) string { - cmd := newPostCommentCmd() - cmd.SilenceUsage = true - cmd.SilenceErrors = true - cmd.SetArgs(append([]string{ - "--repo", "owner/repo", - "--number", "1", - "--marker", "", - "--result", bodyFile, - "--token", "test-token", - "--dry-run", - }, extra...)) - var stderr strings.Builder - cmd.SetErr(&stderr) - require.NoError(t, cmd.Execute()) - return stderr.String() - } - - assert.Contains(t, run("--keep-history=false"), keepHistoryDeprecationWarning, - "an explicit --keep-history must warn on stderr") - assert.NotContains(t, run(), keepHistoryDeprecationWarning, - "the default flag value must not warn") -} - -func TestPostReviewCmd_KeepHistoryWarnsOnExplicitFlag(t *testing.T) { - t.Setenv("FULLSEND_DIR", "") - - resultFile := filepath.Join(t.TempDir(), "result.json") - require.NoError(t, os.WriteFile(resultFile, []byte(`{"action":"comment","body":"ok"}`), 0o644)) - - run := func(extra ...string) string { - cmd := newPostReviewCmd() - cmd.SilenceUsage = true - cmd.SilenceErrors = true - cmd.SetArgs(append([]string{ - "--repo", "owner/repo", - "--pr", "1", - "--result", resultFile, - "--token", "test-token", - "--dry-run", - }, extra...)) - var stderr strings.Builder - cmd.SetErr(&stderr) - require.NoError(t, cmd.Execute()) - return stderr.String() - } - - assert.Contains(t, run("--keep-history=false"), keepHistoryDeprecationWarning, - "an explicit --keep-history must warn on stderr") - assert.NotContains(t, run(), keepHistoryDeprecationWarning, - "the default flag value must not warn") -} - -func TestRunIssuesPostComment_KeepHistoryWarnsOnConfigPath(t *testing.T) { - // The config route: with no explicit --keep-history, resolveKeepHistory - // reads config.yaml through --fullsend-dir, and every door prints the - // same shared notice when that resolution fails. The flag-path tests - // above pin warnKeepHistoryDeprecated; this pins the config leg, so a - // regression dropping the StepWarn (issues.go, postcomment.go and - // postreview.go carry the same branch) fails here. - dir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("{{{"), 0o644)) - - var out bytes.Buffer - cfg := &issuesPostCommentConfig{ - trackerName: trackerGitHub, - project: "acme/widgets", - number: 42, - marker: "", - fullsendDir: dir, - testClient: tracker.NewForgeClient(forge.NewFakeClient()), - testPrinter: ui.New(&out), - testBody: "comment body", - } - require.NoError(t, runIssuesPostComment(context.Background(), cfg)) - assert.Contains(t, out.String(), "keep_history is deprecated and unused", - "a config.yaml that cannot load must still print the keep_history deprecation warning") -} diff --git a/internal/cli/keep_history_flag_acceptance_test.go b/internal/cli/keep_history_flag_acceptance_test.go new file mode 100644 index 0000000000..26d2179b0e --- /dev/null +++ b/internal/cli/keep_history_flag_acceptance_test.go @@ -0,0 +1,305 @@ +package cli + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// keepHistoryDeprecationNotice is the stderr line the three posting doors +// print while --keep-history is still a deprecated, warned no-op. The +// cleanup (#9517) removes it together with the machinery behind the flag: +// whichever way the PR decides — the flag removed, or kept as a hidden +// no-op so generated post-scripts and pinned callers are not rejected — +// this line must never print again. +const keepHistoryDeprecationNotice = "warning: --keep-history is deprecated" + +// withKeepHistory appends an explicit --keep-history to base args without +// touching base. +func withKeepHistory(base []string) []string { + return append(append([]string{}, base...), "--keep-history=false") +} + +// withFullsendDir appends an explicit --fullsend-dir to base args without +// touching base. +func withFullsendDir(base []string) []string { + return append(append([]string{}, base...), "--fullsend-dir", "/legacy") +} + +// runKeepHistoryDoor executes door with args and returns its error and +// stderr. Usage and cobra's error printing are silenced so the assertions +// see the flag decision itself. +func runKeepHistoryDoor(t *testing.T, door *cobra.Command, args ...string) (error, string) { + t.Helper() + door.SilenceUsage = true + door.SilenceErrors = true + door.SetArgs(args) + var stderr strings.Builder + door.SetErr(&stderr) + return door.Execute(), stderr.String() +} + +// requireLegacyNoOpFlag pins #9517's settled choice for a legacy flag: it +// must exist and be hidden. The shims exist because post-scripts generated +// before #9334 pass --keep-history=false unconditionally under +// `set -euo pipefail` (and external callers pass --fullsend-dir), so +// deleting a shim breaks those runs; removing one must fail these tests +// first, not slip through a nil lookup. +func requireLegacyNoOpFlag(t *testing.T, cmd *cobra.Command, name string) { + t.Helper() + flag := cmd.Flags().Lookup(name) + require.NotNil(t, flag, "--%s must stay a hidden no-op: deleting the shim breaks pre-#9334 generated post-scripts and pinned callers (#9517)", name) + assert.True(t, flag.Hidden, "--%s may stay only as a hidden no-op (#9517)", name) +} + +// TestPostCommentCmd_KeepHistoryRemovedOrSilentHiddenNoOp pins #9517's +// second criterion for the post-comment door: --keep-history stays a +// hidden no-op that never prints the deprecation notice, and the post +// itself behaves as if the flag were not passed. The flag must exist: +// pre-#9334 post-scripts pass it unconditionally under +// `set -euo pipefail`, so removing the shim is a deliberate change that +// fails this test, not a silent green. +func TestPostCommentCmd_KeepHistoryRemovedOrSilentHiddenNoOp(t *testing.T) { + t.Setenv("FULLSEND_DIR", "") + + bodyFile := filepath.Join(t.TempDir(), "body.md") + require.NoError(t, os.WriteFile(bodyFile, []byte("comment body"), 0o644)) + base := []string{ + "--repo", "owner/repo", + "--number", "1", + "--marker", "", + "--result", bodyFile, + "--token", "test-token", + "--dry-run", + } + + cmd := newPostCommentCmd() + requireLegacyNoOpFlag(t, cmd, "keep-history") + err, stderr := runKeepHistoryDoor(t, cmd, withKeepHistory(base)...) + require.NoError(t, err) + assert.NotContains(t, stderr, keepHistoryDeprecationNotice, + "the --keep-history deprecation notice is removed with the machinery") +} + +// TestIssuesPostCommentCmd_KeepHistoryRemovedOrSilentHiddenNoOp is the +// same pin for the issues post-comment door. With no GitHub token in the +// environment the run stops before posting; that is the door's own error, +// not a flag decision, so it is accepted while the notice must still +// never print. +func TestIssuesPostCommentCmd_KeepHistoryRemovedOrSilentHiddenNoOp(t *testing.T) { + t.Setenv("GH_TOKEN", "") + t.Setenv("GITHUB_TOKEN", "") + t.Setenv("PATH", "/nonexistent") + + bodyFile := filepath.Join(t.TempDir(), "body.md") + require.NoError(t, os.WriteFile(bodyFile, []byte("comment body"), 0o644)) + base := []string{ + "--tracker", "github", + "--project", "owner/repo", + "--number", "1", + "--marker", "", + "--result", bodyFile, + } + + cmd := newIssuesPostCommentCmd() + requireLegacyNoOpFlag(t, cmd, "keep-history") + err, stderr := runKeepHistoryDoor(t, cmd, withKeepHistory(base)...) + require.Error(t, err, "no token is available, so the run stops before posting") + assert.Contains(t, err.Error(), "no GitHub token found") + assert.NotContains(t, stderr, keepHistoryDeprecationNotice, + "the --keep-history deprecation notice is removed with the machinery") +} + +// TestPostReviewCmd_KeepHistoryRemovedOrSilentHiddenNoOp is the same pin +// for the post-review door. +func TestPostReviewCmd_KeepHistoryRemovedOrSilentHiddenNoOp(t *testing.T) { + t.Setenv("FULLSEND_DIR", "") + + resultFile := filepath.Join(t.TempDir(), "result.json") + require.NoError(t, os.WriteFile(resultFile, []byte(`{"action":"comment","body":"ok"}`), 0o644)) + base := []string{ + "--repo", "owner/repo", + "--pr", "1", + "--result", resultFile, + "--token", "test-token", + "--dry-run", + } + + cmd := newPostReviewCmd() + requireLegacyNoOpFlag(t, cmd, "keep-history") + err, stderr := runKeepHistoryDoor(t, cmd, withKeepHistory(base)...) + require.NoError(t, err) + assert.NotContains(t, stderr, keepHistoryDeprecationNotice, + "the --keep-history deprecation notice is removed with the machinery") +} + +// TestPostCommentCmd_FullsendDirHiddenNoOp pins the same settled choice +// for the orphaned --fullsend-dir on the post-comment door: hidden, +// accepted, no effect. On this door the flag only ever sourced the +// removed keep-history setting, so it stays a hidden no-op until external +// callers have moved off it; deleting the shim must fail this test. +func TestPostCommentCmd_FullsendDirHiddenNoOp(t *testing.T) { + t.Setenv("FULLSEND_DIR", "") + + bodyFile := filepath.Join(t.TempDir(), "body.md") + require.NoError(t, os.WriteFile(bodyFile, []byte("comment body"), 0o644)) + base := []string{ + "--repo", "owner/repo", + "--number", "1", + "--marker", "", + "--result", bodyFile, + "--token", "test-token", + "--dry-run", + } + + cmd := newPostCommentCmd() + requireLegacyNoOpFlag(t, cmd, "fullsend-dir") + err, _ := runKeepHistoryDoor(t, cmd, withFullsendDir(base)...) + require.NoError(t, err, "--fullsend-dir x must parse on the post-comment door") +} + +// TestPostReviewCmd_FullsendDirHiddenNoOp is the same pin for the +// --fullsend-dir no-op on the post-review door. +func TestPostReviewCmd_FullsendDirHiddenNoOp(t *testing.T) { + t.Setenv("FULLSEND_DIR", "") + + resultFile := filepath.Join(t.TempDir(), "result.json") + require.NoError(t, os.WriteFile(resultFile, []byte(`{"action":"comment","body":"ok"}`), 0o644)) + base := []string{ + "--repo", "owner/repo", + "--pr", "1", + "--result", resultFile, + "--token", "test-token", + "--dry-run", + } + + cmd := newPostReviewCmd() + requireLegacyNoOpFlag(t, cmd, "fullsend-dir") + err, _ := runKeepHistoryDoor(t, cmd, withFullsendDir(base)...) + require.NoError(t, err, "--fullsend-dir x must parse on the post-review door") +} + +// TestPostCommentCmd_KeepHistoryDoesNotAffectPosting pins the behaviour +// behind the hidden flag, not only its surface: the post-comment door run +// in dry-run (its plan captured with captureStdout from repos_test.go, +// the doors printing to os.Stdout through ui.New) must print the same +// plan, return the same error and write the same stderr whether +// --keep-history is passed or not, so a regression that makes the shim +// affect the posted body or the run fails here. +func TestPostCommentCmd_KeepHistoryDoesNotAffectPosting(t *testing.T) { + t.Setenv("FULLSEND_DIR", "") + + bodyFile := filepath.Join(t.TempDir(), "body.md") + require.NoError(t, os.WriteFile(bodyFile, []byte("comment body"), 0o644)) + base := []string{ + "--repo", "owner/repo", + "--number", "1", + "--marker", "", + "--result", bodyFile, + "--token", "test-token", + "--dry-run", + } + + run := func(args ...string) (string, string, error) { + cmd := newPostCommentCmd() + requireLegacyNoOpFlag(t, cmd, "keep-history") + var runErr error + var stderr string + out := captureStdout(t, func() { + runErr, stderr = runKeepHistoryDoor(t, cmd, args...) + }) + return out, stderr, runErr + } + + plainOut, plainStderr, plainErr := run(base...) + flagOut, flagStderr, flagErr := run(withKeepHistory(base)...) + require.NoError(t, plainErr) + require.NoError(t, flagErr) + assert.Equal(t, plainOut, flagOut, "--keep-history must not change what the post-comment door posts") + assert.Equal(t, plainStderr, flagStderr, "--keep-history must not change what the post-comment door reports") +} + +// TestPostCommentCmd_KeepHistoryPostsTheSamePayload pins the posting +// equivalence at the payload level, one step behind the dry-run +// comparison above: the post-comment door runs twice without --dry-run +// against a recording test endpoint (GITHUB_API_URL, the test fallback +// newGitHubLiveClient honours), and the create-comment request — method, +// path and JSON body — and the call count are identical with and without +// --keep-history. A regression that only matters on a real post (a +// changed payload, a second call, a different endpoint) fails here even +// when the dry-run plan is unchanged. +func TestPostCommentCmd_KeepHistoryPostsTheSamePayload(t *testing.T) { + type recordedRequest struct { + Method string + Path string + Body string + } + var mu sync.Mutex + var recorded []recordedRequest + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + mu.Lock() + recorded = append(recorded, recordedRequest{Method: r.Method, Path: r.URL.Path, Body: string(body)}) + mu.Unlock() + if r.Method == http.MethodPost && r.URL.Path == "/repos/owner/repo/issues/1/comments" { + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 1, + "html_url": "https://github.com/owner/repo/issues/1#issuecomment-1", + "body": "comment body", + "user": map[string]string{"login": "octocat"}, + }) + return + } + http.NotFound(w, r) + })) + defer srv.Close() + + t.Setenv("GITHUB_API_URL", srv.URL) + t.Setenv("FULLSEND_DIR", "") + + bodyFile := filepath.Join(t.TempDir(), "body.md") + require.NoError(t, os.WriteFile(bodyFile, []byte("comment body"), 0o644)) + base := []string{ + "--repo", "owner/repo", + "--number", "1", + "--marker", "", + "--result", bodyFile, + "--token", "test-token", + } + + run := func(args ...string) error { + cmd := newPostCommentCmd() + requireLegacyNoOpFlag(t, cmd, "keep-history") + var runErr error + _ = captureStdout(t, func() { + runErr, _ = runKeepHistoryDoor(t, cmd, args...) + }) + return runErr + } + + require.NoError(t, run(base...), "the plain run must post its comment") + require.NoError(t, run(withKeepHistory(base)...), "the --keep-history run must post its comment") + + require.Len(t, recorded, 2, "each run must make exactly one create-comment request") + for _, req := range recorded { + assert.Equal(t, http.MethodPost, req.Method, "the comment must be created with a POST") + assert.Equal(t, "/repos/owner/repo/issues/1/comments", req.Path, "the comment must go to the issue's comments endpoint") + } + assert.NotEmpty(t, recorded[0].Body, "the create-comment payload must carry a body") + assert.Equal(t, recorded[0].Body, recorded[1].Body, + "--keep-history must not change the create-comment payload") +} diff --git a/internal/cli/postcomment.go b/internal/cli/postcomment.go index d6bdb3c68f..2e74b4b13a 100644 --- a/internal/cli/postcomment.go +++ b/internal/cli/postcomment.go @@ -14,14 +14,12 @@ import ( func newPostCommentCmd() *cobra.Command { var ( - repo string - number int - marker string - result string - token string - dryRun bool - keepHistory bool - fullsendDir string + repo string + number int + marker string + result string + token string + dryRun bool ) cmd := &cobra.Command{ @@ -70,26 +68,9 @@ The --result flag accepts a file path or "-" for stdin.`, printer.Header("Post Comment") - // Resolve keep_history: explicit --keep-history flag takes - // precedence, otherwise fall back to config.yaml via - // --fullsend-dir (matching the pattern in issues post-comment - // and post-review). - resolvedKeepHistory := keepHistory - if cmd.Flags().Changed("keep-history") { - warnKeepHistoryDeprecated(cmd) - } else { - var khFlag *bool // nil = not explicitly set - resolved, resolveErr := resolveKeepHistory(khFlag, fullsendDir, nil) - if resolveErr != nil { - printer.StepWarn(fmt.Sprintf("Warning: %v (keep_history is deprecated and unused; every result is posted as a new comment)", resolveErr)) - } - resolvedKeepHistory = resolved - } - cfg := sticky.Config{ - Marker: marker, - DryRun: dryRun, - KeepHistory: resolvedKeepHistory, + Marker: marker, + DryRun: dryRun, } _, err = sticky.Post(cmd.Context(), client, owner, repoName, number, body, cfg, printer) return err @@ -102,8 +83,8 @@ The --result flag accepts a file path or "-" for stdin.`, cmd.Flags().StringVar(&result, "result", "-", "path to comment body file, or '-' for stdin") cmd.Flags().StringVar(&token, "token", "", "GitHub token (default: GH_TOKEN, GITHUB_TOKEN, or gh auth token)") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "print what would be posted without making API calls") - cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "deprecated: no effect (every result is posted as a new comment; sticky comments were removed)") - cmd.Flags().StringVar(&fullsendDir, "fullsend-dir", os.Getenv("FULLSEND_DIR"), "path to .fullsend config directory (default: $FULLSEND_DIR; sources defaults from its config.yaml when flags are omitted)") + addLegacyHistoryFlag(cmd) + addLegacyFullsendDirFlag(cmd) _ = cmd.MarkFlagRequired("repo") _ = cmd.MarkFlagRequired("number") _ = cmd.MarkFlagRequired("marker") diff --git a/internal/cli/postreview.go b/internal/cli/postreview.go index 462c0e59e3..45f68aa5b0 100644 --- a/internal/cli/postreview.go +++ b/internal/cli/postreview.go @@ -78,16 +78,14 @@ func reviewTrustedLeadingLineReForHash(diffHash, headSHA string) *regexp.Regexp func newPostReviewCmd() *cobra.Command { var ( - repo string - pr int - result string - token string - headSHA string - dryRun bool - forgeName string - baseURL string - keepHistory bool - fullsendDir string + repo string + pr int + result string + token string + headSHA string + dryRun bool + forgeName string + baseURL string ) cmd := &cobra.Command{ @@ -167,25 +165,9 @@ GITLAB_TOKEN for GitLab and GH_TOKEN / GITHUB_TOKEN for GitHub.`, return err } - // Resolve keep_history: explicit --keep-history flag takes - // precedence, otherwise fall back to config.yaml via - // --fullsend-dir (matching the pattern in issues post-comment). - resolvedKeepHistory := keepHistory - if cmd.Flags().Changed("keep-history") { - warnKeepHistoryDeprecated(cmd) - } else { - var khFlag *bool // nil = not explicitly set - resolved, resolveErr := resolveKeepHistory(khFlag, fullsendDir, nil) - if resolveErr != nil { - printer.StepWarn(fmt.Sprintf("Warning: %v (keep_history is deprecated and unused; every result is posted as a new comment)", resolveErr)) - } - resolvedKeepHistory = resolved - } - cfg := sticky.Config{ - Marker: reviewMarker, - DryRun: dryRun, - KeepHistory: resolvedKeepHistory, + Marker: reviewMarker, + DryRun: dryRun, } // Stale-head check: refuse to post a review against code @@ -216,8 +198,8 @@ GITLAB_TOKEN for GitLab and GH_TOKEN / GITHUB_TOKEN for GitHub.`, cmd.Flags().StringVar(&token, "token", "", "forge token (default: $GH_TOKEN / $GITHUB_TOKEN for GitHub, $GITLAB_TOKEN for GitLab)") cmd.Flags().StringVar(&headSHA, "head-sha", "", "expected PR HEAD SHA (skips review if HEAD has moved)") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "print what would be posted without making API calls") - cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "deprecated: no effect (every result is posted as a new comment; sticky comments were removed)") - cmd.Flags().StringVar(&fullsendDir, "fullsend-dir", os.Getenv("FULLSEND_DIR"), "path to .fullsend config directory (default: $FULLSEND_DIR; sources defaults from its config.yaml when flags are omitted)") + addLegacyHistoryFlag(cmd) + addLegacyFullsendDirFlag(cmd) cmd.Flags().StringVar(&forgeName, "forge", "", "forge backend: github (default) or gitlab") cmd.Flags().StringVar(&baseURL, "base-url", "", "forge instance URL (e.g. https://gitlab.example.com)") _ = cmd.MarkFlagRequired("repo") diff --git a/internal/cli/postreview_test.go b/internal/cli/postreview_test.go index 37efa917b3..4d6327499e 100644 --- a/internal/cli/postreview_test.go +++ b/internal/cli/postreview_test.go @@ -169,7 +169,7 @@ func TestPostStaleHeadNotice(t *testing.T) { fc.PullRequestHeadSHA = "new_sha_456" printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} err := postStaleHeadNotice(context.Background(), fc, "o", "r", 1, "old_sha_123", "new_sha_456", cfg, printer) require.Error(t, err, "should return an error indicating staleness") assert.Contains(t, err.Error(), "stale") @@ -201,7 +201,7 @@ func TestPostFailureNotice_WithBody(t *testing.T) { fc.AuthenticatedUser = "bot" printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} parsed := ReviewResult{Action: "failure", Body: "Custom failure message", Reason: "tool-failure"} err := postFailureNotice(context.Background(), fc, "o", "r", 1, parsed, cfg, printer) require.NoError(t, err) @@ -217,7 +217,7 @@ func TestPostFailureNotice_WithoutBody(t *testing.T) { fc.AuthenticatedUser = "bot" printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} parsed := ReviewResult{Action: "failure", Reason: "token-limit"} err := postFailureNotice(context.Background(), fc, "o", "r", 1, parsed, cfg, printer) require.NoError(t, err) @@ -233,7 +233,7 @@ func TestPostFailureNotice_EmptyReason(t *testing.T) { fc.AuthenticatedUser = "bot" printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: "", KeepHistory: true} + cfg := sticky.Config{Marker: ""} parsed := ReviewResult{Action: "failure", Reason: ""} err := postFailureNotice(context.Background(), fc, "o", "r", 1, parsed, cfg, printer) require.NoError(t, err) @@ -251,7 +251,7 @@ func TestPostReviewContent_FormalReviewFailureDoesNotFailCommand(t *testing.T) { var buf bytes.Buffer printer := ui.New(&buf) - cfg := sticky.Config{Marker: reviewMarker, KeepHistory: true} + cfg := sticky.Config{Marker: reviewMarker} parsed := ReviewResult{Body: "Looks good", Action: "approve"} err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, cfg, false, printer) @@ -272,7 +272,7 @@ func TestPostReviewContent_RequestChangesFormalReviewFailureDoesNotFailCommand(t var buf bytes.Buffer printer := ui.New(&buf) - cfg := sticky.Config{Marker: reviewMarker, KeepHistory: true} + cfg := sticky.Config{Marker: reviewMarker} parsed := ReviewResult{Body: "Please fix these issues", Action: "request-changes"} err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, cfg, false, printer) @@ -291,7 +291,7 @@ func TestPostReviewContent_StickyFailureStillFails(t *testing.T) { fc.Errors["CreateIssueComment"] = fmt.Errorf("comment API error") printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: reviewMarker, KeepHistory: true} + cfg := sticky.Config{Marker: reviewMarker} parsed := ReviewResult{Body: "Looks good", Action: "approve"} err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, cfg, false, printer) @@ -306,7 +306,7 @@ func TestPostReviewContent_SuccessSubmitsFormalReview(t *testing.T) { fc.AuthenticatedUser = "bot" fc.PullRequestHeadSHA = "abc123def456" printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: reviewMarker, KeepHistory: true} + cfg := sticky.Config{Marker: reviewMarker} parsed := ReviewResult{Body: "Looks good", Action: "approve", HeadSHA: "abc123def456"} err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, cfg, false, printer) @@ -467,7 +467,7 @@ func TestPostReviewContent_IncludesDiffHashMarker(t *testing.T) { "o/r/1": {{Path: "README.md", Patch: "@@ -1 +1 @@\n-old\n+new"}}, } printer := ui.New(io.Discard) - cfg := sticky.Config{Marker: reviewMarker, KeepHistory: true} + cfg := sticky.Config{Marker: reviewMarker} parsed := ReviewResult{Body: "Looks good", Action: "approve", HeadSHA: "abc123def456"} err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, cfg, false, printer) @@ -512,7 +512,7 @@ Earlier review err := postReviewContent(context.Background(), fc, "o", "r", 1, ReviewResult{Body: "Looks good", Action: "approve", HeadSHA: "abc123def456"}, - sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard)) + sticky.Config{Marker: reviewMarker}, false, ui.New(io.Discard)) require.NoError(t, err) // The prior comment stands exactly as it was (nothing is folded into @@ -537,14 +537,14 @@ func TestPostReviewContent_PublishesDiffHashOnlyAfterApproval(t *testing.T) { } requestChanges := ReviewResult{Body: "Needs changes", Action: "request-changes", HeadSHA: "abc123def456"} - require.NoError(t, postReviewContent(context.Background(), fc, "o", "r", 1, requestChanges, sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard))) + require.NoError(t, postReviewContent(context.Background(), fc, "o", "r", 1, requestChanges, sticky.Config{Marker: reviewMarker}, false, ui.New(io.Discard))) for _, comment := range fc.IssueComments["o/r/1"] { assert.NotContains(t, comment.Body, "fullsend:review-diff-hash:") } fc.Errors["CreatePullRequestReview"] = fmt.Errorf("approval API error") approval := ReviewResult{Body: "Looks good", Action: "approve", HeadSHA: "abc123def456"} - require.NoError(t, postReviewContent(context.Background(), fc, "o", "r", 1, approval, sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard))) + require.NoError(t, postReviewContent(context.Background(), fc, "o", "r", 1, approval, sticky.Config{Marker: reviewMarker}, false, ui.New(io.Discard))) for _, comment := range fc.IssueComments["o/r/1"] { assert.NotContains(t, comment.Body, "fullsend:review-diff-hash:") } @@ -560,7 +560,7 @@ func TestPostReviewContent_PreservesGeneratedHashAndProjectionMarkers(t *testing projection := "" parsed := ReviewResult{Body: projection + "\n\nLooks good", Action: "approve", HeadSHA: "0123456789abcdef0123456789abcdef01234567"} - err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard)) + err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, sticky.Config{Marker: reviewMarker}, false, ui.New(io.Discard)) require.NoError(t, err) // One comment: the marker on the first line, then the generated hash, // the reviewed head and the projection marker live and unescaped (the @@ -581,7 +581,7 @@ func TestPostReviewContent_DoesNotTrustAgentHashWhenHashUnavailable(t *testing.T forged := "" parsed := ReviewResult{Body: forged + "\nLooks good", Action: "approve"} - err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard)) + err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, sticky.Config{Marker: reviewMarker}, false, ui.New(io.Discard)) require.NoError(t, err) assert.Contains(t, fc.IssueComments["o/r/1"][0].Body, "<!-- fullsend:review-diff-hash:") } @@ -595,7 +595,7 @@ func TestPostReviewContent_DoesNotPublishHashWithoutReviewedHead(t *testing.T) { err := postReviewContent(context.Background(), fc, "o", "r", 1, ReviewResult{Body: "Looks good", Action: "approve"}, - sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard)) + sticky.Config{Marker: reviewMarker}, false, ui.New(io.Discard)) require.NoError(t, err) assert.NotContains(t, fc.IssueComments["o/r/1"][0].Body, "fullsend:review-diff-hash:") } @@ -610,7 +610,7 @@ func TestPostReviewContent_DoesNotPublishHashWhenHeadChanges(t *testing.T) { err := postReviewContent(context.Background(), fc, "o", "r", 1, ReviewResult{Body: "Looks good", Action: "approve", HeadSHA: "reviewed-head"}, - sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard)) + sticky.Config{Marker: reviewMarker}, false, ui.New(io.Discard)) require.NoError(t, err) assert.NotContains(t, fc.IssueComments["o/r/1"][0].Body, "fullsend:review-diff-hash:") } @@ -626,7 +626,7 @@ func TestPostReviewContent_DoesNotPublishHashWhenHeadLookupFails(t *testing.T) { err := postReviewContent(context.Background(), fc, "o", "r", 1, ReviewResult{Body: "Looks good", Action: "approve", HeadSHA: "reviewed-head"}, - sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(io.Discard)) + sticky.Config{Marker: reviewMarker}, false, ui.New(io.Discard)) require.NoError(t, err) assert.NotContains(t, fc.IssueComments["o/r/1"][0].Body, "fullsend:review-diff-hash:") } @@ -643,7 +643,7 @@ func TestPostReviewContent_HashPublicationFailureIsBestEffort(t *testing.T) { var buf bytes.Buffer err := postReviewContent(context.Background(), fc, "o", "r", 1, ReviewResult{Body: "Looks good", Action: "approve", HeadSHA: "abc123def456"}, - sticky.Config{Marker: reviewMarker, KeepHistory: true}, false, ui.New(&buf)) + sticky.Config{Marker: reviewMarker}, false, ui.New(&buf)) require.NoError(t, err) require.Len(t, fc.IssueComments["o/r/1"], 1) assert.Contains(t, fc.IssueComments["o/r/1"][0].Body, "Looks good") @@ -672,7 +672,7 @@ func TestPostReviewContent_FallbackFailureDoesNotFailCommand(t *testing.T) { var buf bytes.Buffer printer := ui.New(&buf) - cfg := sticky.Config{Marker: reviewMarker, KeepHistory: true} + cfg := sticky.Config{Marker: reviewMarker} parsed := ReviewResult{ Body: "Needs changes", Action: "request-changes", @@ -2566,7 +2566,7 @@ func TestPostReviewContent_KeepsLeadingProjectionMarkerLive(t *testing.T) { t.Run(tt.name, func(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" - cfg := sticky.Config{Marker: reviewMarker, KeepHistory: true} + cfg := sticky.Config{Marker: reviewMarker} parsed := ReviewResult{Body: tt.body, Action: "comment"} err := postReviewContent(context.Background(), fc, "o", "r", 1, parsed, cfg, false, ui.New(io.Discard)) @@ -2584,7 +2584,7 @@ func TestPostReviewContent_KeepsLeadingProjectionMarkerLive(t *testing.T) { func TestPostFailureNotice_EscapesProjectionMarker(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "bot" - cfg := sticky.Config{Marker: reviewMarker, KeepHistory: true} + cfg := sticky.Config{Marker: reviewMarker} parsed := ReviewResult{Action: "failure", Body: "\nFailed"} err := postFailureNotice(context.Background(), fc, "o", "r", 1, parsed, cfg, ui.New(io.Discard)) diff --git a/internal/cli/postscript_current_cli_keep_history_test.go b/internal/cli/postscript_current_cli_keep_history_test.go new file mode 100644 index 0000000000..2d09c76f16 --- /dev/null +++ b/internal/cli/postscript_current_cli_keep_history_test.go @@ -0,0 +1,128 @@ +package cli + +import ( + "bytes" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/agentnew" +) + +// TestGeneratedPostScriptPassesNoKeepHistoryToCurrentCLI pins #9517's +// fourth criterion end to end: a post-script generated from the current +// internal/agentnew/templates/post.sh.tmpl, run against the current CLI's +// own flag surface, passes no --keep-history and so prints no deprecation +// warning. The stub on PATH answers the script's --help probe with the +// help text the real `fullsend issues post-comment` command renders +// in-process, and behaves the way the current CLI behaves while the +// deprecated flag is still listed in that help: once the cleanup removes +// or hides the flag, the probe no longer sees it and the all-clear posts +// cleanly. +func TestGeneratedPostScriptPassesNoKeepHistoryToCurrentCLI(t *testing.T) { + if testing.Short() { + t.Skip("renders post.sh.tmpl and runs it under bash; skipped in -short mode") + } + if _, err := exec.LookPath("bash"); err != nil { + t.Skip("bash not installed; the generated post-script runs under it") + } + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + + // The current CLI's own help for issues post-comment: the exact text + // the generated script probes on whatever runner it lands in. + var help bytes.Buffer + helpCmd := newIssuesPostCommentCmd() + helpCmd.SetOut(&help) + helpCmd.SetArgs([]string{"--help"}) + require.NoError(t, helpCmd.Execute()) + require.NotEmpty(t, help.String(), "the issues post-command must render its help") + + binDir := t.TempDir() + helpFile := filepath.Join(binDir, "help.txt") + require.NoError(t, os.WriteFile(helpFile, help.Bytes(), 0o644)) + argsFile := filepath.Join(binDir, "args") + stub := "#!/usr/bin/env bash\n" + + "if [[ \"$*\" == *--help* ]]; then cat \"" + helpFile + "\"; exit 0; fi\n" + + "if [[ \"$*\" == *--keep-history* ]]; then\n" + + " echo 'warning: --keep-history is deprecated and has no effect; every result is posted as a new comment' >&2\n" + + " exit 1\n" + + "fi\n" + + "printf '%s\\n' \"$@\" > \"" + argsFile + "\"\n" + + "cat >/dev/null\n" + require.NoError(t, os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755)) + + script := renderCurrentPostScript(t) + runDir := t.TempDir() + iterationDir := filepath.Join(runDir, "iteration-1", "output") + require.NoError(t, os.MkdirAll(iterationDir, 0o755)) + result, err := json.Marshal(map[string]any{ + "status": "ok", + "summary": "All clear", + "comment": "All added documentation links resolve.", + }) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(iterationDir, "agent-result.json"), result, 0o644)) + + 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 + require.NoError(t, cmd.Run(), + "the ok path must post cleanly against the current CLI; stderr:\n%s", stderr.String()) + assert.NotContains(t, stderr.String(), "warning: --keep-history", + "the generated script must not trigger the deprecation warning on a current CLI") + + got, err := os.ReadFile(argsFile) + require.NoError(t, err, + "the script never invoked fullsend on the ok path; stderr:\n%s", stderr.String()) + args := string(got) + assert.Contains(t, args, "--only-if-exists", + "the all-clear still goes through --only-if-exists") + assert.NotContains(t, args, "--keep-history", + "the generated script must pass no --keep-history to the current CLI") +} + +// renderCurrentPostScript renders the current post.sh.tmpl with the same +// options internal/cli's agent scaffolding uses, and returns the +// generated script's path. +func renderCurrentPostScript(t *testing.T) string { + t.Helper() + trigger, err := agentnew.ExpandTrigger(agentnew.DefaultOn, "lint-docs") + require.NoError(t, err) + role, err := agentnew.LookupRole("triage") + require.NoError(t, err) + files, err := agentnew.Render(agentnew.Options{ + Name: "lint-docs", + Role: "triage", + Description: "Check docs changes for broken links", + Trigger: trigger, + Model: agentnew.DefaultModel, + Effort: agentnew.DefaultEffort, + Slug: "my-org-lint-docs", + Image: role.Image, + TimeoutMinutes: agentnew.DefaultTimeoutMinutes, + }) + require.NoError(t, err) + for _, f := range files { + if f.Path == "scripts/post-lint-docs.sh" { + path := filepath.Join(t.TempDir(), "post-lint-docs.sh") + require.NoError(t, os.WriteFile(path, f.Data, 0o755)) + return path + } + } + t.Fatal("no generated post-script found") + return "" +} diff --git a/internal/cli/repos_managed_config_test.go b/internal/cli/repos_managed_config_test.go index d25e3b933c..71ee298676 100644 --- a/internal/cli/repos_managed_config_test.go +++ b/internal/cli/repos_managed_config_test.go @@ -506,7 +506,7 @@ github: func TestRunReposStatus_NoConfigKeyMarkerlessOverlayRequiresAdoption(t *testing.T) { manifestPath := writeTestManifest(t, githubUnmanagedManifestYAML) fc := newInstalledFakeClientCLI("acme/api") - fc.FileContents[overlayPath("acme/api")] = []byte("keep_history: true\n# local\n") + fc.FileContents[overlayPath("acme/api")] = []byte("kill_switch: true\n# local\n") result, _ := statusJSON(t, manifestPath, fc) d, found := overlayDrift(t, result, "acme/api") diff --git a/internal/cli/reviewdedup.go b/internal/cli/reviewdedup.go index eb0aaabbc4..e9cb35c841 100644 --- a/internal/cli/reviewdedup.go +++ b/internal/cli/reviewdedup.go @@ -228,6 +228,11 @@ func latestVerifiedReviewComment(comments []forge.IssueComment, owner, appSet, a func reviewHashAndHead(body string) (string, string) { section := body + // Read-side shim: reviews posted by pre-#9334 CLIs folded prior + // results below a sticky:history-start sentinel; the diff-hash and + // head markers to compare live in the current section above it. The + // machinery that wrote the sentinel is gone (#9517) — keep reading + // it until those review comments have aged out of open PRs. if idx := strings.Index(section, ""); idx >= 0 { section = section[:idx] } diff --git a/internal/config/config.go b/internal/config/config.go index d903e5a1d3..82b30d3755 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1174,12 +1174,6 @@ type perRepoConfig struct { KillSwitch *bool `yaml:"kill_switch,omitempty"` Runtime string `yaml:"runtime,omitempty"` - // KeepHistory is deprecated and has no effect: sticky comments were - // removed (#9334); every result is a new comment. Kept until a - // cleanup removes the field. When nil (omitted), falls through to - // parent (code default true). - KeepHistory *bool `yaml:"keep_history,omitempty"` - Roles []string `yaml:"roles,omitempty"` Agents []AgentEntry `yaml:"agents,omitempty"` // AllowedRemoteResources holds the locally-set allowed remote @@ -1356,7 +1350,6 @@ type perRepoConfigMarshal struct { Tracker *TrackingConfig `yaml:"tracker,omitempty"` KillSwitch *bool `yaml:"kill_switch,omitempty"` Runtime string `yaml:"runtime,omitempty"` - KeepHistory *bool `yaml:"keep_history,omitempty"` Roles *[]string `yaml:"roles,omitempty"` Agents []AgentEntry `yaml:"agents,omitempty"` AllowedRemoteResources *[]string `yaml:"allowed_remote_resources,omitempty"` @@ -1386,7 +1379,6 @@ func (c *perRepoConfig) MarshalYAML() (interface{}, error) { Tracker: c.Tracker, KillSwitch: c.KillSwitch, Runtime: c.Runtime, - KeepHistory: c.KeepHistory, Agents: c.Agents, StatusNotifications: c.Notifications, MintURL: c.MintURL, diff --git a/internal/config/defaults.go b/internal/config/defaults.go index d478215f2c..e6792557aa 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -98,12 +98,6 @@ func (d *perRepoDefaults) ConfigInferenceWIFAudience() string { return "" } // impersonate (empty — direct federated identity, no impersonation). func (d *perRepoDefaults) ConfigInferenceServiceAccount() string { return "" } -// ConfigKeepHistory returns the default keep-history state (true). -// Deprecated: the setting has no effect — sticky comments were removed -// (#9334); every result is a new comment. Kept until a cleanup removes -// the field. -func (d *perRepoDefaults) ConfigKeepHistory() bool { return true } - // ConfigInferenceOpenAI returns the default OpenAI WIF identifiers (none — // set by `fullsend github setup --openai-*` or the FULLSEND_OPENAI_* // runner variables). diff --git a/internal/config/defaults_test.go b/internal/config/defaults_test.go index d8c89d1d39..fa78f760d3 100644 --- a/internal/config/defaults_test.go +++ b/internal/config/defaults_test.go @@ -22,7 +22,6 @@ func TestPerRepoDefaults_CodeDefaults(t *testing.T) { assert.Equal(t, "1", d.ConfigVersion()) assert.Equal(t, "claude", d.ConfigRuntime()) assert.False(t, d.IsKillSwitchActive()) - assert.True(t, d.ConfigKeepHistory()) assert.Equal(t, PerRepoDefaultRoles(), d.ConfigRoles()) assert.Nil(t, d.AgentEntries()) assert.Equal(t, DefaultAllowedRemoteResources(), d.AllowedResources()) @@ -48,7 +47,6 @@ func TestPerRepoConfig_EmptyConfigResolvesDefaults(t *testing.T) { assert.Equal(t, "1", cfg.ConfigVersion()) assert.Equal(t, "claude", cfg.ConfigRuntime()) assert.False(t, cfg.IsKillSwitchActive()) - assert.True(t, cfg.ConfigKeepHistory()) assert.Equal(t, PerRepoDefaultRoles(), cfg.ConfigRoles()) assert.Nil(t, cfg.AgentEntries()) assert.Equal(t, DefaultAllowedRemoteResources(), cfg.AllowedResources()) @@ -152,39 +150,6 @@ func TestPerRepoConfig_KillSwitch_PointerSemantics(t *testing.T) { }) } -// --- KeepHistory *bool pointer semantics --- - -func TestPerRepoConfig_KeepHistory_PointerSemantics(t *testing.T) { - t.Run("nil falls through to parent default true", func(t *testing.T) { - cfg := &perRepoConfig{parent: &perRepoDefaults{}} - assert.True(t, cfg.ConfigKeepHistory()) - }) - - t.Run("explicit false does not fall through", func(t *testing.T) { - // Parent has keep_history=true (default), overlay explicitly sets false. - f := false - overlay := &perRepoConfig{ - KeepHistory: &f, - parent: &perRepoDefaults{}, - } - assert.False(t, overlay.ConfigKeepHistory()) - }) - - t.Run("explicit true overrides parent false", func(t *testing.T) { - f := false - parentCfg := &perRepoConfig{ - KeepHistory: &f, - parent: &perRepoDefaults{}, - } - tr := true - overlay := &perRepoConfig{ - KeepHistory: &tr, - parent: parentCfg, - } - assert.True(t, overlay.ConfigKeepHistory()) - }) -} - // --- Agents keyed merge by DerivedName --- func TestPerRepoConfig_AgentsMerge(t *testing.T) { @@ -559,19 +524,6 @@ func TestPerRepoConfig_MarshalExplicitFalseKillSwitch(t *testing.T) { assert.Contains(t, string(data), "kill_switch: false") } -func TestPerRepoConfig_MarshalExplicitFalseKeepHistory(t *testing.T) { - f := false - cfg := &perRepoConfig{ - Version: "1", - KeepHistory: &f, - parent: &perRepoDefaults{}, - } - data, err := cfg.Marshal() - require.NoError(t, err) - // Explicit false should appear in output (distinguishable from unset). - assert.Contains(t, string(data), "keep_history: false") -} - func TestPerRepoConfig_MarshalDenyAll(t *testing.T) { cfg := &perRepoConfig{ Version: "1", @@ -829,46 +781,3 @@ roles: assert.Nil(t, prc.KillSwitch) }) } - -// --- KeepHistory YAML round-trip --- - -func TestPerRepoConfig_KeepHistory_YAMLRoundTrip(t *testing.T) { - t.Run("keep_history false round-trips", func(t *testing.T) { - yamlData := `version: "1" -keep_history: false -roles: - - triage -` - cfg, err := ParsePerRepoConfig([]byte(yamlData)) - require.NoError(t, err) - assert.False(t, cfg.ConfigKeepHistory()) - // Verify it was explicitly set (not inherited). - prc := cfg.(*perRepoConfig) - require.NotNil(t, prc.KeepHistory) - assert.False(t, *prc.KeepHistory) - }) - - t.Run("keep_history true round-trips", func(t *testing.T) { - yamlData := `version: "1" -keep_history: true -roles: - - triage -` - cfg, err := ParsePerRepoConfig([]byte(yamlData)) - require.NoError(t, err) - assert.True(t, cfg.ConfigKeepHistory()) - }) - - t.Run("keep_history omitted falls through to default true", func(t *testing.T) { - yamlData := `version: "1" -roles: - - triage -` - cfg, err := ParsePerRepoConfig([]byte(yamlData)) - require.NoError(t, err) - assert.True(t, cfg.ConfigKeepHistory()) - // Verify it was not set. - prc := cfg.(*perRepoConfig) - assert.Nil(t, prc.KeepHistory) - }) -} diff --git a/internal/config/effective.go b/internal/config/effective.go index 95eb42491e..b3ea403673 100644 --- a/internal/config/effective.go +++ b/internal/config/effective.go @@ -22,9 +22,8 @@ func EffectiveYAML(r PerRepoConfigReader) ([]byte, error) { return nil, fmt.Errorf("configuration is required") } out := map[string]any{ - "kill_switch": r.IsKillSwitchActive(), - "keep_history": r.ConfigKeepHistory(), - "roles": r.ConfigRoles(), + "kill_switch": r.IsKillSwitchActive(), + "roles": r.ConfigRoles(), } for key, val := range map[string]string{ "version": r.ConfigVersion(), diff --git a/internal/config/effective_test.go b/internal/config/effective_test.go index f991f0e7cf..05ef0e97ee 100644 --- a/internal/config/effective_test.go +++ b/internal/config/effective_test.go @@ -13,7 +13,6 @@ func TestEffectiveYAML_LayersOverlayBaseAndDefaults(t *testing.T) { "agents:\n - name: review\n harness: { timeout_minutes: 90 }\n - name: code\n effort: high\n")) require.NoError(t, err) base := []byte(`version: "1" -keep_history: false mint_url: https://mint.example.com roles: [triage] runtime: claude @@ -51,7 +50,6 @@ agents: assert.Equal(t, true, got["kill_switch"], "overlay wins") assert.Equal(t, "pi", got["runtime"], "overlay wins over the base") - assert.Equal(t, false, got["keep_history"], "base value") assert.Equal(t, "https://mint.example.com", got["mint_url"]) assert.Equal(t, []any{"triage"}, got["roles"]) assert.Contains(t, got["allowed_remote_resources"], "https://example.com/", "base prefixes merge with the code defaults") @@ -190,7 +188,6 @@ func TestEffectiveYAML_CodeDefaultsAndNil(t *testing.T) { var got map[string]any require.NoError(t, yaml.Unmarshal(data, &got)) assert.Equal(t, false, got["kill_switch"]) - assert.Equal(t, true, got["keep_history"]) assert.NotContains(t, got, "agents") assert.NotContains(t, got, "authorization") diff --git a/internal/config/interfaces.go b/internal/config/interfaces.go index b29fae1c79..504f5f8a49 100644 --- a/internal/config/interfaces.go +++ b/internal/config/interfaces.go @@ -77,7 +77,6 @@ type PerRepoConfigReader interface { // "the file resolves to the default" (e.g. fullsend run's // warn-and-skip-minting fallback) use this instead of ConfigMintURL. ConfigMintURLFromFile() string - ConfigKeepHistory() bool ConfigInferenceProvider() string ConfigInferenceProject() string ConfigInferenceRegion() string @@ -146,7 +145,6 @@ type PerRepoConfigWriter interface { SetRoles([]string) SetRuntime(string) SetMintURL(string) - SetKeepHistory(bool) SetInferenceProvider(string) SetInferenceProject(string) SetInferenceRegion(string) @@ -471,21 +469,6 @@ func (c *perRepoConfig) ConfigForge() string { return "" } -// ConfigKeepHistory reports the keep_history setting, which is deprecated -// and has no effect on posting: sticky comments were removed (#9334); -// every result is a new comment. The field stays until a cleanup removes -// it. KeepHistory is a *bool: nil falls through to parent, non-nil is the -// local decision. Code default is true. -func (c *perRepoConfig) ConfigKeepHistory() bool { - if c.KeepHistory != nil { - return *c.KeepHistory - } - if c.parent != nil { - return c.parent.ConfigKeepHistory() - } - return true -} - // ConfigTracker returns the provider selected by the tracker mapping // ("github", "gitlab", "jira"), or "" when none is selected. It is the // default for `fullsend issues` commands' --tracker flag when that flag @@ -703,11 +686,6 @@ func (c *perRepoConfig) SetRoles(roles []string) { c.Roles = roles } // SetRuntime replaces the configured agent runtime. func (c *perRepoConfig) SetRuntime(runtime string) { c.Runtime = runtime } -// SetKeepHistory stores the deprecated keep_history setting, which has -// no effect on posting (see ConfigKeepHistory). Stores a *bool so that -// an explicit false is distinguishable from unset (nil) across layers. -func (c *perRepoConfig) SetKeepHistory(v bool) { c.KeepHistory = &v } - // SetMintURL sets the token mint URL. func (c *perRepoConfig) SetMintURL(mintURL string) { c.MintURL = mintURL } diff --git a/internal/config/interfaces_test.go b/internal/config/interfaces_test.go index 838865a3b2..53e96125ae 100644 --- a/internal/config/interfaces_test.go +++ b/internal/config/interfaces_test.go @@ -119,15 +119,6 @@ func TestPerRepoConfig_IsKillSwitchActive(t *testing.T) { assert.False(t, cfg.IsKillSwitchActive()) } -func TestPerRepoConfig_ConfigKeepHistory(t *testing.T) { - f := false - cfg := &perRepoConfig{KeepHistory: &f} - assert.False(t, cfg.ConfigKeepHistory()) - tr := true - cfg.KeepHistory = &tr - assert.True(t, cfg.ConfigKeepHistory()) -} - func TestPerRepoConfig_AllowedResources(t *testing.T) { resources := []string{"https://example.com/"} cfg := &perRepoConfig{AllowedRemoteResources: resources} @@ -195,16 +186,6 @@ func TestPerRepoConfig_SetKillSwitch(t *testing.T) { assert.False(t, *cfg.KillSwitch) } -func TestPerRepoConfig_SetKeepHistory(t *testing.T) { - cfg := &perRepoConfig{} - cfg.SetKeepHistory(false) - require.NotNil(t, cfg.KeepHistory) - assert.False(t, *cfg.KeepHistory) - cfg.SetKeepHistory(true) - require.NotNil(t, cfg.KeepHistory) - assert.True(t, *cfg.KeepHistory) -} - func TestPerRepoConfig_SetAgents(t *testing.T) { cfg := &perRepoConfig{} agents := []AgentEntry{{Source: "harness/code.yaml"}} diff --git a/internal/config/issue_targets.go b/internal/config/issue_targets.go index f29156d6c8..d4668a5a33 100644 --- a/internal/config/issue_targets.go +++ b/internal/config/issue_targets.go @@ -24,6 +24,19 @@ const ( var errLegacyCreateIssues = errors.New("create_issues is no longer supported: move create_issues.allow_targets to tracker..allowed_targets " + "(tracker.github.allowed_targets.orgs/repos, tracker.gitlab.allowed_targets.groups/repos, or tracker.jira.allowed_targets.projects)") +// ManagedRemovedKeyError returns the dedicated migration error for a +// top-level key the managed configuration removed with a migration path +// (currently create_issues), or nil when the key has none. Managed-config +// decoding reports it instead of the generic unknown-field error, and the +// adoption proposal keeps such a key in the suggested block so the operator +// reads where the setting moved instead of a bare "no such setting". +func ManagedRemovedKeyError(key string) error { + if key == "create_issues" { + return errLegacyCreateIssues + } + return nil +} + // errLegacyScalarTracker reports a scalar tracker value (tracker: jira), // which the provider-discriminated tracker mapping replaced (#9074). func errLegacyScalarTracker(value string) error { diff --git a/internal/config/keep_history_removal_acceptance_test.go b/internal/config/keep_history_removal_acceptance_test.go new file mode 100644 index 0000000000..df68ee32e0 --- /dev/null +++ b/internal/config/keep_history_removal_acceptance_test.go @@ -0,0 +1,42 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" +) + +// TestLoadConfig_KeepHistoryKeyToleratedAfterRemoval pins #9517's third +// criterion for a repository's own config.yaml: the keep_history setting +// no longer exists, and a config.yaml that still sets the key keeps +// loading — the layered loader ignores keys it does not know, so +// upgrading does not break an existing file. The removal is stated in the +// changelog; managed configuration overlays are held to the stricter +// contract pinned below. +func TestLoadConfig_KeepHistoryKeyToleratedAfterRemoval(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), + []byte("version: \"1\"\nkeep_history: false\n"), 0o644)) + + reader, err := LoadConfig(dir, LoadOpts{}) + require.NoError(t, err, + "a config.yaml that still sets the removed keep_history key must load; the key is ignored") + assert.Equal(t, "1", reader.ConfigVersion(), "the rest of the file still applies") +} + +// TestManagedConfig_KeepHistoryKeyRejectedAfterRemoval pins the managed +// side of #9517's third criterion: managed configuration layers are +// strictly validated against the per-repo config's fields, so an overlay +// that still sets the removed keep_history key is rejected with the +// unknown-field error naming it, instead of silently drifting apart from +// what fullsend writes back. +func TestManagedConfig_KeepHistoryKeyRejectedAfterRemoval(t *testing.T) { + var overlay ManagedConfig + err := yaml.Unmarshal([]byte("keep_history: false\n"), &overlay) + require.Error(t, err, "a managed overlay that still sets keep_history must be rejected") + assert.Contains(t, err.Error(), `unknown field "keep_history"`) +} diff --git a/internal/config/managed.go b/internal/config/managed.go index b7c6b0d215..ee07e39d70 100644 --- a/internal/config/managed.go +++ b/internal/config/managed.go @@ -215,11 +215,11 @@ func decodeManagedConfig(n *yaml.Node) (*perRepoConfig, error) { for i := 0; i+1 < len(node.Content); i += 2 { keyNode := node.Content[i] key := keyNode.Value - if key == "create_issues" { + if mig := ManagedRemovedKeyError(key); mig != nil { // The removed key gets an actionable migration message // instead of the generic unknown-field error. fieldErrs = append(fieldErrs, managedFieldError(keyNode, - fmt.Sprintf("unknown field %q: %s", key, errLegacyCreateIssues))) + fmt.Sprintf("unknown field %q: %s", key, mig))) } else if !known[key] { fieldErrs = append(fieldErrs, managedFieldError(keyNode, fmt.Sprintf("unknown field %q", key))) @@ -404,10 +404,6 @@ func clonePerRepo(src *perRepoConfig) *perRepoConfig { v := *src.KillSwitch out.KillSwitch = &v } - if src.KeepHistory != nil { - v := *src.KeepHistory - out.KeepHistory = &v - } if src.Roles != nil { out.Roles = cloneStringSlice(src.Roles) } @@ -495,10 +491,6 @@ func applyManagedLayer(out, child *perRepoConfig) { if child.Runtime != "" { out.Runtime = child.Runtime } - if child.KeepHistory != nil { - v := *child.KeepHistory - out.KeepHistory = &v - } if child.Roles != nil { out.Roles = cloneStringSlice(child.Roles) } diff --git a/internal/config/managed_test.go b/internal/config/managed_test.go index f9f060cebd..eeabfc12b3 100644 --- a/internal/config/managed_test.go +++ b/internal/config/managed_test.go @@ -144,7 +144,6 @@ func TestManagedConfig_AcceptsRuntimeAndAllowedRemoteResources(t *testing.T) { func TestManagedConfig_ExplicitFalseAndEmptySurviveMarshal(t *testing.T) { input := ` kill_switch: false -keep_history: false roles: [] ` var o ManagedConfig @@ -152,7 +151,6 @@ roles: [] w := o.Writer() require.NotNil(t, w) assert.False(t, w.IsKillSwitchActive()) - assert.False(t, w.ConfigKeepHistory()) assert.NotNil(t, w.ConfigRoles()) assert.Empty(t, w.ConfigRoles()) @@ -160,7 +158,6 @@ roles: [] require.NoError(t, err) text := string(body) assert.Contains(t, text, "kill_switch: false") - assert.Contains(t, text, "keep_history: false") assert.Contains(t, text, "roles: []") } @@ -491,13 +488,12 @@ func TestMergeManaged_AllFieldsAndAgentClone(t *testing.T) { enabled := false sub := "sonnet" parent := &perRepoConfig{ - Version: "1", - Forge: "github", - Runtime: "claude", - MintURL: "https://parent.example.com", - KillSwitch: boolPtr(true), - KeepHistory: boolPtr(true), - Roles: []string{"triage"}, + Version: "1", + Forge: "github", + Runtime: "claude", + MintURL: "https://parent.example.com", + KillSwitch: boolPtr(true), + Roles: []string{"triage"}, Agents: []AgentEntry{{ Name: "code", Source: "harness/code.yaml", @@ -526,13 +522,12 @@ func TestMergeManaged_AllFieldsAndAgentClone(t *testing.T) { parent: &perRepoDefaults{}, } child := &perRepoConfig{ - Version: "1", - Forge: "gitlab", - Runtime: "pi", - MintURL: "https://child.example.com", - KillSwitch: boolPtr(false), - KeepHistory: boolPtr(false), - Roles: []string{"review"}, + Version: "1", + Forge: "gitlab", + Runtime: "pi", + MintURL: "https://child.example.com", + KillSwitch: boolPtr(false), + Roles: []string{"review"}, Agents: []AgentEntry{{ Name: "code", Enabled: &enabled, @@ -563,7 +558,6 @@ func TestMergeManaged_AllFieldsAndAgentClone(t *testing.T) { assert.Equal(t, "pi", merged.ConfigRuntime()) assert.Equal(t, "https://child.example.com", merged.ConfigMintURL()) assert.False(t, merged.IsKillSwitchActive()) - assert.False(t, merged.ConfigKeepHistory()) assert.Equal(t, []string{"review"}, merged.ConfigRoles()) body, err := merged.Marshal() require.NoError(t, err) @@ -627,7 +621,7 @@ func TestManagedConfig_MarshalOmitsUnset(t *testing.T) { func TestManagedConfig_WithIssueTracking(t *testing.T) { var base ManagedConfig - require.NoError(t, yaml.Unmarshal([]byte("keep_history: false\n"), &base)) + require.NoError(t, yaml.Unmarshal([]byte("kill_switch: true\n"), &base)) tracking := &TrackingConfig{GitHub: &GitHubTrackingConfig{AllowedTargets: GitHubAllowedTargets{Repos: []string{"fullsend-ai/fullsend"}}}} withIssues := base.WithIssueTracking(tracking) @@ -635,7 +629,7 @@ func TestManagedConfig_WithIssueTracking(t *testing.T) { got := withIssues.Writer().IssueTracking() require.NotNil(t, got) assert.Equal(t, []string{"fullsend-ai/fullsend"}, got.GitHub.AllowedTargets.Repos) - assert.False(t, withIssues.Writer().ConfigKeepHistory(), "existing values are kept") + assert.True(t, withIssues.Writer().IsKillSwitchActive(), "existing values are kept") assert.Nil(t, base.Writer().IssueTracking(), "the receiver is not modified") tracking.GitHub.AllowedTargets.Repos[0] = "mutated/repo" assert.Equal(t, []string{"fullsend-ai/fullsend"}, got.GitHub.AllowedTargets.Repos, "the argument is copied") diff --git a/internal/config/trace_context_test.go b/internal/config/trace_context_test.go index dea969adfe..e8d922dcc6 100644 --- a/internal/config/trace_context_test.go +++ b/internal/config/trace_context_test.go @@ -434,12 +434,12 @@ func TestManagedConfig_CloneKeepsTraceContext(t *testing.T) { func TestManagedConfig_WithTraceContext(t *testing.T) { t.Run("replaces the block with a copy", func(t *testing.T) { var recv ManagedConfig - require.NoError(t, yaml.Unmarshal(traceContextDoc(t, "keep_history: false\n", otherTraceContext()), &recv)) + require.NoError(t, yaml.Unmarshal(traceContextDoc(t, "kill_switch: true\n", otherTraceContext()), &recv)) arg := validTraceContext() with := recv.WithTraceContext(arg) require.True(t, with.IsSet()) assert.Equal(t, validTraceContext(), localTraceBlock(with.Writer()), "the new block replaces the old one") - assert.False(t, with.Writer().ConfigKeepHistory(), "existing values are kept") + assert.True(t, with.Writer().IsKillSwitchActive(), "existing values are kept") assert.Equal(t, otherTraceContext(), localTraceBlock(recv.Writer()), "the receiver is not modified") mutateTraceBlock(arg) assert.Equal(t, validTraceContext(), localTraceBlock(with.Writer()), "the argument is copied") @@ -460,11 +460,11 @@ func TestManagedConfig_WithTraceContext(t *testing.T) { t.Run("nil removes the block", func(t *testing.T) { var recv ManagedConfig - require.NoError(t, yaml.Unmarshal(traceContextDoc(t, "keep_history: false\n", validTraceContext()), &recv)) + require.NoError(t, yaml.Unmarshal(traceContextDoc(t, "kill_switch: true\n", validTraceContext()), &recv)) removed := recv.WithTraceContext(nil) require.True(t, removed.IsSet()) assert.Nil(t, localTraceBlock(removed.Writer()), "nil removes the block") - assert.False(t, removed.Writer().ConfigKeepHistory(), "existing values are kept") + assert.True(t, removed.Writer().IsKillSwitchActive(), "existing values are kept") assert.Equal(t, validTraceContext(), localTraceBlock(recv.Writer()), "the receiver is not modified") }) } diff --git a/internal/forge/jira/adf.go b/internal/forge/jira/adf.go index ed56917f77..4236075b7c 100644 --- a/internal/forge/jira/adf.go +++ b/internal/forge/jira/adf.go @@ -117,8 +117,10 @@ func adfBlockContent(parent ast.Node, source []byte, depth int, restricted bool) // handles both single-block (no blank lines inside the // markup) and multi-block (blank lines split the
// opening, body, and closing across several AST siblings) - // forms, since sticky.BuildUpdatedBody produces the latter - // while hand-written Markdown typically produces the former. + // forms, since comments posted by pre-#9334 CLIs — which + // folded prior results into
blocks — produce the + // latter while hand-written Markdown typically produces the + // former. if !restricted { if expand, next := tryDetailsExpand(c, source, depth); expand != nil { content = append(content, expand) @@ -144,9 +146,12 @@ var summaryInnerTagPattern = regexp.MustCompile(`<[^>]*>`) // stickyHistorySentinelPattern matches sticky history sentinel comments // on their own line, for stripping from
body content before -// re-parsing as Markdown. These sentinels are metadata used by -// sticky.BuildUpdatedBody for history reconstruction and must not -// become visible text inside the rendered ADF expansion. +// re-parsing as Markdown. Pre-#9334 CLIs wrapped the history they folded +// into
blocks with these sentinels; comments those CLIs posted +// still sit unedited on old pull requests, and the sentinels must not +// become visible text inside the rendered ADF expansion. Kept as a +// read-side shim until such comments have aged out of the threads Jira +// quotes (#9517 removed the machinery that wrote them). var stickyHistorySentinelPattern = regexp.MustCompile(`(?m)^\s*\s*$`) // tryDetailsExpand checks whether c is an HTML block opening a @@ -159,10 +164,11 @@ var stickyHistorySentinelPattern = regexp.MustCompile(`(?m)^\s* or -// ). +// ). Read-side shim: the machinery that wrote +// these sentinels is gone (#9517), but comments posted by pre-#9334 CLIs +// still carry them, so they are recognized and skipped here until those +// comments have aged out of the threads Jira quotes. func isStickyHistorySentinel(raw string) bool { trimmed := strings.TrimSpace(raw) return trimmed == "" || diff --git a/internal/forge/jira/adf_test.go b/internal/forge/jira/adf_test.go index 2d62f58d9f..275da00cc9 100644 --- a/internal/forge/jira/adf_test.go +++ b/internal/forge/jira/adf_test.go @@ -2490,10 +2490,10 @@ func TestMarkdownToADF_DetailsToExpandNode(t *testing.T) { func TestMarkdownToADF_DetailsWithStickySentinelsStripped(t *testing.T) { // Sticky history sentinels () are - // parser metadata used by sticky.BuildUpdatedBody for history - // reconstruction. They must be consumed during the
→ - // expand conversion and must not appear as visible text inside the - // rendered expansion. + // parser metadata carried by comments posted by pre-#9334 CLIs that + // folded prior results into
blocks. They must be consumed + // during the
→ expand conversion and must not appear as + // visible text inside the rendered expansion. input := "text\n\n
Prior run\n" + "\n- item one\n- item two\n" + "\n
\n\nmore text" @@ -2532,7 +2532,7 @@ func TestMarkdownToADF_DetailsWithStickySentinelsStripped(t *testing.T) { } func TestMarkdownToADF_DetailsMultiBlock(t *testing.T) { - // When sticky.BuildUpdatedBody produces
blocks with blank + // When pre-#9334 CLIs produced
blocks with blank // lines inside (between and the sentinel, and between the // sentinel and
), goldmark splits the markup across // multiple AST siblings. tryDetailsExpand must collect them all into diff --git a/internal/repos/config_layers_test.go b/internal/repos/config_layers_test.go index 725181db24..be1068f69d 100644 --- a/internal/repos/config_layers_test.go +++ b/internal/repos/config_layers_test.go @@ -206,7 +206,7 @@ func TestPreflightManagedConfig_ReportsBothLayersAndAdoptionDetail(t *testing.T) ctx := context.Background() m := newConvergeManifest("acme/api") fc := newFakeClientForBatch("acme/api") - fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("keep_history: true\n# note\n") + fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("kill_switch: true\n# note\n") fc.FileContents["acme/api/"+preset.BasePath] = []byte("version: \"1\"\n") adoption, err := PreflightManagedConfig(ctx, m, newTestClientFactory(fc), nil) @@ -218,7 +218,7 @@ func TestPreflightManagedConfig_ReportsBothLayersAndAdoptionDetail(t *testing.T) assert.Contains(t, msg, "proposed repos.yaml entry", "the adoption proposal is part of the install failure") assert.Contains(t, msg, "file settings difference") assert.Contains(t, msg, "effective layered configuration change") - assert.Contains(t, msg, "keep_history") + assert.Contains(t, msg, "kill_switch") } func TestPreflightManagedConfig_MalformedLayers(t *testing.T) { @@ -334,7 +334,7 @@ func TestStatus_BothLayersReportedBeforeInstall(t *testing.T) { t.Run(f+"/overlay adoption and zero-byte undeclared base together", func(t *testing.T) { m, fc := build() - fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("keep_history: true\n") + fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("kill_switch: true\n") fc.FileContents["acme/api/"+preset.BasePath] = []byte{} result, err := Status(ctx, m, newTestClientFactory(fc), 1, []string{"acme/api"}) require.NoError(t, err) diff --git a/internal/repos/config_platform_layers_test.go b/internal/repos/config_platform_layers_test.go index 91bf99af7f..6b67eeb00b 100644 --- a/internal/repos/config_platform_layers_test.go +++ b/internal/repos/config_platform_layers_test.go @@ -57,7 +57,8 @@ github: gitlab: url: https://gitlab.example.com config: - keep_history: false + roles: + - review allowed_remote_resources: - https://gitlab-layer.example.com/ repos: @@ -99,7 +100,7 @@ func TestResolveConfig_PlatformConfigPrecedence(t *testing.T) { assert.Equal(t, "https://github-layer.example.com/", arr[0], "list: the more specific layer comes first") assert.Contains(t, arr, "https://defaults.example.com/", "allowed_remote_resources keeps its union merge rule") assert.NotContains(t, arr, "https://gitlab-layer.example.com/", "gitlab.config never affects GitHub repos") - assert.True(t, w.ConfigKeepHistory(), "gitlab.config keep_history does not leak into GitHub repos") + assert.Equal(t, []string{"triage"}, w.ConfigRoles(), "gitlab.config roles do not leak into GitHub repos") }) t.Run("github repo config wins over every layer", func(t *testing.T) { @@ -135,7 +136,7 @@ func TestResolveConfig_PlatformConfigPrecedence(t *testing.T) { w := rc.Managed assert.Equal(t, "pi", rc.Runtime, "github.config runtime never affects GitLab repos") assert.Equal(t, "pi", w.ConfigRuntime()) - assert.False(t, w.ConfigKeepHistory()) + assert.Equal(t, []string{"review"}, w.ConfigRoles()) assert.Equal(t, "fleet-proj", w.ConfigInferenceProject(), "github.config inference never affects GitLab repos") assert.NotContains(t, w.ConfigModelAliases(), "opus") arr := w.AllowedResources() @@ -161,7 +162,7 @@ func TestRenderManagedConfig_PlatformConfigSparse(t *testing.T) { require.True(t, ok) text := string(body) assert.Contains(t, text, "runtime: pi") - assert.Contains(t, text, "keep_history: false") + assert.Contains(t, text, "- review") assert.Contains(t, text, "https://gitlab-layer.example.com/") assert.Contains(t, text, "https://defaults.example.com/") assert.NotContains(t, text, "codex", "the other forge's config is not rendered") @@ -191,12 +192,11 @@ func TestRenderManagedConfig_PlatformConfigSparse(t *testing.T) { func TestLayeredConfig_PlatformConfigAbovePreset(t *testing.T) { m := loadLayeredPrecedenceManifest(t) - base := []byte("runtime: dummy\nkeep_history: false\nmint_url: https://preset-mint.example.com\n") + base := []byte("runtime: dummy\nmint_url: https://preset-mint.example.com\n") effective, err := m.LayeredConfig(ForgeGitHub, m.GitHub.Repos[0], base) require.NoError(t, err) assert.Equal(t, "codex", effective.ConfigRuntime(), "github.config beats the preset") - assert.False(t, effective.ConfigKeepHistory(), "omitted in every manifest layer: preset value applies") assert.Equal(t, "https://preset-mint.example.com", effective.ConfigMintURL()) bare := &Manifest{Version: 1, GitHub: &PlatformConfig{Repos: []RepoEntry{{Name: "acme/bare"}}}} diff --git a/internal/repos/managed_config_adoption.go b/internal/repos/managed_config_adoption.go index 61d4a8616f..32e62d345b 100644 --- a/internal/repos/managed_config_adoption.go +++ b/internal/repos/managed_config_adoption.go @@ -3,6 +3,7 @@ package repos import ( "bytes" "fmt" + "strconv" "strings" "github.com/fullsend-ai/fullsend/internal/config" @@ -161,6 +162,114 @@ func nodeHasComments(n *yaml.Node) bool { return false } +// manifestHoldsKey reports whether the managed configuration knows a +// top-level setting by this name, whatever it would say about the value: +// the schema's yaml tags are the source of truth (the same tags +// decodeManagedConfig's unknown-field error is derived from), so a key an +// older configuration shipped and a newer one removed is dropped from the +// proposal (named in a note) instead of suggesting a block the managed +// validation rejects, while a live setting whose value the strict decode +// rejects is kept — the combined-block note reports the actual error — +// and the settings difference keeps pointing at the base layer or code +// default. A key with a dedicated migration error (config. +// ManagedRemovedKeyError, currently create_issues) is exempt from the drop: +// the pair stays in the proposed block so the combined-block probe reports +// the migration path, and the settings difference says where the setting +// moved instead of a bare "no longer a setting". +func manifestHoldsKey(key *yaml.Node) bool { + _, ok := yamlField(config.ManagedConfigSchema(), key.Value) + return ok +} + +// settingPair is one top-level key/value candidate of the proposed entry. +type settingPair struct { + key *yaml.Node + val *yaml.Node +} + +// flattenedPairs lists the top-level pairs of the existing file with `<<` +// merge keys resolved to the settings they merge in: a merge key is YAML +// plumbing, not a setting name, and a pair carried into the proposed block +// as-is would fail the managed validator's unknown-field check. Explicit +// keys win over merged ones, and the first merge to name a key wins, per +// the YAML merge-key rules; every alias is expanded first (a relocated +// alias could otherwise precede the anchor it names). Each flattened pair +// then goes through the same drop filter and combined-block probe as an +// explicit one, so a merged setting the manifest no longer holds is +// dropped with a note and one it holds is carried. +func flattenedPairs(current *yaml.Node) []settingPair { + var explicit, merged []settingPair + for i := 0; i+1 < len(current.Content); i += 2 { + key, val := expandYAMLAliases(current.Content[i]), expandYAMLAliases(current.Content[i+1]) + if key.ShortTag() == "!!merge" { + merged = append(merged, mergePairs(val)...) + continue + } + explicit = append(explicit, settingPair{key: key, val: val}) + } + pairs := explicit + seen := make(map[string]bool, len(explicit)+len(merged)) + for _, p := range explicit { + seen[p.key.Value] = true + } + for _, p := range merged { + if seen[p.key.Value] { + continue + } + seen[p.key.Value] = true + pairs = append(pairs, p) + } + return pairs +} + +// mergePairs lists the pairs a `<<` merge key's value merges in: a mapping, +// or a sequence of mappings with the first naming a key winning. A merge +// key nested inside those mappings is flattened the same way, with the +// same precedence, so a setting merged through an anchor that is itself +// merged is carried as a plain pair instead of being left behind a +// literal `<<` key the drop filter would misreport. A value of any other +// shape merges nothing (the file's own decode would have rejected it as +// a map-merge error). +func mergePairs(val *yaml.Node) []settingPair { + var out []settingPair + seen := make(map[string]bool) + add := func(m *yaml.Node) { + if m == nil || m.Kind != yaml.MappingNode { + return + } + var explicit, merged []settingPair + for i := 0; i+1 < len(m.Content); i += 2 { + key, v := m.Content[i], m.Content[i+1] + if key.ShortTag() == "!!merge" { + merged = append(merged, mergePairs(v)...) + continue + } + explicit = append(explicit, settingPair{key: key, val: v}) + } + for _, p := range explicit { + seen[p.key.Value] = true + out = append(out, p) + } + for _, p := range merged { + if seen[p.key.Value] { + continue + } + seen[p.key.Value] = true + out = append(out, p) + } + } + switch { + case val == nil: + case val.Kind == yaml.SequenceNode: + for _, item := range val.Content { + add(item) + } + default: + add(val) + } + return out +} + // proposedManifestEntry renders the repos.yaml entry that carries every // top-level setting of the existing file under the entry's config. func proposedManifestEntry(cfg ResolvedConfig, current *yaml.Node) string { @@ -168,21 +277,39 @@ func proposedManifestEntry(cfg ResolvedConfig, current *yaml.Node) string { entryCfg := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"} scalar := func(v string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: v} } entry.Content = append(entry.Content, scalar("name"), scalar(cfg.Owner+"/"+cfg.Repo)) - for i := 0; i+1 < len(current.Content); i += 2 { - // Aliases are expanded before settings move under config: a - // relocated alias could otherwise precede the anchor it names. - key, val := expandYAMLAliases(current.Content[i]), expandYAMLAliases(current.Content[i+1]) + var dropped []string + for _, pair := range flattenedPairs(current) { + key, val := pair.key, pair.val + // A key with a dedicated migration error is carried rather than + // dropped: the combined-block probe below then reports where the + // setting moved, which a plain dropped-key note would lose. + if !manifestHoldsKey(key) && config.ManagedRemovedKeyError(key.Value) == nil { + dropped = append(dropped, key.Value) + continue + } entryCfg.Content = append(entryCfg.Content, key, val) } - var note string + var notes []string + if len(dropped) > 0 { + // Each key is quoted: a YAML key can carry a decoded newline, and + // a raw one would end the comment early and add text that looks + // like an active repos.yaml entry to the advisory snippet. + quoted := make([]string, len(dropped)) + for i, k := range dropped { + quoted[i] = strconv.Quote(k) + } + notes = append(notes, fmt.Sprintf("# note: dropped (repos.yaml holds no such setting): %s", strings.Join(quoted, ", "))) + } if len(entryCfg.Content) > 0 { entry.Content = append(entry.Content, scalar("config"), entryCfg) - // The manifest config block is decoded strictly: a key it cannot - // hold must be resolved by the operator before adoption. + // Every pair was probed on its own and only removed keys were + // dropped, so a block that still fails carries a value the + // strict decode rejects and must be resolved by the operator + // before adoption. if body, err := yaml.Marshal(entryCfg); err == nil { var probe config.ManagedConfig if err := yaml.Unmarshal(body, &probe); err != nil { - note = fmt.Sprintf("\n# note: repos.yaml cannot hold these settings as written: %v", err) + notes = append(notes, fmt.Sprintf("# note: repos.yaml cannot hold these settings as written: %v", err)) } } } @@ -190,7 +317,11 @@ func proposedManifestEntry(cfg ResolvedConfig, current *yaml.Node) string { if err != nil { return fmt.Sprintf("(unrenderable: %v)", err) } - return strings.TrimRight(string(out), "\n") + note + suffix := "" + if len(notes) > 0 { + suffix = "\n" + strings.Join(notes, "\n") + } + return strings.TrimRight(string(out), "\n") + suffix } // effectiveMapping returns the effective settings of layer over base over @@ -229,18 +360,35 @@ func effectiveDifference(existing, desired, currentBase, proposedBase []byte) (s if err != nil { return "", fmt.Errorf("managed configuration: %w", err) } - return yamlDifference(current, next, " # removed: no longer set"), nil + return yamlDifference(current, next, func(_, _ *yaml.Node) string { return " # removed: no longer set" }), nil } // overlayDifference lists, in `- `/`+ ` lines, each top-level setting // that the existing file and the managed file render differently. A -// setting only the existing file declares is reported as removed (it then -// falls back to the base layer or code default). +// setting only the existing file declares is reported as removed with +// what that means (see removedSettingNote). func overlayDifference(current, next *yaml.Node) string { - return yamlDifference(current, next, " # removed: falls back to the base layer or code default") + return yamlDifference(current, next, removedSettingNote) +} + +// removedSettingNote says what a top-level setting only the existing file +// declares means once adoption drops it: a setting the manifest still +// holds falls back to the base layer or code default, while one it no +// longer holds has nothing to fall back to — the setting is gone, and the +// file should drop it. A key with a dedicated migration error says where +// the setting moved instead. A `<<` merge key is not a setting name; the +// settings it merges in are live and fall back like any other. +func removedSettingNote(key, _ *yaml.Node) string { + if key.ShortTag() != "!!merge" && !manifestHoldsKey(key) { + if mig := config.ManagedRemovedKeyError(key.Value); mig != nil { + return " # removed: no longer a setting: " + mig.Error() + } + return " # removed: no longer a setting" + } + return " # removed: falls back to the base layer or code default" } -func yamlDifference(current, next *yaml.Node, removedNote string) string { +func yamlDifference(current, next *yaml.Node, removedNote func(key, val *yaml.Node) string) string { render := func(key, val *yaml.Node) string { out, err := yaml.Marshal(&yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{key, val}}) if err != nil { @@ -272,7 +420,7 @@ func yamlDifference(current, next *yaml.Node, removedNote string) string { if w, ok := want[key]; ok { prefix("+", w) } else { - lines[len(lines)-1] += removedNote + lines[len(lines)-1] += removedNote(current.Content[i], current.Content[i+1]) } } for i := 0; i+1 < len(next.Content); i += 2 { diff --git a/internal/repos/managed_config_adoption_test.go b/internal/repos/managed_config_adoption_test.go index 631530b98f..26ff4cd60a 100644 --- a/internal/repos/managed_config_adoption_test.go +++ b/internal/repos/managed_config_adoption_test.go @@ -3,6 +3,7 @@ package repos import ( "context" "fmt" + "strconv" "strings" "testing" @@ -102,11 +103,161 @@ func TestAdoptionProposal_UnparseableAndNonMapping(t *testing.T) { assert.Contains(t, got, "rendering the managed") } -func TestAdoptionProposal_NotesSettingsTheManifestCannotHold(t *testing.T) { +func TestAdoptionProposalDropsSettingsTheManifestCannotHold(t *testing.T) { m := newConvergeManifest("acme/api") + m.Defaults.Config = mustManagedConfig(t, "kill_switch: true\n") got := adoptionProposal(adoptionCfg(), []byte("not_a_real_setting: true\n"), desiredFor(t, m), nil, nil) + assert.Contains(t, got, "not_a_real_setting", "the dropped setting is named in the note") + assert.Contains(t, got, "repos.yaml holds no such setting") + assert.NotContains(t, got, "config:", "nothing the manifest cannot hold is suggested under config") + + // A key an older configuration shipped and this one removed gets the + // same treatment, and the difference no longer points at a base layer + // or code default that no longer exists for it. + existing := []byte("keep_history: true\nkill_switch: false\n") + got = adoptionProposal(adoptionCfg(), existing, desiredFor(t, m), nil, nil) + current, err := overlayMapping(existing) + require.NoError(t, err) + entry := proposedManifestEntry(adoptionCfg(), current) + var parsed []map[string]any + require.NoError(t, yaml.Unmarshal([]byte(entry), &parsed)) + require.Len(t, parsed, 1) + cfg, hasConfig := parsed[0]["config"].(map[string]any) + require.True(t, hasConfig, "a live setting still moves under config") + assert.Equal(t, false, cfg["kill_switch"]) + assert.NotContains(t, cfg, "keep_history", "a setting repos.yaml no longer holds is not suggested") + assert.Contains(t, got, "keep_history", "the dropped key is named in the note") + assert.Contains(t, got, "- kill_switch: false") + assert.Contains(t, got, "+ kill_switch: true") + assert.Contains(t, got, "- keep_history: true # removed: no longer a setting") + + // A live setting whose value the strict decode rejects is not a + // removed setting: the proposal keeps the pair and the combined-block + // note reports the actual error instead of claiming the setting does + // not exist. + existing = []byte("tracker:\n github:\n allowed_targetz: []\n") + got = adoptionProposal(adoptionCfg(), existing, desiredFor(t, m), nil, nil) + assert.Contains(t, got, "config:", "a live setting is still suggested under config") + assert.Contains(t, got, "tracker:", "the live setting is not dropped from the entry") assert.Contains(t, got, "repos.yaml cannot hold these settings as written") - assert.Contains(t, got, "not_a_real_setting") + assert.Contains(t, got, "field allowed_targetz not found", "the note names the real problem") + assert.NotContains(t, got, "repos.yaml holds no such setting", "a live setting is not called removed") + assert.Contains(t, got, "# removed: falls back to the base layer or code default") + + // A live setting is judged by the schema, not by a decode error that + // happens to name it: an agent entry with an unknown field sharing a + // top-level key's name must not drop the whole agents setting. + existing = []byte("agents:\n - name: code\n roles: x\n") + got = adoptionProposal(adoptionCfg(), existing, desiredFor(t, m), nil, nil) + assert.Contains(t, got, "config:", "a live setting is still suggested under config") + assert.Contains(t, got, "agents:", "the live agents setting is not dropped from the entry") + assert.Contains(t, got, "repos.yaml cannot hold these settings as written") + assert.Contains(t, got, `agents[0]: unknown field "roles"`, "the note names the real problem") + assert.NotContains(t, got, "repos.yaml holds no such setting", "a live setting is not called removed") + + // A `<<` merge key is YAML plumbing, not a removed setting: its + // pairs are flattened into the proposed entry as plain top-level + // settings (so the proposal never carries a key the managed + // validator rejects as unknown), and the settings difference says + // its merged settings fall back, never that the key is no longer a + // setting. + existing = []byte("defaults: &d\n kill_switch: false\n<<: *d\n") + got = adoptionProposal(adoptionCfg(), existing, desiredFor(t, m), nil, nil) + assert.NotContains(t, got, `unknown field "<<"`, + "the merge key must not make the proposal fail managed validation") + current, err = overlayMapping(existing) + require.NoError(t, err) + entry = proposedManifestEntry(adoptionCfg(), current) + var mergedParse []map[string]any + require.NoError(t, yaml.Unmarshal([]byte(entry), &mergedParse)) + require.Len(t, mergedParse, 1) + merged, hasConfig := mergedParse[0]["config"].(map[string]any) + require.True(t, hasConfig, "a merge key's settings still move under config") + assert.Equal(t, false, merged["kill_switch"], "the merged setting is carried, not dropped with its anchor key") + assert.NotContains(t, merged, "<<", "the merge key itself is never carried into the entry") + assert.Contains(t, got, "# removed: falls back to the base layer or code default") + + // Explicit keys win over merged ones: the merge key cannot override + // a setting the file sets directly, and the first merge of a + // sequence to name a key wins over a later one. + existing = []byte("first: &f\n kill_switch: true\n roles: [triage]\nsecond: &s\n kill_switch: false\n<<: [*f, *s]\nkill_switch: false\n") + got = adoptionProposal(adoptionCfg(), existing, desiredFor(t, m), nil, nil) + assert.NotContains(t, got, `unknown field "<<"`) + current, err = overlayMapping(existing) + require.NoError(t, err) + entry = proposedManifestEntry(adoptionCfg(), current) + mergedParse = nil + require.NoError(t, yaml.Unmarshal([]byte(entry), &mergedParse)) + require.Len(t, mergedParse, 1) + merged, hasConfig = mergedParse[0]["config"].(map[string]any) + require.True(t, hasConfig, "the flattened settings still move under config") + assert.Equal(t, false, merged["kill_switch"], "an explicit key beats the merged ones") + assert.Equal(t, []any{"triage"}, merged["roles"], "a merged setting the file does not set is carried") + assert.NotContains(t, merged, "<<") + + // Without an explicit key, the first merge of the sequence to name + // a key wins. + existing = []byte("first: &f\n kill_switch: true\nsecond: &s\n kill_switch: false\n<<: [*f, *s]\n") + got = adoptionProposal(adoptionCfg(), existing, desiredFor(t, m), nil, nil) + assert.NotContains(t, got, `unknown field "<<"`) + current, err = overlayMapping(existing) + require.NoError(t, err) + entry = proposedManifestEntry(adoptionCfg(), current) + mergedParse = nil + require.NoError(t, yaml.Unmarshal([]byte(entry), &mergedParse)) + require.Len(t, mergedParse, 1) + merged, hasConfig = mergedParse[0]["config"].(map[string]any) + require.True(t, hasConfig) + assert.Equal(t, true, merged["kill_switch"], "the first merge to name a key wins") + assert.NotContains(t, merged, "<<") + + // A merge key nested inside an anchor that is itself merged is + // flattened too: go-yaml resolves the doubly-merged setting as live, + // so the proposal carries it as a plain top-level setting and never + // leaves a literal `<<` pair behind to be dropped with a bogus + // "no such setting" note. + existing = []byte("inner: &i\n kill_switch: false\nouter: &o\n <<: *i\n<<: *o\n") + got = adoptionProposal(adoptionCfg(), existing, desiredFor(t, m), nil, nil) + assert.NotContains(t, got, `unknown field "<<"`, + "a nested merge key must not make the proposal fail managed validation") + assert.NotContains(t, got, `repos.yaml holds no such setting: "<<"`, + "a nested merge key is plumbing, not a dropped setting") + current, err = overlayMapping(existing) + require.NoError(t, err) + entry = proposedManifestEntry(adoptionCfg(), current) + mergedParse = nil + require.NoError(t, yaml.Unmarshal([]byte(entry), &mergedParse)) + require.Len(t, mergedParse, 1) + merged, hasConfig = mergedParse[0]["config"].(map[string]any) + require.True(t, hasConfig, "the doubly-merged settings still move under config") + assert.Equal(t, false, merged["kill_switch"], "a setting merged through a nested merge key is carried") + assert.NotContains(t, merged, "<<") + + // A key with a dedicated migration error is not dropped like an + // unknown key: the proposal keeps the pair so the combined-block + // probe reports where the setting moved, and the settings difference + // carries the same migration text instead of a bare "no longer a + // setting" that loses the migration path. + existing = []byte("create_issues:\n allow_targets:\n orgs:\n - acme\nkill_switch: false\n") + got = adoptionProposal(adoptionCfg(), existing, desiredFor(t, m), nil, nil) + assert.Contains(t, got, "create_issues:", "a migration-error key stays in the proposed config") + assert.Contains(t, got, "create_issues is no longer supported: move create_issues.allow_targets to tracker..allowed_targets", + "the probe note carries the migration message") + assert.NotContains(t, got, "repos.yaml holds no such setting: create_issues", "a migration-error key is not called dropped") + assert.Contains(t, got, "# removed: no longer a setting: create_issues is no longer supported: move create_issues.allow_targets to tracker..allowed_targets", + "the settings difference says where the setting moved") + + // A dropped key is quoted: a YAML key can carry a decoded newline, + // and a raw one would end the comment early and add text that looks + // like an active repos.yaml entry to the advisory snippet. + existing = []byte("\"not-a-setting\\nroles: [triage]\": true\n") + got = adoptionProposal(adoptionCfg(), existing, desiredFor(t, m), nil, nil) + assert.Contains(t, got, "dropped (repos.yaml holds no such setting): "+strconv.Quote("not-a-setting\nroles: [triage]"), + "the dropped key is quoted with its newline escaped") + for _, line := range strings.Split(got, "\n") { + assert.NotEqual(t, "roles: [triage]", strings.TrimSpace(line), + "the injected text never becomes an active line") + } } func TestOverlayDifference_MultilineAndAdded(t *testing.T) { diff --git a/internal/repos/managed_config_allowlist_test.go b/internal/repos/managed_config_allowlist_test.go index 298c0f7edf..e33f6a5b6b 100644 --- a/internal/repos/managed_config_allowlist_test.go +++ b/internal/repos/managed_config_allowlist_test.go @@ -90,7 +90,7 @@ func TestPreflightManagedConfig_PresetLoadFailureIsReportedInGuidance(t *testing m := newConvergeManifest("acme/api") m.Defaults.ConfigBase.Source = filepath.Join(t.TempDir(), "missing-preset.yaml") fc := newFakeClientForBatch("acme/api") - fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("keep_history: true\n") + fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("kill_switch: true\n") adoption, err := PreflightManagedConfig(context.Background(), m, newTestClientFactory(fc), nil) require.NoError(t, err) diff --git a/internal/repos/managed_config_blocked_install_test.go b/internal/repos/managed_config_blocked_install_test.go index d3f17b199e..c970113c46 100644 --- a/internal/repos/managed_config_blocked_install_test.go +++ b/internal/repos/managed_config_blocked_install_test.go @@ -395,7 +395,7 @@ func TestStatus_MarkerlessOverlayErrorsAndGuidance(t *testing.T) { m := newConvergeManifest("acme/api") m.Defaults.ConfigBase = ConfigBase{Source: presetPath} fc := newFakeClientForBatch("acme/api") - fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("keep_history: false\n") + fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("kill_switch: true\n") fc.FileContents["acme/api/"+preset.BasePath] = []byte(wideningPreset) result, err := Status(ctx, m, newTestClientFactory(fc), 1, []string{"acme/api"}) require.NoError(t, err) @@ -410,18 +410,19 @@ func TestStatus_MarkerlessOverlayErrorsAndGuidance(t *testing.T) { require.NotEmpty(t, detail, "drifts: %+v", r.Drifts) assert.Contains(t, detail, "file settings difference") assert.Contains(t, detail, "effective layered configuration change") - // keep_history is dropped by adoption, so the layered default returns. - assert.Contains(t, detail, "- keep_history: false") - assert.Contains(t, detail, "+ keep_history: true") + // The overlay's kill_switch is dropped by adoption, so the + // layered default returns. + assert.Contains(t, detail, "- kill_switch: true") + assert.Contains(t, detail, "+ kill_switch: false") }) } func TestPreflightManagedConfig_AdoptionGuidanceUsesDeclaredPreset(t *testing.T) { - presetPath := writePresetFile(t, "version: \"1\"\nkeep_history: false\n") + presetPath := writePresetFile(t, "version: \"1\"\nkill_switch: false\n") m := newConvergeManifest("acme/api") m.Defaults.ConfigBase = ConfigBase{Source: presetPath} fc := newFakeClientForBatch("acme/api") - fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("keep_history: true\n") + fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("kill_switch: true\n") adoption, err := PreflightManagedConfig(context.Background(), m, newTestClientFactory(fc), nil) require.NoError(t, err) @@ -429,9 +430,9 @@ func TestPreflightManagedConfig_AdoptionGuidanceUsesDeclaredPreset(t *testing.T) msg := adoption[0].Guidance assert.Contains(t, msg, "effective layered configuration change") // The preset the install would add changes the effective value once the - // overlay stops declaring keep_history. - assert.Contains(t, msg, "- keep_history: true") - assert.Contains(t, msg, "+ keep_history: false") + // overlay stops declaring kill_switch. + assert.Contains(t, msg, "- kill_switch: true") + assert.Contains(t, msg, "+ kill_switch: false") } func TestAdoptionProposal_EffectiveChangeLayersBases(t *testing.T) { @@ -440,7 +441,7 @@ func TestAdoptionProposal_EffectiveChangeLayersBases(t *testing.T) { currentBase := []byte("version: \"1\"\nruntime: pi\n") proposedBase := []byte("version: \"1\"\nruntime: claude\n") - got := adoptionProposal(adoptionCfg(), []byte("keep_history: true\n"), desired, currentBase, proposedBase) + got := adoptionProposal(adoptionCfg(), []byte("kill_switch: true\n"), desired, currentBase, proposedBase) assert.Contains(t, got, "effective layered configuration change") assert.Contains(t, got, "- runtime: pi") assert.Contains(t, got, "+ runtime: claude") @@ -454,7 +455,7 @@ func TestAdoptionProposal_EffectiveChangeLayersBases(t *testing.T) { // An unparseable layer reports the comparison as unavailable instead of // dropping the section. - bad := adoptionProposal(adoptionCfg(), []byte("keep_history: true\n"), desired, []byte(": bad ["), nil) + bad := adoptionProposal(adoptionCfg(), []byte("kill_switch: true\n"), desired, []byte(": bad ["), nil) assert.Contains(t, bad, "effective layered configuration change") assert.Contains(t, bad, "unavailable") diff --git a/internal/repos/managed_config_test.go b/internal/repos/managed_config_test.go index e348cf24b3..0934a85226 100644 --- a/internal/repos/managed_config_test.go +++ b/internal/repos/managed_config_test.go @@ -488,7 +488,7 @@ github: repos: - name: acme/managed config: - keep_history: false + kill_switch: true - name: acme/unmanaged ` var m Manifest @@ -498,7 +498,7 @@ github: managed, ok := m.ResolveConfig("acme", "managed") require.True(t, ok) assert.True(t, managed.ConfigManaged) - assert.False(t, managed.Managed.ConfigKeepHistory()) + assert.True(t, managed.Managed.IsKillSwitchActive()) // Without a config key the repository is still managed, with an // empty sparse configuration (#8218). @@ -533,7 +533,6 @@ defaults: runtime: pi kill_switch: false roles: [] - keep_history: false github: repos: - name: acme/app @@ -549,7 +548,6 @@ github: require.True(t, ok) text := string(body) assert.Contains(t, text, "kill_switch: false") - assert.Contains(t, text, "keep_history: false") assert.Contains(t, text, "roles: []") assert.Contains(t, text, "runtime: pi") assert.Contains(t, text, "mint_url: https://mint.example.com") diff --git a/internal/repos/managed_config_writeback_test.go b/internal/repos/managed_config_writeback_test.go index 07fc5985c0..5a3c36832f 100644 --- a/internal/repos/managed_config_writeback_test.go +++ b/internal/repos/managed_config_writeback_test.go @@ -358,8 +358,8 @@ func TestPreflightManagedConfig(t *testing.T) { t.Run("markerless overlay needs adoption without a config key", func(t *testing.T) { m := newConvergeManifest("acme/api", "acme/web") fc := newFakeClientForBatch("acme/api", "acme/web") - fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("keep_history: true\n") - fc.FileContents["acme/web/"+preset.OverlayPath] = []byte("keep_history: false\n") + fc.FileContents["acme/api/"+preset.OverlayPath] = []byte("kill_switch: true\n") + fc.FileContents["acme/web/"+preset.OverlayPath] = []byte("kill_switch: false\n") adoption, err := PreflightManagedConfig(ctx, m, newTestClientFactory(fc), nil) require.NoError(t, err, "adoption is a per-repository failure, not a run-level one (#8511)") require.Len(t, adoption, 2, "every offending repo is reported") @@ -374,7 +374,7 @@ func TestPreflightManagedConfig(t *testing.T) { t.Run("one repo needs adoption and the other is clean", func(t *testing.T) { m := newConvergeManifest("acme/api", "acme/web") fc := newFakeClientForBatch("acme/api", "acme/web") - fc.FileContents["acme/web/"+preset.OverlayPath] = []byte("keep_history: false\n") + fc.FileContents["acme/web/"+preset.OverlayPath] = []byte("kill_switch: false\n") adoption, err := PreflightManagedConfig(ctx, m, newTestClientFactory(fc), nil) require.NoError(t, err) require.Len(t, adoption, 1) @@ -384,7 +384,7 @@ func TestPreflightManagedConfig(t *testing.T) { m := newConvergeManifest("acme/api", "acme/web") fc := newFakeClientForBatch("acme/api", "acme/web") fc.FileContents["acme/api/"+preset.BasePath] = []byte("version: \"1\"\n") - fc.FileContents["acme/web/"+preset.OverlayPath] = []byte("keep_history: false\n") + fc.FileContents["acme/web/"+preset.OverlayPath] = []byte("kill_switch: false\n") adoption, err := PreflightManagedConfig(ctx, m, newTestClientFactory(fc), nil) require.Error(t, err) assert.Nil(t, adoption) @@ -394,7 +394,7 @@ func TestPreflightManagedConfig(t *testing.T) { t.Run("filter limits the check", func(t *testing.T) { m := newConvergeManifest("acme/api", "acme/web") fc := newFakeClientForBatch("acme/api", "acme/web") - fc.FileContents["acme/web/"+preset.OverlayPath] = []byte("keep_history: false\n") + fc.FileContents["acme/web/"+preset.OverlayPath] = []byte("kill_switch: false\n") adoption, err := PreflightManagedConfig(ctx, m, newTestClientFactory(fc), []string{"acme/api"}) require.NoError(t, err) assert.Empty(t, adoption) @@ -408,7 +408,7 @@ func TestPreflightManagedConfig(t *testing.T) { t.Run("glob-covered filter name is checked", func(t *testing.T) { m := &Manifest{Version: 1, Defaults: testInferenceDefaults(), GitHub: &PlatformConfig{Repos: []RepoEntry{{Name: "acme/*"}}}} fc := newFakeClientForBatch() - fc.FileContents["acme/fork/"+preset.OverlayPath] = []byte("keep_history: false\n") + fc.FileContents["acme/fork/"+preset.OverlayPath] = []byte("kill_switch: false\n") adoption, err := PreflightManagedConfig(ctx, m, newTestClientFactory(fc), []string{"acme/fork"}) require.NoError(t, err) require.Len(t, adoption, 1, "a glob-covered repo ListOrgRepos omits is still checked") diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh index f49d623f66..50cc9cb966 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh @@ -742,6 +742,10 @@ if [ "${STAGE}" = "review" ]; then echo "WARNING: Prior review body too large (${BYTE_COUNT} bytes), skipping anchoring" : > "${PRIOR_REVIEW_FILE}" elif [ "${BYTE_COUNT}" -gt 1 ]; then + # Read-side shim: pre-#9334 CLIs folded prior results below the + # sentinel when they edited one + # comment in place; #9517 removed the writer, and this cut stays + # until those old review comments have aged out of open PRs. CURRENT_SECTION=$(awk '//{exit} {print}' "${PRIOR_REVIEW_FILE}") # sed -nE, not grep -oP — kept in lockstep with the GitHub # scaffold's pre-fetch-prior-review.sh (see its comment for why). diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh index 127b84475e..654bf04897 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review-test.sh @@ -297,9 +297,9 @@ run_test "html-comment-wrapped-sha" \ "5fcdfb95cc5d61819a8e1f5bf60db024cf88b5f0" \ 0 -# 13. Production re-review shape (generated by sticky.BuildUpdatedBody): -# wrapped current SHA plus a collapsed history entry carrying an older -# wrapped SHA — the current one wins. +# 13. Legacy re-review shape (posted by pre-#9334 CLIs that folded prior +# results): wrapped current SHA plus a collapsed history entry carrying +# an older wrapped SHA — the current one wins. BODY_HTML_COMMENT_SHA_HISTORY=" diff --git a/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review.sh b/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review.sh index fee9f8beaf..20581b843e 100644 --- a/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review.sh +++ b/internal/scaffold/fullsend-repo/scripts/pre-fetch-prior-review.sh @@ -109,7 +109,11 @@ fi echo "prior_review_file=${PRIOR_FILE}" >> "${GITHUB_OUTPUT:-/dev/null}" if [[ "${BYTE_COUNT}" -gt 1 ]]; then - # Extract SHA from current section only (before sticky history sentinels) + # Extract SHA from current section only (before sticky history sentinels). + # Read-side shim: pre-#9334 CLIs folded prior results below the + # sentinel when they edited one comment in + # place; #9517 removed the writer, and this cut stays until those old + # review comments have aged out of open PRs. CURRENT_SECTION="$(awk '//{exit} {print}' "${PRIOR_FILE}")" # sed -nE, not grep -oP: BSD grep (macOS) has no -P, so the PCRE # lookbehind exited with "invalid option" and the `|| true` swallowed diff --git a/internal/sticky/history_folding_removal_guard_test.go b/internal/sticky/history_folding_removal_guard_test.go new file mode 100644 index 0000000000..813ad21679 --- /dev/null +++ b/internal/sticky/history_folding_removal_guard_test.go @@ -0,0 +1,138 @@ +package sticky + +import ( + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// historyFoldingShimMarker is the justification marker every allowlisted +// read-side shim must carry: a comment naming itself a read-side shim. +// The guard requires it, so deleting a shim's why-and-until-when comment +// fails the test instead of silently keeping the exemption. +const historyFoldingShimMarker = "Read-side shim" + +// historyFoldingReadSideShims lists the production Go files that may keep +// referencing the sticky history sentinels after the cleanup (#9517). Both +// parse comments that pre-#9334 CLIs posted and that still sit unedited on +// old pull requests, so they read the sentinels rather than write them. +// Each shim must carry the historyFoldingShimMarker justification comment +// saying why it is kept and until when — the guard below requires the +// marker, and a person checks the full comment on the PR; anything outside +// this list that references a sentinel is new code reaching back into the +// removed machinery. +var historyFoldingReadSideShims = map[string]bool{ + // reviewHashAndHead cuts a review body at the history sentinel so the + // diff-hash and head markers are read from the current section only. + "internal/cli/reviewdedup.go": true, + // The Jira Markdown→ADF conversion strips sentinel comments so they do + // not render as visible text inside
expansions quoted from + // comments posted by older CLIs. + "internal/forge/jira/adf.go": true, +} + +// historyFoldingShimFiles returns the allowlist's paths for failure +// messages. +func historyFoldingShimFiles() []string { + out := make([]string, 0, len(historyFoldingReadSideShims)) + for p := range historyFoldingReadSideShims { + out = append(out, p) + } + sort.Strings(out) + return out +} + +// TestHistoryFoldingMachineryRemovedFromProductionGo is the acceptance +// test for #9517's first criterion (and, through the BuildUpdatedBody +// token, its fifth): after the cleanup no production Go file references +// the history-folding machinery — BuildUpdatedBody, the detailsRe and +// legacyDetailsRe matchers, Config.KeepHistory — or the keep_history +// setting, and the sticky history sentinels survive only in the read-side +// shims allowlisted above. The guard pins production sources the way +// internal/repos' quiescence guard does; test files, testdata fixtures, +// docs and the scaffold's shell scripts are read by a person on the PR +// (they keep their own read-side sentinel handling for old comments). +func TestHistoryFoldingMachineryRemovedFromProductionGo(t *testing.T) { + root, err := filepath.Abs(filepath.Join("..", "..")) + require.NoError(t, err) + + // Tokens that must vanish outright: the folding entry point, its + // matchers, and the keep_history surface (the Go symbol and the YAML + // key). A deliberate compatibility shim for the key would have to name + // it here; the PR decides against one, so the loader's existing + // behaviour for unknown keys is the whole story. + forbidden := []string{ + "BuildUpdatedBody", + "detailsRe", + "legacyDetailsRe", + "KeepHistory", + "keep_history", + } + // The sentinels old comments still carry; reading them is a shim. + sentinels := []string{ + "sticky:history-start", + "sticky:history-end", + } + + var hits []string + scanned := 0 + for _, dir := range []string{"cmd", "internal", "pkg"} { + walkErr := filepath.WalkDir(filepath.Join(root, dir), func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + switch d.Name() { + case "testdata", "vendor", "node_modules": + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + data, readErr := os.ReadFile(path) + if readErr != nil { + return readErr + } + scanned++ + rel, relErr := filepath.Rel(root, path) + if relErr != nil { + return relErr + } + rel = filepath.ToSlash(rel) + text := string(data) + for _, tok := range forbidden { + if strings.Contains(text, tok) { + hits = append(hits, rel+" references "+tok) + } + } + if historyFoldingReadSideShims[rel] { + // The allowlist is an exemption with a stated reason: + // a shim without its justification marker fails closed. + if !strings.Contains(text, historyFoldingShimMarker) { + hits = append(hits, rel+" is allowlisted as a read-side shim but carries no '"+historyFoldingShimMarker+"' justification") + } + } else { + for _, tok := range sentinels { + if strings.Contains(text, tok) { + hits = append(hits, rel+" references "+tok) + } + } + } + return nil + }) + require.NoError(t, walkErr) + } + require.NotZero(t, scanned, "the guard must scan the production sources") + sort.Strings(hits) + assert.Empty(t, hits, "the history-folding machinery and the keep_history setting are removed (#9517); "+ + "the sticky history sentinels may survive only as read-side shims in %v, each with a comment saying why it is kept and until when", + historyFoldingShimFiles()) +} diff --git a/internal/sticky/markers_test.go b/internal/sticky/markers_test.go index e85dd40fb3..f021ca84c2 100644 --- a/internal/sticky/markers_test.go +++ b/internal/sticky/markers_test.go @@ -27,7 +27,7 @@ func TestPost_NeutralizesMarkersInBody_AcrossRuns(t *testing.T) { client := forge.NewFakeClient() client.AuthenticatedUser = "bot" printer := ui.New(io.Discard) - cfg := Config{Marker: "", KeepHistory: true} + cfg := Config{Marker: ""} agentBody := func(run string) string { return "Run " + run + " " + @@ -61,74 +61,6 @@ func TestPost_NeutralizesMarkersInBody_AcrossRuns(t *testing.T) { assert.NotNil(t, FindMarkedComment(comments, cfg.Marker, "bot")) } -// Marker text already present in an old body (for example one posted -// before escaping existed) is escaped as it moves into history, while the -// runner's own marker and footer are removed first and kept live. -func TestBuildUpdatedBody_NeutralizesMarkersInHistory(t *testing.T) { - oldBody := "\nOld review text." + - "\n\n\n_footer_" - newBody := "\nNew review." - - result := BuildUpdatedBody(oldBody, newBody, testCfg) - - assert.True(t, strings.HasPrefix(result, newBody)) - assert.Contains(t, result, "Old review <!-- fullsend:sibling --> text.") - assert.NotContains(t, result, "")) - assert.Equal(t, 1, strings.Count(result, "")) - assert.True(t, strings.HasSuffix(result, "\n_footer_")) -} - -// Cutting a
block out of the old body joins the text on either -// side of it. A marker opener split around a block must still come out -// inert, in both the legacy and the sentinel history formats. -func TestBuildUpdatedBody_NeutralizesMarkerJoinedByHistoryRemoval(t *testing.T) { - cfg := Config{Marker: "", KeepHistory: true} - newBody := cfg.Marker + "\nNew review." - - for name, block := range map[string]string{ - "legacy": "
Previous runx
", - "sentinel": "
\nPrevious run\n\n" + historyStart + "\nx\n" + historyEnd + "\n\n
", - } { - t.Run(name, func(t *testing.T) { - oldBody := cfg.Marker + "\n" - - result := BuildUpdatedBody(oldBody, newBody, cfg) - - assert.Len(t, liveMarkerRe.FindAllString(result, -1), 1, "only the runner's marker is live") - assert.Contains(t, result, "<!-- fullsend:triage-agent -->") - assert.Nil(t, FindMarkedComment([]forge.IssueComment{{Author: "bot", Body: result}}, - "", "bot")) - }) - } -} - -// The footer is found by its last occurrence, so a copy of the footer -// marker inside the content does not cut the old body short. -func TestBuildUpdatedBody_FooterFoundByLastOccurrence(t *testing.T) { - oldBody := "\nOld start old end." + - "\n\n\n_footer_" - newBody := "\nNew review." - - result := BuildUpdatedBody(oldBody, newBody, testCfg) - - assert.Contains(t, result, "Old start <!-- fullsend:test-footer --> old end.") - assert.Equal(t, 1, strings.Count(result, "")) - assert.True(t, strings.HasSuffix(result, "\n\n\n_footer_")) -} - -func TestBuildUpdatedBody_NoHistory_FooterFoundByLastOccurrence(t *testing.T) { - cfg := testCfg - cfg.KeepHistory = false - oldBody := "\nOld copy." + - "\n\n\n_footer_" - newBody := "\nNew review." - - result := BuildUpdatedBody(oldBody, newBody, cfg) - - assert.Equal(t, newBody+"\n\n\n_footer_", result) -} - // trustedLineRe stands in for a caller's anchored trusted marker pattern. var trustedLineRe = regexp.MustCompile(`^$`) @@ -220,7 +152,7 @@ func TestPost_TrustedLeadingLine_AcrossRuns(t *testing.T) { client := forge.NewFakeClient() client.AuthenticatedUser = "bot" printer := ui.New(io.Discard) - cfg := Config{Marker: "", KeepHistory: true, TrustedLeadingLine: trustedLineRe} + cfg := Config{Marker: "", TrustedLeadingLine: trustedLineRe} body := trustedLine + "\n\nReview " for i := 1; i <= 3; i++ { diff --git a/internal/sticky/post_new_comment_test.go b/internal/sticky/post_new_comment_test.go index d0acad598b..6d2a08b3c0 100644 --- a/internal/sticky/post_new_comment_test.go +++ b/internal/sticky/post_new_comment_test.go @@ -27,7 +27,7 @@ func TestPost_SecondRunAddsNewCommentAtEnd(t *testing.T) { } printer := ui.New(io.Discard) - cfg := Config{Marker: "", KeepHistory: true} + cfg := Config{Marker: ""} commentURL, err := Post(context.Background(), client, "o", "r", 1, "Second result.", cfg, printer) require.NoError(t, err) @@ -47,7 +47,7 @@ func TestPost_EveryRunAppendsNewComment(t *testing.T) { client.AuthenticatedUser = "bot" printer := ui.New(io.Discard) - cfg := Config{Marker: "", KeepHistory: true} + cfg := Config{Marker: ""} for _, body := range []string{"Run 1.", "Run 2.", "Run 3."} { _, err := Post(context.Background(), client, "o", "r", 1, body, cfg, printer) require.NoError(t, err) diff --git a/internal/sticky/sticky.go b/internal/sticky/sticky.go index 0d6c3f18da..f8c1bda236 100644 --- a/internal/sticky/sticky.go +++ b/internal/sticky/sticky.go @@ -18,18 +18,9 @@ const DefaultMaxSize = 65000 // Config controls how an agent result comment is marked and posted. type Config struct { - Marker string // hidden HTML comment, e.g. "" - FooterMarker string // optional footer delimiter, stripped before collapsing history - MaxSize int // max comment body size (default 65000) - DryRun bool - - // KeepHistory is deprecated and has no effect on posting: sticky - // comments were removed (#9334), so every result is a new comment and - // nothing is folded into "Previous run" blocks. It is still read by - // BuildUpdatedBody, which no posting path calls anymore; the flag and - // config field that set it stay accepted so existing callers keep - // working until a cleanup removes them. - KeepHistory bool + Marker string // hidden HTML comment, e.g. "" + MaxSize int // max comment body size (default 65000) + DryRun bool // TrustedLeadingLine, when set, matches a marker line that the trusted // caller places at the start of the body. Matching leading lines are @@ -226,143 +217,6 @@ func FindMarkedComment(comments []forge.IssueComment, marker, botUser string) *f return nil } -// History blocks are wrapped with sentinel comments so extraction is safe -// even when review content contains nested
tags. -const ( - historyStart = "" - historyEnd = "" -) - -// detailsRe matches history blocks using sentinel comment delimiters. -var detailsRe = regexp.MustCompile(`(?s)
\s*Previous [^<]*\s*` + regexp.QuoteMeta(historyStart) + `\s*(.*?)\s*` + regexp.QuoteMeta(historyEnd) + `\s*
`) - -// legacyDetailsRe matches old-format history blocks without sentinel comments. -var legacyDetailsRe = regexp.MustCompile(`(?s)
\s*Previous [^<]*\s*(.*?)\s*
`) - -// BuildUpdatedBody collapses the old comment body into a flat list of -//
blocks and prepends the new body. Footer content (delimited -// by FooterMarker) is stripped before collapsing and re-appended after. -// -// When cfg.KeepHistory is false, the old body is discarded entirely and -// the new body is returned with footer re-appended (no "Previous run" -// blocks). -// -// Deprecated: no posting path calls this anymore — sticky comments were -// removed (#9334) and every result is posted as a new comment. It is kept -// only until the cleanup deletes the history-folding machinery (#9517). -func BuildUpdatedBody(oldBody, newBody string, cfg Config) string { - // When history is disabled, replace the body entirely. We still - // need to preserve the footer from the old body if configured. - if !cfg.KeepHistory { - var footer string - if cfg.FooterMarker != "" { - stripped, _ := strings.CutPrefix(oldBody, cfg.Marker+"\n") - stripped, _ = strings.CutPrefix(stripped, cfg.Marker) - if idx := strings.LastIndex(stripped, cfg.FooterMarker); idx >= 0 { - footer = stripped[idx:] - } - } - result := newBody - if footer != "" { - result += "\n\n" + footer - } - if len(result) > cfg.EffectiveMaxSize() { - result = TruncateBody(result, cfg.EffectiveMaxSize()) - } - return result - } - - // Strip marker from the old body (prefix-only to avoid matching - // the marker if it appears embedded in review content). - oldContent, _ := strings.CutPrefix(oldBody, cfg.Marker+"\n") - oldContent, _ = strings.CutPrefix(oldContent, cfg.Marker) - - // Strip footer if configured. The footer is found by its last - // occurrence so a copy of the footer marker inside the content does - // not cut the old body short. - var footer string - if cfg.FooterMarker != "" { - if idx := strings.LastIndex(oldContent, cfg.FooterMarker); idx >= 0 { - footer = oldContent[idx:] - oldContent = strings.TrimRight(oldContent[:idx], "\n") - } - } - - // Extract existing
blocks from old content to flatten history. - // Try sentinel-delimited blocks first, fall back to legacy format. - var historyBlocks []string - matches := detailsRe.FindAllStringSubmatch(oldContent, -1) - activeRe := detailsRe - if len(matches) == 0 { - matches = legacyDetailsRe.FindAllStringSubmatch(oldContent, -1) - activeRe = legacyDetailsRe - } - for _, m := range matches { - historyBlocks = append(historyBlocks, statuscomment.NeutralizeMarkers(m[1])) - } - - // The "current" old content is everything minus the old
blocks. - currentOld := activeRe.ReplaceAllString(oldContent, "") - currentOld = strings.TrimSpace(currentOld) - - // Escape marker syntax in each piece that moves into history. This - // runs after the runner's own marker and footer are removed above, so - // the exact-prefix strip keeps matching on later updates and no copy - // of the marker accumulates in history. It also runs after the - //
blocks are cut out, since removing a block can join the - // text on either side of it into a new marker opener. - currentOld = statuscomment.NeutralizeMarkers(currentOld) - - // Assemble history entries and drop the oldest ones first if the - // combined body would exceed the size limit. This avoids blind - // byte-level truncation that could sever HTML sentinels and corrupt - // history on subsequent runs. - type histEntry struct { - summary string - content string - } - var entries []histEntry - if currentOld != "" { - entries = append(entries, histEntry{summary: "Previous run", content: currentOld}) - } - for i, block := range historyBlocks { - entries = append(entries, histEntry{ - summary: fmt.Sprintf("Previous run (%d)", i+2), - content: strings.TrimSpace(block), - }) - } - - formatHistory := func(ents []histEntry) string { - var b strings.Builder - for _, e := range ents { - b.WriteString(fmt.Sprintf("\n\n
\n%s\n\n", e.summary)) - b.WriteString(historyStart + "\n") - b.WriteString(e.content) - b.WriteString("\n" + historyEnd) - b.WriteString("\n\n
") - } - return b.String() - } - - footerStr := "" - if footer != "" { - footerStr = "\n\n" + footer - } - - combined := newBody + formatHistory(entries) + footerStr - - for len(combined) > cfg.EffectiveMaxSize() && len(entries) > 0 { - entries = entries[:len(entries)-1] - combined = newBody + formatHistory(entries) + footerStr - } - - if len(combined) > cfg.EffectiveMaxSize() { - combined = TruncateBody(combined, cfg.EffectiveMaxSize()) - } - - return combined -} - // TruncateBody trims body to fit within maxSize, keeping the content at // the top and cutting the end. The truncation point is aligned to a valid // UTF-8 boundary. diff --git a/internal/sticky/sticky_test.go b/internal/sticky/sticky_test.go index c66fe927fb..c22878cb21 100644 --- a/internal/sticky/sticky_test.go +++ b/internal/sticky/sticky_test.go @@ -14,12 +14,6 @@ import ( "github.com/fullsend-ai/fullsend/internal/ui" ) -var testCfg = Config{ - Marker: "", - FooterMarker: "", - KeepHistory: true, -} - func TestFindMarkedComment(t *testing.T) { comments := []forge.IssueComment{ {ID: 1, Body: "regular comment", Author: "human"}, @@ -60,167 +54,6 @@ func TestFindMarkedComment_Empty(t *testing.T) { assert.Nil(t, found) } -func TestBuildUpdatedBody_CollapsesOldContent(t *testing.T) { - oldBody := "\nOld findings." - newBody := "\nNew findings." - - result := BuildUpdatedBody(oldBody, newBody, testCfg) - - assert.Contains(t, result, "New findings.") - assert.Contains(t, result, "
") - assert.Contains(t, result, "Previous run") - assert.Contains(t, result, "Old findings.") -} - -func TestBuildUpdatedBody_FlatHistory(t *testing.T) { - cfg := Config{Marker: "", KeepHistory: true} - - // Run 1 → Run 2 - body1 := "\nRun 1 content." - body2 := "\nRun 2 content." - result2 := BuildUpdatedBody(body1, body2, cfg) - - // Run 2 → Run 3 - body3 := "\nRun 3 content." - result3 := BuildUpdatedBody(result2, body3, cfg) - - // Run 3 → Run 4 - body4 := "\nRun 4 content." - result4 := BuildUpdatedBody(result3, body4, cfg) - - // Run 4 → Run 5 - body5 := "\nRun 5 content." - result5 := BuildUpdatedBody(result4, body5, cfg) - - // 4 re-runs should produce 4
blocks, all flat (not nested). - assert.Equal(t, 4, strings.Count(result5, "
")) - assert.Equal(t, 4, strings.Count(result5, "
")) - - // All run contents should be present. - assert.Contains(t, result5, "Run 5 content.") - assert.Contains(t, result5, "Run 4 content.") - assert.Contains(t, result5, "Run 3 content.") - assert.Contains(t, result5, "Run 2 content.") - assert.Contains(t, result5, "Run 1 content.") - - // No nested details — each
should not be inside another
. - // A simple proxy: no line should contain both
and
. - for _, line := range strings.Split(result5, "\n") { - if strings.Contains(line, "
") { - assert.NotContains(t, line, "
") - } - } -} - -func TestBuildUpdatedBody_NestedDetailsInContent(t *testing.T) { - cfg := Config{Marker: "", KeepHistory: true} - - // Run 1 content contains a
block (common in GitHub review output). - body1 := "\nReview findings:\n
\nExpanded diff\nsome diff content\n
\nEnd of review." - body2 := "\nRun 2 content." - result2 := BuildUpdatedBody(body1, body2, cfg) - - // Run 2 → Run 3 to verify content survives multiple collapses. - body3 := "\nRun 3 content." - result3 := BuildUpdatedBody(result2, body3, cfg) - - // All content should be preserved. - assert.Contains(t, result3, "Run 3 content.") - assert.Contains(t, result3, "Run 2 content.") - assert.Contains(t, result3, "some diff content") - assert.Contains(t, result3, "End of review.") -} - -func TestBuildUpdatedBody_FooterStripping(t *testing.T) { - oldBody := "\nOld review.\n\n\n_some footer info_" - newBody := "\nNew review." - - result := BuildUpdatedBody(oldBody, newBody, testCfg) - - assert.Contains(t, result, "New review.") - assert.Contains(t, result, "Old review.") - assert.Contains(t, result, "") - assert.Contains(t, result, "_some footer info_") - - // Footer should not be inside a
block. - footerIdx := strings.Index(result, "") - lastDetailsClose := strings.LastIndex(result, "
") - if lastDetailsClose >= 0 { - assert.Greater(t, footerIdx, lastDetailsClose, "footer should come after all
blocks") - } -} - -func TestBuildUpdatedBody_NoFooterMarker(t *testing.T) { - cfg := Config{Marker: "", KeepHistory: true} - oldBody := "\nOld content." - newBody := "\nNew content." - - result := BuildUpdatedBody(oldBody, newBody, cfg) - - assert.Contains(t, result, "New content.") - assert.Contains(t, result, "Old content.") -} - -func TestBuildUpdatedBody_NoHistory(t *testing.T) { - cfg := Config{ - Marker: "", - KeepHistory: false, - } - oldBody := "\nold content" - newBody := "\nnew content" - - got := BuildUpdatedBody(oldBody, newBody, cfg) - - if strings.Contains(got, "
") { - t.Error("expected no history block when KeepHistory is false") - } - if !strings.Contains(got, "new content") { - t.Error("expected new content in result") - } - if strings.Contains(got, "old content") { - t.Error("expected old content to be discarded when KeepHistory is false") - } -} - -func TestBuildUpdatedBody_NoHistory_PreservesFooter(t *testing.T) { - cfg := Config{ - Marker: "", - FooterMarker: "", - KeepHistory: false, - } - oldBody := "\nOld review.\n\n\n_some footer info_" - newBody := "\nNew review." - - got := BuildUpdatedBody(oldBody, newBody, cfg) - - assert.Contains(t, got, "New review.") - assert.NotContains(t, got, "Old review.") - assert.NotContains(t, got, "
") - assert.Contains(t, got, "") - assert.Contains(t, got, "_some footer info_") -} - -func TestBuildUpdatedBody_NoHistory_MultipleRuns(t *testing.T) { - cfg := Config{Marker: "", KeepHistory: false} - - body1 := "\nRun 1 content." - body2 := "\nRun 2 content." - result2 := BuildUpdatedBody(body1, body2, cfg) - - // After update, only run 2 should be present. - assert.Contains(t, result2, "Run 2 content.") - assert.NotContains(t, result2, "Run 1 content.") - assert.NotContains(t, result2, "
") - - // Run 2 → Run 3 - body3 := "\nRun 3 content." - result3 := BuildUpdatedBody(result2, body3, cfg) - - assert.Contains(t, result3, "Run 3 content.") - assert.NotContains(t, result3, "Run 2 content.") - assert.NotContains(t, result3, "
") -} - func TestTruncateBody_UnderLimit(t *testing.T) { body := "short body" assert.Equal(t, body, TruncateBody(body, DefaultMaxSize)) @@ -233,24 +66,6 @@ func TestTruncateBody_OverLimit(t *testing.T) { assert.Contains(t, result, "truncated") } -func TestBuildUpdatedBody_DropsOldestHistoryOnOverflow(t *testing.T) { - cfg := Config{Marker: "", MaxSize: 500, KeepHistory: true} - - body1 := "\n" + strings.Repeat("A", 100) - body2 := "\n" + strings.Repeat("B", 100) - result2 := BuildUpdatedBody(body1, body2, cfg) - - body3 := "\n" + strings.Repeat("C", 100) - result3 := BuildUpdatedBody(result2, body3, cfg) - - body4 := "\n" + strings.Repeat("D", 100) - result4 := BuildUpdatedBody(result3, body4, cfg) - - assert.LessOrEqual(t, len(result4), 500, "combined body should not exceed maxSize") - assert.Contains(t, result4, strings.Repeat("D", 100), "current content must be preserved") - assert.NotContains(t, result4, "truncated", "should drop history blocks, not blind-truncate") -} - func TestTruncateBody_RuneSafe(t *testing.T) { // Build a string with multi-byte UTF-8 characters that would be split // at a naive byte boundary.