diff --git a/docs/guides/getting-started/repo-management.md b/docs/guides/getting-started/repo-management.md index aad1b1000e..e371d92ddc 100644 --- a/docs/guides/getting-started/repo-management.md +++ b/docs/guides/getting-started/repo-management.md @@ -1017,7 +1017,10 @@ upgraded keeps working there (the warning appears only in public repositories). Any upgrade to a fullsend version with the new shim installs the same `pull_request` shim, with the effects below. `fullsend repos install` rewrites the trigger and the workflow pin in one -commit. After the upgrade: +commit. If it cannot fetch the templates of the new version, it upgrades +only the pin and prints `template fetch at the target ref failed: delivering +the pin upgrade only; run install again to deliver template changes`. Run it +again once the fetch works to deliver the trigger. After the upgrade: - **Same-repo PRs** are reviewed automatically, as before, except while the PR has a merge conflict: GitHub does not run `pull_request` workflows until diff --git a/internal/repos/converge.go b/internal/repos/converge.go index 387f6c5d50..b595360ed9 100644 --- a/internal/repos/converge.go +++ b/internal/repos/converge.go @@ -3517,6 +3517,12 @@ func convergeScaffoldFiles(ctx context.Context, // isUnstampedInstallRef). When neither fullsend_ref nor a release ref is // available, the expected content is then still rendered, at // config.DefaultUpstreamRef, exactly as that install rendered it. +// +// targetTemplates reports whether the expected files were rendered from +// templates that match the target ref: the remote fetch at the pinned ref +// succeeded, the install is vendored, or no explicit pin was set. It is +// false when a GitHub fetch failed and the running binary's embedded +// templates were used instead. func convergeContentDriftFiles(ctx context.Context, resolved ResolvedConfig, cfg ConvergeConfig, @@ -3524,10 +3530,10 @@ func convergeContentDriftFiles(ctx context.Context, coveredPaths map[string]bool, dcfg DriftConfig, unstampedInstall bool, - progress ProgressFunc) ([]forge.TreeFile, []ComponentAction) { + progress ProgressFunc) (files []forge.TreeFile, actions []ComponentAction, targetTemplates bool) { repoFullName := resolved.Owner + "/" + resolved.Repo - var actions []ComponentAction + targetTemplates = true targetRef := resolved.FullsendRef if targetRef == "" && cfg.UpstreamRef == "" && !unstampedInstall { @@ -3538,7 +3544,7 @@ func convergeContentDriftFiles(ctx context.Context, progress(repoFullName, "content-drift", fmt.Sprintf("scaffold content drift not checked: %s.fullsend_ref is not set and this build has no release ref; "+ "set %s.fullsend_ref to converge template changes such as runner tags", resolved.Forge, resolved.Forge)) - return nil, actions + return nil, actions, targetTemplates } rref := resolveTargetRef(ctx, resolved.FullsendRef, cfg.UpstreamRef, cfg.UpstreamTag, refResolver) @@ -3565,13 +3571,22 @@ func convergeContentDriftFiles(ctx context.Context, installCfg.PrebuiltScaffoldFiles = scaffoldFiles } else { if resolved.Forge == ForgeGitLab { - return nil, []ComponentAction{{Component: "scaffold", Action: "error", Detail: fmt.Sprintf("fetching pinned GitLab scaffold: %v", fetchErr)}} + return nil, []ComponentAction{{Component: "scaffold", Action: "error", Detail: fmt.Sprintf("fetching pinned GitLab scaffold: %v", fetchErr)}}, false } + targetTemplates = false progress(repoFullName, "content-drift", fmt.Sprintf("remote scaffold fetch failed, using embedded templates: %v", fetchErr)) } } + // An explicit pin renders the target ref's templates only when they + // were fetched (or the install is vendored). Without a resolver the + // fetch never ran and the embedded templates are used, as after a + // failed fetch. + if manifestRef != "" && !installCfg.VendorBinary && installCfg.PrebuiltScaffoldFiles == nil { + targetTemplates = false + } + expectedFiles, buildErr := BuildScaffoldFiles(installCfg) if buildErr != nil { actions = append(actions, ComponentAction{ @@ -3579,7 +3594,7 @@ func convergeContentDriftFiles(ctx context.Context, Action: "error", Detail: fmt.Sprintf("failed to build expected scaffold for content drift check: %v", buildErr), }) - return nil, actions + return nil, actions, targetTemplates } // Content drift detection — shared between dry-run and live paths. @@ -3595,7 +3610,7 @@ func convergeContentDriftFiles(ctx context.Context, Action: "error", Detail: fmt.Sprintf("content drift check failed: %v", driftErr), }) - return nil, actions + return nil, actions, targetTemplates } var repairFiles []forge.TreeFile @@ -3624,13 +3639,9 @@ func convergeContentDriftFiles(ctx context.Context, } } - if cfg.DryRun && len(actions) > 0 { - progress(repoFullName, "dry-run", - fmt.Sprintf("Would repair %d files with content drift", len(actions))) - } else if len(repairFiles) > 0 { - progress(repoFullName, "repair", - fmt.Sprintf("Repairing %d files with content drift", len(repairFiles))) - } + // The caller reports the repair count after it filters the repairs + // (collectConvergeScaffoldFiles), so the count matches what is + // committed or previewed. // Orphan file detection: check for managed scaffold files that // exist on the forge but are no longer produced by the current @@ -3650,7 +3661,7 @@ func convergeContentDriftFiles(ctx context.Context, Action: "error", Detail: fmt.Sprintf("orphan file check failed: %v", orphanErr), }) - return repairFiles, actions + return repairFiles, actions, targetTemplates } for _, o := range orphanFiles { if coveredPaths[o.Path] { @@ -3679,7 +3690,7 @@ func convergeContentDriftFiles(ctx context.Context, Action: "error", Detail: fmt.Sprintf("orphan variable check failed: %v", orphanVarErr), }) - return repairFiles, actions + return repairFiles, actions, targetTemplates } for _, o := range orphanVars { actions = append(actions, ComponentAction{ @@ -3691,7 +3702,7 @@ func convergeContentDriftFiles(ctx context.Context, fmt.Sprintf("Orphan variable %s (not in managed set)", o.Name)) } - return repairFiles, actions + return repairFiles, actions, targetTemplates } // resolvedRef holds the result of resolving a manifest's fullsend_ref @@ -3837,6 +3848,71 @@ func convergeRepoCredentials(ctx context.Context, d convergeDiscovery, wifProvid return actions, nil } +// supersedePinOnlyRefFiles merges content-drift repairs into files, the +// scaffold files already queued. A repair for a pin-only ref path (see +// collectConvergeScaffoldFiles) replaces that queued file in place, so one +// run delivers both the new pin and any template change shipped with it, +// such as a changed shim trigger (#9714). The replacement keeps the pin the +// ref upgrade wrote (withQueuedPin), so the repository's pinning style +// (SHA with tag comment, plain tag or branch) does not change. A shim +// repair rendered at the other workflow extension (.yml vs .yaml) replaces +// the queued shim at its installed path instead of adding a second shim. +// Other repairs are appended. +func supersedePinOnlyRefFiles(files, driftFiles []forge.TreeFile, pinOnly map[string]bool, fc ForgeConfig) []forge.TreeFile { + workflowPaths := fc.WorkflowPaths + for _, df := range driftFiles { + idx := slices.IndexFunc(files, func(f forge.TreeFile) bool { + if !pinOnly[f.Path] { + return false + } + return f.Path == df.Path || + (slices.Contains(workflowPaths, f.Path) && slices.Contains(workflowPaths, df.Path)) + }) + if idx < 0 { + files = append(files, df) + continue + } + files[idx].Content = withQueuedPin(df.Content, files[idx].Content, fc) + } + return files +} + +// countUpdates counts the update actions in actions. +func countUpdates(actions []ComponentAction) int { + n := 0 + for _, a := range actions { + if a.Action == "update" { + n++ + } + } + return n +} + +// withoutRefPathRepairs drops the content-drift repairs, and their update +// actions, for the paths skip selects. +func withoutRefPathRepairs(files []forge.TreeFile, actions []ComponentAction, skip func(string) bool) ([]forge.TreeFile, []ComponentAction) { + files = slices.DeleteFunc(files, func(f forge.TreeFile) bool { return skip(f.Path) }) + actions = slices.DeleteFunc(actions, func(a ComponentAction) bool { return a.Action == "update" && skip(a.Component) }) + return files, actions +} + +// withQueuedPin returns full with every fullsend workflow pin replaced by +// the pin in queued, the pin-only rewrite convergeRefFiles produced. The +// content-drift template always renders a semver target as " # tag", +// while the ref upgrade keeps a repository's own style (a plain tag stays +// a plain tag). When queued has no pin, full is returned unchanged. +func withQueuedPin(full, queued []byte, fc ForgeConfig) []byte { + if fc.ShimRefPattern == nil { + return full + } + m := fc.ShimRefPattern.FindSubmatchIndex(queued) + if len(m) < 4 || m[3] < 0 { + return full + } + pin := strings.ReplaceAll(string(queued[m[3]:m[1]]), "$", "$$") + return []byte(fc.ShimRefPattern.ReplaceAllString(string(full), "${1}"+pin)) +} + // collectConvergeScaffoldFiles plans atomic scaffold and configuration delivery. // It returns the planned files and actions without writing credentials. func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg ConvergeConfig, refResolver *RefResolver, progress ProgressFunc) ([]forge.TreeFile, []ComponentAction, error) { @@ -3858,11 +3934,10 @@ func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg } // A ref upgrade only rewrites the shim's version marker. When the - // installed GitHub shim cannot forward FULLSEND_OPENAI_API_KEY, queueing - // that marker-only rewrite would also exclude the shim from content-drift - // repair and deliver a shim that still cannot use the selected credential. - // Leave the shim to content-drift repair, which renders the full template - // at the target ref. + // installed GitHub shim cannot forward FULLSEND_OPENAI_API_KEY, that + // marker-only rewrite would deliver a shim that still cannot use the + // selected credential. Leave the shim to content-drift repair, which + // renders the full template at the target ref. refFiles, legacyErr := withoutLegacyOpenAIConsumer(ctx, resolved, refFiles) if legacyErr != nil { return allScaffoldFiles, actions, legacyErr @@ -3917,8 +3992,28 @@ func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg // structure changed between releases while the ref stayed the // same). This is the gap that caused #6576: converge only checked // presence, not content, so stale-but-present files were skipped. - contentDriftFiles, contentDriftActions := convergeContentDriftFiles( - ctx, resolved, cfg, refResolver, refFileSet, + // + // On GitHub every ref file is a pin-only rewrite (see + // convergeRefFiles), so content drift still checks those paths and + // may supersede them with the full template at the target ref. The + // dry run queues no ref files, so this also gives both runs the same + // skip set (#9714). + driftCoveredPaths := refFileSet + var pinOnlyPaths map[string]bool + if resolved.Forge != ForgeGitLab && len(refFiles) > 0 { + pinOnlyPaths = make(map[string]bool, len(refFiles)) + for _, f := range refFiles { + pinOnlyPaths[f.Path] = true + } + driftCoveredPaths = make(map[string]bool, len(refFileSet)) + for p := range refFileSet { + if !pinOnlyPaths[p] { + driftCoveredPaths[p] = true + } + } + } + contentDriftFiles, contentDriftActions, targetTemplates := convergeContentDriftFiles( + ctx, resolved, cfg, refResolver, driftCoveredPaths, DriftConfig{ ReviewAppClientID: d.reviewClientID, AgentRunnerTags: gitlabAgentRunnerTags(cfg.Manifest), @@ -3927,6 +4022,39 @@ func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg unstampedWorkflow(resolved.Forge, d.components), progress, ) + // The drift templates replace the shim and thin callers on a ref + // upgrade only when they match the target ref. After a failed remote + // fetch they are the running binary's embedded templates, which can + // call inputs the target release lacks: keep the pin-only rewrite and + // leave the template change to the next run. Filtering here, before + // the actions are recorded, keeps the dry run and the live run in step. + if !targetTemplates && resolved.Forge != ForgeGitLab && slices.ContainsFunc(refActions, func(a ComponentAction) bool { + return a.Component == "ref" && a.Action == "upgrade" + }) { + // Both runs drop the repairs for every ref-upgrade path: the shim + // at either workflow extension (the template always renders + // fullsend.yaml, even for an installed fullsend.yml) and the thin + // callers. A legacy shim that withoutLegacyOpenAIConsumer took out + // of the queue also waits for a run whose fetch succeeds, rather + // than taking another release's template now. Using one rule in + // both runs keeps the dry run and the live run in step. + skip := func(p string) bool { + return slices.Contains(resolved.ForgeConfig.WorkflowPaths, p) || slices.Contains(scaffold.PerRepoThinCallerPaths(), p) + } + before := len(contentDriftActions) + contentDriftFiles, contentDriftActions = withoutRefPathRepairs(contentDriftFiles, contentDriftActions, skip) + if len(contentDriftActions) < before { + progress(resolved.Owner+"/"+resolved.Repo, "content-drift", + "template fetch at the target ref failed: delivering the pin upgrade only; run install again to deliver template changes") + } + } + if n := countUpdates(contentDriftActions); n > 0 { + if cfg.DryRun { + progress(resolved.Owner+"/"+resolved.Repo, "dry-run", fmt.Sprintf("Would repair %d files with content drift", n)) + } else { + progress(resolved.Owner+"/"+resolved.Repo, "repair", fmt.Sprintf("Repairing %d files with content drift", n)) + } + } actions = append(actions, contentDriftActions...) var contentErrors []string @@ -3938,7 +4066,8 @@ func collectConvergeScaffoldFiles(ctx context.Context, d convergeDiscovery, cfg if len(contentErrors) > 0 { return allScaffoldFiles, actions, fmt.Errorf("convergence errors: %s", strings.Join(contentErrors, "; ")) } - allScaffoldFiles = append(allScaffoldFiles, contentDriftFiles...) + allScaffoldFiles = supersedePinOnlyRefFiles(allScaffoldFiles, contentDriftFiles, + pinOnlyPaths, resolved.ForgeConfig) // Root input migration uses the wrapper that will actually be committed, // including ref upgrades, repairs and remote pinned templates. diff --git a/internal/repos/converge_test.go b/internal/repos/converge_test.go index 47b15eb447..86f80466e7 100644 --- a/internal/repos/converge_test.go +++ b/internal/repos/converge_test.go @@ -3,6 +3,7 @@ package repos import ( "context" "fmt" + "regexp" "slices" "strings" "sync" @@ -1246,6 +1247,340 @@ func TestConverge_RefUpgradeWithThinCallers(t *testing.T) { } } +// TestConverge_RefUpgradeDeliversFullShimTemplate covers #9714: a ref +// upgrade of a shim whose template also changed (pull_request_target → +// pull_request) must deliver the full template at the new pin in one +// pass, not a pin-only rewrite that leaves content drift for a second run. +// The dry run must report the same shim repair. +func TestConverge_RefUpgradeDeliversFullShimTemplate(t *testing.T) { + const shimPath = ".github/workflows/fullsend.yaml" + // v2.0.0 resolves to this SHA, so the content-drift template renders + // " # v2.0.0" while the installed plain-tag pin must stay a plain + // tag (withQueuedPin). + const targetSHA = "2222222222222222222222222222222222222222" + setupAt := func(t *testing.T, serveTemplates bool, installedShim string) *forge.FakeClient { + t.Helper() + fc := newFakeClientForBatch("acme/api") + markFullyInstalled(fc, "acme", "api") + populateScaffoldContent(t, fc, "acme", "api", "v1.0.0", "https://mint.example.com") + shim := string(fc.FileContents["acme/api/"+shimPath]) + oldShim := strings.Replace(shim, "\n pull_request:\n", "\n pull_request_target:\n", 1) + if oldShim == shim { + t.Fatal("shim template has no pull_request trigger to rewrite") + } + if installedShim != shimPath { + delete(fc.FileContents, "acme/api/"+shimPath) + } + fc.FileContents["acme/api/"+installedShim] = []byte(oldShim) + fc.Refs[shimOwner+"/"+shimRepo+"/tags/v2.0.0"] = targetSHA + if serveTemplates { + // Serve the templates at the target ref, as the upstream repo + // does, so content drift renders them instead of falling back + // to the embedded templates. + raw, err := scaffold.FullsendRepoFile("templates/shim-per-repo.yaml") + if err != nil { + t.Fatal(err) + } + // A marker the embedded template lacks proves the committed + // shim is the target ref's template. + raw = append([]byte("# served-at-v2.0.0\n"), raw...) + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+scaffoldGitHubShimPath+"@v2.0.0"] = raw + for _, tc := range scaffold.PerRepoThinCallerPaths() { + raw, err := scaffold.FullsendRepoFile(tc) + if err != nil { + t.Fatal(err) + } + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/internal/scaffold/fullsend-repo/"+tc+"@v2.0.0"] = raw + } + } + return fc + } + setup := func(t *testing.T, serveTemplates bool) *forge.FakeClient { + t.Helper() + return setupAt(t, serveTemplates, shimPath) + } + manifest := func() *Manifest { + m := newConvergeManifest("acme/api") + m.GitHub.FullsendRef = "v2.0.0" + return m + } + + t.Run("live", func(t *testing.T) { + fc := setup(t, true) + var committed []forge.TreeFile + commitFn := func(_ context.Context, _, _ string, files []forge.TreeFile, _ bool, _ bool) error { + committed = files + return nil + } + cfg := withoutInferenceInputs(convergeCfgWithDefaults(manifest())) + if _, err := Converge(context.Background(), cfg, newTestClientFactory(fc), commitFn, noopProgress); err != nil { + t.Fatalf("Converge() error: %v", err) + } + + var shims []forge.TreeFile + for _, f := range committed { + if slices.Contains(GitHubForgeConfig().WorkflowPaths, f.Path) { + shims = append(shims, f) + } + } + if len(shims) != 1 { + t.Fatalf("committed %d shim files, want exactly 1", len(shims)) + } + got := string(shims[0].Content) + if strings.Contains(got, "pull_request_target:") || !strings.Contains(got, "\n pull_request:\n") { + t.Errorf("committed shim does not use the pull_request trigger:\n%s", got) + } + if ref := extractWorkflowRef(shims[0].Content, GitHubForgeConfig()); ref != "v2.0.0" { + t.Errorf("committed shim ref = %q, want the plain tag v2.0.0 (pin style kept)", ref) + } + if !strings.Contains(got, "# served-at-v2.0.0") { + t.Errorf("committed shim is not the template served at v2.0.0:\n%s", got) + } + if strings.Contains(got, targetSHA) { + t.Errorf("committed shim carries the resolved SHA; the plain-tag pin style must be kept:\n%s", got) + } + + // The commit leaves no shim content drift for a second run. + fc.FileContents["acme/api/"+shims[0].Path] = shims[0].Content + served, err := FetchRemoteScaffold(context.Background(), fc, "v2.0.0", targetSHA, ForgeGitHub, nil, nil, false) + if err != nil { + t.Fatalf("FetchRemoteScaffold: %v", err) + } + expected, err := BuildScaffoldFiles(InstallConfig{ + Owner: "acme", Repo: "api", Forge: ForgeGitHub, + Roles: []string{"triage"}, MintURL: "https://mint.example.com", + UpstreamRef: "v2.0.0", UpstreamTag: "v2.0.0", + ManagedConfig: emptyManagedOverlay(t), + PrebuiltScaffoldFiles: served, + }) + if err != nil { + t.Fatalf("BuildScaffoldFiles: %v", err) + } + drifted, err := CheckFileContentDrift(context.Background(), fc, "acme", "api", + GitHubForgeConfig(), ForgeGitHub, expected) + if err != nil { + t.Fatalf("CheckFileContentDrift: %v", err) + } + for _, d := range drifted { + if d.InstalledPath == shims[0].Path { + t.Errorf("shim %s still drifts after one converge pass", d.InstalledPath) + } + } + }) + + for _, installed := range GitHubForgeConfig().WorkflowPaths { + t.Run("template fetch failure keeps the pin-only rewrite at "+installed, func(t *testing.T) { + testRefUpgradeFetchFailure(t, setupAt(t, false, installed), manifest()) + }) + t.Run("dry-run after a template fetch failure reports no shim repair at "+installed, func(t *testing.T) { + fc := setupAt(t, false, installed) + cfg := withoutInferenceInputs(convergeCfgWithDefaults(manifest())) + cfg.DryRun = true + result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), (&fakeScaffoldCommit{}).fn(), noopProgress) + if err != nil { + t.Fatalf("Converge() error: %v", err) + } + for _, a := range result.Results[0].Actions { + if slices.Contains(GitHubForgeConfig().WorkflowPaths, a.Component) && a.Action == "update" { + t.Errorf("dry run reports a shim repair the live run would not deliver: %+v", a) + } + } + }) + } + + t.Run("template fetch failure keeps the pin-only rewrite", func(t *testing.T) { + fc := setup(t, false) + var committed []forge.TreeFile + commitFn := func(_ context.Context, _, _ string, files []forge.TreeFile, _ bool, _ bool) error { + committed = files + return nil + } + var notes []string + progress := func(_, _, msg string) { notes = append(notes, msg) } + cfg := withoutInferenceInputs(convergeCfgWithDefaults(manifest())) + if _, err := Converge(context.Background(), cfg, newTestClientFactory(fc), commitFn, progress); err != nil { + t.Fatalf("Converge() error: %v", err) + } + var shims []forge.TreeFile + for _, f := range committed { + if slices.Contains(GitHubForgeConfig().WorkflowPaths, f.Path) { + shims = append(shims, f) + } + } + if len(shims) != 1 { + t.Fatalf("committed %d shim files, want exactly 1", len(shims)) + } + got := string(shims[0].Content) + if !strings.Contains(got, "pull_request_target:") { + t.Errorf("embedded templates must not replace the shim after a failed fetch:\n%s", got) + } + if ref := extractWorkflowRef(shims[0].Content, GitHubForgeConfig()); ref != "v2.0.0" { + t.Errorf("committed shim ref = %q, want v2.0.0", ref) + } + if !slices.ContainsFunc(notes, func(n string) bool { return strings.Contains(n, "delivering the pin upgrade only") }) { + t.Errorf("no progress note about the pin-only fallback; notes: %q", notes) + } + }) + + t.Run("dry-run", func(t *testing.T) { + fc := setup(t, true) + sc := &fakeScaffoldCommit{} + cfg := withoutInferenceInputs(convergeCfgWithDefaults(manifest())) + cfg.DryRun = true + result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), sc.fn(), noopProgress) + if err != nil { + t.Fatalf("Converge() error: %v", err) + } + if len(result.Results) != 1 { + t.Fatalf("expected 1 result, got %d", len(result.Results)) + } + var refUpgrade, shimRepair bool + for _, a := range result.Results[0].Actions { + if a.Component == "ref" && a.Action == "upgrade" { + refUpgrade = true + } + if a.Component == shimPath && a.Action == "update" { + shimRepair = true + } + } + if !refUpgrade || !shimRepair { + t.Errorf("dry run actions: ref upgrade=%v, shim repair=%v; want both", refUpgrade, shimRepair) + } + }) +} + +func TestSupersedePinOnlyRefFiles(t *testing.T) { + queued := []forge.TreeFile{ + {Path: ".github/workflows/fullsend.yml", Content: []byte("pin-only shim"), Mode: "100644"}, + {Path: ".github/workflows/prioritize.yml", Content: []byte("pin-only caller"), Mode: "100644"}, + {Path: ".github/workflows/repaired.yml", Content: []byte("repair"), Mode: "100644"}, + } + pinOnly := map[string]bool{queued[0].Path: true, queued[1].Path: true} + drift := []forge.TreeFile{ + {Path: ".github/workflows/fullsend.yaml", Content: []byte("full shim"), Mode: "100644"}, + {Path: ".github/workflows/prioritize.yml", Content: []byte("full caller"), Mode: "100644"}, + {Path: ".fullsend/other.yaml", Content: []byte("other"), Mode: "100644"}, + } + + got := supersedePinOnlyRefFiles(slices.Clone(queued), drift, pinOnly, GitHubForgeConfig()) + want := []forge.TreeFile{ + {Path: ".github/workflows/fullsend.yml", Content: []byte("full shim"), Mode: "100644"}, + {Path: ".github/workflows/prioritize.yml", Content: []byte("full caller"), Mode: "100644"}, + {Path: ".github/workflows/repaired.yml", Content: []byte("repair"), Mode: "100644"}, + {Path: ".fullsend/other.yaml", Content: []byte("other"), Mode: "100644"}, + } + if len(got) != len(want) { + t.Fatalf("got %d files, want %d: %+v", len(got), len(want), got) + } + for i := range want { + if got[i].Path != want[i].Path || string(got[i].Content) != string(want[i].Content) { + t.Errorf("file %d = %s %q, want %s %q", i, got[i].Path, got[i].Content, want[i].Path, want[i].Content) + } + } + + // Without pin-only paths every repair is appended. + if got := supersedePinOnlyRefFiles(slices.Clone(queued), drift, nil, GitHubForgeConfig()); len(got) != len(queued)+len(drift) { + t.Errorf("nil pinOnly: got %d files, want %d", len(got), len(queued)+len(drift)) + } +} + +// TestSupersedePinOnlyRefFiles_KeepsPinStyle checks that a superseding +// template keeps the pin the ref upgrade wrote. The drift template renders +// a semver target as " # tag"; a repository pinned to a plain tag +// must keep the plain tag (#9714). +func TestSupersedePinOnlyRefFiles_KeepsPinStyle(t *testing.T) { + const shim = ".github/workflows/fullsend.yaml" + const prefix = " uses: fullsend-ai/fullsend/.github/workflows/reusable-dispatch.yml@" + cases := []struct{ name, queuedPin, wantPin string }{ + {"plain tag", "v2.0.0", "v2.0.0"}, + {"sha with tag comment", "abc1234567890abc1234567890abc1234567890a # v2.0.0", "abc1234567890abc1234567890abc1234567890a # v2.0.0"}, + {"branch", "main", "main"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + queued := []forge.TreeFile{{Path: shim, Content: []byte("on:\n pull_request_target:\n" + prefix + tc.queuedPin + "\n"), Mode: "100644"}} + drift := []forge.TreeFile{{Path: shim, Content: []byte("on:\n pull_request:\n" + prefix + "fffffffffffffffffffffffffffffffffffffff0 # v2.0.0\n"), Mode: "100644"}} + got := supersedePinOnlyRefFiles(queued, drift, map[string]bool{shim: true}, GitHubForgeConfig()) + if len(got) != 1 { + t.Fatalf("got %d files, want 1", len(got)) + } + want := "on:\n pull_request:\n" + prefix + tc.wantPin + "\n" + if string(got[0].Content) != want { + t.Errorf("content = %q, want %q", got[0].Content, want) + } + }) + } +} + +// testRefUpgradeFetchFailure runs a live converge whose template fetch at +// the target ref fails and checks that the committed shim keeps the +// pull_request_target body (no embedded template) at the new pin. +func testRefUpgradeFetchFailure(t *testing.T, fc *forge.FakeClient, m *Manifest) { + t.Helper() + var committed []forge.TreeFile + commitFn := func(_ context.Context, _, _ string, files []forge.TreeFile, _ bool, _ bool) error { + committed = files + return nil + } + var notes []string + progress := func(_, _, msg string) { notes = append(notes, msg) } + cfg := withoutInferenceInputs(convergeCfgWithDefaults(m)) + if _, err := Converge(context.Background(), cfg, newTestClientFactory(fc), commitFn, progress); err != nil { + t.Fatalf("Converge() error: %v", err) + } + var shims []forge.TreeFile + for _, f := range committed { + if slices.Contains(GitHubForgeConfig().WorkflowPaths, f.Path) { + shims = append(shims, f) + } + } + if len(shims) != 1 { + t.Fatalf("committed %d shim files, want exactly 1", len(shims)) + } + if got := string(shims[0].Content); !strings.Contains(got, "pull_request_target:") { + t.Errorf("embedded templates must not replace the shim after a failed fetch:\n%s", got) + } + if ref := extractWorkflowRef(shims[0].Content, GitHubForgeConfig()); ref != "v2.0.0" { + t.Errorf("committed shim ref = %q, want v2.0.0", ref) + } + if !slices.ContainsFunc(notes, func(n string) bool { return strings.Contains(n, "delivering the pin upgrade only") }) { + t.Errorf("no progress note about the pin-only fallback; notes: %q", notes) + } +} + +func TestWithQueuedPin_NoPin(t *testing.T) { + full := []byte("uses: fullsend-ai/fullsend/.github/workflows/reusable-dispatch.yml@abc # v2.0.0\n") + if got := withQueuedPin(full, []byte("no pin here\n"), GitHubForgeConfig()); string(got) != string(full) { + t.Errorf("queued without a pin: got %q, want full unchanged", got) + } + if got := withQueuedPin(full, full, ForgeConfig{}); string(got) != string(full) { + t.Errorf("no ShimRefPattern: got %q, want full unchanged", got) + } + noGroup := ForgeConfig{ShimRefPattern: regexp.MustCompile(`@v[0-9.]+`)} + if got := withQueuedPin(full, []byte("x@v2.0.0\n"), noGroup); string(got) != string(full) { + t.Errorf("pattern without a capture group: got %q, want full unchanged", got) + } +} + +func TestWithoutRefPathRepairs(t *testing.T) { + tc := scaffold.PerRepoThinCallerPaths()[0] + files := []forge.TreeFile{{Path: ".github/workflows/fullsend.yaml"}, {Path: tc}, {Path: ".fullsend/config.yaml"}} + actions := []ComponentAction{ + {Component: ".github/workflows/fullsend.yaml", Action: "update"}, + {Component: tc, Action: "update"}, + {Component: ".fullsend/config.yaml", Action: "update"}, + {Component: "ref", Action: "upgrade"}, + } + skip := func(p string) bool { return p == ".github/workflows/fullsend.yaml" || p == tc } + gotFiles, gotActions := withoutRefPathRepairs(files, actions, skip) + if len(gotFiles) != 1 || gotFiles[0].Path != ".fullsend/config.yaml" { + t.Errorf("files = %+v, want only .fullsend/config.yaml", gotFiles) + } + if len(gotActions) != 2 || gotActions[0].Component != ".fullsend/config.yaml" || gotActions[1].Component != "ref" { + t.Errorf("actions = %+v", gotActions) + } +} + func TestConverge_SameRefNoCommit(t *testing.T) { repoNames := []string{"acme/api"} fc := newFakeClientForBatch(repoNames...)