From 4e53436211f7ab9ff46da85a938a5783a133a9a3 Mon Sep 17 00:00:00 2001 From: Nathan Kester Date: Mon, 16 Nov 2026 12:55:23 -0700 Subject: [PATCH 1/2] AIC-3901 part 1: read and write variation ownership rules Co-Authored-By: Claude Opus 5.5 --- internal/sync/api/errors.go | 31 ++++- internal/sync/api/settings.go | 41 ++++-- internal/sync/api/settings_test.go | 25 ++++ internal/sync/api/settings_write.go | 64 +++++++++ internal/sync/api/settings_write_test.go | 163 +++++++++++++++++++++++ internal/sync/error.go | 15 +++ internal/sync/interactive/settings.go | 77 +++++++++++ internal/sync/ownership.go | 38 ++++++ internal/sync/ownership_test.go | 55 ++++++++ internal/sync/resource.go | 18 +++ 10 files changed, 512 insertions(+), 15 deletions(-) create mode 100644 internal/sync/api/settings_write.go create mode 100644 internal/sync/api/settings_write_test.go create mode 100644 internal/sync/interactive/settings.go create mode 100644 internal/sync/ownership.go create mode 100644 internal/sync/ownership_test.go diff --git a/internal/sync/api/errors.go b/internal/sync/api/errors.go index 8b937c2d3..bdf5f85e5 100644 --- a/internal/sync/api/errors.go +++ b/internal/sync/api/errors.go @@ -81,14 +81,35 @@ func responseStatusCode(err error) (int, bool) { return int(status), ok && status != 0 } -// responseError finds the JSON response body in an error chain. The resources +// responseError finds the JSON response body in an error tree. The resources // client reports an API failure as an error whose text is the response body. func responseError(err error) (map[string]any, bool) { - for current := err; current != nil; current = errors.Unwrap(current) { - var response map[string]any - if json.Unmarshal([]byte(current.Error()), &response) == nil && len(response) != 0 { - return response, true + if err == nil { + return nil, false + } + var response map[string]any + if json.Unmarshal([]byte(err.Error()), &response) == nil && len(response) != 0 { + return response, true + } + switch wrapped := err.(type) { + case interface{ Unwrap() error }: + return responseError(wrapped.Unwrap()) + case interface{ Unwrap() []error }: + for _, inner := range wrapped.Unwrap() { + if response, ok := responseError(inner); ok { + return response, true + } } } return nil, false } + +// ErrSyncSettingsForbidden marks a sync settings write the caller's role does +// not allow. +var ErrSyncSettingsForbidden = errors.New("sync settings write forbidden") + +// IsForbidden reports whether a LaunchDarkly API error has a 403 status. +func IsForbidden(err error) bool { + status, ok := responseStatusCode(err) + return ok && status == http.StatusForbidden +} diff --git a/internal/sync/api/settings.go b/internal/sync/api/settings.go index 773e78ef0..dc2fc28fa 100644 --- a/internal/sync/api/settings.go +++ b/internal/sync/api/settings.go @@ -19,6 +19,9 @@ type resolvedSetting struct { ResourceKind syncdomain.Kind `json:"resourceKind"` ResourceLookupKey string `json:"resourceLookupKey"` Direction syncdomain.SyncDirection `json:"direction"` + // MatchedResourcePattern is the stored rule pattern that produced the + // direction. It is absent or empty when no rule matched. + MatchedResourcePattern string `json:"matchedResourcePattern,omitempty"` } // SyncDirections returns the effective LaunchDarkly setting for each @@ -28,8 +31,26 @@ func (client Client) SyncDirections( projectKey string, ids []syncdomain.ResourceID, ) (map[syncdomain.ResourceID]syncdomain.SyncDirection, error) { + ownership, err := client.ResolveOwnership(projectKey, ids) + if err != nil { + return nil, err + } + result := make(map[syncdomain.ResourceID]syncdomain.SyncDirection, len(ownership)) + for id, owner := range ownership { + result[id] = owner.Direction + } + return result, nil +} + +// ResolveOwnership returns the effective LaunchDarkly setting of each +// resource and the stored rule pattern that matched it. A resource of a kind +// that LaunchDarkly has no setting for is left out. +func (client Client) ResolveOwnership( + projectKey string, + ids []syncdomain.ResourceID, +) (map[syncdomain.ResourceID]syncdomain.Ownership, error) { if len(ids) == 0 { - return map[syncdomain.ResourceID]syncdomain.SyncDirection{}, nil + return map[syncdomain.ResourceID]syncdomain.Ownership{}, nil } if len(ids) > 100 { return nil, fmt.Errorf("read sync settings: at most 100 resources are allowed") @@ -41,31 +62,31 @@ func (client Client) SyncDirections( } byKind[id.Kind] = append(byKind[id.Kind], id) } - result := make(map[syncdomain.ResourceID]syncdomain.SyncDirection, len(ids)) + result := make(map[syncdomain.ResourceID]syncdomain.Ownership, len(ids)) // The endpoint rejects a request that names a kind it has no setting for, // and the rejection fails every resource of the request. Each kind travels // alone, so a tool or a skill cannot take the variations down with it. for _, kind := range slices.Sorted(maps.Keys(byKind)) { - directions, err := client.syncDirectionsOfKind(projectKey, byKind[kind]) + ownership, err := client.ownershipOfKind(projectKey, byKind[kind]) if err != nil { return nil, err } - maps.Copy(result, directions) + maps.Copy(result, ownership) } return result, nil } -// syncDirectionsOfKind reads the settings of resources of one kind. A kind -// that LaunchDarkly rejects as unsupported has no settings. -func (client Client) syncDirectionsOfKind( +// ownershipOfKind reads the settings of resources of one kind. A kind that +// LaunchDarkly rejects as unsupported has no settings. +func (client Client) ownershipOfKind( projectKey string, ids []syncdomain.ResourceID, -) (map[syncdomain.ResourceID]syncdomain.SyncDirection, error) { +) (map[syncdomain.ResourceID]syncdomain.Ownership, error) { query := url.Values{} for _, id := range ids { query.Add("resources", string(id.Kind)+":"+id.LookupKey) } - result := make(map[syncdomain.ResourceID]syncdomain.SyncDirection, len(ids)) + result := make(map[syncdomain.ResourceID]syncdomain.Ownership, len(ids)) // The endpoint pages its items. Read every page, so that a batch of more // than one page of resources does not look like missing settings. for offset := 0; ; { @@ -87,7 +108,7 @@ func (client Client) syncDirectionsOfKind( "Configure a supported sync setting in LaunchDarkly.", ).WithResource(id) } - result[id] = item.Direction + result[id] = syncdomain.Ownership{Direction: item.Direction, MatchedPattern: item.MatchedResourcePattern} } offset += len(page.Items) // The total count ends the paging when the response has one. Without diff --git a/internal/sync/api/settings_test.go b/internal/sync/api/settings_test.go index eb5a655f4..a2fe5a86a 100644 --- a/internal/sync/api/settings_test.go +++ b/internal/sync/api/settings_test.go @@ -130,3 +130,28 @@ func TestSyncDirectionsPagesWithoutATotalCount(t *testing.T) { require.Len(t, transport.Requests, 2, "a full page without a total count is followed by a request for the next page") assert.Equal(t, []string{"100"}, transport.Requests[1].Query["offset"]) } + +// ResolveOwnership keeps the stored rule pattern that matched each resource. +// A missing or empty pattern means that no rule is stored. +func TestResolveOwnershipReportsTheMatchedRule(t *testing.T) { + transport := &recordingClient{Responses: [][]byte{ + []byte(`{"items": [ + {"resourceKind":"variation","resourceLookupKey":"support/wild","direction":"code_canonical","matchedResourcePattern":"support/*"}, + {"resourceKind":"variation","resourceLookupKey":"support/absent","direction":"both"}, + {"resourceKind":"variation","resourceLookupKey":"support/empty","direction":"server_canonical","matchedResourcePattern":""} + ], "totalCount": 3}`), + }} + client := NewClient(transport, "token", "https://example.com") + wild := syncdomain.VariationID("project", "support", "wild") + absent := syncdomain.VariationID("project", "support", "absent") + empty := syncdomain.VariationID("project", "support", "empty") + + ownership, err := client.ResolveOwnership("project", []syncdomain.ResourceID{wild, absent, empty}) + + require.NoError(t, err) + assert.Equal(t, map[syncdomain.ResourceID]syncdomain.Ownership{ + wild: {Direction: syncdomain.SyncDirectionCodeCanonical, MatchedPattern: "support/*"}, + absent: {Direction: syncdomain.SyncDirectionBoth}, + empty: {Direction: syncdomain.SyncDirectionServerCanonical}, + }, ownership) +} diff --git a/internal/sync/api/settings_write.go b/internal/sync/api/settings_write.go new file mode 100644 index 000000000..f1d5afcf5 --- /dev/null +++ b/internal/sync/api/settings_write.go @@ -0,0 +1,64 @@ +package api + +import ( + "fmt" + "net/http" + + syncdomain "github.com/launchdarkly/ldcli/internal/sync" +) + +// syncSettingsWriteLimit is the most rules one sync settings write accepts. +const syncSettingsWriteLimit = 100 + +type syncSettingsPatch struct { + Upserts []syncSettingRule `json:"upserts"` + Deletions []syncSettingRule `json:"deletions"` +} + +type syncSettingRule struct { + ResourceKind syncdomain.Kind `json:"resourceKind"` + ResourcePattern string `json:"resourcePattern"` + Direction syncdomain.SyncDirection `json:"direction"` +} + +// ClaimForCode makes code the owner of each resource. +func (client Client) ClaimForCode(projectKey string, ids []syncdomain.ResourceID) error { + return client.setSyncDirection(projectKey, ids, syncdomain.SyncDirectionCodeCanonical) +} + +// ReturnToLaunchDarkly makes LaunchDarkly the owner of each resource. +func (client Client) ReturnToLaunchDarkly(projectKey string, ids []syncdomain.ResourceID) error { + return client.setSyncDirection(projectKey, ids, syncdomain.SyncDirectionServerCanonical) +} + +// setSyncDirection upserts one exact rule per resource, in batches of at most +// syncSettingsWriteLimit rules. It checks every resource before it writes. +func (client Client) setSyncDirection( + projectKey string, ids []syncdomain.ResourceID, direction syncdomain.SyncDirection, +) error { + rules := make([]syncSettingRule, 0, len(ids)) + for _, id := range ids { + if id.ProjectKey != projectKey { + return fmt.Errorf("update sync settings: %s is not in project %q", id.Label(), projectKey) + } + rules = append(rules, syncSettingRule{ResourceKind: id.Kind, ResourcePattern: id.LookupKey, Direction: direction}) + } + for start := 0; start < len(rules); start += syncSettingsWriteLimit { + end := min(start+syncSettingsWriteLimit, len(rules)) + _, err := client.mutate(mutation{ + method: http.MethodPatch, action: "update", resource: "sync settings in project", key: projectKey, + body: syncSettingsPatch{Upserts: rules[start:end], Deletions: []syncSettingRule{}}, + }, projectPath(projectKey, "configs", "sync", "settings")...) + if IsForbidden(err) { + return fmt.Errorf( + "%w: your role needs the updateSyncSettings action on proj/%s:ai-code-sync/*; "+ + "ask a LaunchDarkly admin to grant it: %w", + ErrSyncSettingsForbidden, projectKey, err, + ) + } + if err != nil { + return err + } + } + return nil +} diff --git a/internal/sync/api/settings_write_test.go b/internal/sync/api/settings_write_test.go new file mode 100644 index 000000000..cbe4cf402 --- /dev/null +++ b/internal/sync/api/settings_write_test.go @@ -0,0 +1,163 @@ +package api + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/launchdarkly/ldcli/internal/resources" + syncdomain "github.com/launchdarkly/ldcli/internal/sync" +) + +func TestClaimForCodeUpsertsCodeCanonicalRules(t *testing.T) { + transport := &recordingClient{} + client := NewClient(transport, "token", "https://example.com") + + err := client.ClaimForCode("project", []syncdomain.ResourceID{ + syncdomain.VariationID("project", "support", "default"), + syncdomain.VariationID("project", "support", "concise"), + }) + + require.NoError(t, err) + require.Len(t, transport.Requests, 1) + request := transport.Requests[0] + assert.Equal(t, "token", request.AccessToken) + assert.Equal(t, http.MethodPatch, request.Method) + assert.Equal(t, "https://example.com/api/v2/projects/project/configs/sync/settings", request.Path) + assert.Equal(t, "application/json", request.ContentType) + assert.Empty(t, request.Query) + assert.False(t, request.IsBeta) + assert.JSONEq(t, `{ + "upserts": [ + {"resourceKind": "variation", "resourcePattern": "support/default", "direction": "code_canonical"}, + {"resourceKind": "variation", "resourcePattern": "support/concise", "direction": "code_canonical"} + ], + "deletions": [] + }`, string(request.Body)) +} + +func TestReturnToLaunchDarklyUpsertsServerCanonicalRules(t *testing.T) { + transport := &recordingClient{} + client := NewClient(transport, "token", "https://example.com") + + err := client.ReturnToLaunchDarkly("project", []syncdomain.ResourceID{ + syncdomain.VariationID("project", "support", "default"), + }) + + require.NoError(t, err) + require.Len(t, transport.Requests, 1) + request := transport.Requests[0] + assert.Equal(t, http.MethodPatch, request.Method) + assert.Equal(t, "https://example.com/api/v2/projects/project/configs/sync/settings", request.Path) + assert.JSONEq(t, `{ + "upserts": [ + {"resourceKind": "variation", "resourcePattern": "support/default", "direction": "server_canonical"} + ], + "deletions": [] + }`, string(request.Body)) +} + +func TestClaimForCodeSendsAtMostOneHundredRulesPerRequest(t *testing.T) { + transport := &recordingClient{} + client := NewClient(transport, "token", "https://example.com") + ids := make([]syncdomain.ResourceID, 0, 150) + for index := range 150 { + ids = append(ids, syncdomain.VariationID("project", "support", fmt.Sprintf("variation-%03d", index))) + } + + require.NoError(t, client.ClaimForCode("project", ids)) + + require.Len(t, transport.Requests, 2) + var patterns []string + for index, size := range []int{100, 50} { + var body struct { + Upserts []struct { + ResourcePattern string `json:"resourcePattern"` + } `json:"upserts"` + } + require.NoError(t, json.Unmarshal(transport.Requests[index].Body, &body)) + require.Len(t, body.Upserts, size) + for _, rule := range body.Upserts { + patterns = append(patterns, rule.ResourcePattern) + } + } + expected := make([]string, 0, len(ids)) + for _, id := range ids { + expected = append(expected, id.LookupKey) + } + assert.Equal(t, expected, patterns, "every rule is sent once, in order") +} + +// The rule pattern holds only the lookup key, so a resource of another +// project would get a rule in the wrong project. +func TestClaimForCodeRejectsResourceOfAnotherProject(t *testing.T) { + transport := &recordingClient{} + client := NewClient(transport, "token", "https://example.com") + + err := client.ClaimForCode("project", []syncdomain.ResourceID{ + syncdomain.VariationID("project", "support", "default"), + syncdomain.VariationID("other", "support", "default"), + }) + + require.Error(t, err) + assert.Contains(t, err.Error(), `"project"`) + assert.Empty(t, transport.Requests) +} + +// A 403 names the missing permission. Any other failure must not say that a +// permission is missing. +func TestClaimForCodeExplainsForbidden403(t *testing.T) { + ids := []syncdomain.ResourceID{syncdomain.VariationID("project", "support", "default")} + + t.Run("403", func(t *testing.T) { + transport := &recordingClient{Err: errors.New(`{"code":"forbidden","statusCode":403}`)} + + err := NewClient(transport, "token", "https://example.com").ClaimForCode("project", ids) + + require.Error(t, err) + assert.ErrorIs(t, err, ErrSyncSettingsForbidden) + assert.True(t, IsForbidden(err), "IsForbidden(%v)", err) + assert.Contains(t, err.Error(), "updateSyncSettings") + assert.Contains(t, err.Error(), "proj/project:ai-code-sync/*") + assert.Contains(t, strings.ToLower(err.Error()), "ask a launchdarkly admin") + }) + t.Run("500", func(t *testing.T) { + transport := &recordingClient{Err: errors.New(`{"code":"internal_server_error","statusCode":500}`)} + + err := NewClient(transport, "token", "https://example.com").ClaimForCode("project", ids) + + require.Error(t, err) + assert.NotErrorIs(t, err, ErrSyncSettingsForbidden) + assert.False(t, IsForbidden(err)) + assert.NotContains(t, err.Error(), "updateSyncSettings") + }) +} + +// The server identifies sync writes by the ldcli User-Agent, so the settings +// write must go through the shared resources client. The test server stands +// in for the LaunchDarkly API, which can't run locally. +func TestSyncSettingsWritesSendCLIUserAgent(t *testing.T) { + const version = "9.8.7-test" + var method, path, userAgent string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + method, path, userAgent = r.Method, r.URL.Path, r.Header.Get("User-Agent") + w.WriteHeader(http.StatusNoContent) + })) + t.Cleanup(server.Close) + client := NewClient(resources.NewClient(version), "api-token", server.URL) + + require.NoError(t, client.ClaimForCode("project", []syncdomain.ResourceID{ + syncdomain.VariationID("project", "support", "default"), + })) + + assert.Equal(t, http.MethodPatch, method) + assert.Equal(t, "/api/v2/projects/project/configs/sync/settings", path) + assert.Equal(t, "launchdarkly-cli/v"+version, userAgent) +} diff --git a/internal/sync/error.go b/internal/sync/error.go index a256da44f..8fd735671 100644 --- a/internal/sync/error.go +++ b/internal/sync/error.go @@ -26,6 +26,8 @@ const ( ErrorLinkedSourceMissing ErrorCode = "linked_source_missing" ErrorAttachmentDefinitionMissing ErrorCode = "attachment_definition_missing" ErrorSyncSettingUnavailable ErrorCode = "sync_setting_unavailable" + ErrorSyncSettingsForbidden ErrorCode = "sync_settings_forbidden" + ErrorSyncVariationForbidden ErrorCode = "sync_variation_forbidden" ErrorBindingStale ErrorCode = "binding_stale" ErrorStateChanged ErrorCode = "state_changed" ErrorSourceNotWritable ErrorCode = "source_not_writable" @@ -74,6 +76,19 @@ func NewProblem(code ErrorCode, message, suggestion string) *Problem { return &Problem{Code: code, Message: message, Suggestion: suggestion} } +// SyncSettingsForbiddenProblem reports that the caller's role cannot write +// the project's sync settings, so the action, for example "record code +// ownership", failed. +func SyncSettingsForbiddenProblem(projectKey, action, consequence string, cause error) *Problem { + problem := NewProblem( + ErrorSyncSettingsForbidden, + fmt.Sprintf("your role cannot %s in project %q, so %s", action, projectKey, consequence), + fmt.Sprintf("Ask a LaunchDarkly admin to grant your role the updateSyncSettings action on proj/%s:ai-code-sync/*.", projectKey), + ) + problem.Cause = cause + return problem +} + // ProblemFrom returns the first sync problem in an error chain. func ProblemFrom(err error) (*Problem, bool) { var problem *Problem diff --git a/internal/sync/interactive/settings.go b/internal/sync/interactive/settings.go new file mode 100644 index 000000000..030612e70 --- /dev/null +++ b/internal/sync/interactive/settings.go @@ -0,0 +1,77 @@ +package interactive + +import ( + "context" + "fmt" + "io" + "strings" + + syncconsole "github.com/launchdarkly/ldcli/internal/sync/console" +) + +// SettingsUnavailable describes a command that cannot record ownership +// because some projects have no sync settings. +type SettingsUnavailable struct { + Context context.Context + Input io.Reader + // Prompt is the stream that the question goes to and that must be a + // terminal. If it is nil, ErrorOutput is used. + Prompt io.Writer + // Output gets the cancel line. + Output io.Writer + ErrorOutput io.Writer + NoInput bool + Yes bool + // IsTerminal reports whether the streams are a terminal. If it is nil, + // StreamsAreTerminal is used. + IsTerminal func(io.Reader, io.Writer) bool + // ProjectKeys are the projects without sync settings. + ProjectKeys []string + // Unrecorded names what LaunchDarkly cannot record, for example + // "ownership of the detached variations". + Unrecorded string + // Question asks whether to go on without recording ownership. + Question string + // Verb names the command in the cancel line, for example "Detach". + Verb string +} + +// SettingsUnavailableWarning tells the user that LaunchDarkly could not +// record what unrecorded names in the projects, because they have no sync +// settings. +func SettingsUnavailableWarning(unrecorded string, projectKeys []string) string { + return fmt.Sprintf( + "Warning: LaunchDarkly could not record %s in project %s, because the project has no sync settings.", + unrecorded, strings.Join(projectKeys, ", "), + ) +} + +// ConfirmWithoutSettings warns on the error output that LaunchDarkly cannot +// record ownership in the projects, and reports whether to go on. With Yes, +// it goes on. When the prompt stream is a terminal, it asks the question +// there and writes " canceled." to the output on a no. Without a +// terminal, it returns an error that suggests --yes. +func ConfirmWithoutSettings(settings SettingsUnavailable) (bool, error) { + errorOutput := settings.ErrorOutput + if errorOutput == nil { + errorOutput = io.Discard + } + _ = syncconsole.New(errorOutput).Line(SettingsUnavailableWarning(settings.Unrecorded, settings.ProjectKeys)) + if settings.Yes { + return true, nil + } + isTerminal := settings.IsTerminal + if isTerminal == nil { + isTerminal = StreamsAreTerminal + } + prompt := settings.Prompt + if prompt == nil { + prompt = errorOutput + } + interactive := !settings.NoInput && isTerminal(settings.Input, prompt) + confirmed, err := Confirm(settings.Context, settings.Input, prompt, interactive, settings.Question) + if err == nil && !confirmed { + _ = syncconsole.New(settings.Output).Printf("%s canceled.\n", settings.Verb) + } + return confirmed, err +} diff --git a/internal/sync/ownership.go b/internal/sync/ownership.go new file mode 100644 index 000000000..c7b731f83 --- /dev/null +++ b/internal/sync/ownership.go @@ -0,0 +1,38 @@ +package sync + +// OwnershipAction is what sync does with a variation's ownership before it +// pushes or pulls the variation. +type OwnershipAction int + +const ( + // OwnershipNothingToDo means that an exact rule already makes the + // variation code-owned. + OwnershipNothingToDo OwnershipAction = iota + // OwnershipClaim means that sync writes an exact code_canonical rule. + OwnershipClaim + // OwnershipManagedInLaunchDarkly means that an explicit LaunchDarkly rule + // owns the variation: sync pulls it, and never pushes or claims it. + OwnershipManagedInLaunchDarkly +) + +// DecideOwnership decides what sync does with the ownership of one variation. +func DecideOwnership(id ResourceID, ownership Ownership) OwnershipAction { + if !ownership.HasRule() { + return OwnershipClaim + } + switch ownership.Direction { + case SyncDirectionServerCanonical: + return OwnershipManagedInLaunchDarkly + case SyncDirectionCodeCanonical: + if ownership.HasExactRule(id) { + return OwnershipNothingToDo + } + } + return OwnershipClaim +} + +// ManagedInLaunchDarklyMessage tells the user that LaunchDarkly owns a +// variation and how to move it to code. +func ManagedInLaunchDarklyMessage(id ResourceID) string { + return id.LookupKey + " is managed in LaunchDarkly; pulled, not pushed. To manage it in code, switch it to Code in LaunchDarkly." +} diff --git a/internal/sync/ownership_test.go b/internal/sync/ownership_test.go new file mode 100644 index 000000000..db70d944f --- /dev/null +++ b/internal/sync/ownership_test.go @@ -0,0 +1,55 @@ +package sync + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDecideOwnership(t *testing.T) { + id := VariationID("p", "support", "default") + exact := id.LookupKey + wildcard := "support/*" + + tests := []struct { + name string + ownership Ownership + want OwnershipAction + }{ + { + name: "exact code_canonical rule is already code-owned", + ownership: Ownership{Direction: SyncDirectionCodeCanonical, MatchedPattern: exact}, + want: OwnershipNothingToDo, + }, + { + name: "wildcard code_canonical rule is claimed with an exact rule", + ownership: Ownership{Direction: SyncDirectionCodeCanonical, MatchedPattern: wildcard}, + want: OwnershipClaim, + }, + { + name: "explicit server_canonical rule is managed in LaunchDarkly", + ownership: Ownership{Direction: SyncDirectionServerCanonical, MatchedPattern: exact}, + want: OwnershipManagedInLaunchDarkly, + }, + { + name: "no rule with direction both is claimed", + ownership: Ownership{Direction: SyncDirectionBoth}, + want: OwnershipClaim, + }, + { + name: "no rule with direction server_canonical is claimed", + ownership: Ownership{Direction: SyncDirectionServerCanonical}, + want: OwnershipClaim, + }, + { + name: "rule with legacy direction both is claimed", + ownership: Ownership{Direction: SyncDirectionBoth, MatchedPattern: exact}, + want: OwnershipClaim, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + assert.Equal(t, test.want, DecideOwnership(id, test.ownership)) + }) + } +} diff --git a/internal/sync/resource.go b/internal/sync/resource.go index b80743366..dfe93a799 100644 --- a/internal/sync/resource.go +++ b/internal/sync/resource.go @@ -38,6 +38,24 @@ func (direction SyncDirection) Valid() bool { direction == SyncDirectionBoth } +// Ownership is the effective LaunchDarkly sync setting of one resource, and +// the stored rule pattern that produced it. MatchedPattern is empty when no +// stored rule matched. +type Ownership struct { + Direction SyncDirection + MatchedPattern string +} + +// HasRule reports whether a stored rule matched the resource. +func (o Ownership) HasRule() bool { + return o.MatchedPattern != "" +} + +// HasExactRule reports whether the matched rule names the resource itself. +func (o Ownership) HasExactRule(id ResourceID) bool { + return o.MatchedPattern == id.LookupKey +} + // ResourceID identifies one synchronized resource. // // For a variation, LookupKey is "config-key/variation-key". For a tool or a From 679ee1483b1b3d6f6662ffc6e171cb8f8731e578 Mon Sep 17 00:00:00 2001 From: Nathan Kester Date: Mon, 16 Nov 2026 12:58:47 -0700 Subject: [PATCH 2/2] AIC-3901 part 2: push, link and create make a variation code-owned Co-Authored-By: Claude Opus 5.5 --- internal/sync/prompt/acceptance_test.go | 69 ++++- internal/sync/prompt/create.go | 4 + internal/sync/prompt/create_test.go | 21 ++ internal/sync/prompt/execute.go | 9 + internal/sync/prompt/output.go | 26 +- internal/sync/prompt/ownership_test.go | 326 ++++++++++++++++++++++++ internal/sync/prompt/plan.go | 41 +++ internal/sync/prompt/review.go | 3 +- internal/sync/prompt/state.go | 79 +++++- internal/sync/prompt/sync.go | 26 ++ 10 files changed, 586 insertions(+), 18 deletions(-) create mode 100644 internal/sync/prompt/ownership_test.go diff --git a/internal/sync/prompt/acceptance_test.go b/internal/sync/prompt/acceptance_test.go index babd464bf..d5afad4ff 100644 --- a/internal/sync/prompt/acceptance_test.go +++ b/internal/sync/prompt/acceptance_test.go @@ -43,7 +43,16 @@ type directAPI struct { skills map[string]versionedSkill manifest *syncapi.SyncManifest directions map[string]syncdomain.SyncDirection - requests []string + // patterns is the matchedResourcePattern of each resource, such as + // "variation:support/default". A resource without one matched no rule. + patterns map[string]string + // settingsReadErr fails each read of the sync settings. + settingsReadErr error + // settingsWriteErr fails each write of the sync settings. + settingsWriteErr error + // settingsWrites records the body of each write of the sync settings. + settingsWrites []settingsWrite + requests []string // expandTools makes each read of the variation add the content of its // tools to model.parameters.tools, as LaunchDarkly does. expandTools bool @@ -59,6 +68,8 @@ type directAPI struct { manifestWriteErr error // toolWriteErr fails each update of a tool. toolWriteErr error + // variationWriteErr fails each update of a variation. + variationWriteErr error } type notFoundAPI struct{} @@ -104,6 +115,9 @@ func (api *directAPI) MakeRequest( if api.onRequest != nil { api.onRequest(method, path) } + if api.variationWriteErr != nil && method == http.MethodPatch && strings.Contains(path, "/ai-configs/support/variations/") { + return nil, api.variationWriteErr + } if strings.HasSuffix(path, "/configs/sync/manifests") { if api.manifestWriteErr != nil && method != http.MethodGet { return nil, api.manifestWriteErr @@ -111,6 +125,9 @@ func (api *directAPI) MakeRequest( return handleManifestRequest(api.manifest, method, query, body) } if strings.HasSuffix(path, "/configs/sync/settings") && method == http.MethodGet { + if api.settingsReadErr != nil { + return nil, api.settingsReadErr + } items := make([]map[string]any, 0, len(query["resources"])) for _, resource := range query["resources"] { kind, lookupKey, _ := strings.Cut(resource, ":") @@ -118,12 +135,27 @@ func (api *directAPI) MakeRequest( if configured := api.directions[resource]; configured != "" { direction = configured } - items = append(items, map[string]any{ + item := map[string]any{ "resourceKind": kind, "resourceLookupKey": lookupKey, "direction": direction, - }) + } + if pattern := api.patterns[resource]; pattern != "" { + item["matchedResourcePattern"] = pattern + } + items = append(items, item) } return json.Marshal(map[string]any{"items": items}) } + if strings.HasSuffix(path, "/configs/sync/settings") && method == http.MethodPatch { + var write settingsWrite + if err := json.Unmarshal(body, &write); err != nil { + return nil, err + } + api.settingsWrites = append(api.settingsWrites, write) + if api.settingsWriteErr != nil { + return nil, api.settingsWriteErr + } + return nil, nil + } isCreate := method == http.MethodPost && (strings.HasSuffix(path, "/ai-tools") || strings.HasSuffix(path, "/ai-configs/skills") || strings.HasSuffix(path, "/variations")) if isCreate && api.createErr != nil { @@ -2027,7 +2059,7 @@ support = Agent(instructions="Local instructions.") variation: &server, directions: map[string]syncdomain.SyncDirection{ "variation:support/default": syncdomain.SyncDirectionCodeCanonical, - }, + }, patterns: map[string]string{"variation:support/default": "support/default"}, } id := syncdomain.VariationID("production", "support", "default") @@ -2296,6 +2328,7 @@ func TestCompletionSourcePullsOneSystemMessage(t *testing.T) { directions: map[string]syncdomain.SyncDirection{ "variation:support/default": syncdomain.SyncDirectionServerCanonical, }, + patterns: map[string]string{"variation:support/default": "support/default"}, } id := syncdomain.VariationID("production", "support", "default") @@ -2338,6 +2371,7 @@ completion = Agent( directions: map[string]syncdomain.SyncDirection{ "variation:support/default": syncdomain.SyncDirectionServerCanonical, }, + patterns: map[string]string{"variation:support/default": "support/default"}, } id := syncdomain.VariationID("production", "support", "default") action := syncprompt.SourceLinkAction{ @@ -2537,6 +2571,7 @@ func TestStructuredSourceLinksPushAndPull(t *testing.T) { changeServer: func(api *directAPI) { api.variation.Instructions = "Pulled YAML prompt" api.directions["variation:support/default"] = syncdomain.SyncDirectionServerCanonical + api.patterns = map[string]string{"variation:support/default": "support/default"} }, wantPush: func(t *testing.T, api *directAPI) { assert.Equal(t, "Local YAML prompt", api.variation.Instructions) @@ -2559,6 +2594,7 @@ func TestStructuredSourceLinksPushAndPull(t *testing.T) { changeServer: func(api *directAPI) { api.variation.Instructions = "Pulled TOML prompt" api.directions["variation:support/default"] = syncdomain.SyncDirectionServerCanonical + api.patterns = map[string]string{"variation:support/default": "support/default"} }, wantPush: func(t *testing.T, api *directAPI) { assert.Equal(t, "Local TOML prompt", api.variation.Instructions) @@ -2718,6 +2754,7 @@ func TestMarkdownProviderProfilesPullAndPreserveMetadata(t *testing.T) { directions: map[string]syncdomain.SyncDirection{ "variation:support/default": syncdomain.SyncDirectionServerCanonical, }, + patterns: map[string]string{"variation:support/default": "support/default"}, } id := syncdomain.VariationID("production", "support", "default") @@ -2936,7 +2973,9 @@ func (api *ambiguousWriteAPI) MakeRequest( beta bool, ) ([]byte, error) { response, err := api.directAPI.MakeRequest(accessToken, method, path, contentType, query, body, beta) - if err == nil && (method == "POST" || method == "PATCH") { + // The ambiguity is about the write of the variation, not about the claim + // of its ownership. + if err == nil && (method == "POST" || method == "PATCH") && !strings.HasSuffix(path, "/configs/sync/settings") { return nil, fmt.Errorf("connection closed after write") } return response, err @@ -2956,7 +2995,8 @@ func (api *changingReadAPI) MakeRequest( body []byte, beta bool, ) ([]byte, error) { - if method == "GET" && !strings.Contains(path, "/configs/sync/manifests") { + if method == "GET" && !strings.Contains(path, "/configs/sync/manifests") && + !strings.Contains(path, "/configs/sync/settings") { api.reads++ if api.reads == 2 { api.variation = pointer(variation("Concurrent")) @@ -3017,6 +3057,20 @@ func (api *multiDirectAPI) MakeRequest( if strings.HasSuffix(path, "/configs/sync/manifests") { return handleManifestRequest(api.manifest, method, query, body) } + if strings.HasSuffix(path, "/configs/sync/settings") { + // No resource matches a rule, and a claim succeeds. + if method != http.MethodGet { + return nil, nil + } + items := make([]map[string]any, 0, len(query["resources"])) + for _, resource := range query["resources"] { + kind, lookupKey, _ := strings.Cut(resource, ":") + items = append(items, map[string]any{ + "resourceKind": kind, "resourceLookupKey": lookupKey, "direction": syncdomain.SyncDirectionBoth, + }) + } + return json.Marshal(map[string]any{"items": items}) + } if method == "GET" { variations := make([]syncdomain.Variation, 0, len(api.variations)) for _, variation := range api.variations { @@ -3378,6 +3432,7 @@ func TestServerCanonicalSourcePullRepinsStaleToolVersions(t *testing.T) { directions: map[string]syncdomain.SyncDirection{ "variation:support/default": syncdomain.SyncDirectionServerCanonical, }, + patterns: map[string]string{"variation:support/default": "support/default"}, } stdout, _, err := runPrompt(t, root, api, "--dry-run", "--output", "json") @@ -3412,6 +3467,7 @@ func TestLinkedPullRepinsOnTheLatestLaunchDarklyCopy(t *testing.T) { directions: map[string]syncdomain.SyncDirection{ "variation:support/default": syncdomain.SyncDirectionServerCanonical, }, + patterns: map[string]string{"variation:support/default": "support/default"}, } onNthRead(api, "/ai-configs/support", 3, func() { api.variation.Name = "Renamed after review" }) @@ -3443,6 +3499,7 @@ func TestLinkedPullRecordsTheLockBeforeAFailedPinRefresh(t *testing.T) { directions: map[string]syncdomain.SyncDirection{ "variation:support/default": syncdomain.SyncDirectionServerCanonical, }, + patterns: map[string]string{"variation:support/default": "support/default"}, } pulled := server.Instructions // The mapped field changes after the review, so the pin update stops. diff --git a/internal/sync/prompt/create.go b/internal/sync/prompt/create.go index a15c96988..d0d41f394 100644 --- a/internal/sync/prompt/create.go +++ b/internal/sync/prompt/create.go @@ -177,6 +177,10 @@ func (runner Runner) createResource( return err } reviewed := workspaceState{projectKeys: []string{row.ID.ProjectKey}, plan: Plan{Scope: options.Scope, Resources: []PlannedResource{row}}} + // The review sees the ownership that the apply reads again. + if err := applySourceDirections(client, reviewed.plan.Resources); err != nil { + return err + } if options.dryRun() { if err := writePlanOutput(options.Output, options.OutputKind, reviewed.plan, options.Diff); err != nil { return err diff --git a/internal/sync/prompt/create_test.go b/internal/sync/prompt/create_test.go index 810ede1e7..18fd7e353 100644 --- a/internal/sync/prompt/create_test.go +++ b/internal/sync/prompt/create_test.go @@ -820,3 +820,24 @@ func createVariationAction(key string, input synccreate.Input) syncprompt.AddAct Filter: syncdomain.Filter{Project: "production", ConfigKey: "support", Keys: []string{key}}, Create: &input, } } + +// A variation that add creates is claimed for code in the same run, before +// LaunchDarkly creates it. +func TestCreateVariationClaimsItBeforeTheCreate(t *testing.T) { + root := initRepository(t) + api := &directAPI{modelConfigs: []syncapi.ModelConfig{claude}} + + _, _, err := runPrompt(t, root, api, "add", "--project", "production", "--config-key", "support", "--key", "escalation", + "--model-config-key", "claude", "--content", "Hand the conversation to a person.", "--yes", "--no-input") + + require.NoError(t, err) + assert.Equal(t, []string{"variation:support/escalation code_canonical"}, codeClaims(api.settingsWrites)) + assert.Equal(t, 1, countRequests(api.requests, http.MethodPatch, "/configs/sync/settings"), "one claim") + claim := requestIndex(api.requests, http.MethodPatch, "/configs/sync/settings") + create := requestIndex(api.requests, http.MethodPost, "/variations") + require.NotEqual(t, -1, claim, "the claim is sent") + require.NotEqual(t, -1, create, "the variation is created") + assert.Less(t, claim, create, "the claim comes before the create") + require.NotNil(t, api.variation) + assert.Equal(t, "escalation", api.variation.Key) +} diff --git a/internal/sync/prompt/execute.go b/internal/sync/prompt/execute.go index cd29c04da..5901c093f 100644 --- a/internal/sync/prompt/execute.go +++ b/internal/sync/prompt/execute.go @@ -755,6 +755,15 @@ func applyServerChange( if writeErr == nil { return pinsOf(variation), nil } + if syncapi.IsForbidden(writeErr) { + problem := syncdomain.NewProblem( + syncdomain.ErrorSyncVariationForbidden, + fmt.Sprintf("your role cannot write variation %q of AI Config %q in project %q", variationKey, configKey, projectKey), + fmt.Sprintf("Ask a LaunchDarkly admin to grant your role the syncAIConfigVariation action on the AI Config proj/%s:env/*:aiconfig/%s.", projectKey, configKey), + ) + problem.Cause = writeErr + return nil, problem + } createConflict := resource.Action == ActionCreateServer && syncapi.IsConflict(writeErr) if !syncapi.MutationMayHaveSucceeded(writeErr) && !createConflict { return nil, writeErr diff --git a/internal/sync/prompt/output.go b/internal/sync/prompt/output.go index 5f1627faf..bfdbadc03 100644 --- a/internal/sync/prompt/output.go +++ b/internal/sync/prompt/output.go @@ -123,7 +123,23 @@ func writePlanOutput(out io.Writer, outputKind string, plan Plan, showDiffs bool } resources = append(resources, item) } - return writeJSON(out, map[string]any{"resources": resources}) + return writeJSON(out, jsonDocument(resources, plan)) +} + +// jsonDocument is the top-level JSON document: the resources, plus notes such +// as a push skipped because the variation is managed in LaunchDarkly. +func jsonDocument(resources any, plan Plan) map[string]any { + document := map[string]any{"resources": resources} + var notes []string + for _, resource := range plan.Resources { + if resource.managedInLaunchDarkly { + notes = append(notes, syncdomain.ManagedInLaunchDarklyMessage(resource.ID)) + } + } + if len(notes) > 0 { + document["notes"] = notes + } + return document } // writeOutcomeOutput writes the result of each action, which includes @@ -152,7 +168,7 @@ func writeOutcomeOutput(out io.Writer, outputKind string, plan Plan, outcomes [] Create: skillCreate(planned[outcome.ID]), Source: plannedSource(planned[outcome.ID]), }) } - return writeJSON(out, map[string]any{"resources": resources}) + return writeJSON(out, jsonDocument(resources, plan)) } var rows []reviewRow @@ -277,6 +293,12 @@ func writePlanNotes(out io.Writer, plan Plan) { "Note: Another working copy synced %s after your sync.lock. %s\n", resource.ID.Label(), staleSuggestion(resource), ) } + if resource.managedInLaunchDarkly { + _ = console.Printf("Note: %s\n", syncdomain.ManagedInLaunchDarklyMessage(resource.ID)) + } + } + if projectKeys := plan.ownershipUnrecordedProjects(); len(projectKeys) != 0 { + _ = console.Line(pushUnrecordedWarning(projectKeys)) } var counts []string diff --git a/internal/sync/prompt/ownership_test.go b/internal/sync/prompt/ownership_test.go new file mode 100644 index 000000000..a16907e0b --- /dev/null +++ b/internal/sync/prompt/ownership_test.go @@ -0,0 +1,326 @@ +package prompt_test + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + syncdomain "github.com/launchdarkly/ldcli/internal/sync" + synclocal "github.com/launchdarkly/ldcli/internal/sync/local" + syncprompt "github.com/launchdarkly/ldcli/internal/sync/prompt" +) + +// settingsWrite is the body of a write of the sync settings. +type settingsWrite struct { + Upserts []struct { + ResourceKind string `json:"resourceKind"` + ResourcePattern string `json:"resourcePattern"` + Direction string `json:"direction"` + } `json:"upserts"` + Deletions []any `json:"deletions"` +} + +// codeClaims returns "kind:pattern direction" for each upserted rule. +func codeClaims(writes []settingsWrite) []string { + claims := []string{} + for _, write := range writes { + for _, rule := range write.Upserts { + claims = append(claims, rule.ResourceKind+":"+rule.ResourcePattern+" "+rule.Direction) + } + } + return claims +} + +// requestIndex returns the index of the first request with the method and +// the path suffix, or -1. +func requestIndex(requests []string, method, pathSuffix string) int { + for index, request := range requests { + if strings.HasPrefix(request, method+" ") && strings.HasSuffix(request, pathSuffix) { + return index + } + } + return -1 +} + +// requireClaimBeforeWrite checks that the claim of the sync settings and the +// variation write were both sent, the claim first. +func requireClaimBeforeWrite(t *testing.T, requests []string) { + t.Helper() + claim := requestIndex(requests, http.MethodPatch, "/configs/sync/settings") + write := requestIndex(requests, http.MethodPatch, "/variations/default") + require.NotEqual(t, -1, claim, "the claim is sent") + require.NotEqual(t, -1, write, "the variation is written") + assert.Less(t, claim, write, "the claim comes before the variation write") +} + +// managedVariationWithLocalChange returns a working copy that tracks the +// managed variation support/default, with a local change to push. +func managedVariationWithLocalChange(t *testing.T) (string, *directAPI) { + t.Helper() + root := initRepository(t) + baseline := variation("Baseline") + writeVariation(t, root, variation("Local"), true) + writeManifest(t, root, baseline) + return root, &directAPI{variation: pointer(baseline)} +} + +// linkPrompt links prompt.md to support/default and pushes the local copy. +func linkPrompt(t *testing.T, root string, api *directAPI) (string, error) { + t.Helper() + _, notes, err := runPrompt(t, root, api, "link", "--file", "prompt.md", "--format", "markdown", + "--project", "production", "--config-key", "support", "--key", "default", + "--conflict", "local", "--yes", "--no-input") + return notes, err +} + +const ( + supportDefaultSetting = "variation:support/default" + managedMessage = "support/default is managed in LaunchDarkly; pulled, not pushed. " + + "To manage it in code, switch it to Code in LaunchDarkly." +) + +func managedInLaunchDarkly(api *directAPI) { + api.directions = map[string]syncdomain.SyncDirection{supportDefaultSetting: syncdomain.SyncDirectionServerCanonical} + api.patterns = map[string]string{supportDefaultSetting: "support/default"} +} + +// A push of a variation that no rule matches claims it for code before it +// writes the variation. +func TestPushClaimsAVariationWithoutARuleBeforeWritingIt(t *testing.T) { + root, api := managedVariationWithLocalChange(t) + + _, _, err := runPrompt(t, root, api, "--yes") + + require.NoError(t, err) + assert.Equal(t, []string{"variation:support/default code_canonical"}, codeClaims(api.settingsWrites)) + assert.Equal(t, 1, countRequests(api.requests, http.MethodPatch, "/configs/sync/settings"), "one claim per project") + requireClaimBeforeWrite(t, api.requests) + assert.Equal(t, "Local", api.variation.Name) +} + +// A variation with an exact code rule is already owned by code, so the push +// does not claim it again. +func TestPushDoesNotClaimAVariationWithAnExactCodeRule(t *testing.T) { + root, api := managedVariationWithLocalChange(t) + api.directions = map[string]syncdomain.SyncDirection{supportDefaultSetting: syncdomain.SyncDirectionCodeCanonical} + api.patterns = map[string]string{supportDefaultSetting: "support/default"} + + _, _, err := runPrompt(t, root, api, "--yes") + + require.NoError(t, err) + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/configs/sync/settings")) + assert.Equal(t, 1, countRequests(api.requests, http.MethodPatch, "/variations/default")) + assert.Equal(t, "Local", api.variation.Name) +} + +// A variation with an explicit LaunchDarkly rule is never pushed or claimed, +// and the user learns why: on stderr, and as a notes entry in --output json. +func TestPushSkipsAVariationManagedInLaunchDarkly(t *testing.T) { + for _, arguments := range [][]string{{"--yes"}, {"--yes", "--output", "json"}} { + t.Run(strings.Join(arguments, " "), func(t *testing.T) { + root, api := managedVariationWithLocalChange(t) + managedInLaunchDarkly(api) + + stdout, stderr, err := runPrompt(t, root, api, arguments...) + + require.NoError(t, err) + assert.Contains(t, stderr, managedMessage) + if len(arguments) > 1 { + assert.Contains(t, jsonNotes(t, stdout), managedMessage, "stdout: %s", stdout) + } + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/configs/sync/settings"), "no claim") + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/variations/default"), "no push") + assert.Equal(t, "Baseline", api.variation.Name) + }) + } +} + +// jsonNotes returns the notes of every JSON document in stdout. +func jsonNotes(t *testing.T, stdout string) []string { + t.Helper() + var notes []string + decoder := json.NewDecoder(strings.NewReader(stdout)) + for { + var document struct { + Notes []string `json:"notes"` + } + err := decoder.Decode(&document) + if errors.Is(err, io.EOF) { + return notes + } + require.NoError(t, err, "stdout is JSON: %s", stdout) + notes = append(notes, document.Notes...) + } +} + +// A variation with an explicit LaunchDarkly rule still pulls the changes made +// in LaunchDarkly. +func TestPullOfAVariationManagedInLaunchDarkly(t *testing.T) { + root := initRepository(t) + baseline := variation("Baseline") + writeVariation(t, root, baseline, false) + writeManifest(t, root, baseline) + api := &directAPI{variation: pointer(variation("Server"))} + managedInLaunchDarkly(api) + + _, _, err := runPrompt(t, root, api, "--yes") + + require.NoError(t, err) + compiled, err := synclocal.Compile(os.DirFS(root)) + require.NoError(t, err) + require.Len(t, compiled, 1) + assert.Equal(t, "Server", compiled[0].Variation.Name) + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/configs/sync/settings")) +} + +// D2: linked variations follow ownership too. A server_canonical direction +// that no rule produced is not a LaunchDarkly owner, so a linked variation is +// claimed and pushed. +func TestPushClaimsALinkedVariationWithoutARule(t *testing.T) { + root, api := linkedVariationForPush(t) + api.directions[supportDefaultSetting] = syncdomain.SyncDirectionServerCanonical + + _, _, err := runPrompt(t, root, api, "--yes") + + require.NoError(t, err) + assert.Equal(t, []string{"variation:support/default code_canonical"}, codeClaims(api.settingsWrites)) + requireClaimBeforeWrite(t, api.requests) + assert.Equal(t, "Local text", api.variation.Instructions) +} + +// A role that cannot write the sync settings stops the push before any +// variation write, with a message that names the missing permission. +func TestPushStopsWhenTheClaimIsForbidden(t *testing.T) { + root, api := managedVariationWithLocalChange(t) + api.settingsWriteErr = errors.New(`{"code":"forbidden","statusCode":403}`) + + _, _, err := runPrompt(t, root, api, "--yes") + + require.Error(t, err) + assert.Contains(t, err.Error(), "code ownership") + assert.Contains(t, err.Error(), "updateSyncSettings") + assert.Contains(t, err.Error(), "proj/production:ai-code-sync/*") + assert.Equal(t, 1, countRequests(api.requests, http.MethodPatch, "/configs/sync/settings"), "the claim is tried") + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/variations/default"), "no variation write") + assert.Equal(t, "Baseline", api.variation.Name) +} + +// A read or a claim of the sync settings that fails with an error other than +// 404 or 403 stops the push before any variation write. +func TestPushStopsWhenTheSyncSettingsFail(t *testing.T) { + internal := errors.New(`{"code":"internal","statusCode":500}`) + for name, configure := range map[string]func(*directAPI){ + "read": func(api *directAPI) { api.settingsReadErr = internal }, + "claim": func(api *directAPI) { api.settingsWriteErr = internal }, + } { + t.Run(name, func(t *testing.T) { + root, api := managedVariationWithLocalChange(t) + configure(api) + + _, _, err := runPrompt(t, root, api, "--yes") + + require.Error(t, err) + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/variations/default"), "no variation write") + assert.Equal(t, "Baseline", api.variation.Name) + }) + } +} + +// Without the sync settings API, the push warns, naming the project, that +// ownership is not recorded. --yes proceeds, whether the read or the claim +// after the confirmation finds the API missing. +func TestPushWithoutTheSettingsAPIProceedsWithYes(t *testing.T) { + notFound := errors.New(`{"code":"not_found","message":"Not found","statusCode":404}`) + for name, configure := range map[string]func(*directAPI){ + "read": func(api *directAPI) { api.settingsReadErr = notFound }, + "claim": func(api *directAPI) { api.settingsWriteErr = notFound }, + } { + t.Run(name, func(t *testing.T) { + root, api := managedVariationWithLocalChange(t) + configure(api) + + _, notes, err := runScoped(t, root, api, syncprompt.Options{ + Scope: syncdomain.ScopePrompts, Action: syncprompt.SyncAction{}, Yes: true, + }) + + require.NoError(t, err) + assert.Contains(t, notes, "ownership") + assert.Contains(t, notes, "in project production", "the warning names the project") + assert.Equal(t, 1, countRequests(api.requests, http.MethodPatch, "/variations/default")) + assert.Equal(t, "Local", api.variation.Name) + }) + } +} + +// Without the sync settings API and without a terminal, the push needs --yes +// and writes no variation. +func TestPushWithoutTheSettingsAPINeedsYes(t *testing.T) { + root, api := managedVariationWithLocalChange(t) + api.settingsReadErr = errors.New(`{"code":"not_found","message":"Not found","statusCode":404}`) + + _, notes, err := runScoped(t, root, api, syncprompt.Options{ + Scope: syncdomain.ScopePrompts, Action: syncprompt.SyncAction{}, + }) + + require.Error(t, err) + assert.Contains(t, err.Error(), "--yes") + assert.Contains(t, notes, "ownership") + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/variations/default"), "no variation write") + assert.Equal(t, "Baseline", api.variation.Name) +} + +// A push of a code-owned variation that the server lock rejects because the +// role lacks syncAIConfigVariation names that action, not a generic error. +func TestPromptPushNamesSyncAIConfigVariationWhenTheVariationWriteIsForbidden(t *testing.T) { + root, api := managedVariationWithLocalChange(t) + api.directions = map[string]syncdomain.SyncDirection{supportDefaultSetting: syncdomain.SyncDirectionCodeCanonical} + api.patterns = map[string]string{supportDefaultSetting: "support/default"} + api.variationWriteErr = errors.New(`{"code":"forbidden","statusCode":403}`) + + _, _, err := runPrompt(t, root, api, "--yes", "--output=plaintext") + + require.Error(t, err) + assert.Equal(t, 1, countRequests(api.requests, http.MethodPatch, "/ai-configs/support/variations/default"), "the variation write is tried") + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/configs/sync/settings"), "no claim is needed") + assert.Contains(t, err.Error(), "syncAIConfigVariation") + assert.Contains(t, err.Error(), "proj/production:env/*:aiconfig/support", "names the AI Config resource as roles use it") +} + +// A link of a LaunchDarkly variation that no rule matches makes it code-owned. +func TestLinkClaimsAVariationWithoutARule(t *testing.T) { + root := initRepository(t) + require.NoError(t, os.WriteFile(filepath.Join(root, "prompt.md"), []byte("Local prompt.\n"), 0o644)) + api := &directAPI{variation: pointer(variation("Server"))} + + _, err := linkPrompt(t, root, api) + + require.NoError(t, err) + assert.Equal(t, []string{"variation:support/default code_canonical"}, codeClaims(api.settingsWrites)) + requireClaimBeforeWrite(t, api.requests) + assert.Equal(t, "Local prompt.", api.variation.Instructions) +} + +// A link of a variation with an explicit LaunchDarkly rule neither claims nor +// pushes it, and the user learns why. +func TestLinkLeavesAVariationManagedInLaunchDarkly(t *testing.T) { + root := initRepository(t) + require.NoError(t, os.WriteFile(filepath.Join(root, "prompt.md"), []byte("Local prompt.\n"), 0o644)) + api := &directAPI{variation: pointer(variation("Server"))} + managedInLaunchDarkly(api) + + notes, err := linkPrompt(t, root, api) + + require.NoError(t, err) + assert.Contains(t, notes, "support/default is managed in LaunchDarkly") + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/configs/sync/settings"), "no claim") + assert.Zero(t, countRequests(api.requests, http.MethodPatch, "/variations/default"), "no push") + assert.Equal(t, "Help", api.variation.Instructions) +} diff --git a/internal/sync/prompt/plan.go b/internal/sync/prompt/plan.go index 3c3e19bea..26c660e21 100644 --- a/internal/sync/prompt/plan.go +++ b/internal/sync/prompt/plan.go @@ -8,6 +8,7 @@ import ( syncdomain "github.com/launchdarkly/ldcli/internal/sync" syncadapter "github.com/launchdarkly/ldcli/internal/sync/adapter" + syncinteractive "github.com/launchdarkly/ldcli/internal/sync/interactive" syncmanifest "github.com/launchdarkly/ldcli/internal/sync/manifest" ) @@ -101,6 +102,15 @@ type PlannedResource struct { // createsConfig is true when the create of the variation also creates // its config, because LaunchDarkly has none. createsConfig bool + // claimOwnership is true when a push of the variation first records code + // as its owner in the LaunchDarkly sync settings. + claimOwnership bool + // managedInLaunchDarkly is true when an explicit LaunchDarkly rule turned + // a push of the variation into a pull or a skip. + managedInLaunchDarkly bool + // ownershipUnavailable is true when LaunchDarkly has no sync settings to + // read the ownership of the variation from. + ownershipUnavailable bool } func setProblem(resource *PlannedResource, problem *syncdomain.Problem) { @@ -723,6 +733,37 @@ func (plan Plan) RequiresConfirmation() bool { }) } +// pushUnrecordedWarning tells the user that a push cannot record code as the +// owner of its variations in the named projects. +func pushUnrecordedWarning(projectKeys []string) string { + return syncinteractive.SettingsUnavailableWarning("code ownership of the pushed variations", projectKeys) +} + +// ownershipUnrecordedProjects returns, sorted, the projects in which the plan +// pushes a variation whose ownership LaunchDarkly cannot record. +func (plan Plan) ownershipUnrecordedProjects() []string { + var projectKeys []string + for _, resource := range plan.Resources { + if resource.ownershipUnavailable && resource.Action.changesServer() && !slices.Contains(projectKeys, resource.ID.ProjectKey) { + projectKeys = append(projectKeys, resource.ID.ProjectKey) + } + } + slices.Sort(projectKeys) + return projectKeys +} + +// ownershipClaims returns, by project, the variations that the plan pushes +// and that code does not own yet in the LaunchDarkly sync settings. +func (plan Plan) ownershipClaims() map[string][]ResourceID { + claims := make(map[string][]ResourceID) + for _, resource := range plan.Resources { + if resource.ID.Kind == syncdomain.KindVariation && resource.claimOwnership && resource.Action.changesServer() { + claims[resource.ID.ProjectKey] = append(claims[resource.ID.ProjectKey], resource.ID) + } + } + return claims +} + // HasDestructiveActions reports whether the plan deletes a local file. func (plan Plan) HasDestructiveActions() bool { return slices.ContainsFunc(plan.Resources, func(resource PlannedResource) bool { diff --git a/internal/sync/prompt/review.go b/internal/sync/prompt/review.go index 43a3f2fdf..b9c67c6a8 100644 --- a/internal/sync/prompt/review.go +++ b/internal/sync/prompt/review.go @@ -32,7 +32,8 @@ func reviewAndConfirmPlan(options Options, plan Plan, interactive bool) (bool, e } return false, review() } - autoApply := options.Yes || (options.watching() && !plan.HasDestructiveActions()) + // A push that cannot record ownership asks first, even in watch mode. + autoApply := options.Yes || (options.watching() && !plan.HasDestructiveActions() && len(plan.ownershipUnrecordedProjects()) == 0) if autoApply || !plan.RequiresConfirmation() { return true, nil } diff --git a/internal/sync/prompt/state.go b/internal/sync/prompt/state.go index 9130e531e..fa8b69a46 100644 --- a/internal/sync/prompt/state.go +++ b/internal/sync/prompt/state.go @@ -251,10 +251,17 @@ func allowRelink(resources []PlannedResource, id ResourceID) { } } +// applySourceDirections applies the LaunchDarkly sync settings to the rows. +// Every variation follows its ownership: an explicit LaunchDarkly rule makes +// it pull, and any other setting lets it push after a claim for code. A +// linked tool or skill follows its direction. func applySourceDirections(client syncapi.Client, resources []PlannedResource) error { + if err := applyVariationOwnership(client, resources); err != nil { + return err + } byProject := make(map[string][]ResourceID) for _, resource := range resources { - if resource.Source != nil { + if resource.Source != nil && resource.ID.Kind != syncdomain.KindVariation { byProject[resource.ID.ProjectKey] = append(byProject[resource.ID.ProjectKey], resource.ID) } } @@ -278,17 +285,13 @@ func applySourceDirections(client syncapi.Client, resources []PlannedResource) e continue } if !ok { - suggestion := "Configure the resource sync setting in LaunchDarkly, then run link again." - if resource.ID.Kind != syncdomain.KindVariation { - suggestion = fmt.Sprintf( - "LaunchDarkly does not provide a %s sync setting. Configure one when support is available, or run detach.", - resource.ID.Kind, - ) - } return syncdomain.NewProblem( syncdomain.ErrorSyncSettingUnavailable, "LaunchDarkly returned no sync setting", - suggestion, + fmt.Sprintf( + "LaunchDarkly does not provide a %s sync setting. Configure one when support is available, or run detach.", + resource.ID.Kind, + ), ).WithResource(resource.ID) } enforceDirection(resource, direction) @@ -298,6 +301,64 @@ func applySourceDirections(client syncapi.Client, resources []PlannedResource) e return nil } +// applyVariationOwnership reads the ownership of every variation row and +// applies it. Without the sync settings API, the rows keep their actions and +// record that their ownership is unknown. +func applyVariationOwnership(client syncapi.Client, resources []PlannedResource) error { + byProject := make(map[string][]ResourceID) + for _, resource := range resources { + if resource.ID.Kind == syncdomain.KindVariation { + byProject[resource.ID.ProjectKey] = append(byProject[resource.ID.ProjectKey], resource.ID) + } + } + for projectKey, ids := range byProject { + for start := 0; start < len(ids); start += 100 { + end := min(start+100, len(ids)) + ownership, err := client.ResolveOwnership(projectKey, ids[start:end]) + unavailable := syncapi.IsNotFound(err) + if err != nil && !unavailable { + return err + } + for index := range resources { + resource := &resources[index] + if resource.ID.Kind != syncdomain.KindVariation || resource.ID.ProjectKey != projectKey || + !slices.Contains(ids[start:end], resource.ID) { + continue + } + if unavailable { + resource.ownershipUnavailable = true + enforceDirection(resource, syncdomain.SyncDirectionBoth) + continue + } + enforceOwnership(resource, ownership[resource.ID]) + } + } + } + return nil +} + +// enforceOwnership applies the ownership of one variation. An explicit +// LaunchDarkly rule makes it server-canonical. An exact code rule makes it +// code-canonical. Any other setting lets it push, and a push claims it for +// code first: a code_canonical direction stays code-canonical, and a +// server_canonical direction that no rule produced does not make it pull. +func enforceOwnership(resource *PlannedResource, ownership syncdomain.Ownership) { + switch syncdomain.DecideOwnership(resource.ID, ownership) { + case syncdomain.OwnershipManagedInLaunchDarkly: + resource.managedInLaunchDarkly = resource.Action.changesServer() || resource.Action == ActionConflict + enforceDirection(resource, syncdomain.SyncDirectionServerCanonical) + case syncdomain.OwnershipNothingToDo: + enforceDirection(resource, syncdomain.SyncDirectionCodeCanonical) + default: + resource.claimOwnership = true + direction := syncdomain.SyncDirectionBoth + if ownership.Direction == syncdomain.SyncDirectionCodeCanonical { + direction = syncdomain.SyncDirectionCodeCanonical + } + enforceDirection(resource, direction) + } +} + func enforceDirection(resource *PlannedResource, direction syncdomain.SyncDirection) { resource.Direction = direction // A conflict over a shared tool or skill is about that attachment, not diff --git a/internal/sync/prompt/sync.go b/internal/sync/prompt/sync.go index a0eddc1c5..20f7518c8 100644 --- a/internal/sync/prompt/sync.go +++ b/internal/sync/prompt/sync.go @@ -4,6 +4,7 @@ import ( "bytes" "errors" "io" + "maps" "slices" syncdomain "github.com/launchdarkly/ldcli/internal/sync" @@ -192,6 +193,9 @@ func (runner Runner) applyPlan( resolutions map[syncdomain.ResourceID]ConflictResolution, ) ([]ResourceOutcome, error) { plan := applyConflictResolutions(current.plan, resolutions) + if err := claimOwnership(options, client, plan); err != nil { + return nil, err + } outcomes, next, err := executePlan(workspace.root, workspace.local, client, current.baseline.Lock, plan, current.localFiles) failures := []error{err} @@ -207,3 +211,25 @@ func (runner Runner) applyPlan( writeRepinNotes(options.ErrorOutput, plan, outcomes) return outcomes, errors.Join(failures...) } + +// claimOwnership records code as the owner of each variation that the plan +// pushes, one write per project, before the plan writes anything. Without the +// sync settings API, the push goes on and the user learns that its ownership +// is not recorded. +func claimOwnership(options Options, client syncapi.Client, plan Plan) error { + claims := plan.ownershipClaims() + for _, projectKey := range slices.Sorted(maps.Keys(claims)) { + err := client.ClaimForCode(projectKey, claims[projectKey]) + if syncapi.IsNotFound(err) { + _ = syncconsole.New(options.ErrorOutput).Line(pushUnrecordedWarning([]string{projectKey})) + continue + } + if errors.Is(err, syncapi.ErrSyncSettingsForbidden) { + return syncdomain.SyncSettingsForbiddenProblem(projectKey, "record code ownership", "nothing was pushed", err) + } + if err != nil { + return err + } + } + return nil +}