From 961b7df3449130a8f2ea0afaef85083a2395556d Mon Sep 17 00:00:00 2001 From: Jose Armesto Date: Mon, 30 Nov 2026 11:47:41 +0100 Subject: [PATCH 1/3] fix(organizations): leave a content path without kustomization.yaml to Flux's generated kustomization An organization write in mode commit into a content path without a kustomization.yaml (an organization created in mode apply) created one with its own files only, and the organization's Kustomization then pruned agent-manager/ and every other file that Flux had generated the list from. The write no longer creates that file, also not in a dry run or a credential operation, so Flux keeps generating the list. Part of giantswarm/agent-manager#498. --- docs/organizations-commit-mode.md | 12 ++ internal/api/credential_operations_test.go | 2 + internal/api/organizations_commit_test.go | 107 ++++++++++++++++++ internal/organizations/commit.go | 47 ++++++-- .../credential_operations_commit.go | 9 +- 5 files changed, 166 insertions(+), 11 deletions(-) diff --git a/docs/organizations-commit-mode.md b/docs/organizations-commit-mode.md index 125ca16..4c63106 100644 --- a/docs/organizations-commit-mode.md +++ b/docs/organizations-commit-mode.md @@ -56,6 +56,18 @@ Secret. Commits, over MCP and REST, use the configured RFC 8693 manager App gran the content path, as for the first agent. The answer then names no Kustomization, and a delete asks for no step by hand: the organization's Kustomization prunes. A refused read of a Kustomization of another name stays an error. +- A content path can have no `kustomization.yaml`: git did not get it from + `create_organization` in mode commit, for example for an organization created in mode + apply. Flux then generates its kustomization from the files there, with `agent-manager/` + of the agent tools. An organization write in mode commit into such a content path does + not create a `kustomization.yaml` there, also when it only removes a file, and does not + list the content path in a `kustomization.yaml` above it. A dry run shows no such file + in `commit.files`. Flux continues to generate the list, with the agents and every + other file. A `kustomization.yaml` of the write's own objects would leave them out, + and the organization's Kustomization would prune them. The same applies to a content + path with a `kustomization.yml` or `Kustomization`: Kustomize refuses a directory with + two kustomization files. Where the content path has a `kustomization.yaml`, the write + lists its objects there, as before. - The admins are not a file of the content path: they are `spec.admins` of the organization's file, and agent-platform-operator binds them to `agent-platform:admin` in the organization namespace. diff --git a/internal/api/credential_operations_test.go b/internal/api/credential_operations_test.go index 05919c0..f79de1c 100644 --- a/internal/api/credential_operations_test.go +++ b/internal/api/credential_operations_test.go @@ -403,6 +403,8 @@ func TestCredentialOperationCommitsConsumerAndEncryptedSecretTogether(t *testing files := forge.Files(mcRepo, forge.PullRequests()[0].Head) require.Contains(t, files, paymentsPath+"/modelconfig-claude.yaml") require.Contains(t, string(files[paymentsPath+"/tenant-credential-claude-secret.enc.yaml"]), "ENC[AES256_GCM,") + _, created := files[contentKustomization] + require.False(t, created, "a content path without kustomization.yaml stays Flux's to generate") for _, raw := range files { require.NotContains(t, string(raw), "synthetic-credential") require.NotContains(t, string(raw), "c3ludGhldGljLWNyZWRlbnRpYWw=") diff --git a/internal/api/organizations_commit_test.go b/internal/api/organizations_commit_test.go index 4786f6c..30c266d 100644 --- a/internal/api/organizations_commit_test.go +++ b/internal/api/organizations_commit_test.go @@ -3,7 +3,9 @@ package api import ( "context" "errors" + "maps" "net/http" + "slices" "strings" "testing" @@ -22,6 +24,7 @@ import ( "github.com/giantswarm/agent-manager/internal/agents" "github.com/giantswarm/agent-manager/internal/organizations" + "github.com/giantswarm/agent-manager/internal/tags/tagstest" ) var mcRepo = commit.Repository{Owner: "giantswarm", Name: "gazelle-config"} @@ -1069,6 +1072,110 @@ func TestRemovingTheLastContentObjectKeepsTheContentPath(t *testing.T) { assert.Equal(t, "resources: []\n", string(head[paymentsPath+"/kustomization.yaml"])) } +// contentKustomization is the content path's own kustomization.yaml. +const contentKustomization = paymentsPath + "/kustomization.yaml" + +// commitFiles are the paths of the files a tool's answer names in +// commit.files. +func commitFiles(t *testing.T, text string) []string { + t.Helper() + var out []string + for _, file := range decode(t, text)["commit"].(map[string]any)["files"].([]any) { + out = append(out, file.(map[string]any)["path"].(string)) + } + return out +} + +// An organization that git did not get from create_organization in mode +// commit, one created in mode apply, has no kustomization.yaml in its content +// path: Flux generates one from the path's files, with agent-manager's +// directory of its first agent. An organization write in mode commit after +// that agent's merge creates no kustomization.yaml there, so Flux goes on +// building agent-manager's directory beside the new file; one of the write's +// own file alone would drop the agent (giantswarm/agent-manager#498). +func TestAnOrganizationWriteAfterItsFirstAgentKeepsTheAgent(t *testing.T) { + chartSource := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "source.toolkit.fluxcd.io/v1", "kind": "OCIRepository", + "metadata": map[string]any{"name": "agent", "namespace": orgNS}, + "spec": map[string]any{"interval": "30m", "url": agents.DefaultChartOCIURL, "ref": map[string]any{"semver": agents.DefaultChartSemver}}, + }} + f, fake := commitFixture(t, nil, ownModel(), chartSource) + svc := agents.New(f.provider, embeddedChart{}, nil, agents.InProcessPinner(pinner{}), agents.Config{ + DefaultNamespace: "kagent", Version: "test", Tags: tagstest.Rule(), Tenants: f.cfg.Namespaces, + OrganizationContent: f.orgs.ContentLocation, + GitHub: func(string) (agents.GitHubRemote, error) { return fake, nil }, + GitHubUser: f.cfg.Commit.User, + }, nil) + f.srv = NewMCPServer(svc, "test", WithOrganizations(f.orgs), WithLifecycle(t.Context())) + + text, isErr := f.call(t, ToolCreateAgent, map[string]any{"organization": "payments", "name": "sre", "modelConfig": "own", "toolset": []string{"preset:read-only"}, "mode": "commit"}) + require.False(t, isErr, text) + require.Len(t, fake.PullRequests(), 1) + require.NoError(t, fake.Merge(t.Context(), fake.PullRequests()[0].PullRequest)) + + merged := fake.Files(mcRepo, "main") + require.Contains(t, slices.Collect(maps.Keys(merged)), paymentsPath+"/agent-manager/kustomization.yaml") + require.NotContains(t, slices.Collect(maps.Keys(merged)), contentKustomization, "Flux generates the content path's kustomization") + + text, isErr = f.call(t, ToolSetOrganizationEgress, map[string]any{"organization": "payments", "name": "github", "destinations": []any{map[string]any{"origin": "https://api.github.com"}}, "mode": "commit"}) + require.False(t, isErr, text) + require.Len(t, fake.PullRequests(), 2) + assert.NotContains(t, commitFiles(t, text), contentKustomization) + head := fake.Files(mcRepo, fake.PullRequests()[1].Head) + assert.NotContains(t, slices.Collect(maps.Keys(head)), contentKustomization, "Flux goes on generating the content path's kustomization") + assert.Contains(t, slices.Collect(maps.Keys(head)), paymentsPath+"/egresspolicy-github.yaml") + for p, content := range merged { + if strings.HasPrefix(p, paymentsPath+"/agent-manager/") { + assert.Equal(t, string(content), string(head[p]), "the agent stays as merged") + } + } +} + +// A content path without a kustomization.yaml whose agent an older +// agent-manager merged: every organization write in mode commit leaves it to +// Flux's generated kustomization. A dry run names no content-path +// kustomization.yaml, a write that only removes a file creates none, and a +// content path with a kustomization.yml gets no second kustomization file, +// which Kustomize refuses. +func TestOrganizationWritesLeaveAContentPathWithoutKustomizationToFlux(t *testing.T) { + claude := model("claude", true) + claude.SetLabels(fromGitLabels(orgNS)) + claudeFile := model("claude", true) + claudeFile.SetNamespace("") + claudeYAML, err := yaml.Marshal(claudeFile.Object) + require.NoError(t, err) + agent := []byte("apiVersion: helm.toolkit.fluxcd.io/v2\nkind: HelmRelease\nmetadata:\n name: sre\n") + egress := map[string]any{"organization": "payments", "name": "github", "destinations": []any{map[string]any{"origin": "https://api.github.com"}}, "mode": "commit"} + for _, tc := range []struct { + name string + more map[string][]byte + tool string + args map[string]any + }{ + {"a dry run", nil, ToolSetOrganizationEgress, map[string]any{"organization": "payments", "name": "github", "destinations": egress["destinations"], "mode": "commit", "dryRun": true}}, + {"a write that only removes a file", nil, ToolDeleteOrganizationObject, map[string]any{"organization": "payments", "kind": "model", "name": "claude", "mode": "commit"}}, + {"a content path with a kustomization.yml", map[string][]byte{paymentsPath + "/kustomization.yml": []byte("resources:\n - agent-manager\n - modelconfig-claude.yaml\n")}, ToolSetOrganizationEgress, egress}, + } { + t.Run(tc.name, func(t *testing.T) { + base := map[string][]byte{ + paymentsPath + "/agent-manager/kustomization.yaml": []byte("resources:\n - sre.yaml\n"), + paymentsPath + "/agent-manager/sre.yaml": agent, + paymentsPath + "/modelconfig-claude.yaml": claudeYAML, + } + maps.Copy(base, tc.more) + f, fake := commitFixture(t, base, claude.DeepCopy()) + text, isErr := f.call(t, tc.tool, tc.args) + require.False(t, isErr, text) + assert.NotContains(t, commitFiles(t, text), contentKustomization) + for _, pr := range fake.PullRequests() { + head := fake.Files(mcRepo, pr.Head) + assert.NotContains(t, slices.Collect(maps.Keys(head)), contentKustomization) + assert.Equal(t, agent, head[paymentsPath+"/agent-manager/sre.yaml"]) + } + }) + } +} + // A .sops.yaml rule that makes a plain object's file secret is refused: // gitops-commit would encrypt the file once and never update it. func TestAPlainFileTheRepositoryWouldEncryptIsRefused(t *testing.T) { diff --git a/internal/organizations/commit.go b/internal/organizations/commit.go index 56d5ac7..6424239 100644 --- a/internal/organizations/commit.go +++ b/internal/organizations/commit.go @@ -317,10 +317,12 @@ type fileChange struct { // add are files added beside layout.Build, which takes object files // only: the empty kustomization.yaml of a new content path. add map[string][]byte - // keep keeps the directory's own kustomization.yaml, with an empty - // list, when its last object goes: a Flux Kustomization builds the - // directory, and would fail on a path that does not exist. - keep bool + // content marks an organization's content path. Its own + // kustomization.yaml stays, with an empty list, when its last object + // goes: a Flux Kustomization builds the directory, and would fail on a + // path that does not exist. A content path without one is left to Flux's + // generated kustomization (leaveToFlux). + content bool // objects marks the objects path: it is kept, and the kustomization // above it, outside the objects path, is never changed. objects bool @@ -347,21 +349,25 @@ func (c *orgCommit) open(ctx context.Context, changes []fileChange, object, titl if err != nil { return nil, commitError(c.gh, err) } - for _, f := range plan.Files { + change = plan.Change() + files := plan.Files + if ch.content { + files = leaveToFlux(ch.dir, &change, files) + } + for _, f := range files { file := agents.CommitFile{Path: f.Path, Action: string(f.Action)} if dryRun { file.Content = string(f.Content) } out.Files = append(out.Files, file) } - change = plan.Change() } if ch.objects { above := path.Join(ch.dir.Directory, layout.KustomizationFile) delete(change.Files, above) out.Files = slices.DeleteFunc(out.Files, func(f agents.CommitFile) bool { return f.Path == above }) } - if ch.keep || ch.objects { + if ch.content || ch.objects { if err := c.keepKustomization(ctx, ch.dir, &change, out, dryRun); err != nil { return nil, err } @@ -467,6 +473,31 @@ func (c *orgCommit) keepKustomization(ctx context.Context, dir layout.Directory, return nil } +// leaveToFlux takes out of change, the plan layout.Build made for dir, an +// organization's content path, the content path's kustomization.yaml that +// the plan creates, and returns files, the plan's files, without it. Without +// a kustomization.yaml on the base branch, Flux generates the content path's +// kustomization from its files: agent-manager's directory of the agent tools +// and every other file (giantswarm/agent-manager#498). A kustomization.yaml +// of the write's own files would leave them out, and the organization's +// Kustomization would prune them. The same holds for a content path with a +// kustomization.yml or Kustomization, where a second kustomization file +// would break the build. Build decides the directory's kustomization.yaml on +// every write, so a plan that does not create it either changes the one the +// base carries, which stays as planned, or finds none and writes none. With +// no kustomization.yaml in the content path, the kustomization above it does +// not list the directory either. +func leaveToFlux(dir layout.Directory, change *commit.Change, files []layout.File) []layout.File { + own := path.Join(dir.Path(), layout.KustomizationFile) + if i := slices.IndexFunc(files, func(f layout.File) bool { return f.Path == own }); i >= 0 && files[i].Action != layout.Add { + return files + } + above := path.Join(dir.Directory, layout.KustomizationFile) + delete(change.Files, own) + delete(change.Files, above) + return slices.DeleteFunc(slices.Clone(files), func(f layout.File) bool { return f.Path == own || f.Path == above }) +} + // land is commit.Open for the one repository and base of c, with the files // creates must still be absent from the base once the branch is cut: a file // another commit added to the base after the plan was decided, and so before @@ -823,7 +854,7 @@ func (w *contentWriter) land(ctx context.Context, s *Service, writes []write, dr if err != nil { return nil, err } - ch := fileChange{dir: w.dir, write: map[string][]byte{}, keep: w.org.Scope != scopePlatform} + ch := fileChange{dir: w.dir, write: map[string][]byte{}, content: w.org.Scope != scopePlatform} for _, wr := range writes { if err := segment(wr.kind+" name", wr.name); err != nil { return nil, err diff --git a/internal/organizations/credential_operations_commit.go b/internal/organizations/credential_operations_commit.go index 818a39a..563c693 100644 --- a/internal/organizations/credential_operations_commit.go +++ b/internal/organizations/credential_operations_commit.go @@ -165,7 +165,7 @@ func (s *Service) prepareCredentialCommit(ctx context.Context, operation *creden if !maps.Equal(current, operation.GitFiles) { return nil, gitInputsChanged{fmt.Errorf("%w: Git files or encryption policy changed; prepare the credential operation again", agents.ErrConflict)} } - change := fileChange{dir: writer.dir, write: map[string][]byte{}} + change := fileChange{dir: writer.dir, write: map[string][]byte{}, content: writer.org.Scope != scopePlatform} isSecret, err := writer.commit.secretFiles(ctx) if err != nil { return nil, err @@ -194,7 +194,10 @@ func (s *Service) prepareCredentialCommit(ctx context.Context, operation *creden if err != nil { return nil, commitError(writer.commit.gh, err) } - landed := plan.Change() + landed, files := plan.Change(), plan.Files + if change.content { + files = leaveToFlux(change.dir, &landed, files) + } for _, credential := range operation.Credentials { file := contentFile(writer.dir, kindSecret, credential.Secret) var encrypted struct { @@ -211,7 +214,7 @@ func (s *Service) prepareCredentialCommit(ctx context.Context, operation *creden } prepared := &credentialCommit{files: landed.Files, written: map[string]string{}} prepared.result = &CommitResult{Repository: writer.commit.cfg.Objects.Repository.String(), Base: writer.commit.cfg.Objects.Branch, Branch: "agent-manager/credential-" + operation.ElicitationID, Author: writer.commit.gh.Login, Review: reviewNote, Files: []agents.CommitFile{}} - for _, file := range plan.Files { + for _, file := range files { prepared.result.Files = append(prepared.result.Files, agents.CommitFile{Path: file.Path, Action: string(file.Action)}) if raw, ok := landed.Files[file.Path]; ok { prepared.written[file.Path] = fileDigest(raw) From 1da70bda4d642a67adee43ffbbc01b4b2b1f6dd1 Mon Sep 17 00:00:00 2001 From: Jose Armesto Date: Mon, 30 Nov 2026 12:02:33 +0100 Subject: [PATCH 2/3] fix(organizations): keep a generated content path that a removal empties A removal of the last file of a content path without kustomization.yaml writes the file with resources: [], so the path stays and Flux prunes. Test the kustomization above the content path, and say in the docs that a kustomization.yml gets no entry. --- docs/organizations-commit-mode.md | 12 +++-- internal/api/organizations_commit_test.go | 31 +++++++++--- internal/organizations/commit.go | 47 ++++++++++++++----- .../credential_operations_commit.go | 4 +- 4 files changed, 71 insertions(+), 23 deletions(-) diff --git a/docs/organizations-commit-mode.md b/docs/organizations-commit-mode.md index 4c63106..a8f77ec 100644 --- a/docs/organizations-commit-mode.md +++ b/docs/organizations-commit-mode.md @@ -64,10 +64,14 @@ Secret. Commits, over MCP and REST, use the configured RFC 8693 manager App gran list the content path in a `kustomization.yaml` above it. A dry run shows no such file in `commit.files`. Flux continues to generate the list, with the agents and every other file. A `kustomization.yaml` of the write's own objects would leave them out, - and the organization's Kustomization would prune them. The same applies to a content - path with a `kustomization.yml` or `Kustomization`: Kustomize refuses a directory with - two kustomization files. Where the content path has a `kustomization.yaml`, the write - lists its objects there, as before. + and the organization's Kustomization would prune them. Only a write that removes the + last file of the content path writes its `kustomization.yaml`, with `resources: []`: + git keeps no empty directory, and the organization's Kustomization would fail on a + path that does not exist and prune nothing. A content path with a `kustomization.yml` + or `Kustomization` also gets no `kustomization.yaml`, because Kustomize refuses a + directory with two kustomization files; but no write lists its objects in that file, + so Flux does not apply them. Where the content path has a `kustomization.yaml`, the + write lists its objects there, as before. - The admins are not a file of the content path: they are `spec.admins` of the organization's file, and agent-platform-operator binds them to `agent-platform:admin` in the organization namespace. diff --git a/internal/api/organizations_commit_test.go b/internal/api/organizations_commit_test.go index 30c266d..e7ba39e 100644 --- a/internal/api/organizations_commit_test.go +++ b/internal/api/organizations_commit_test.go @@ -3,6 +3,7 @@ package api import ( "context" "errors" + "fmt" "maps" "net/http" "slices" @@ -1046,8 +1047,18 @@ func TestEveryContentToolCommits(t *testing.T) { // The removal of the last object of an organization's content path keeps // its kustomization.yaml, with an empty list: the organization's -// Kustomization builds that path, and would fail on one that does not exist. +// Kustomization builds that path, and would fail on one that does not exist, +// pruning nothing. A content path whose kustomization Flux generates gets +// that file for the same reason: git keeps no empty directory. func TestRemovingTheLastContentObjectKeepsTheContentPath(t *testing.T) { + for _, generated := range []bool{false, true} { + t.Run(fmt.Sprintf("generated=%v", generated), func(t *testing.T) { + testRemovingTheLastContentObject(t, generated) + }) + } +} + +func testRemovingTheLastContentObject(t *testing.T, generated bool) { editors := &unstructured.Unstructured{Object: map[string]any{ "apiVersion": "rbac.authorization.k8s.io/v1", "kind": "RoleBinding", "metadata": map[string]any{"name": "organization-editors"}, @@ -1059,10 +1070,11 @@ func TestRemovingTheLastContentObjectKeepsTheContentPath(t *testing.T) { live := editors.DeepCopy() live.SetNamespace(orgNS) live.SetLabels(fromGitLabels("agents-payments-x7k2q")) - f, fake := commitFixture(t, map[string][]byte{ - paymentsPath + "/kustomization.yaml": []byte("resources:\n - rolebinding-organization-editors.yaml\n"), - paymentsPath + "/rolebinding-organization-editors.yaml": file, - }, live) + base := map[string][]byte{paymentsPath + "/rolebinding-organization-editors.yaml": file} + if !generated { + base[contentKustomization] = []byte("resources:\n - rolebinding-organization-editors.yaml\n") + } + f, fake := commitFixture(t, base, live) text, isErr := f.call(t, ToolRemoveOrganizationMember, map[string]any{"organization": "payments", "group": "payments-team", "mode": "commit"}) require.False(t, isErr, text) @@ -1134,10 +1146,12 @@ func TestAnOrganizationWriteAfterItsFirstAgentKeepsTheAgent(t *testing.T) { // A content path without a kustomization.yaml whose agent an older // agent-manager merged: every organization write in mode commit leaves it to // Flux's generated kustomization. A dry run names no content-path -// kustomization.yaml, a write that only removes a file creates none, and a +// kustomization.yaml, a write that only removes a file creates none, a // content path with a kustomization.yml gets no second kustomization file, -// which Kustomize refuses. +// which Kustomize refuses, and a kustomization above the content path does +// not list it, nor loses its entry. func TestOrganizationWritesLeaveAContentPathWithoutKustomizationToFlux(t *testing.T) { + const above = "agent-platform/organizations/kustomization.yaml" claude := model("claude", true) claude.SetLabels(fromGitLabels(orgNS)) claudeFile := model("claude", true) @@ -1155,6 +1169,8 @@ func TestOrganizationWritesLeaveAContentPathWithoutKustomizationToFlux(t *testin {"a dry run", nil, ToolSetOrganizationEgress, map[string]any{"organization": "payments", "name": "github", "destinations": egress["destinations"], "mode": "commit", "dryRun": true}}, {"a write that only removes a file", nil, ToolDeleteOrganizationObject, map[string]any{"organization": "payments", "kind": "model", "name": "claude", "mode": "commit"}}, {"a content path with a kustomization.yml", map[string][]byte{paymentsPath + "/kustomization.yml": []byte("resources:\n - agent-manager\n - modelconfig-claude.yaml\n")}, ToolSetOrganizationEgress, egress}, + {"a kustomization above that does not list it", map[string][]byte{above: []byte("resources:\n - billing\n")}, ToolSetOrganizationEgress, egress}, + {"a removal under a kustomization above that lists it", map[string][]byte{above: []byte("resources:\n - payments\n")}, ToolDeleteOrganizationObject, map[string]any{"organization": "payments", "kind": "model", "name": "claude", "mode": "commit"}}, } { t.Run(tc.name, func(t *testing.T) { base := map[string][]byte{ @@ -1171,6 +1187,7 @@ func TestOrganizationWritesLeaveAContentPathWithoutKustomizationToFlux(t *testin head := fake.Files(mcRepo, pr.Head) assert.NotContains(t, slices.Collect(maps.Keys(head)), contentKustomization) assert.Equal(t, agent, head[paymentsPath+"/agent-manager/sre.yaml"]) + assert.Equal(t, string(base[above]), string(head[above]), "the kustomization above the content path stays") } }) } diff --git a/internal/organizations/commit.go b/internal/organizations/commit.go index 6424239..4cfc3a8 100644 --- a/internal/organizations/commit.go +++ b/internal/organizations/commit.go @@ -352,7 +352,9 @@ func (c *orgCommit) open(ctx context.Context, changes []fileChange, object, titl change = plan.Change() files := plan.Files if ch.content { - files = leaveToFlux(ch.dir, &change, files) + if files, err = c.leaveToFlux(ctx, ch.dir, &change, files); err != nil { + return nil, err + } } for _, f := range files { file := agents.CommitFile{Path: f.Path, Action: string(f.Action)} @@ -480,22 +482,45 @@ func (c *orgCommit) keepKustomization(ctx context.Context, dir layout.Directory, // kustomization from its files: agent-manager's directory of the agent tools // and every other file (giantswarm/agent-manager#498). A kustomization.yaml // of the write's own files would leave them out, and the organization's -// Kustomization would prune them. The same holds for a content path with a -// kustomization.yml or Kustomization, where a second kustomization file -// would break the build. Build decides the directory's kustomization.yaml on -// every write, so a plan that does not create it either changes the one the -// base carries, which stays as planned, or finds none and writes none. With -// no kustomization.yaml in the content path, the kustomization above it does -// not list the directory either. -func leaveToFlux(dir layout.Directory, change *commit.Change, files []layout.File) []layout.File { +// Kustomization would prune them. A content path with a kustomization.yml +// or Kustomization gets no second kustomization file either, which Kustomize +// refuses. Build decides the directory's kustomization.yaml on every write, +// so a plan that does not create it either changes the one the base carries, +// which stays as planned, or finds none and writes none. With no +// kustomization.yaml in the content path, the kustomization above it does +// not list the directory either. A write that removes the content path's last +// file writes its kustomization.yaml with an empty list instead: git keeps no +// empty directory, and the organization's Kustomization, which builds the +// path, would fail on a path that does not exist and prune nothing. +func (c *orgCommit) leaveToFlux(ctx context.Context, dir layout.Directory, change *commit.Change, files []layout.File) ([]layout.File, error) { own := path.Join(dir.Path(), layout.KustomizationFile) if i := slices.IndexFunc(files, func(f layout.File) bool { return f.Path == own }); i >= 0 && files[i].Action != layout.Add { - return files + return files, nil } above := path.Join(dir.Directory, layout.KustomizationFile) delete(change.Files, own) delete(change.Files, above) - return slices.DeleteFunc(slices.Clone(files), func(f layout.File) bool { return f.Path == own || f.Path == above }) + files = slices.DeleteFunc(slices.Clone(files), func(f layout.File) bool { return f.Path == own || f.Path == above }) + if !slices.ContainsFunc(files, func(f layout.File) bool { return f.Action == layout.Remove }) { + return files, nil + } + left, err := c.list(ctx, dir.Path()) + if err != nil { + return nil, err + } + for p, content := range change.Files { + if content != nil && strings.HasPrefix(p, dir.Path()+"/") { + return files, nil + } + } + for _, p := range left { + if content, changed := change.Files[p]; !changed || content != nil { + return files, nil + } + } + empty := []byte("resources: []\n") + change.Files[own] = empty + return append(files, layout.File{Path: own, Action: layout.Add, Content: empty}), nil } // land is commit.Open for the one repository and base of c, with the files diff --git a/internal/organizations/credential_operations_commit.go b/internal/organizations/credential_operations_commit.go index 563c693..c529287 100644 --- a/internal/organizations/credential_operations_commit.go +++ b/internal/organizations/credential_operations_commit.go @@ -196,7 +196,9 @@ func (s *Service) prepareCredentialCommit(ctx context.Context, operation *creden } landed, files := plan.Change(), plan.Files if change.content { - files = leaveToFlux(change.dir, &landed, files) + if files, err = writer.commit.leaveToFlux(ctx, change.dir, &landed, files); err != nil { + return nil, err + } } for _, credential := range operation.Credentials { file := contentFile(writer.dir, kindSecret, credential.Secret) From cd2f02d8a8219060b1df0e0a7808bf1dda9fa1be Mon Sep 17 00:00:00 2001 From: Jose Armesto Date: Mon, 30 Nov 2026 12:13:30 +0100 Subject: [PATCH 3/3] fix(organizations): keep an emptied generated content path with a .gitkeep A removal into a content path without kustomization.yaml adds a .gitkeep when git lacks it, instead of listing the path and writing resources: []. Flux keeps generating the list, so an agent merged in parallel or a submodule stays, and the path never disappears. --- docs/organizations-commit-mode.md | 10 +++-- internal/api/organizations_commit_test.go | 55 ++++++++++++++++------- internal/organizations/commit.go | 38 ++++++++-------- 3 files changed, 62 insertions(+), 41 deletions(-) diff --git a/docs/organizations-commit-mode.md b/docs/organizations-commit-mode.md index a8f77ec..c1c0455 100644 --- a/docs/organizations-commit-mode.md +++ b/docs/organizations-commit-mode.md @@ -64,10 +64,12 @@ Secret. Commits, over MCP and REST, use the configured RFC 8693 manager App gran list the content path in a `kustomization.yaml` above it. A dry run shows no such file in `commit.files`. Flux continues to generate the list, with the agents and every other file. A `kustomization.yaml` of the write's own objects would leave them out, - and the organization's Kustomization would prune them. Only a write that removes the - last file of the content path writes its `kustomization.yaml`, with `resources: []`: - git keeps no empty directory, and the organization's Kustomization would fail on a - path that does not exist and prune nothing. A content path with a `kustomization.yml` + and the organization's Kustomization would prune them. A write that removes a file + adds `//.gitkeep` when git does not have it: git keeps no empty + directory, and the organization's Kustomization would fail on a path that does not + exist and prune nothing. Flux's generator lists YAML files only, so the `.gitkeep` + changes nothing that Flux applies, and a delete of the organization removes it with the + rest of the content path. A content path with a `kustomization.yml` or `Kustomization` also gets no `kustomization.yaml`, because Kustomize refuses a directory with two kustomization files; but no write lists its objects in that file, so Flux does not apply them. Where the content path has a `kustomization.yaml`, the diff --git a/internal/api/organizations_commit_test.go b/internal/api/organizations_commit_test.go index e7ba39e..1be2032 100644 --- a/internal/api/organizations_commit_test.go +++ b/internal/api/organizations_commit_test.go @@ -3,7 +3,6 @@ package api import ( "context" "errors" - "fmt" "maps" "net/http" "slices" @@ -228,11 +227,13 @@ func gitOrganizationWith(t *testing.T, wrap func(*commit.Fake) organizations.Git } // Delete in commit mode, two steps: the pull request removes the object's -// file and the whole content path and the live object is marked with it; a -// live delete is refused while the file is in git; after the merge, which -// removed the file, Erase now marks the delete intent and deletes. +// file and the whole content path, its .gitkeep too, and the live object is +// marked with it; a live delete is refused while the file is in git; after +// the merge, which removed the file, Erase now marks the delete intent and +// deletes. func TestDeleteOrganizationInCommitModeTakesTwoSteps(t *testing.T) { f, fake := gitOrganization(t) + require.NoError(t, fake.Commit(t.Context(), mcRepo, "main", "keep the path", map[string][]byte{paymentsPath + "/.gitkeep": []byte("\n")})) del := func(confirm string) (string, bool) { args := map[string]any{"name": "payments", "mode": "commit"} if confirm != "" { @@ -1046,19 +1047,29 @@ func TestEveryContentToolCommits(t *testing.T) { } // The removal of the last object of an organization's content path keeps -// its kustomization.yaml, with an empty list: the organization's -// Kustomization builds that path, and would fail on one that does not exist, -// pruning nothing. A content path whose kustomization Flux generates gets -// that file for the same reason: git keeps no empty directory. +// the path: the organization's Kustomization builds it, and would fail on one +// that does not exist, pruning nothing. A content path with a +// kustomization.yaml keeps it, with an empty list. One whose kustomization +// Flux generates gets a .gitkeep, since git keeps no empty directory, and no +// kustomization file; a .gitkeep that git carries already is not written +// again. func TestRemovingTheLastContentObjectKeepsTheContentPath(t *testing.T) { - for _, generated := range []bool{false, true} { - t.Run(fmt.Sprintf("generated=%v", generated), func(t *testing.T) { - testRemovingTheLastContentObject(t, generated) + for _, tc := range []struct { + name string + base map[string][]byte + marker bool + }{ + {"with a kustomization.yaml", map[string][]byte{contentKustomization: []byte("resources:\n - rolebinding-organization-editors.yaml\n")}, false}, + {"generated by Flux", nil, true}, + {"generated by Flux, with a .gitkeep", map[string][]byte{paymentsPath + "/.gitkeep": []byte("\n")}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + testRemovingTheLastContentObject(t, tc.base, tc.marker) }) } } -func testRemovingTheLastContentObject(t *testing.T, generated bool) { +func testRemovingTheLastContentObject(t *testing.T, more map[string][]byte, marker bool) { editors := &unstructured.Unstructured{Object: map[string]any{ "apiVersion": "rbac.authorization.k8s.io/v1", "kind": "RoleBinding", "metadata": map[string]any{"name": "organization-editors"}, @@ -1071,17 +1082,27 @@ func testRemovingTheLastContentObject(t *testing.T, generated bool) { live.SetNamespace(orgNS) live.SetLabels(fromGitLabels("agents-payments-x7k2q")) base := map[string][]byte{paymentsPath + "/rolebinding-organization-editors.yaml": file} - if !generated { - base[contentKustomization] = []byte("resources:\n - rolebinding-organization-editors.yaml\n") - } + maps.Copy(base, more) f, fake := commitFixture(t, base, live) text, isErr := f.call(t, ToolRemoveOrganizationMember, map[string]any{"organization": "payments", "group": "payments-team", "mode": "commit"}) require.False(t, isErr, text) require.Len(t, fake.PullRequests(), 1) head := fake.Files(mcRepo, fake.PullRequests()[0].Head) - assert.NotContains(t, head, paymentsPath+"/rolebinding-organization-editors.yaml") - assert.Equal(t, "resources: []\n", string(head[paymentsPath+"/kustomization.yaml"])) + var left []string + for p := range head { + if strings.HasPrefix(p, paymentsPath+"/") { + left = append(left, p) + } + } + slices.Sort(left) + if _, kept := more[contentKustomization]; kept { + assert.Equal(t, []string{contentKustomization}, left) + assert.Equal(t, "resources: []\n", string(head[contentKustomization])) + return + } + assert.Equal(t, []string{paymentsPath + "/.gitkeep"}, left, "the path stays with no kustomization file") + assert.Equal(t, marker, slices.Contains(commitFiles(t, text), paymentsPath+"/.gitkeep"), "the .gitkeep is written only when git lacks it") } // contentKustomization is the content path's own kustomization.yaml. diff --git a/internal/organizations/commit.go b/internal/organizations/commit.go index 4cfc3a8..697219f 100644 --- a/internal/organizations/commit.go +++ b/internal/organizations/commit.go @@ -488,10 +488,12 @@ func (c *orgCommit) keepKustomization(ctx context.Context, dir layout.Directory, // so a plan that does not create it either changes the one the base carries, // which stays as planned, or finds none and writes none. With no // kustomization.yaml in the content path, the kustomization above it does -// not list the directory either. A write that removes the content path's last -// file writes its kustomization.yaml with an empty list instead: git keeps no -// empty directory, and the organization's Kustomization, which builds the -// path, would fail on a path that does not exist and prune nothing. +// not list the directory either. A write that removes a file adds the +// content path's keepFile when the base has none: git keeps no empty +// directory, and the organization's Kustomization, which builds the path, +// would fail on a path that does not exist and prune nothing. Flux's +// generator lists YAML files only, so the marker changes nothing of what it +// builds. func (c *orgCommit) leaveToFlux(ctx context.Context, dir layout.Directory, change *commit.Change, files []layout.File) ([]layout.File, error) { own := path.Join(dir.Path(), layout.KustomizationFile) if i := slices.IndexFunc(files, func(f layout.File) bool { return f.Path == own }); i >= 0 && files[i].Action != layout.Add { @@ -504,25 +506,21 @@ func (c *orgCommit) leaveToFlux(ctx context.Context, dir layout.Directory, chang if !slices.ContainsFunc(files, func(f layout.File) bool { return f.Action == layout.Remove }) { return files, nil } - left, err := c.list(ctx, dir.Path()) - if err != nil { - return nil, err + marker := path.Join(dir.Path(), keepFile) + if has, err := c.exists(ctx, marker); err != nil || has { + return files, err } - for p, content := range change.Files { - if content != nil && strings.HasPrefix(p, dir.Path()+"/") { - return files, nil - } - } - for _, p := range left { - if content, changed := change.Files[p]; !changed || content != nil { - return files, nil - } - } - empty := []byte("resources: []\n") - change.Files[own] = empty - return append(files, layout.File{Path: own, Action: layout.Add, Content: empty}), nil + change.Files[marker] = keepContent + return append(files, layout.File{Path: marker, Action: layout.Add, Content: keepContent}), nil } +// keepFile keeps a content path without kustomization.yaml in git when a +// write removes its last file (leaveToFlux). +const keepFile = ".gitkeep" + +// keepContent says why keepFile is there. +var keepContent = []byte("# Keeps this organization's content path in git when it has no other file: Flux generates its kustomization and prunes what left it.\n") + // land is commit.Open for the one repository and base of c, with the files // creates must still be absent from the base once the branch is cut: a file // another commit added to the base after the plan was decided, and so before