diff --git a/internal/archtest/closed_plane_ratchet.go b/internal/archtest/closed_plane_ratchet.go index 2c9d54b3..b6e0e73f 100644 --- a/internal/archtest/closed_plane_ratchet.go +++ b/internal/archtest/closed_plane_ratchet.go @@ -13,10 +13,11 @@ import ( ) const ( - RuleClosedPlaneNoArbitraryValueMaps = "closed_plane_no_arbitrary_value_maps" - RuleClosedPlaneNoReflectionFallback = "closed_plane_no_reflection_fallback" - RuleClosedPlaneNoMapReplayHelpers = "closed_plane_no_map_replay_helpers" - RuleClosedPlaneTypedStorageOnly = "closed_plane_typed_storage_only" + RuleClosedPlaneNoArbitraryValueMaps = "closed_plane_no_arbitrary_value_maps" + RuleClosedPlaneNoReflectionFallback = "closed_plane_no_reflection_fallback" + RuleClosedPlaneNoMapReplayHelpers = "closed_plane_no_map_replay_helpers" + RuleClosedPlaneTypedStorageOnly = "closed_plane_typed_storage_only" + RuleClosedPlaneNoGlobalPlaneSelectors = "closed_plane_no_global_plane_selectors" ) // ScanClosedPlaneViolations walks production Go files to verify that arbitrary-plane map/reflection @@ -109,11 +110,11 @@ func ScanFileClosedPlaneViolations(relPath string, fset *token.FileSet, f *ast.F if !ok { return true } - sel, ok := call.Fun.(*ast.SelectorExpr) + sel, ok := unwrapParen(call.Fun).(*ast.SelectorExpr) if !ok { return true } - pkgIdent, ok := sel.X.(*ast.Ident) + pkgIdent, ok := unwrapParen(sel.X).(*ast.Ident) if !ok || pkgIdent.Name != "reflect" { return true } @@ -168,7 +169,8 @@ func ScanFileClosedPlaneViolations(relPath string, fset *token.FileSet, f *ast.F } } case *ast.RangeStmt: - if !isAllowedPluginIDsRangeExpr(node.X) && isMapRangeTarget(node.X, localMapVars, typeDefs) { + rangeX := unwrapParen(node.X) + if !isAllowedPluginIDsRangeExpr(rangeX) && isMapRangeTarget(rangeX, localMapVars, typeDefs) { findings = append(findings, RuleFinding{ Rule: RuleClosedPlaneNoMapReplayHelpers, Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(node.Pos()).Line), @@ -187,6 +189,11 @@ func ScanFileClosedPlaneViolations(relPath string, fset *token.FileSet, f *ast.F return true }) + // 4. Reject PlaneX policy selectors and aliases outside narrow canonical initialization (narrowly for plane_generated.go) + if isGeneratedPlanesFile(normalizedRel) { + findings = append(findings, checkPlaneGeneratedSelectors(fset, normalizedRel, f)...) + } + return findings } @@ -395,11 +402,16 @@ func isMapRangeTarget(expr ast.Expr, localMapVars map[string]bool, typeDefs map[ } func extractCalledIdent(fun ast.Expr) string { + fun = unwrapParen(fun) switch x := fun.(type) { case *ast.Ident: return x.Name case *ast.SelectorExpr: return x.Sel.Name + case *ast.IndexExpr: + return extractCalledIdent(x.X) + case *ast.IndexListExpr: + return extractCalledIdent(x.X) default: return "" } diff --git a/internal/archtest/closed_plane_ratchet_helpers.go b/internal/archtest/closed_plane_ratchet_helpers.go new file mode 100644 index 00000000..e64ebb34 --- /dev/null +++ b/internal/archtest/closed_plane_ratchet_helpers.go @@ -0,0 +1,282 @@ +package archtest + +import ( + "fmt" + "go/ast" + "go/token" + "path/filepath" + "strings" +) + +var directPolicyFieldMapping = map[string]string{ + "planeID": "ID", + "rules": "Rules", + "nilPolicy": "NilPolicy", + "isNil": "IsNil", + "validate": "Validate", + "validateIdentity": "ValidateIdentity", + "combine": "Combine", + "identity": "Identity", + "exclusiveConflictError": "ExclusiveConflictError", + "requestMaterializer": "RequestMaterializer", + "requestBorrow": "RequestBorrow", + "hookTarget": "HookTarget", +} + +var diagPolicyFieldMapping = map[string]string{ + "diagStageID": "StageID", + "diagCoalesceGroup": "CoalesceGroup", + "diagOrder": "Order", + "diagMaterialize": "Materialize", + "diagPrivileges": "Privileges", +} + +var expectedPolicyFieldsList = []string{ + "planeID", + "rules", + "nilPolicy", + "isNil", + "validate", + "validateIdentity", + "combine", + "identity", + "exclusiveConflictError", + "requestMaterializer", + "requestBorrow", + "hookTarget", + "diagStageID", + "diagCoalesceGroup", + "diagOrder", + "diagMaterialize", + "diagPrivileges", +} + +func isGeneratedPlanesFile(path string) bool { + norm := filepath.ToSlash(path) + return norm == "pkg/lipsdk/feature/plane_generated.go" || + strings.HasSuffix(norm, "/pkg/lipsdk/feature/plane_generated.go") || + filepath.Base(norm) == "plane_generated.go" +} + +func isPlaneVarName(name string) bool { + if name == "PlaneDeclaration" { + return false + } + return strings.HasPrefix(name, "Plane") && len(name) > 5 && name[5] >= 'A' && name[5] <= 'Z' +} + +func isPlaneIdent(expr ast.Expr) bool { + expr = unwrapParen(expr) + if id, ok := expr.(*ast.Ident); ok { + return isPlaneVarName(id.Name) + } + return false +} + +func parseCanonicalPolicyVar(name string) (string, bool) { + if strings.HasPrefix(name, "canonicalPlane") && strings.HasSuffix(name, "Policy") { + p := strings.TrimSuffix(strings.TrimPrefix(name, "canonical"), "Policy") + if isPlaneVarName(p) { + return p, true + } + } + return "", false +} + +func parseCanonicalAccessVar(name string) (string, bool) { + if strings.HasPrefix(name, "canonicalPlane") && strings.HasSuffix(name, "Access") { + p := strings.TrimSuffix(strings.TrimPrefix(name, "canonical"), "Access") + if isPlaneVarName(p) { + return p, true + } + } + return "", false +} + +func isPlaneGeneratedSelector(expr ast.Expr) (string, bool) { + expr = unwrapParen(expr) + sel, ok := expr.(*ast.SelectorExpr) + if !ok || sel.Sel == nil || sel.Sel.Name != "generated" { + return "", false + } + p := rootPlaneVar(sel.X) + if isPlaneVarName(p) { + return p, true + } + return "", false +} + +func rootPlaneVar(expr ast.Expr) string { + expr = unwrapParen(expr) + switch x := expr.(type) { + case *ast.Ident: + if isPlaneVarName(x.Name) { + return x.Name + } + case *ast.SelectorExpr: + return rootPlaneVar(x.X) + } + return "" +} + +func extractCompositeLit(expr ast.Expr) *ast.CompositeLit { + expr = unwrapParen(expr) + switch e := expr.(type) { + case *ast.CompositeLit: + return e + case *ast.UnaryExpr: + if e.Op == token.AND { + return extractCompositeLit(e.X) + } + } + return nil +} + +func exprString(expr ast.Expr) string { + expr = unwrapParen(expr) + if expr == nil { + return "" + } + switch x := expr.(type) { + case *ast.Ident: + return x.Name + case *ast.SelectorExpr: + return exprString(x.X) + "." + x.Sel.Name + default: + return fmt.Sprintf("%T", expr) + } +} + +func validateCanonicalPolicyFields( + fset *token.FileSet, + normalizedRel string, + policyIdent *ast.Ident, + expectedPlaneVar string, + compLit *ast.CompositeLit, + allowedSelectors map[ast.Expr]bool, + reportedExprs map[ast.Expr]bool, +) []RuleFinding { + var findings []RuleFinding + seenFields := make(map[string]bool) + for _, elt := range compLit.Elts { + eltExpr := unwrapParen(elt) + kv, ok := eltExpr.(*ast.KeyValueExpr) + if !ok { + continue + } + keyId, ok := unwrapParen(kv.Key).(*ast.Ident) + if !ok { + continue + } + destField := keyId.Name + valExpr := unwrapParen(kv.Value) + + if seenFields[destField] { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(kv.Pos()).Line), + Detail: fmt.Sprintf("duplicate field %q in canonical policy %s", destField, policyIdent.Name), + }) + } + seenFields[destField] = true + + if expectedSrc, isDirect := directPolicyFieldMapping[destField]; isDirect { + sel, ok := valExpr.(*ast.SelectorExpr) + if !ok { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(valExpr.Pos()).Line), + Detail: fmt.Sprintf("mismatched source field in %s: destination field %s must capture %s.%s, got %s", policyIdent.Name, destField, expectedPlaneVar, expectedSrc, exprString(valExpr)), + }) + reportedExprs[valExpr] = true + continue + } + targetPlane := rootPlaneVar(sel.X) + if targetPlane == "" || targetPlane != expectedPlaneVar { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(sel.Pos()).Line), + Detail: fmt.Sprintf("cross-plane capture in %s: destination field %s must capture from %s, but captures from %s", policyIdent.Name, destField, expectedPlaneVar, exprString(sel.X)), + }) + reportedExprs[sel] = true + continue + } + if sel.Sel.Name != expectedSrc { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(sel.Pos()).Line), + Detail: fmt.Sprintf("mismatched source field in %s: destination field %s must capture %s, but captures %s", policyIdent.Name, destField, expectedSrc, sel.Sel.Name), + }) + reportedExprs[sel] = true + continue + } + allowedSelectors[sel] = true + } else if expectedDiagSub, isDiag := diagPolicyFieldMapping[destField]; isDiag { + sel, ok := valExpr.(*ast.SelectorExpr) + if !ok { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(valExpr.Pos()).Line), + Detail: fmt.Sprintf("mismatched source field in %s: destination field %s must capture %s.Diagnostics.%s, got %s", policyIdent.Name, destField, expectedPlaneVar, expectedDiagSub, exprString(valExpr)), + }) + reportedExprs[valExpr] = true + continue + } + innerSel, ok := unwrapParen(sel.X).(*ast.SelectorExpr) + if !ok { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(sel.Pos()).Line), + Detail: fmt.Sprintf("mismatched source field in %s: destination field %s must capture %s.Diagnostics.%s, got %s", policyIdent.Name, destField, expectedPlaneVar, expectedDiagSub, exprString(valExpr)), + }) + reportedExprs[valExpr] = true + continue + } + targetPlane := rootPlaneVar(innerSel.X) + if targetPlane == "" || targetPlane != expectedPlaneVar { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(innerSel.Pos()).Line), + Detail: fmt.Sprintf("cross-plane capture in %s: destination field %s must capture from %s, but captures from %s", policyIdent.Name, destField, expectedPlaneVar, exprString(innerSel.X)), + }) + reportedExprs[innerSel] = true + reportedExprs[sel] = true + continue + } + if innerSel.Sel.Name != "Diagnostics" || sel.Sel.Name != expectedDiagSub { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(sel.Pos()).Line), + Detail: fmt.Sprintf("mismatched source field in %s: destination field %s must capture Diagnostics.%s, but captures %s.%s", policyIdent.Name, destField, expectedDiagSub, innerSel.Sel.Name, sel.Sel.Name), + }) + reportedExprs[sel] = true + reportedExprs[innerSel] = true + continue + } + allowedSelectors[sel] = true + allowedSelectors[innerSel] = true + } else { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(kv.Pos()).Line), + Detail: fmt.Sprintf("unknown destination field %s in canonical policy %s", destField, policyIdent.Name), + }) + reportedExprs[valExpr] = true + } + } + + var missingFields []string + for _, expField := range expectedPolicyFieldsList { + if !seenFields[expField] { + missingFields = append(missingFields, expField) + } + } + if len(missingFields) > 0 { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(compLit.Pos()).Line), + Detail: fmt.Sprintf("incomplete canonical policy initialization in %s: missing expected field %q (missing %d of %d expected fields: %v)", policyIdent.Name, missingFields[0], len(missingFields), len(expectedPolicyFieldsList), missingFields), + }) + } + return findings +} diff --git a/internal/archtest/closed_plane_ratchet_policy_test.go b/internal/archtest/closed_plane_ratchet_policy_test.go new file mode 100644 index 00000000..c578ab32 --- /dev/null +++ b/internal/archtest/closed_plane_ratchet_policy_test.go @@ -0,0 +1,419 @@ +package archtest + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestClosedPlaneArchitectureRatchets_PolicyBindingAdversarialCases(t *testing.T) { + t.Parallel() + + t.Run("rejects mismatched PlaneX.generated binding", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } + PlaneSubmitHooks.generated = canonicalPlaneRequestPartHooksAccess +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "mismatched binding: PlaneSubmitHooks.generated must be bound to canonicalPlaneSubmitHooksAccess") { + found = true + break + } + } + assert.True(t, found, "must report mismatched binding") + }) + + t.Run("rejects mismatched policy in canonical access binding", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneRequestPartHooksPolicy, + } + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "mismatched policy in canonicalPlaneSubmitHooksAccess") { + found = true + break + } + } + assert.True(t, found, "must report mismatched policy in access binding") + }) + + // --- Duplicate init adversarial tests --- + + t.Run("rejects duplicate canonical policy initialization in same init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess + + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "duplicate canonical policy initialization for PlaneSubmitHooks") { + found = true + break + } + } + assert.True(t, found, "must report duplicate canonical policy initialization") + }) + + t.Run("rejects duplicate canonical policy initialization across multiple inits", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess +} + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "duplicate canonical policy initialization for PlaneSubmitHooks") { + found = true + break + } + } + assert.True(t, found, "must report duplicate canonical policy across multiple inits") + }) + + t.Run("rejects duplicate canonical access binding in init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "duplicate canonical access binding for PlaneSubmitHooks") { + found = true + break + } + } + assert.True(t, found, "must report duplicate canonical access binding") + }) + + t.Run("rejects duplicate PlaneX.generated binding in init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "duplicate PlaneSubmitHooks.generated binding in init()") { + found = true + break + } + } + assert.True(t, found, "must report duplicate PlaneSubmitHooks.generated binding") + }) + + // --- Later reassignment adversarial tests --- + + t.Run("rejects reassignment of canonical policy later in init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess + + canonicalPlaneSubmitHooksPolicy = nil +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "forbidden reassignment of canonicalPlaneSubmitHooksPolicy") { + found = true + break + } + } + assert.True(t, found, "must report forbidden reassignment of canonicalPlaneSubmitHooksPolicy") + }) + + t.Run("rejects reassignment of canonical policy in runtime function", func(t *testing.T) { + t.Parallel() + src := `package feature + +func tamper() { + canonicalPlaneSubmitHooksPolicy = nil +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "forbidden reassignment of canonicalPlaneSubmitHooksPolicy") { + found = true + break + } + } + assert.True(t, found, "must report forbidden reassignment in runtime function") + }) + + t.Run("rejects reassignment of canonical access in runtime function", func(t *testing.T) { + t.Parallel() + src := `package feature + +func tamper() { + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{} +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "forbidden reassignment of canonicalPlaneSubmitHooksAccess") { + found = true + break + } + } + assert.True(t, found, "must report forbidden access reassignment in runtime function") + }) + + t.Run("rejects reassignment of PlaneX.generated in runtime function", func(t *testing.T) { + t.Parallel() + src := `package feature + +func tamper() { + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "forbidden reassignment of PlaneSubmitHooks.generated") { + found = true + break + } + } + assert.True(t, found, "must report forbidden PlaneX.generated reassignment in runtime function") + }) +} diff --git a/internal/archtest/closed_plane_ratchet_selector.go b/internal/archtest/closed_plane_ratchet_selector.go new file mode 100644 index 00000000..7c103286 --- /dev/null +++ b/internal/archtest/closed_plane_ratchet_selector.go @@ -0,0 +1,409 @@ +package archtest + +import ( + "fmt" + "go/ast" + "go/token" + "slices" +) + +func checkPlaneGeneratedSelectors(fset *token.FileSet, normalizedRel string, f *ast.File) []RuleFinding { + var findings []RuleFinding + + allowedSelectors := make(map[ast.Expr]bool) + reportedExprs := make(map[ast.Expr]bool) + aliasVars := make(map[string]bool) + + // Gather all generated plane names in this file + generatedPlanes := make(map[string]bool) + + // 1. Gather from package-level variable declarations + for _, decl := range f.Decls { + gd, ok := decl.(*ast.GenDecl) + if !ok || gd.Tok != token.VAR { + continue + } + for _, spec := range gd.Specs { + vs, ok := spec.(*ast.ValueSpec) + if !ok { + continue + } + for _, name := range vs.Names { + if p, ok := parseCanonicalPolicyVar(name.Name); ok { + generatedPlanes[p] = true + } + if p, ok := parseCanonicalAccessVar(name.Name); ok { + generatedPlanes[p] = true + } + } + } + } + + // 2. Gather from assignments in the file (supporting synthetic test snippets without package-level vars) + ast.Inspect(f, func(n ast.Node) bool { + switch node := n.(type) { + case *ast.AssignStmt: + for _, lhs := range node.Lhs { + lhsUnwrapped := unwrapParen(lhs) + if id, ok := lhsUnwrapped.(*ast.Ident); ok { + if p, ok := parseCanonicalPolicyVar(id.Name); ok { + generatedPlanes[p] = true + } + if p, ok := parseCanonicalAccessVar(id.Name); ok { + generatedPlanes[p] = true + } + } else if p, ok := isPlaneGeneratedSelector(lhsUnwrapped); ok { + generatedPlanes[p] = true + } + } + } + return true + }) + + policyInitCount := make(map[string]int) + accessInitCount := make(map[string]int) + planeGeneratedInitCount := make(map[string]int) + + policyAttempted := make(map[string]bool) + accessAttempted := make(map[string]bool) + planeGeneratedAttempted := make(map[string]bool) + + designatedAssigns := make(map[*ast.AssignStmt]bool) + reportedAssigns := make(map[*ast.AssignStmt]bool) + + // Step 1: Find init() and whitelist only canonical policy initialization composite literals, + // canonical access bindings, and PlaneX.generated binding assignments, strictly validating + // semantic correspondence and completeness. + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Recv != nil || fn.Name == nil || fn.Name.Name != "init" || fn.Body == nil { + continue + } + + for _, stmt := range fn.Body.List { + assign, ok := stmt.(*ast.AssignStmt) + if !ok { + continue + } + + if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 || assign.Tok != token.ASSIGN { + continue + } + + lhs := unwrapParen(assign.Lhs[0]) + rhs := unwrapParen(assign.Rhs[0]) + + // 1. Policy initialization: canonicalPlaneXPolicy = &generatedPolicy[...]{ ... } + if id, ok := lhs.(*ast.Ident); ok { + if expectedPlaneVar, ok := parseCanonicalPolicyVar(id.Name); ok { + compLit := extractCompositeLit(rhs) + if compLit == nil { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(rhs.Pos()).Line), + Detail: fmt.Sprintf("forbidden reassignment of %s; closed planes must not be reassigned outside designated init capture/binding statements", id.Name), + }) + reportedAssigns[assign] = true + continue + } + policyAttempted[expectedPlaneVar] = true + if policyInitCount[expectedPlaneVar] > 0 { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(assign.Pos()).Line), + Detail: fmt.Sprintf("duplicate canonical policy initialization for %s in init(); closed planes require exactly one canonical generatedPolicy literal", expectedPlaneVar), + }) + reportedAssigns[assign] = true + continue + } + policyInitCount[expectedPlaneVar]++ + designatedAssigns[assign] = true + + findings = append(findings, validateCanonicalPolicyFields(fset, normalizedRel, id, expectedPlaneVar, compLit, allowedSelectors, reportedExprs)...) + continue + } + + // 2. Access binding: canonicalPlaneXAccess = generatedAccess[...]{ policy: canonicalPlaneXPolicy, ... } + if expectedPlaneVar, ok := parseCanonicalAccessVar(id.Name); ok { + compLit := extractCompositeLit(rhs) + if compLit == nil { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(rhs.Pos()).Line), + Detail: fmt.Sprintf("forbidden reassignment of %s; closed planes must not be reassigned outside designated init capture/binding statements", id.Name), + }) + reportedAssigns[assign] = true + continue + } + accessAttempted[expectedPlaneVar] = true + if accessInitCount[expectedPlaneVar] > 0 { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(assign.Pos()).Line), + Detail: fmt.Sprintf("duplicate canonical access binding for %s in init(); closed planes require exactly one canonical access binding", expectedPlaneVar), + }) + reportedAssigns[assign] = true + continue + } + accessInitCount[expectedPlaneVar]++ + designatedAssigns[assign] = true + + expectedPolicyVar := "canonical" + expectedPlaneVar + "Policy" + foundPolicy := false + for _, elt := range compLit.Elts { + eltExpr := unwrapParen(elt) + kv, ok := eltExpr.(*ast.KeyValueExpr) + if !ok { + continue + } + keyId, ok := unwrapParen(kv.Key).(*ast.Ident) + if !ok || keyId.Name != "policy" { + continue + } + foundPolicy = true + valExpr := unwrapParen(kv.Value) + valId, ok := valExpr.(*ast.Ident) + if !ok || valId.Name != expectedPolicyVar { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(valExpr.Pos()).Line), + Detail: fmt.Sprintf("mismatched policy in %s: policy must be %s, got %s", id.Name, expectedPolicyVar, exprString(valExpr)), + }) + reportedExprs[valExpr] = true + } + } + if !foundPolicy { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(compLit.Pos()).Line), + Detail: fmt.Sprintf("missing policy field in %s; canonical access must bind %s", id.Name, expectedPolicyVar), + }) + } + continue + } + } + + // 3. PlaneX.generated binding: PlaneX.generated = canonicalPlaneXAccess + if expectedPlaneVar, ok := isPlaneGeneratedSelector(lhs); ok { + expectedAccess := "canonical" + expectedPlaneVar + "Access" + rhsId, ok := rhs.(*ast.Ident) + if planeGeneratedInitCount[expectedPlaneVar] > 0 { + if ok && rhsId.Name == expectedAccess { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(assign.Pos()).Line), + Detail: fmt.Sprintf("duplicate %s.generated binding in init(); closed planes require exactly one PlaneX.generated binding", expectedPlaneVar), + }) + } else { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(assign.Pos()).Line), + Detail: fmt.Sprintf("forbidden reassignment of %s.generated; closed planes must not be reassigned outside designated init capture/binding statements", expectedPlaneVar), + }) + } + reportedAssigns[assign] = true + continue + } + planeGeneratedAttempted[expectedPlaneVar] = true + planeGeneratedInitCount[expectedPlaneVar]++ + designatedAssigns[assign] = true + + if ok && rhsId.Name == expectedAccess { + allowedSelectors[lhs] = true + if sel, ok := lhs.(*ast.SelectorExpr); ok { + allowedSelectors[sel] = true + } + } else { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(rhs.Pos()).Line), + Detail: fmt.Sprintf("mismatched binding: %s.generated must be bound to %s, got %s", expectedPlaneVar, expectedAccess, exprString(rhs)), + }) + reportedExprs[rhs] = true + reportedExprs[lhs] = true + } + continue + } + } + } + + // Step 2: Track aliases and forbidden passing/assignments + ast.Inspect(f, func(n ast.Node) bool { + switch node := n.(type) { + case *ast.AssignStmt: + for i, rhs := range node.Rhs { + rhsExpr := unwrapParen(rhs) + if isPlaneIdent(rhsExpr) { + if i < len(node.Lhs) { + lhsExpr := unwrapParen(node.Lhs[i]) + if id, ok := lhsExpr.(*ast.Ident); ok { + aliasVars[id.Name] = true + } + } + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(rhs.Pos()).Line), + Detail: fmt.Sprintf("forbidden alias assignment of %s; closed planes must not be aliased for runtime authority", exprString(rhsExpr)), + }) + } + } + case *ast.ValueSpec: + for i, val := range node.Values { + valExpr := unwrapParen(val) + if isPlaneIdent(valExpr) { + if i < len(node.Names) { + aliasVars[node.Names[i].Name] = true + } + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(val.Pos()).Line), + Detail: fmt.Sprintf("forbidden alias declaration of %s; closed planes must not be aliased for runtime authority", exprString(valExpr)), + }) + } + } + case *ast.CallExpr: + calledIdent := extractCalledIdent(node.Fun) + for _, arg := range node.Args { + argExpr := unwrapParen(arg) + if isPlaneIdent(argExpr) && calledIdent != "Get" { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(arg.Pos()).Line), + Detail: fmt.Sprintf("forbidden passing of %s to %s; closed planes must not be passed for runtime authority", exprString(argExpr), calledIdent), + }) + } + } + } + return true + }) + + // Step 3: Reject any canonical policy/access or PlaneX.generated reassignment outside designated init capture/binding statements. + ast.Inspect(f, func(n ast.Node) bool { + switch node := n.(type) { + case *ast.AssignStmt: + if designatedAssigns[node] || reportedAssigns[node] { + return true + } + for _, lhs := range node.Lhs { + lhsExpr := unwrapParen(lhs) + if id, ok := lhsExpr.(*ast.Ident); ok { + if _, ok := parseCanonicalPolicyVar(id.Name); ok { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(lhs.Pos()).Line), + Detail: fmt.Sprintf("forbidden reassignment of %s; closed planes must not be reassigned outside designated init capture/binding statements", id.Name), + }) + reportedAssigns[node] = true + } else if _, ok := parseCanonicalAccessVar(id.Name); ok { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(lhs.Pos()).Line), + Detail: fmt.Sprintf("forbidden reassignment of %s; closed planes must not be reassigned outside designated init capture/binding statements", id.Name), + }) + reportedAssigns[node] = true + } + } else if planeName, ok := isPlaneGeneratedSelector(lhsExpr); ok { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(lhs.Pos()).Line), + Detail: fmt.Sprintf("forbidden reassignment of %s.generated; closed planes must not be reassigned outside designated init capture/binding statements", planeName), + }) + reportedAssigns[node] = true + reportedExprs[lhsExpr] = true + } + } + case *ast.IncDecStmt: + xExpr := unwrapParen(node.X) + if id, ok := xExpr.(*ast.Ident); ok { + if _, ok := parseCanonicalPolicyVar(id.Name); ok { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(xExpr.Pos()).Line), + Detail: fmt.Sprintf("forbidden reassignment of %s; closed planes must not be reassigned outside designated init capture/binding statements", id.Name), + }) + } else if _, ok := parseCanonicalAccessVar(id.Name); ok { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(xExpr.Pos()).Line), + Detail: fmt.Sprintf("forbidden reassignment of %s; closed planes must not be reassigned outside designated init capture/binding statements", id.Name), + }) + } + } else if planeName, ok := isPlaneGeneratedSelector(xExpr); ok { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(xExpr.Pos()).Line), + Detail: fmt.Sprintf("forbidden reassignment of %s.generated; closed planes must not be reassigned outside designated init capture/binding statements", planeName), + }) + reportedExprs[xExpr] = true + } + } + return true + }) + + // Step 4: Inspect all selector expressions + ast.Inspect(f, func(n ast.Node) bool { + sel, ok := n.(*ast.SelectorExpr) + if !ok { + return true + } + + if allowedSelectors[sel] || reportedExprs[sel] { + return true + } + + // Check if target is a PlaneX + if planeName := rootPlaneVar(sel); planeName != "" { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(sel.Pos()).Line), + Detail: fmt.Sprintf("forbidden selector %s; closed planes must use canonical policy captured during init", exprString(sel)), + }) + return false // do not duplicate on nested selectors + } + + // Check if target is an aliased var + if id, ok := unwrapParen(sel.X).(*ast.Ident); ok && aliasVars[id.Name] { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(sel.Pos()).Line), + Detail: fmt.Sprintf("forbidden selector %s on aliased plane; closed planes must use canonical policy captured during init", exprString(sel)), + }) + return false + } + + return true + }) + + // Step 5: Verify completeness across all declared generated planes + sortedPlanes := make([]string, 0, len(generatedPlanes)) + for p := range generatedPlanes { + sortedPlanes = append(sortedPlanes, p) + } + slices.Sort(sortedPlanes) + + for _, planeName := range sortedPlanes { + if policyInitCount[planeName] == 0 && !policyAttempted[planeName] { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(f.Pos()).Line), + Detail: fmt.Sprintf("missing canonical policy initialization for %s; closed planes require exactly one complete canonical generatedPolicy literal", planeName), + }) + } + if accessInitCount[planeName] == 0 && !accessAttempted[planeName] { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(f.Pos()).Line), + Detail: fmt.Sprintf("missing canonical access binding for %s; closed planes require exactly one canonical access binding", planeName), + }) + } + if planeGeneratedInitCount[planeName] == 0 && !planeGeneratedAttempted[planeName] { + findings = append(findings, RuleFinding{ + Rule: RuleClosedPlaneNoGlobalPlaneSelectors, + Path: fmt.Sprintf("%s:%d", normalizedRel, fset.Position(f.Pos()).Line), + Detail: fmt.Sprintf("missing %s.generated binding; closed planes require exactly one PlaneX.generated binding to matching canonical access", planeName), + }) + } + } + + return findings +} diff --git a/internal/archtest/closed_plane_ratchet_selector_test.go b/internal/archtest/closed_plane_ratchet_selector_test.go new file mode 100644 index 00000000..3b962241 --- /dev/null +++ b/internal/archtest/closed_plane_ratchet_selector_test.go @@ -0,0 +1,426 @@ +package archtest + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestClosedPlaneArchitectureRatchets_SelectorAdversarialCases(t *testing.T) { + t.Parallel() + + t.Run("rejects PlaneX alias assignment in init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + alias := PlaneSubmitHooks + _ = alias +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "forbidden alias assignment of PlaneSubmitHooks") + }) + + t.Run("rejects PlaneX var declaration in init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + var alias = PlaneSubmitHooks + _ = alias +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "forbidden alias declaration of PlaneSubmitHooks") + }) + + t.Run("rejects PlaneX passing to function in init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func register(p any) {} + +func init() { + register(PlaneSubmitHooks) +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "forbidden passing of PlaneSubmitHooks to register") + }) + + t.Run("rejects PlaneX policy selector assignment to variable in init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + rules := PlaneSubmitHooks.Rules + _ = rules +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "PlaneSubmitHooks.Rules") + }) + + t.Run("rejects PlaneX policy selector passed to function in init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func checkRules(r SourceRules) {} + +func init() { + checkRules(PlaneSubmitHooks.Rules) +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "PlaneSubmitHooks.Rules") + }) + + t.Run("rejects PlaneX alias selector usage in init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + alias := PlaneSubmitHooks + _ = alias.Rules +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + foundAlias := false + foundSelector := false + for _, f := range findings { + if f.Rule == RuleClosedPlaneNoGlobalPlaneSelectors { + if strings.Contains(f.Detail, "forbidden alias assignment") { + foundAlias = true + } + if strings.Contains(f.Detail, "alias.Rules") { + foundSelector = true + } + } + } + assert.True(t, foundAlias, "must detect alias assignment") + assert.True(t, foundSelector, "must detect selector on alias") + }) + + t.Run("rejects PlaneX alias in runtime function", func(t *testing.T) { + t.Parallel() + src := `package feature + +func helper() { + alias := PlaneSubmitHooks + _ = alias +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "forbidden alias assignment of PlaneSubmitHooks") + }) + + t.Run("allows PlaneX selectors and declarations in non-generated file without false positives", func(t *testing.T) { + t.Parallel() + src := `package feature + +var PlaneCustom = Plane[string]{ + ID: "custom", +} + +func GetCustomID() string { + return PlaneCustom.ID +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/custom_plane.go", src) + assert.Empty(t, findings, "non-generated files must not trigger global plane selector ratchet") + }) + + t.Run("allows valid canonical policy initialization with arbitrary parentheses", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + (((canonicalPlaneSubmitHooksPolicy))) = (&generatedPolicy[[]hooks.SubmitHook]{ + planeID: (((PlaneSubmitHooks))).ID, + rules: ((PlaneSubmitHooks)).Rules, + nilPolicy: (PlaneSubmitHooks).NilPolicy, + isNil: (PlaneSubmitHooks).IsNil, + validate: (PlaneSubmitHooks).Validate, + validateIdentity: (PlaneSubmitHooks).ValidateIdentity, + combine: (PlaneSubmitHooks).Combine, + identity: (PlaneSubmitHooks).Identity, + exclusiveConflictError: (PlaneSubmitHooks).ExclusiveConflictError, + requestMaterializer: (PlaneSubmitHooks).RequestMaterializer, + requestBorrow: (PlaneSubmitHooks).RequestBorrow, + hookTarget: (PlaneSubmitHooks).HookTarget, + diagStageID: ((PlaneSubmitHooks).Diagnostics).StageID, + diagCoalesceGroup: (PlaneSubmitHooks).Diagnostics.CoalesceGroup, + diagOrder: (PlaneSubmitHooks).Diagnostics.Order, + diagMaterialize: (PlaneSubmitHooks).Diagnostics.Materialize, + diagPrivileges: (PlaneSubmitHooks).Diagnostics.Privileges, + }) + (((canonicalPlaneSubmitHooksAccess))) = (generatedAccess[[]hooks.SubmitHook]{ + policy: (canonicalPlaneSubmitHooksPolicy), + }) + ((PlaneSubmitHooks)).generated = (canonicalPlaneSubmitHooksAccess) +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + assert.Empty(t, findings, "parentheses in valid canonical policy init must be permitted") + }) + + t.Run("rejects forbidden PlaneX selector wrapped in parentheses outside init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func helper() { + rules := (((PlaneSubmitHooks))).Rules + _ = rules +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "PlaneSubmitHooks.Rules") + }) + + t.Run("rejects forbidden PlaneX alias wrapped in parentheses", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + alias := (((PlaneSubmitHooks))) + _ = ((alias)).Rules +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + }) + + t.Run("rejects cross-plane direct field capture in canonical policy init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneRequestPartHooks.ID, + } +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "cross-plane capture") + }) + + t.Run("rejects cross-plane diagnostics subfield capture in canonical policy init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + diagOrder: PlaneRequestPartHooks.Diagnostics.Order, + } +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "cross-plane capture") + }) + + t.Run("rejects mismatched direct source field in canonical policy init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.Rules, + } +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "mismatched source field") + }) + + t.Run("rejects mismatched diagnostics subfield in canonical policy init", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + diagOrder: PlaneSubmitHooks.Diagnostics.StageID, + } +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "mismatched source field") + }) + + t.Run("rejects non-diagnostics selector on diagnostics destination field", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + diagStageID: PlaneSubmitHooks.ID, + } +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "mismatched source field") + }) + + // --- Omission adversarial tests --- + + t.Run("rejects omission of expected fields in canonical policy composite literal", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + assert.Equal(t, RuleClosedPlaneNoGlobalPlaneSelectors, findings[0].Rule) + assert.Contains(t, findings[0].Detail, "incomplete canonical policy initialization") + assert.Contains(t, findings[0].Detail, "missing expected field") + }) + + t.Run("rejects omission of canonical policy initialization statement", func(t *testing.T) { + t.Parallel() + src := `package feature + +var ( + canonicalPlaneSubmitHooksPolicy *generatedPolicy[[]hooks.SubmitHook] + canonicalPlaneSubmitHooksAccess generatedAccess[[]hooks.SubmitHook] +) + +func init() { + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "missing canonical policy initialization for PlaneSubmitHooks") { + found = true + break + } + } + assert.True(t, found, "must report missing canonical policy initialization") + }) + + // --- Missing binding adversarial tests --- + + t.Run("rejects omission of canonical access binding", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "missing canonical access binding for PlaneSubmitHooks") { + found = true + break + } + } + assert.True(t, found, "must report missing canonical access binding") + }) + + t.Run("rejects omission of PlaneX.generated binding", func(t *testing.T) { + t.Parallel() + src := `package feature + +func init() { + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, + } +} +` + findings := scanClosedPlaneSyntheticSource(t, "pkg/lipsdk/feature/plane_generated.go", src) + require.NotEmpty(t, findings) + found := false + for _, f := range findings { + if strings.Contains(f.Detail, "missing PlaneSubmitHooks.generated binding") { + found = true + break + } + } + assert.True(t, found, "must report missing PlaneSubmitHooks.generated binding") + }) +} diff --git a/internal/archtest/plane_emitter.go b/internal/archtest/plane_emitter.go index 2a02baf6..bf96ce7e 100644 --- a/internal/archtest/plane_emitter.go +++ b/internal/archtest/plane_emitter.go @@ -6,6 +6,14 @@ import ( "strings" ) +func canonicalPolicyVar(p planeInfo) string { + return fmt.Sprintf("canonical%sPolicy", p.varName) +} + +func canonicalAccessVar(p planeInfo) string { + return fmt.Sprintf("canonical%sAccess", p.varName) +} + func generatePlanesCode(planes []planeInfo, sdkImports []string) ([]byte, error) { var buf bytes.Buffer @@ -109,11 +117,12 @@ func generatePlanesCode(planes []planeInfo, sdkImports []string) ([]byte, error) buf.WriteString("\tif gf == nil {\n\t\treturn nil\n\t}\n") buf.WriteString("\tnext := &generatedFrozen{\n") for _, p := range planes { + policyVar := canonicalPolicyVar(p) if p.hasRequestMaterializer { if strings.HasPrefix(p.typeExpr, "[]") { - fmt.Fprintf(&buf, "\t\t%s: materializeRequestSlice(gf.%s, %s.RequestMaterializer),\n", p.fieldName, p.fieldName, p.varName) + fmt.Fprintf(&buf, "\t\t%s: materializeRequestSlice(gf.%s, %s.requestMaterializer),\n", p.fieldName, p.fieldName, policyVar) } else { - fmt.Fprintf(&buf, "\t\t%s: %s.RequestMaterializer(gf.%s),\n", p.fieldName, p.varName, p.fieldName) + fmt.Fprintf(&buf, "\t\t%s: %s.requestMaterializer(gf.%s),\n", p.fieldName, policyVar, p.fieldName) } } else if strings.HasPrefix(p.typeExpr, "[]") { fmt.Fprintf(&buf, "\t\t%s: cloneSlice(gf.%s),\n", p.fieldName, p.fieldName) @@ -152,71 +161,72 @@ func generatePlanesCode(planes []planeInfo, sdkImports []string) ([]byte, error) buf.WriteString("func (gf *generatedFrozen) validate() error {\n") buf.WriteString("\tif gf == nil {\n\t\treturn nil\n\t}\n") for _, p := range planes { + policyVar := canonicalPolicyVar(p) if strings.HasPrefix(p.typeExpr, "[]") { if p.hasIdentity { fmt.Fprintf(&buf, "\tif gf.%s == nil {\n", p.fieldName) fmt.Fprintf(&buf, "\t\tif gf.%sHasID || gf.%sID != \"\" {\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.ID, errors.New(\"malformed metadata without value\"))\n", p.varName) + fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.planeID, errors.New(\"malformed metadata without value\"))\n", policyVar) fmt.Fprintf(&buf, "\t\t}\n") fmt.Fprintf(&buf, "\t} else {\n") - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.ID, err)\n", p.varName) + fmt.Fprintf(&buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(&buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.planeID, err)\n", policyVar) fmt.Fprintf(&buf, "\t\t\t}\n") fmt.Fprintf(&buf, "\t\t}\n") fmt.Fprintf(&buf, "\t\tif !gf.%sHasID {\n", p.fieldName) fmt.Fprintf(&buf, "\t\t\tif gf.%sID != \"\" || len(gf.%s) > 0 {\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.ID, errors.New(\"missing cached identity\"))\n", p.varName) + fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.planeID, errors.New(\"missing cached identity\"))\n", policyVar) fmt.Fprintf(&buf, "\t\t\t}\n") fmt.Fprintf(&buf, "\t\t} else {\n") fmt.Fprintf(&buf, "\t\t\tif gf.%sID == \"\" {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.ID, errors.New(\"missing cached identity\"))\n", p.varName) + fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.planeID, errors.New(\"missing cached identity\"))\n", policyVar) fmt.Fprintf(&buf, "\t\t\t}\n") if p.hasValidateIdentity { - fmt.Fprintf(&buf, "\t\t\tif err := %s.ValidateIdentity(gf.%sID); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.ID, err)\n", p.varName) + fmt.Fprintf(&buf, "\t\t\tif err := %s.validateIdentity(gf.%sID); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.planeID, err)\n", policyVar) fmt.Fprintf(&buf, "\t\t\t}\n") } fmt.Fprintf(&buf, "\t\t}\n") fmt.Fprintf(&buf, "\t}\n") } else { fmt.Fprintf(&buf, "\tif gf.%s != nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.ID, err)\n", p.varName) + fmt.Fprintf(&buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(&buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.planeID, err)\n", policyVar) fmt.Fprintf(&buf, "\t\t\t}\n") fmt.Fprintf(&buf, "\t\t}\n") fmt.Fprintf(&buf, "\t}\n") } } else if p.typeExpr == "int" { fmt.Fprintf(&buf, "\tif gf.%s < 0 {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\treturn newPlaneValidationError(%s.ID, fmt.Errorf(\"must be >= 0, got %%d\", gf.%s))\n", p.varName, p.fieldName) + fmt.Fprintf(&buf, "\t\treturn newPlaneValidationError(%s.planeID, fmt.Errorf(\"must be >= 0, got %%d\", gf.%s))\n", policyVar, p.fieldName) fmt.Fprintf(&buf, "\t}\n") - fmt.Fprintf(&buf, "\tif gf.%s > 0 && %s.Validate != nil {\n", p.fieldName, p.varName) - fmt.Fprintf(&buf, "\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.ID, err)\n", p.varName) + fmt.Fprintf(&buf, "\tif gf.%s > 0 && %s.validate != nil {\n", p.fieldName, policyVar) + fmt.Fprintf(&buf, "\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.planeID, err)\n", policyVar) fmt.Fprintf(&buf, "\t\t}\n") fmt.Fprintf(&buf, "\t}\n") } else if p.isExclusive { fmt.Fprintf(&buf, "\tif gf.%s == nil {\n", p.fieldName) fmt.Fprintf(&buf, "\t\tif gf.%sHasID || gf.%sID != \"\" {\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.ID, errors.New(\"malformed metadata without value\"))\n", p.varName) + fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.planeID, errors.New(\"malformed metadata without value\"))\n", policyVar) fmt.Fprintf(&buf, "\t\t}\n") fmt.Fprintf(&buf, "\t} else {\n") fmt.Fprintf(&buf, "\t\tif !gf.%sHasID || gf.%sID == \"\" {\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.ID, errors.New(\"missing cached identity\"))\n", p.varName) + fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.planeID, errors.New(\"missing cached identity\"))\n", policyVar) fmt.Fprintf(&buf, "\t\t}\n") if p.hasValidateIdentity { - fmt.Fprintf(&buf, "\t\tif err := %s.ValidateIdentity(gf.%sID); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.ID, err)\n", p.varName) + fmt.Fprintf(&buf, "\t\tif err := %s.validateIdentity(gf.%sID); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(&buf, "\t\t\treturn newPlaneValidationError(%s.planeID, err)\n", policyVar) fmt.Fprintf(&buf, "\t\t}\n") } fmt.Fprintf(&buf, "\t}\n") } else { fmt.Fprintf(&buf, "\tif gf.%s != nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.ID, err)\n", p.varName) + fmt.Fprintf(&buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(&buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(&buf, "\t\t\t\treturn newPlaneValidationError(%s.planeID, err)\n", policyVar) fmt.Fprintf(&buf, "\t\t\t}\n") fmt.Fprintf(&buf, "\t\t}\n") fmt.Fprintf(&buf, "\t}\n") @@ -225,157 +235,15 @@ func generatePlanesCode(planes []planeInfo, sdkImports []string) ([]byte, error) buf.WriteString("\treturn nil\n") buf.WriteString("}\n\n") + // 6b. checkSourceAdmission and checkCandidateSourceAdmission methods on generatedFrozen + emitCheckSourceAdmission(&buf, planes) + emitCheckCandidateSourceAdmission(&buf, planes) + // 7. contributeCandidateTo method on generatedFrozen - buf.WriteString("func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, source SourceKind, contributorID string) error {\n") - buf.WriteString("\tif gf == nil || gc == nil {\n\t\treturn nil\n\t}\n") - for _, p := range planes { - if !p.candidate { - continue - } - if strings.HasPrefix(p.typeExpr, "[]") { - if p.hasIdentity { - fmt.Fprintf(&buf, "\tif gf.%s == nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif gf.%sHasID || gf.%sID != \"\" {\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.ID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: malformed metadata without value\", ErrInvalidContribution),\n\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t} else {\n") - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif !gf.%sHasID {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\t\tif gf.%sID != \"\" || len(gf.%s) > 0 {\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: missing cached identity\", ErrInvalidContribution),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - fmt.Fprintf(&buf, "\t\t} else {\n") - fmt.Fprintf(&buf, "\t\t\tif gf.%sID == \"\" {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: missing cached identity\", ErrInvalidContribution),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - if p.hasValidateIdentity { - fmt.Fprintf(&buf, "\t\t\tif err := %s.ValidateIdentity(gf.%sID); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - } - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif err := %s.generated.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", p.varName, p.fieldName) - } else { - fmt.Fprintf(&buf, "\tif gf.%s != nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif err := %s.generated.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", p.varName, p.fieldName) - } - } else if p.typeExpr == "int" { - fmt.Fprintf(&buf, "\tif gf.%s < 0 {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\treturn &AttributedError{\n\t\t\tPluginID: contributorID,\n\t\t\tPlaneID: %s.ID,\n\t\t\tErr: fmt.Errorf(\"%%w: must be >= 0, got %%d\", ErrInvalidContribution, gf.%s),\n\t\t}\n", p.varName, p.fieldName) - buf.WriteString("\t}\n") - fmt.Fprintf(&buf, "\tif gf.%s > 0 {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif err := %s.generated.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", p.varName, p.fieldName) - } else if p.isExclusive { - fmt.Fprintf(&buf, "\tif gf.%s != nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif !gf.%sHasID || gf.%sID == \"\" {\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.ID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: frozen exclusive identity is missing\", ErrInvalidContribution),\n\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif gc.%sHasID {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn makeExclusiveConflictError(contributorID, %s.ID, %s.ExclusiveConflictError, gc.%sID, gf.%sID)\n", p.varName, p.varName, p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tgc.%s = gf.%s\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\tgc.%sID = gf.%sID\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\tgc.%sHasID = true\n", p.fieldName) - fmt.Fprintf(&buf, "\t}\n") - } else { - fmt.Fprintf(&buf, "\tif gf.%s != nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif err := %s.generated.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", p.varName, p.fieldName) - } - } - buf.WriteString("\treturn nil\n") - buf.WriteString("}\n\n") + emitContributeCandidateTo(&buf, planes) // 7b. replayAllPlanesTo method on generatedFrozen - buf.WriteString("func (gf *generatedFrozen) replayAllPlanesTo(gc *generatedContributions, source SourceKind, contributorID string) error {\n") - buf.WriteString("\tif gf == nil || gc == nil {\n\t\treturn nil\n\t}\n") - for _, p := range planes { - if strings.HasPrefix(p.typeExpr, "[]") { - if p.hasIdentity { - fmt.Fprintf(&buf, "\tif gf.%s != nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\thadDestinationValue := len(gc.%s) > 0\n", p.fieldName) - fmt.Fprintf(&buf, "\t\texistingID := gc.%sID\n", p.fieldName) - fmt.Fprintf(&buf, "\t\texistingHasID := gc.%sHasID\n\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tincoming := cloneSlice(gf.%s)\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tcurrent := cloneSlice(gc.%s)\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tcombined, err := %s.Combine(source, current, incoming)\n", p.varName) - buf.WriteString("\t\tif err != nil {\n") - fmt.Fprintf(&buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.ID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t}\n", p.varName) - buf.WriteString("\t\t}\n") - fmt.Fprintf(&buf, "\t\tif (gf.%s != nil || gc.%s != nil) && combined == nil {\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\tcombined = make(%s, 0)\n", p.typeExpr) - buf.WriteString("\t\t}\n") - fmt.Fprintf(&buf, "\t\tgc.%s = cloneSlice(combined)\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif len(gc.%s) == 0 {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\t\tgc.%sID = \"\"\n", p.fieldName) - fmt.Fprintf(&buf, "\t\t\tgc.%sHasID = false\n", p.fieldName) - buf.WriteString("\t\t} else if hadDestinationValue {\n") - fmt.Fprintf(&buf, "\t\t\tgc.%sID = existingID\n", p.fieldName) - fmt.Fprintf(&buf, "\t\t\tgc.%sHasID = existingHasID\n", p.fieldName) - buf.WriteString("\t\t} else {\n") - fmt.Fprintf(&buf, "\t\t\tgc.%sID = gf.%sID\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\tgc.%sHasID = gf.%sHasID\n", p.fieldName, p.fieldName) - buf.WriteString("\t\t}\n") - buf.WriteString("\t}\n") - } else { - fmt.Fprintf(&buf, "\tif gf.%s != nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif err := %s.generated.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", p.varName, p.fieldName) - } - } else if p.typeExpr == "int" { - fmt.Fprintf(&buf, "\tif gf.%s > 0 {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif err := %s.generated.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", p.varName, p.fieldName) - } else if p.isExclusive { - fmt.Fprintf(&buf, "\tif gf.%s != nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif !gf.%sHasID || gf.%sID == \"\" {\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.ID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: frozen exclusive identity is missing\", ErrInvalidContribution),\n\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif gc.%sHasID {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\t\treturn makeExclusiveConflictError(contributorID, %s.ID, %s.ExclusiveConflictError, gc.%sID, gf.%sID)\n", p.varName, p.varName, p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tgc.%s = gf.%s\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\tgc.%sID = gf.%sID\n", p.fieldName, p.fieldName) - fmt.Fprintf(&buf, "\t\tgc.%sHasID = true\n", p.fieldName) - fmt.Fprintf(&buf, "\t}\n") - } else { - fmt.Fprintf(&buf, "\tif gf.%s != nil {\n", p.fieldName) - fmt.Fprintf(&buf, "\t\tif %s.Validate != nil {\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tif err := %s.Validate(gf.%s); err != nil {\n", p.varName, p.fieldName) - fmt.Fprintf(&buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.ID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", p.varName) - fmt.Fprintf(&buf, "\t\t\t}\n") - fmt.Fprintf(&buf, "\t\t}\n") - fmt.Fprintf(&buf, "\t\tif err := %s.generated.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", p.varName, p.fieldName) - } - } - buf.WriteString("\treturn nil\n") - buf.WriteString("}\n\n") + emitReplayAllPlanesTo(&buf, planes) // 7c. hasIdentityReplayRule method on generatedFrozen buf.WriteString("// hasIdentityReplayRule reports whether gf contains a present identity-bearing plane\n") @@ -386,30 +254,64 @@ func generatePlanesCode(planes []planeInfo, sdkImports []string) ([]byte, error) if !p.hasIdentity { continue } - fmt.Fprintf(&buf, "\tif %s.Rules.RuleFor(source) == rule {\n", p.varName) + policyVar := canonicalPolicyVar(p) + fmt.Fprintf(&buf, "\tif %s.rules.RuleFor(source) == rule {\n", policyVar) if strings.HasPrefix(p.typeExpr, "[]") { - fmt.Fprintf(&buf, "\t\tif len(gf.%s) > 0 {\n\t\t\treturn %s.ID, true\n\t\t}\n", p.fieldName, p.varName) + fmt.Fprintf(&buf, "\t\tif len(gf.%s) > 0 {\n\t\t\treturn %s.planeID, true\n\t\t}\n", p.fieldName, policyVar) } else if p.typeExpr == "int" { - fmt.Fprintf(&buf, "\t\tif gf.%s > 0 {\n\t\t\treturn %s.ID, true\n\t\t}\n", p.fieldName, p.varName) + fmt.Fprintf(&buf, "\t\tif gf.%s > 0 {\n\t\t\treturn %s.planeID, true\n\t\t}\n", p.fieldName, policyVar) } else { - fmt.Fprintf(&buf, "\t\tif !isNilValue(gf.%s) {\n\t\t\treturn %s.ID, true\n\t\t}\n", p.fieldName, p.varName) + fmt.Fprintf(&buf, "\t\tif !isNilValue(gf.%s) {\n\t\t\treturn %s.planeID, true\n\t\t}\n", p.fieldName, policyVar) } buf.WriteString("\t}\n") } buf.WriteString("\treturn \"\", false\n") buf.WriteString("}\n\n") + // 8b. canonical policy and access declarations + buf.WriteString("// Canonical plane policies and access handles captured once at package init.\n") + buf.WriteString("var (\n") + for _, p := range planes { + fmt.Fprintf(&buf, "\t%s *generatedPolicy[%s]\n", canonicalPolicyVar(p), p.typeExpr) + fmt.Fprintf(&buf, "\t%s generatedAccess[%s]\n", canonicalAccessVar(p), p.typeExpr) + } + buf.WriteString(")\n\n") + // 9. init() binding closures buf.WriteString("func init() {\n") for _, p := range planes { - fmt.Fprintf(&buf, "\t%s.generated = generatedAccess[%s]{\n", p.varName, p.typeExpr) + policyVar := canonicalPolicyVar(p) + accessVar := canonicalAccessVar(p) + + // 1. Capture canonical policy first before any closures + fmt.Fprintf(&buf, "\t%s = &generatedPolicy[%s]{\n", policyVar, p.typeExpr) + fmt.Fprintf(&buf, "\t\tplaneID: %s.ID,\n", p.varName) + fmt.Fprintf(&buf, "\t\trules: %s.Rules,\n", p.varName) + fmt.Fprintf(&buf, "\t\tnilPolicy: %s.NilPolicy,\n", p.varName) + fmt.Fprintf(&buf, "\t\tisNil: %s.IsNil,\n", p.varName) + fmt.Fprintf(&buf, "\t\tvalidate: %s.Validate,\n", p.varName) + fmt.Fprintf(&buf, "\t\tvalidateIdentity: %s.ValidateIdentity,\n", p.varName) + fmt.Fprintf(&buf, "\t\tcombine: %s.Combine,\n", p.varName) + fmt.Fprintf(&buf, "\t\tidentity: %s.Identity,\n", p.varName) + fmt.Fprintf(&buf, "\t\texclusiveConflictError: %s.ExclusiveConflictError,\n", p.varName) + fmt.Fprintf(&buf, "\t\trequestMaterializer: %s.RequestMaterializer,\n", p.varName) + fmt.Fprintf(&buf, "\t\trequestBorrow: %s.RequestBorrow,\n", p.varName) + fmt.Fprintf(&buf, "\t\thookTarget: %s.HookTarget,\n", p.varName) + fmt.Fprintf(&buf, "\t\tdiagStageID: %s.Diagnostics.StageID,\n", p.varName) + fmt.Fprintf(&buf, "\t\tdiagCoalesceGroup: %s.Diagnostics.CoalesceGroup,\n", p.varName) + fmt.Fprintf(&buf, "\t\tdiagOrder: %s.Diagnostics.Order,\n", p.varName) + fmt.Fprintf(&buf, "\t\tdiagMaterialize: %s.Diagnostics.Materialize,\n", p.varName) + fmt.Fprintf(&buf, "\t\tdiagPrivileges: %s.Diagnostics.Privileges,\n", p.varName) + buf.WriteString("\t}\n") - // contribute closure + // 2. Access closure definition using canonicalPolicyVar + fmt.Fprintf(&buf, "\t%s = generatedAccess[%s]{\n", accessVar, p.typeExpr) + fmt.Fprintf(&buf, "\t\tpolicy: %s,\n", policyVar) fmt.Fprintf(&buf, "\t\tcontribute: func(gc *generatedContributions, source SourceKind, pluginID string, v %s) error {\n", p.typeExpr) if strings.HasPrefix(p.typeExpr, "[]") { - fmt.Fprintf(&buf, "\t\t\tincoming := cloneSlice(v)\n") + buf.WriteString("\t\t\tincoming := cloneSlice(v)\n") fmt.Fprintf(&buf, "\t\t\tcurrent := cloneSlice(gc.%s)\n", p.fieldName) - fmt.Fprintf(&buf, "\t\t\tcombined, err := %s.Combine(source, current, incoming)\n", p.varName) + fmt.Fprintf(&buf, "\t\t\tcombined, err := %s.combine(source, current, incoming)\n", policyVar) buf.WriteString("\t\t\tif err != nil {\n") buf.WriteString("\t\t\t\treturn err\n") buf.WriteString("\t\t\t}\n") @@ -418,18 +320,18 @@ func generatePlanesCode(planes []planeInfo, sdkImports []string) ([]byte, error) buf.WriteString("\t\t\t}\n") fmt.Fprintf(&buf, "\t\t\tgc.%s = cloneSlice(combined)\n", p.fieldName) if p.hasIdentity { - fmt.Fprintf(&buf, "\t\t\tid, hasID := %s.Identity(gc.%s)\n", p.varName, p.fieldName) + fmt.Fprintf(&buf, "\t\t\tid, hasID := %s.identity(gc.%s)\n", policyVar, p.fieldName) fmt.Fprintf(&buf, "\t\t\tgc.%sID = id\n", p.fieldName) fmt.Fprintf(&buf, "\t\t\tgc.%sHasID = hasID\n", p.fieldName) } } else { - fmt.Fprintf(&buf, "\t\t\tcombined, err := %s.Combine(source, gc.%s, v)\n", p.varName, p.fieldName) + fmt.Fprintf(&buf, "\t\t\tcombined, err := %s.combine(source, gc.%s, v)\n", policyVar, p.fieldName) buf.WriteString("\t\t\tif err != nil {\n") buf.WriteString("\t\t\t\treturn err\n") buf.WriteString("\t\t\t}\n") fmt.Fprintf(&buf, "\t\t\tgc.%s = combined\n", p.fieldName) if p.hasIdentity { - fmt.Fprintf(&buf, "\t\t\tid, hasID := %s.Identity(gc.%s)\n", p.varName, p.fieldName) + fmt.Fprintf(&buf, "\t\t\tid, hasID := %s.identity(gc.%s)\n", policyVar, p.fieldName) fmt.Fprintf(&buf, "\t\t\tgc.%sID = id\n", p.fieldName) fmt.Fprintf(&buf, "\t\t\tgc.%sHasID = hasID\n", p.fieldName) } @@ -465,20 +367,8 @@ func generatePlanesCode(planes []planeInfo, sdkImports []string) ([]byte, error) buf.WriteString("\t\t},\n") } - // policy - fmt.Fprintf(&buf, "\t\tpolicy: &generatedPolicy[%s]{\n", p.typeExpr) - fmt.Fprintf(&buf, "\t\t\tplaneID: %s.ID,\n", p.varName) - fmt.Fprintf(&buf, "\t\t\trules: %s.Rules,\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tnilPolicy: %s.NilPolicy,\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tisNil: %s.IsNil,\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tvalidate: %s.Validate,\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tvalidateIdentity: %s.ValidateIdentity,\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tcombine: %s.Combine,\n", p.varName) - fmt.Fprintf(&buf, "\t\t\tidentity: %s.Identity,\n", p.varName) - fmt.Fprintf(&buf, "\t\t\texclusiveConflictError: %s.ExclusiveConflictError,\n", p.varName) - buf.WriteString("\t\t},\n") - buf.WriteString("\t}\n") + fmt.Fprintf(&buf, "\t%s.generated = %s\n\n", p.varName, accessVar) } buf.WriteString("}\n\n") diff --git a/internal/archtest/plane_emitter_diag.go b/internal/archtest/plane_emitter_diag.go index 51952c85..9f220267 100644 --- a/internal/archtest/plane_emitter_diag.go +++ b/internal/archtest/plane_emitter_diag.go @@ -17,11 +17,12 @@ func emitProjectDiagnostics(buf *bytes.Buffer, planes []planeInfo) { if !p.hasDiagStageID { continue } + policyVar := canonicalPolicyVar(p) fmt.Fprintf(buf, "\t// Project %s\n", p.varName) buf.WriteString("\t{\n") fmt.Fprintf(buf, "\t\tval := gf.%s\n", p.fieldName) - fmt.Fprintf(buf, "\t\tocc := %s.MaterializeOccupants(val)\n", p.varName) - fmt.Fprintf(buf, "\t\tpriv := %s.ProjectPrivileges(val)\n", p.varName) + fmt.Fprintf(buf, "\t\tocc := %s.materializeOccupants(val)\n", policyVar) + fmt.Fprintf(buf, "\t\tpriv := %s.projectPrivileges(val)\n", policyVar) buf.WriteString("\t\tif len(occ) > 0 || len(priv.Flags) > 0 {\n") buf.WriteString("\t\t\tvar occCopy []DiagnosticOccupant\n") buf.WriteString("\t\t\tif len(occ) > 0 {\n") @@ -44,10 +45,10 @@ func emitProjectDiagnostics(buf *bytes.Buffer, planes []planeInfo) { buf.WriteString("\t\t\t\tprivCopy = append([]string(nil), priv.Flags...)\n") buf.WriteString("\t\t\t}\n") buf.WriteString("\t\t\tprojections = append(projections, DiagnosticPlaneProjection{\n") - fmt.Fprintf(buf, "\t\t\t\tPlaneID: %s.ID,\n", p.varName) - fmt.Fprintf(buf, "\t\t\t\tStageID: %s.Diagnostics.StageID,\n", p.varName) - fmt.Fprintf(buf, "\t\t\t\tCoalesceGroup: %s.Diagnostics.CoalesceGroup,\n", p.varName) - fmt.Fprintf(buf, "\t\t\t\tOrder: %s.Diagnostics.Order,\n", p.varName) + fmt.Fprintf(buf, "\t\t\t\tPlaneID: %s.planeID,\n", policyVar) + fmt.Fprintf(buf, "\t\t\t\tStageID: %s.diagStageID,\n", policyVar) + fmt.Fprintf(buf, "\t\t\t\tCoalesceGroup: %s.diagCoalesceGroup,\n", policyVar) + fmt.Fprintf(buf, "\t\t\t\tOrder: %s.diagOrder,\n", policyVar) buf.WriteString("\t\t\t\tOccupants: occCopy,\n") buf.WriteString("\t\t\t\tPrivileges: PrivilegeProjection{Flags: privCopy},\n") buf.WriteString("\t\t\t})\n") diff --git a/internal/archtest/plane_emitter_helpers.go b/internal/archtest/plane_emitter_helpers.go index d178d69c..64e412be 100644 --- a/internal/archtest/plane_emitter_helpers.go +++ b/internal/archtest/plane_emitter_helpers.go @@ -37,16 +37,250 @@ func emitRequestExecutionView(buf *bytes.Buffer, planes []planeInfo) { func emitGenerationBinderMethods(buf *bytes.Buffer, planes []planeInfo) { for _, p := range planes { if p.genBinderRule == "CombReplaceByIdentity" { + policyVar := canonicalPolicyVar(p) + accessVar := canonicalAccessVar(p) pascalName := strings.TrimPrefix(p.varName, "Plane") fmt.Fprintf(buf, "// Bind%s replaces %s under SourceGenerationBinder semantics.\n", pascalName, pascalName) fmt.Fprintf(buf, "func (s *ContributionSet) Bind%s(contributorID string, v %s) error {\n", pascalName, p.typeExpr) - fmt.Fprintf(buf, "\treturn ContributeSource(s, %s, SourceGenerationBinder, contributorID, v)\n", p.varName) + fmt.Fprintf(buf, "\treturn contributePolicy(s, %s, %s.contribute, %s.identity, SourceGenerationBinder, contributorID, v)\n", policyVar, accessVar, accessVar) buf.WriteString("}\n\n") fmt.Fprintf(buf, "// Replace%s replaces %s under SourceGenerationBinder semantics.\n", pascalName, pascalName) fmt.Fprintf(buf, "func (s *ContributionSet) Replace%s(contributorID string, v %s) error {\n", pascalName, p.typeExpr) - fmt.Fprintf(buf, "\treturn ContributeSource(s, %s, SourceGenerationBinder, contributorID, v)\n", p.varName) + fmt.Fprintf(buf, "\treturn contributePolicy(s, %s, %s.contribute, %s.identity, SourceGenerationBinder, contributorID, v)\n", policyVar, accessVar, accessVar) buf.WriteString("}\n\n") } } } + +// emitCheckSourceAdmission generates checkSourceAdmission method on generatedFrozen. +func emitCheckSourceAdmission(buf *bytes.Buffer, planes []planeInfo) { + buf.WriteString("// checkSourceAdmission checks whether all present planes in gf support source.\n") + buf.WriteString("func (gf *generatedFrozen) checkSourceAdmission(source SourceKind, contributorID string) error {\n") + buf.WriteString("\tif gf == nil {\n\t\treturn nil\n\t}\n") + for _, p := range planes { + policyVar := canonicalPolicyVar(p) + if strings.HasPrefix(p.typeExpr, "[]") { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + } else if p.typeExpr == "int" { + fmt.Fprintf(buf, "\tif gf.%s > 0 {\n", p.fieldName) + } else { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + } + fmt.Fprintf(buf, "\t\tif %s.rules.RuleFor(source) == CombUnsupported {\n", policyVar) + fmt.Fprintf(buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: source %%v is not supported on plane %%q\", ErrUnsupportedSource, source, %s.planeID),\n\t\t\t}\n", policyVar, policyVar) + buf.WriteString("\t\t}\n\t}\n") + } + buf.WriteString("\treturn nil\n") + buf.WriteString("}\n\n") +} + +// emitCheckCandidateSourceAdmission generates checkCandidateSourceAdmission method on generatedFrozen. +func emitCheckCandidateSourceAdmission(buf *bytes.Buffer, planes []planeInfo) { + buf.WriteString("// checkCandidateSourceAdmission checks whether all present candidate planes in gf support source.\n") + buf.WriteString("func (gf *generatedFrozen) checkCandidateSourceAdmission(source SourceKind, contributorID string) error {\n") + buf.WriteString("\tif gf == nil {\n\t\treturn nil\n\t}\n") + for _, p := range planes { + if !p.candidate { + continue + } + policyVar := canonicalPolicyVar(p) + if strings.HasPrefix(p.typeExpr, "[]") { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + } else if p.typeExpr == "int" { + fmt.Fprintf(buf, "\tif gf.%s > 0 {\n", p.fieldName) + } else { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + } + fmt.Fprintf(buf, "\t\tif %s.rules.RuleFor(source) == CombUnsupported {\n", policyVar) + fmt.Fprintf(buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: source %%v is not supported on plane %%q\", ErrUnsupportedSource, source, %s.planeID),\n\t\t\t}\n", policyVar, policyVar) + buf.WriteString("\t\t}\n\t}\n") + } + buf.WriteString("\treturn nil\n") + buf.WriteString("}\n\n") +} + +// emitContributeCandidateTo generates contributeCandidateTo method on generatedFrozen. +func emitContributeCandidateTo(buf *bytes.Buffer, planes []planeInfo) { + buf.WriteString("func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, source SourceKind, contributorID string) error {\n") + buf.WriteString("\tif gf == nil || gc == nil {\n\t\treturn nil\n\t}\n") + buf.WriteString("\tif err := gf.checkCandidateSourceAdmission(source, contributorID); err != nil {\n\t\treturn err\n\t}\n") + for _, p := range planes { + if !p.candidate { + continue + } + policyVar := canonicalPolicyVar(p) + accessVar := canonicalAccessVar(p) + if strings.HasPrefix(p.typeExpr, "[]") { + if p.hasIdentity { + fmt.Fprintf(buf, "\tif gf.%s == nil {\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif gf.%sHasID || gf.%sID != \"\" {\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: malformed metadata without value\", ErrInvalidContribution),\n\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t} else {\n") + fmt.Fprintf(buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\tif !gf.%sHasID {\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\tif gf.%sID != \"\" || len(gf.%s) > 0 {\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: missing cached identity\", ErrInvalidContribution),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + fmt.Fprintf(buf, "\t\t} else {\n") + fmt.Fprintf(buf, "\t\t\tif gf.%sID == \"\" {\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: missing cached identity\", ErrInvalidContribution),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + if p.hasValidateIdentity { + fmt.Fprintf(buf, "\t\t\tif err := %s.validateIdentity(gf.%sID); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + } + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\thadDestinationValue := len(gc.%s) > 0\n", p.fieldName) + fmt.Fprintf(buf, "\t\texistingID := gc.%sID\n", p.fieldName) + fmt.Fprintf(buf, "\t\texistingHasID := gc.%sHasID\n\n", p.fieldName) + fmt.Fprintf(buf, "\t\tincoming := cloneSlice(gf.%s)\n", p.fieldName) + fmt.Fprintf(buf, "\t\tcurrent := cloneSlice(gc.%s)\n", p.fieldName) + fmt.Fprintf(buf, "\t\tcombined, err := %s.combine(source, current, incoming)\n", policyVar) + buf.WriteString("\t\tif err != nil {\n") + fmt.Fprintf(buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t}\n", policyVar) + buf.WriteString("\t\t}\n") + fmt.Fprintf(buf, "\t\tif (gf.%s != nil || gc.%s != nil) && combined == nil {\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t\tcombined = make(%s, 0)\n", p.typeExpr) + buf.WriteString("\t\t}\n") + fmt.Fprintf(buf, "\t\tgc.%s = cloneSlice(combined)\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif len(gc.%s) == 0 {\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\tgc.%sID = \"\"\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\tgc.%sHasID = false\n", p.fieldName) + buf.WriteString("\t\t} else if hadDestinationValue {\n") + fmt.Fprintf(buf, "\t\t\tgc.%sID = existingID\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\tgc.%sHasID = existingHasID\n", p.fieldName) + buf.WriteString("\t\t} else {\n") + fmt.Fprintf(buf, "\t\t\tgc.%sID = gf.%sID\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t\tgc.%sHasID = gf.%sHasID\n", p.fieldName, p.fieldName) + buf.WriteString("\t\t}\n") + fmt.Fprintf(buf, "\t}\n") + } else { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\tif err := %s.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", accessVar, p.fieldName) + } + } else if p.typeExpr == "int" { + fmt.Fprintf(buf, "\tif gf.%s < 0 {\n", p.fieldName) + fmt.Fprintf(buf, "\t\treturn &AttributedError{\n\t\t\tPluginID: contributorID,\n\t\t\tPlaneID: %s.planeID,\n\t\t\tErr: fmt.Errorf(\"%%w: must be >= 0, got %%d\", ErrInvalidContribution, gf.%s),\n\t\t}\n", policyVar, p.fieldName) + buf.WriteString("\t}\n") + fmt.Fprintf(buf, "\tif gf.%s > 0 {\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\tif err := %s.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", accessVar, p.fieldName) + } else if p.isExclusive { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif !gf.%sHasID || gf.%sID == \"\" {\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: frozen exclusive identity is missing\", ErrInvalidContribution),\n\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\tif gc.%sHasID {\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\treturn makeExclusiveConflictError(contributorID, %s.planeID, %s.exclusiveConflictError, gc.%sID, gf.%sID)\n", policyVar, policyVar, p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\tgc.%s = gf.%s\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\tgc.%sID = gf.%sID\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\tgc.%sHasID = true\n", p.fieldName) + fmt.Fprintf(buf, "\t}\n") + } else { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\tif err := %s.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", accessVar, p.fieldName) + } + } + buf.WriteString("\treturn nil\n") + buf.WriteString("}\n\n") +} + +// emitReplayAllPlanesTo generates replayAllPlanesTo method on generatedFrozen. +func emitReplayAllPlanesTo(buf *bytes.Buffer, planes []planeInfo) { + buf.WriteString("func (gf *generatedFrozen) replayAllPlanesTo(gc *generatedContributions, source SourceKind, contributorID string) error {\n") + buf.WriteString("\tif gf == nil || gc == nil {\n\t\treturn nil\n\t}\n") + buf.WriteString("\tif err := gf.checkSourceAdmission(source, contributorID); err != nil {\n\t\treturn err\n\t}\n") + for _, p := range planes { + policyVar := canonicalPolicyVar(p) + accessVar := canonicalAccessVar(p) + if strings.HasPrefix(p.typeExpr, "[]") { + if p.hasIdentity { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + fmt.Fprintf(buf, "\t\thadDestinationValue := len(gc.%s) > 0\n", p.fieldName) + fmt.Fprintf(buf, "\t\texistingID := gc.%sID\n", p.fieldName) + fmt.Fprintf(buf, "\t\texistingHasID := gc.%sHasID\n\n", p.fieldName) + fmt.Fprintf(buf, "\t\tincoming := cloneSlice(gf.%s)\n", p.fieldName) + fmt.Fprintf(buf, "\t\tcurrent := cloneSlice(gc.%s)\n", p.fieldName) + fmt.Fprintf(buf, "\t\tcombined, err := %s.combine(source, current, incoming)\n", policyVar) + buf.WriteString("\t\tif err != nil {\n") + fmt.Fprintf(buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t}\n", policyVar) + buf.WriteString("\t\t}\n") + fmt.Fprintf(buf, "\t\tif (gf.%s != nil || gc.%s != nil) && combined == nil {\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t\tcombined = make(%s, 0)\n", p.typeExpr) + buf.WriteString("\t\t}\n") + fmt.Fprintf(buf, "\t\tgc.%s = cloneSlice(combined)\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif len(gc.%s) == 0 {\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\tgc.%sID = \"\"\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\tgc.%sHasID = false\n", p.fieldName) + buf.WriteString("\t\t} else if hadDestinationValue {\n") + fmt.Fprintf(buf, "\t\t\tgc.%sID = existingID\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\tgc.%sHasID = existingHasID\n", p.fieldName) + buf.WriteString("\t\t} else {\n") + fmt.Fprintf(buf, "\t\t\tgc.%sID = gf.%sID\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t\tgc.%sHasID = gf.%sHasID\n", p.fieldName, p.fieldName) + buf.WriteString("\t\t}\n") + fmt.Fprintf(buf, "\t}\n") + } else { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\tif err := %s.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", accessVar, p.fieldName) + } + } else if p.typeExpr == "int" { + fmt.Fprintf(buf, "\tif gf.%s > 0 {\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\tif err := %s.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", accessVar, p.fieldName) + } else if p.isExclusive { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif !gf.%sHasID || gf.%sID == \"\" {\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t\treturn &AttributedError{\n\t\t\t\tPluginID: contributorID,\n\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\tErr: fmt.Errorf(\"%%w: frozen exclusive identity is missing\", ErrInvalidContribution),\n\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\tif gc.%sHasID {\n", p.fieldName) + fmt.Fprintf(buf, "\t\t\treturn makeExclusiveConflictError(contributorID, %s.planeID, %s.exclusiveConflictError, gc.%sID, gf.%sID)\n", policyVar, policyVar, p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\tgc.%s = gf.%s\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\tgc.%sID = gf.%sID\n", p.fieldName, p.fieldName) + fmt.Fprintf(buf, "\t\tgc.%sHasID = true\n", p.fieldName) + fmt.Fprintf(buf, "\t}\n") + } else { + fmt.Fprintf(buf, "\tif gf.%s != nil {\n", p.fieldName) + fmt.Fprintf(buf, "\t\tif %s.validate != nil {\n", policyVar) + fmt.Fprintf(buf, "\t\t\tif err := %s.validate(gf.%s); err != nil {\n", policyVar, p.fieldName) + fmt.Fprintf(buf, "\t\t\t\treturn &AttributedError{\n\t\t\t\t\tPluginID: contributorID,\n\t\t\t\t\tPlaneID: %s.planeID,\n\t\t\t\t\tErr: fmt.Errorf(\"%%w: %%w\", ErrInvalidContribution, err),\n\t\t\t\t}\n", policyVar) + fmt.Fprintf(buf, "\t\t\t}\n") + fmt.Fprintf(buf, "\t\t}\n") + fmt.Fprintf(buf, "\t\tif err := %s.contribute(gc, source, contributorID, gf.%s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n", accessVar, p.fieldName) + } + } + buf.WriteString("\treturn nil\n") + buf.WriteString("}\n\n") +} diff --git a/internal/archtest/plane_emitter_hook.go b/internal/archtest/plane_emitter_hook.go index 3c1f8791..45bc02a8 100644 --- a/internal/archtest/plane_emitter_hook.go +++ b/internal/archtest/plane_emitter_hook.go @@ -37,7 +37,7 @@ func emitHookConfig(buf *bytes.Buffer, planes []planeInfo) { fmt.Fprintf(buf, "func ProjectHookConfig(frozen FrozenPlaneSet, policy %s.ToolReactorErrorPolicy) HookConfig {\n", hookPkg) buf.WriteString("\treturn HookConfig{\n") for _, p := range hookPlanes { - fmt.Fprintf(buf, "\t\t%s: Get(frozen, %s),\n", p.hookTarget, p.varName) + fmt.Fprintf(buf, "\t\t%s: %s.get(frozen.frozen),\n", p.hookTarget, canonicalAccessVar(p)) } buf.WriteString("\t\tToolReactorErrorPolicy: policy,\n") buf.WriteString("\t}\n") diff --git a/internal/archtest/plane_generator_identity_test.go b/internal/archtest/plane_generator_identity_test.go index 5d04786b..5582a907 100644 --- a/internal/archtest/plane_generator_identity_test.go +++ b/internal/archtest/plane_generator_identity_test.go @@ -56,7 +56,7 @@ var StandardPlanes = []any{PlaneSyntheticReplace} assert.Contains(t, code, "gc.syntheticReplaceHasID = gf.syntheticReplaceHasID") // 3. Verify contribute closure extracts identity - assert.Contains(t, code, "id, hasID := PlaneSyntheticReplace.Identity(gc.syntheticReplace)") + assert.Contains(t, code, "id, hasID := canonicalPlaneSyntheticReplacePolicy.identity(gc.syntheticReplace)") assert.Contains(t, code, "gc.syntheticReplaceID = id") assert.Contains(t, code, "gc.syntheticReplaceHasID = hasID") @@ -66,16 +66,16 @@ var StandardPlanes = []any{PlaneSyntheticReplace} // 5. Verify validate checks structural metadata and calls ValidateIdentity assert.Contains(t, code, "malformed metadata without value") assert.Contains(t, code, "missing cached identity") - assert.Contains(t, code, "PlaneSyntheticReplace.ValidateIdentity(gf.syntheticReplaceID)") + assert.Contains(t, code, "canonicalPlaneSyntheticReplacePolicy.validateIdentity(gf.syntheticReplaceID)") // 6. Verify replayAllPlanesTo combines slices directly and preserves cached IDs without calling live Identity - assert.Contains(t, code, "combined, err := PlaneSyntheticReplace.Combine(source, current, incoming)") + assert.Contains(t, code, "combined, err := canonicalPlaneSyntheticReplacePolicy.combine(source, current, incoming)") assert.Contains(t, code, "gc.syntheticReplaceID = gf.syntheticReplaceID") assert.Contains(t, code, "gc.syntheticReplaceHasID = gf.syntheticReplaceHasID") // 7. Verify hasIdentityReplayRule is generated assert.Contains(t, code, "func (gf *generatedFrozen) hasIdentityReplayRule(") - assert.Contains(t, code, "PlaneSyntheticReplace.Rules.RuleFor(source) == rule") + assert.Contains(t, code, "canonicalPlaneSyntheticReplacePolicy.rules.RuleFor(source) == rule") // 8. Verify map-backed replay/validation helpers are NOT generated assert.NotContains(t, code, "validateAllPlanesMap") diff --git a/internal/archtest/plane_generator_test.go b/internal/archtest/plane_generator_test.go index e613365f..9fbe3da3 100644 --- a/internal/archtest/plane_generator_test.go +++ b/internal/archtest/plane_generator_test.go @@ -169,8 +169,9 @@ var StandardPlanes = []any{PlaneSyntheticSlice} require.NoError(t, err) generatedCode := string(generatedBytes) - assert.Contains(t, generatedCode, "materializeRequestSlice(gf.syntheticSlice, PlaneSyntheticSlice.RequestMaterializer)") - assert.NotContains(t, generatedCode, "cloneSlice(PlaneSyntheticSlice.RequestMaterializer(gf.syntheticSlice))") + assert.Contains(t, generatedCode, "materializeRequestSlice(gf.syntheticSlice, canonicalPlaneSyntheticSlicePolicy.requestMaterializer)") + assert.NotContains(t, generatedCode, "cloneSlice(canonicalPlaneSyntheticSlicePolicy.requestMaterializer(gf.syntheticSlice))") + assert.NotContains(t, generatedCode, "canonicalPlaneSyntheticSlicePolicy.requestMaterializer(gf.syntheticSlice)") assert.NotContains(t, generatedCode, "PlaneSyntheticSlice.RequestMaterializer(gf.syntheticSlice)") } @@ -211,11 +212,13 @@ var StandardPlanes = []any{PlaneDisposableProbe, PlaneNonDiag} code := string(generatedBytes) assert.Contains(t, code, "func ProjectDiagnostics(") - assert.Contains(t, code, "PlaneDisposableProbe.MaterializeOccupants(") - assert.Contains(t, code, "PlaneDisposableProbe.ProjectPrivileges(") - assert.Contains(t, code, "PlaneDisposableProbe.Diagnostics.Order") - assert.Contains(t, code, "PlaneDisposableProbe.Diagnostics.CoalesceGroup") - assert.NotContains(t, code, "PlaneNonDiag.MaterializeOccupants(") + assert.Contains(t, code, "canonicalPlaneDisposableProbePolicy.materializeOccupants(") + assert.Contains(t, code, "canonicalPlaneDisposableProbePolicy.projectPrivileges(") + assert.Contains(t, code, "canonicalPlaneDisposableProbePolicy.diagOrder") + assert.Contains(t, code, "canonicalPlaneDisposableProbePolicy.diagCoalesceGroup") + assert.NotContains(t, code, "canonicalPlaneNonDiagPolicy.materializeOccupants(") + assert.NotContains(t, code, "PlaneDisposableProbe.MaterializeOccupants(") + assert.NotContains(t, code, "PlaneDisposableProbe.ProjectPrivileges(") root := repoRoot(t) diagPath := filepath.Join(root, "internal", "core", "diag", "inventory_extensions.go") diff --git a/internal/archtest/plane_hook_generator_test.go b/internal/archtest/plane_hook_generator_test.go index 793fb8ef..f1a3bcfe 100644 --- a/internal/archtest/plane_hook_generator_test.go +++ b/internal/archtest/plane_hook_generator_test.go @@ -143,35 +143,33 @@ func hookGenExtractReturnHookConfigLit(t *testing.T, fn *ast.FuncDecl) *ast.Comp func hookGenAssertHookConfigLiteral(t *testing.T, comp *ast.CompositeLit, expectedOrder []hookGenExpectedKV) { t.Helper() require.NotNil(t, comp) - expectedTotal := len(expectedOrder) + 1 - require.Equal(t, expectedTotal, len(comp.Elts), "literal element count mismatch") - + require.Equal(t, len(expectedOrder)+1, len(comp.Elts), "literal element count mismatch") seenKeys := make(map[string]bool, len(comp.Elts)) for i, exp := range expectedOrder { elt := comp.Elts[i] kv, ok := elt.(*ast.KeyValueExpr) require.True(t, ok, "element at index %d must be KeyValueExpr", i) - keyIdent, ok := kv.Key.(*ast.Ident) require.True(t, ok, "key at index %d must be Ident", i) assert.False(t, seenKeys[keyIdent.Name], "duplicate key %s at index %d", keyIdent.Name, i) seenKeys[keyIdent.Name] = true assert.Equal(t, exp.Key, keyIdent.Name, "key mismatch at index %d", i) - call, ok := kv.Value.(*ast.CallExpr) require.True(t, ok, "field %s value must be CallExpr", keyIdent.Name) - fnIdent, ok := call.Fun.(*ast.Ident) + sel, ok := call.Fun.(*ast.SelectorExpr) require.True(t, ok) - assert.Equal(t, "Get", fnIdent.Name) - require.Len(t, call.Args, 2) - arg0Ident, ok := call.Args[0].(*ast.Ident) + assert.Equal(t, "get", sel.Sel.Name) + accessIdent, ok := sel.X.(*ast.Ident) require.True(t, ok) - assert.Equal(t, "frozen", arg0Ident.Name) - arg1Ident, ok := call.Args[1].(*ast.Ident) + assert.Equal(t, "canonical"+exp.PlaneVar+"Access", accessIdent.Name) + require.Len(t, call.Args, 1) + argSel, ok := call.Args[0].(*ast.SelectorExpr) require.True(t, ok) - assert.Equal(t, exp.PlaneVar, arg1Ident.Name) + assert.Equal(t, "frozen", argSel.Sel.Name) + xIdent, ok := argSel.X.(*ast.Ident) + require.True(t, ok, "call argument selector X must be an Ident") + assert.Equal(t, "frozen", xIdent.Name) } - lastIdx := len(expectedOrder) lastKV, ok := comp.Elts[lastIdx].(*ast.KeyValueExpr) require.True(t, ok) diff --git a/pkg/lipsdk/feature/canonical_policy_regression_test.go b/pkg/lipsdk/feature/canonical_policy_regression_test.go new file mode 100644 index 00000000..50975458 --- /dev/null +++ b/pkg/lipsdk/feature/canonical_policy_regression_test.go @@ -0,0 +1,348 @@ +package feature + +import ( + "context" + "errors" + "os" + "os/exec" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/matdev83/go-llm-interactive-proxy/pkg/lipapi" + "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/hooks" + "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/prerequest" + "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/request" + "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/session" + "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/terminaldecision" +) + +type regressSubmitHook struct { + id string + ord int +} + +func (h regressSubmitHook) ID() string { return h.id } +func (h regressSubmitHook) Order() int { return h.ord } +func (h regressSubmitHook) FailureMode() hooks.FailureMode { return hooks.FailClosed } +func (h regressSubmitHook) Handle(context.Context, *lipapi.Call, *hooks.SubmitMeta) (hooks.SubmitDecision, error) { + return hooks.SubmitDecision{}, nil +} + +type regressTerminalProvider struct { + id string +} + +func (p regressTerminalProvider) ID() string { return p.id } +func (p regressTerminalProvider) Decide(context.Context, terminaldecision.Input) (terminaldecision.Decision, error) { + return terminaldecision.Decision{}, nil +} + +type regressAttemptTransform struct { + id string + ord int +} + +func (t regressAttemptTransform) ID() string { return t.id } +func (t regressAttemptTransform) Order() int { return t.ord } +func (t regressAttemptTransform) FailureMode() hooks.FailureMode { return hooks.FailClosed } +func (t regressAttemptTransform) HandleAttempt(context.Context, *lipapi.Call, request.AttemptMeta, request.Services) (request.AttemptDecision, error) { + return request.AttemptDecision{}, nil +} + +type regressSessionOpener struct { + id string +} + +func (o regressSessionOpener) ID() string { return o.id } +func (regressSessionOpener) Open(context.Context, session.OpenInput) (session.OpenResult, error) { + return session.OpenResult{}, nil +} + +type regressPreRequestHandler struct { + id string + ord int +} + +func (h regressPreRequestHandler) ID() string { return h.id } +func (h regressPreRequestHandler) Order() int { return h.ord } +func (h regressPreRequestHandler) FailureMode() hooks.FailureMode { return hooks.FailClosed } +func (h regressPreRequestHandler) Handle(context.Context, *lipapi.Call, prerequest.Meta, prerequest.Services) (prerequest.Decision, error) { + return prerequest.Decision{}, nil +} + +func TestCanonicalPlanePolicy_ChangedID_DirectGetAndFrozenIdentity(t *testing.T) { + t.Parallel() + + cs := NewContributionSet() + require.NoError(t, Contribute(cs, PlaneSubmitHooks, "plugin-1", []hooks.SubmitHook{ + regressSubmitHook{id: "hook-1", ord: 1}, + })) + require.NoError(t, Contribute(cs, PlaneTerminalDecisionProvider, "plugin-2", terminaldecision.Provider(regressTerminalProvider{id: "term-1"}))) + require.NoError(t, Contribute(cs, PlaneAttemptTransforms, "plugin-3", []request.AttemptTransform{ + regressAttemptTransform{id: "attempt-1", ord: 1}, + })) + + frozen := cs.Freeze() + + // Normal reads succeed + assert.Len(t, Get(frozen, PlaneSubmitHooks), 1) + assert.NotNil(t, Get(frozen, PlaneTerminalDecisionProvider)) + assert.Equal(t, "term-1", Get(frozen, PlaneTerminalDecisionProvider).ID()) + termID, ok := FrozenIdentity(frozen, PlaneTerminalDecisionProvider) + assert.True(t, ok) + assert.Equal(t, "term-1", termID) + attemptID, ok := FrozenIdentity(frozen, PlaneAttemptTransforms) + assert.True(t, ok) + assert.Equal(t, "attempt-1", attemptID) + + // Changed-ID copies MUST return zero values and false + mutSubmit := PlaneSubmitHooks + mutSubmit.ID = "tampered_submit_hooks" + assert.Nil(t, Get(frozen, mutSubmit), "Get on changed-ID plane copy must return nil") + + mutTerm := PlaneTerminalDecisionProvider + mutTerm.ID = "tampered_terminal_decision_provider" + assert.Nil(t, Get(frozen, mutTerm), "Get on changed-ID exclusive plane copy must return nil") + id, ok := FrozenIdentity(frozen, mutTerm) + assert.False(t, ok, "FrozenIdentity on changed-ID exclusive plane must return false") + assert.Empty(t, id) + + mutAttempt := PlaneAttemptTransforms + mutAttempt.ID = "tampered_attempt_transforms" + assert.Nil(t, Get(frozen, mutAttempt), "Get on changed-ID replace-by-identity plane copy must return nil") + id, ok = FrozenIdentity(frozen, mutAttempt) + assert.False(t, ok, "FrozenIdentity on changed-ID replace-by-identity plane must return false") + assert.Empty(t, id) + + // Nil policy plane + nilPolicyPlane := PlaneSubmitHooks + nilPolicyPlane.generated.policy = nil + assert.Nil(t, Get(frozen, nilPolicyPlane), "Get on nil policy plane must return nil") + id, ok = FrozenIdentity(frozen, nilPolicyPlane) + assert.False(t, ok, "FrozenIdentity on nil policy plane must return false") + assert.Empty(t, id) + + // Unbound plane + unbound := Plane[[]hooks.SubmitHook]{ID: "unbound_plane"} + assert.Nil(t, Get(frozen, unbound)) + id, ok = FrozenIdentity(frozen, unbound) + assert.False(t, ok) + assert.Empty(t, id) +} + +func TestCanonicalPlanePolicy_GlobalPlaneXMutation_ChildProcess(t *testing.T) { + if os.Getenv("GO_WANT_PLANE_MUTATION_HELPER") == "1" { + runGlobalPlaneXMutationSubprocess(t) + return + } + + t.Parallel() + cmd := exec.Command(os.Args[0], "-test.run=^TestCanonicalPlanePolicy_GlobalPlaneXMutation_ChildProcess$", "-test.v") + cmd.Env = append(os.Environ(), "GO_WANT_PLANE_MUTATION_HELPER=1") + out, err := cmd.CombinedOutput() + require.NoError(t, err, "child process failed:\n%s", string(out)) + assert.Contains(t, string(out), "PASS") +} + +func runGlobalPlaneXMutationSubprocess(t *testing.T) { + t.Helper() + + // Ensure initialization captured canonical policies before any mutations occur + require.NotNil(t, PlaneSubmitHooks.generated.policy, "initialization must capture canonical policy before mutations") + require.Equal(t, "submit_hooks", PlaneSubmitHooks.generated.policy.planeID) + require.NotNil(t, PlaneAttemptTransforms.generated.policy) + require.Equal(t, "attempt_transforms", PlaneAttemptTransforms.generated.policy.planeID) + require.NotNil(t, PlaneTerminalDecisionProvider.generated.policy) + require.Equal(t, "terminal_decision_provider", PlaneTerminalDecisionProvider.generated.policy.planeID) + require.NotNil(t, PlaneSessionOpeners.generated.policy) + require.Equal(t, "session_openers", PlaneSessionOpeners.generated.policy.planeID) + require.NotNil(t, PlanePreRequestHandlers.generated.policy) + require.Equal(t, "pre_request_handlers", PlanePreRequestHandlers.generated.policy.planeID) + require.NotNil(t, PlaneToolCallFinalizationMaxArgsBytes.generated.policy) + require.Equal(t, "tool_call_finalization_max_args_bytes", PlaneToolCallFinalizationMaxArgsBytes.generated.policy.planeID) + + // Save original globals and reliably restore in child process + origSubmitHooks := PlaneSubmitHooks + origAttemptTransforms := PlaneAttemptTransforms + origTerminalProvider := PlaneTerminalDecisionProvider + origSessionOpeners := PlaneSessionOpeners + origPreRequestHandlers := PlanePreRequestHandlers + origMaxArgsBytes := PlaneToolCallFinalizationMaxArgsBytes + t.Cleanup(func() { + PlaneSubmitHooks = origSubmitHooks + PlaneAttemptTransforms = origAttemptTransforms + PlaneTerminalDecisionProvider = origTerminalProvider + PlaneSessionOpeners = origSessionOpeners + PlanePreRequestHandlers = origPreRequestHandlers + PlaneToolCallFinalizationMaxArgsBytes = origMaxArgsBytes + }) + + // 1. Global Combiner + PlaneSubmitHooks.Combine = func(source SourceKind, current, incoming []hooks.SubmitHook) ([]hooks.SubmitHook, error) { + return nil, errors.New("mutated global PlaneSubmitHooks combiner") + } + + // 2. Global Validator (positive and inverse mutations) + PlaneSubmitHooks.Validate = func(v []hooks.SubmitHook) error { + return errors.New("mutated global PlaneSubmitHooks validator") + } + PlaneToolCallFinalizationMaxArgsBytes.Validate = func(v int) error { + return nil // mutated to allow malformed negative integers + } + + // 3. Global RequestMaterializer + PlaneSessionOpeners.RequestMaterializer = func(v []session.Opener) []session.Opener { + return []session.Opener{} + } + PlanePreRequestHandlers.RequestMaterializer = func(v []prerequest.Handler) []prerequest.Handler { + return []prerequest.Handler{regressPreRequestHandler{id: "mutated-materializer", ord: 999}} + } + + // 4. Replay & Candidate Combiner/Rules + PlaneAttemptTransforms.Combine = func(source SourceKind, current, incoming []request.AttemptTransform) ([]request.AttemptTransform, error) { + return nil, errors.New("mutated global PlaneAttemptTransforms combiner") + } + PlaneAttemptTransforms.Rules.Feature = CombUnsupported + PlaneAttemptTransforms.Rules.GenerationBinder = CombUnsupported + + // 5. Terminal Decision Provider validate identity & conflict error + PlaneTerminalDecisionProvider.ValidateIdentity = func(string) error { + return nil // mutated to accept invalid identifiers + } + PlaneTerminalDecisionProvider.ExclusiveConflictError = errors.New("mutated conflict error") + + // 6. Diagnostics metadata + PlaneSubmitHooks.Diagnostics = DiagnosticDescriptor[[]hooks.SubmitHook]{ + StageID: "mutated_stage_id", + CoalesceGroup: "mutated_group", + Order: 99999, + Materialize: func(v []hooks.SubmitHook) []DiagnosticOccupant { + return []DiagnosticOccupant{{Label: "mutated_occupant"}} + }, + Privileges: func(v []hooks.SubmitHook) PrivilegeProjection { + return PrivilegeProjection{Flags: []string{"mutated_flag"}} + }, + } + + // Now run verification asserting that all canonical generated paths are immune to the mutations above: + csInitial := NewContributionSet() + require.NoError(t, csInitial.BindAttemptTransforms("binder-1", []request.AttemptTransform{ + regressAttemptTransform{id: "at-1", ord: 1}, + })) + require.NoError(t, Contribute(csInitial, PlaneSubmitHooks, "plugin-submit", []hooks.SubmitHook{ + regressSubmitHook{id: "sub-1", ord: 1}, + }), "Contribute must use canonical combiner and validator, ignoring mutated global PlaneSubmitHooks") + require.NoError(t, Contribute(csInitial, PlaneTerminalDecisionProvider, "plugin-term", terminaldecision.Provider(regressTerminalProvider{id: "term-1"}))) + require.NoError(t, Contribute(csInitial, PlaneSessionOpeners, "plugin-session", []session.Opener{ + regressSessionOpener{id: "op-1"}, + })) + require.NoError(t, Contribute(csInitial, PlanePreRequestHandlers, "plugin-pre", []prerequest.Handler{ + regressPreRequestHandler{id: "handler-late", ord: 50}, + regressPreRequestHandler{id: "handler-early", ord: 10}, + })) + + // Inverse validator test 1: Contributing malformed value must fail despite mutated permissive global validator + errInvalidMax := Contribute(csInitial, PlaneToolCallFinalizationMaxArgsBytes, "plugin-max", -10) + assert.Error(t, errInvalidMax, "Contribute must enforce canonical validator rejecting negative max args bytes despite mutated global validator") + + // Inverse validator test 2: Malformed state fixture validation must fail using test exports + malformedMaxFrozen := NewMalformedGeneratedFrozenToolCallFinalizationMaxArgsBytesForTest(-5) + assert.Error(t, malformedMaxFrozen.Validate(), "Validate must reject malformed max args bytes fixture") + + // Inverse validator test 3: Malformed terminal decision fixture with missing cached identity must fail + malformedTermMissingID := NewMalformedGeneratedFrozenTerminalDecisionMissingIdentityForTest(regressTerminalProvider{id: "term-1"}) + assert.Error(t, malformedTermMissingID.Validate(), "Validate must reject exclusive plane missing cached identity") + + // Inverse validator test 4: Malformed terminal decision fixture with invalid blank identity must fail canonical ValidateIdentity + malformedTermBadID := NewMalformedGeneratedFrozenTerminalDecisionForTest(regressTerminalProvider{id: " "}, " ", true) + assert.Error(t, malformedTermBadID.Validate(), "Validate must enforce canonical ValidateIdentity rejecting blank identity despite mutated global ValidateIdentity") + + frozen := csInitial.Freeze() + + // Same-ID policy-mutated reads + termVal := Get(frozen, PlaneTerminalDecisionProvider) + require.NotNil(t, termVal) + assert.Equal(t, "term-1", termVal.ID()) + termID, ok := FrozenIdentity(frozen, PlaneTerminalDecisionProvider) + assert.True(t, ok) + assert.Equal(t, "term-1", termID) + + // Direct changed-ID Get: mutate ID on copy and verify zero value + changedIDSubmit := PlaneSubmitHooks + changedIDSubmit.ID = "mutated_submit_hooks_id" + assert.Nil(t, Get(frozen, changedIDSubmit), "Get with changed ID must return zero value") + + // FreezeRequestPlanes must use canonical RequestMaterializer with meaningful sorting (prerequest.MaterializeSorted) + reqFrozen := FreezeRequestPlanes(frozen) + reqOpeners := Get(reqFrozen, PlaneSessionOpeners) + assert.Len(t, reqOpeners, 1, "FreezeRequestPlanes must use canonical materializer on PlaneSessionOpeners") + + reqHandlers := Get(reqFrozen, PlanePreRequestHandlers) + require.Len(t, reqHandlers, 2, "FreezeRequestPlanes must execute canonical request materializer on PlanePreRequestHandlers") + assert.Equal(t, "handler-early", reqHandlers[0].ID(), "canonical request materializer must sort handlers by Order ascending") + assert.Equal(t, "handler-late", reqHandlers[1].ID(), "canonical request materializer must sort handlers by Order ascending") + + // Candidate replay + candCS := NewContributionSet() + require.NoError(t, Contribute(candCS, PlaneSessionOpeners, "cand-session", []session.Opener{ + regressSessionOpener{id: "op-cand"}, + })) + candFrozen := candCS.Freeze() + dstCS := csInitial.Clone() + err := candFrozen.ContributeCandidateTo(dstCS, SourceFeature, "candidate") + assert.NoError(t, err, "ContributeCandidateTo must succeed using canonical policy") + + // Replay under SourceFeature succeeds using canonical policy + replayDst := NewContributionSet() + err = frozen.ReplaySourceTo(replayDst, SourceFeature, "replayer") + assert.NoError(t, err, "ReplaySourceTo must succeed under SourceFeature using canonical policy") + + // Replay under SourceGenerationBinder: PlaneAttemptTransforms has canonical CombReplaceByIdentity for GenerationBinder. + // Even though global PlaneAttemptTransforms.Rules.GenerationBinder was mutated to CombUnsupported, + // canonical policy enforcement still detects CombReplaceByIdentity and returns ErrUnsupportedReplaySource. + err = frozen.ReplaySourceTo(replayDst, SourceGenerationBinder, "replayer") + assert.ErrorIs(t, err, ErrUnsupportedReplaySource, "ReplaySourceTo must enforce canonical CombReplaceByIdentity rule despite mutated global rules") + + // hasIdentityReplayRule directly on frozen.frozen + rulePlaneID, hasRule := frozen.frozen.hasIdentityReplayRule(SourceGenerationBinder, CombReplaceByIdentity) + assert.True(t, hasRule, "hasIdentityReplayRule must use canonical rules, not mutated global rules") + assert.Equal(t, "attempt_transforms", rulePlaneID) + + // Now mutate global PlaneX IDs to assert that hook projection and diagnostics retain canonical state + PlaneSubmitHooks.ID = "mutated_global_submit_hooks_id" + PlaneAttemptTransforms.ID = "mutated_global_attempt_transforms_id" + PlaneTerminalDecisionProvider.ID = "mutated_global_terminal_decision_id" + PlaneSessionOpeners.ID = "mutated_global_session_openers_id" + PlanePreRequestHandlers.ID = "mutated_global_prerequest_handlers_id" + PlaneToolCallFinalizationMaxArgsBytes.ID = "mutated_global_max_args_id" + + // Ordinary Get on globally mutated plane returns zero value (policy-ID mismatch) + assert.Nil(t, Get(frozen, PlaneSubmitHooks), "Get with globally mutated PlaneSubmitHooks.ID must return zero value") + + // Hook projection directly retains hooks even when PlaneSubmitHooks.ID is globally mutated + hookCfg := ProjectHookConfig(frozen, hooks.ToolReactorErrorsFailClosed) + require.Len(t, hookCfg.SubmitHooks, 1, "ProjectHookConfig must retain submit hooks even under global PlaneSubmitHooks.ID mutation") + assert.Equal(t, "sub-1", hookCfg.SubmitHooks[0].ID()) + + // Diagnostics retain canonical plane ID and diagnostics metadata under global PlaneSubmitHooks.ID mutation + projections := ProjectDiagnostics(frozen) + foundSubmitHooks := false + for _, proj := range projections { + if proj.PlaneID == "submit_hooks" { + foundSubmitHooks = true + assert.Equal(t, StageIDSubmit, proj.StageID) + assert.Equal(t, 10, proj.Order) + require.Len(t, proj.Occupants, 1) + assert.Equal(t, "sub-1", proj.Occupants[0].Label) + } + assert.NotEqual(t, "mutated_global_submit_hooks_id", proj.PlaneID, "diagnostics must retain canonical plane ID, not mutated global PlaneSubmitHooks.ID") + assert.NotEqual(t, "mutated_stage_id", proj.StageID) + assert.NotEqual(t, 99999, proj.Order) + for _, occ := range proj.Occupants { + assert.NotEqual(t, "mutated_occupant", occ.Label) + } + } + assert.True(t, foundSubmitHooks, "must find submit_hooks projection in diagnostics with canonical plane ID") +} diff --git a/pkg/lipsdk/feature/closed_plane_characterization_test.go b/pkg/lipsdk/feature/closed_plane_characterization_test.go index 8dc63345..8e610a41 100644 --- a/pkg/lipsdk/feature/closed_plane_characterization_test.go +++ b/pkg/lipsdk/feature/closed_plane_characterization_test.go @@ -16,6 +16,7 @@ import ( "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/secretguard" "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/session" "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/terminaldecision" + "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/traffic" "github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/workspace" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -367,11 +368,23 @@ func TestClosedPlane_OrdinaryReplay_FailBeforeMutate(t *testing.T) { assert.Equal(t, "src-hook-1", gotHooks[0].ID()) assert.Equal(t, "src-hook-2", gotHooks[1].ID()) - // 2. ReplaySourceTo into dst under SourceHost using standard plane + // 2. ReplaySourceTo into dst under SourceHost: + // PlaneSubmitHooks rejects SourceHost with ErrUnsupportedSource before mutation. + dstHostRejected := feature.NewContributionSet() + err = frozenSrc.ReplaySourceTo(dstHostRejected, feature.SourceHost, "host-replay") + require.ErrorIs(t, err, feature.ErrUnsupportedSource) + assert.Empty(t, feature.Get(dstHostRejected.Freeze(), feature.PlaneSubmitHooks)) + + // ReplaySourceTo under SourceHost succeeds on planes that support SourceHost (e.g. PlaneTrafficObservers). + csHostSupported := feature.NewContributionSet() + require.NoError(t, feature.Contribute(csHostSupported, feature.PlaneTrafficObservers, "plugin-traffic", []traffic.Observer{ + traffic.NoopObserver{}, + })) + frozenTraffic := csHostSupported.Freeze() dstHost := feature.NewContributionSet() - err = frozenSrc.ReplaySourceTo(dstHost, feature.SourceFeature, "host-replay") + err = frozenTraffic.ReplaySourceTo(dstHost, feature.SourceHost, "host-replay") require.NoError(t, err) - assert.Len(t, feature.Get(dstHost.Freeze(), feature.PlaneSubmitHooks), 2) + assert.Len(t, feature.Get(dstHost.Freeze(), feature.PlaneTrafficObservers), 1) // 3. Fail-before-mutate on replay conflict: destination must remain atomically unmodified dstAtomic := feature.NewContributionSet() diff --git a/pkg/lipsdk/feature/contributions.go b/pkg/lipsdk/feature/contributions.go index c93d0880..4eb02e56 100644 --- a/pkg/lipsdk/feature/contributions.go +++ b/pkg/lipsdk/feature/contributions.go @@ -83,23 +83,28 @@ var ( // ContributeSource adds a typed contribution from an explicit source (e.g. [SourceFeature], [SourceHost], // [SourceGenerationBinder]) to the [ContributionSet]. If any validation or combination fails, the set is // left unmodified (fail-before-mutate) and an [AttributedError] attributing the contributor ID and plane ID is returned. -func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, contributorID string, v P) error { +func contributePolicy[P any]( + s *ContributionSet, + gp *generatedPolicy[P], + contribute func(*generatedContributions, SourceKind, string, P) error, + getIdentity func(*generatedFrozen) (string, bool), + source SourceKind, + contributorID string, + v P, +) error { if s == nil { return fmt.Errorf("feature: nil ContributionSet") } - - gp := p.generated.policy - if p.generated.contribute == nil || p.generated.get == nil || gp == nil || gp.planeID != p.ID { + if gp == nil || contribute == nil { return &AttributedError{ PluginID: contributorID, - PlaneID: p.ID, Err: ErrUngeneratedPlane, } } if contributorID == "" { return &AttributedError{ - PlaneID: p.ID, + PlaneID: gp.planeID, Err: fmt.Errorf("%w: plugin ID must not be empty", ErrInvalidContribution), } } @@ -108,8 +113,8 @@ func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, if rule == CombUnsupported { return &AttributedError{ PluginID: contributorID, - PlaneID: p.ID, - Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, p.ID), + PlaneID: gp.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, gp.planeID), } } @@ -127,8 +132,8 @@ func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, case NilReject: return &AttributedError{ PluginID: contributorID, - PlaneID: p.ID, - Err: fmt.Errorf("%w: nil contribution rejected by policy on plane %q", ErrNilContribution, p.ID), + PlaneID: gp.planeID, + Err: fmt.Errorf("%w: nil contribution rejected by policy on plane %q", ErrNilContribution, gp.planeID), } case NilSkip: // Omit consistently from combination and diagnostics (leave set untouched) @@ -143,7 +148,7 @@ func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, if err := gp.validate(v); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: p.ID, + PlaneID: gp.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } @@ -159,13 +164,13 @@ func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, if rule == CombExclusive { return &AttributedError{ PluginID: contributorID, - PlaneID: p.ID, + PlaneID: gp.planeID, Err: fmt.Errorf("%w: failed to extract identity from exclusive contribution", ErrInvalidContribution), } } return &AttributedError{ PluginID: contributorID, - PlaneID: p.ID, + PlaneID: gp.planeID, Err: fmt.Errorf("%w: failed to extract identity from replace_by_identity contribution", ErrInvalidContribution), } } @@ -173,7 +178,7 @@ func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, if err := gp.validateIdentity(incomingID); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: p.ID, + PlaneID: gp.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } @@ -183,34 +188,54 @@ func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, // 4. Exclusive conflict check. if rule == CombExclusive { - if _, occupied := s.pluginIDs[p.ID]; occupied { + if _, occupied := s.pluginIDs[gp.planeID]; occupied { var existingID string - if p.generated.identity != nil { + if getIdentity != nil { frozen := s.Freeze() if frozen.frozen != nil { - existingID, _ = p.generated.identity(frozen.frozen) + existingID, _ = getIdentity(frozen.frozen) } } - return makeExclusiveConflictError(contributorID, p.ID, gp.exclusiveConflictError, existingID, incomingID) + return makeExclusiveConflictError(contributorID, gp.planeID, gp.exclusiveConflictError, existingID, incomingID) } } // 5. Generated storage path: pure storage, closures are NOT responsible for identity validation or conflict checks. if s.generated != nil { - if err := p.generated.contribute(s.generated, source, contributorID, v); err != nil { + if err := contribute(s.generated, source, contributorID, v); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: p.ID, + PlaneID: gp.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } - s.pluginIDs[p.ID] = contributorID + s.pluginIDs[gp.planeID] = contributorID return nil } return nil } +// ContributeSource adds a typed contribution from an explicit source (e.g. [SourceFeature], [SourceHost], +// [SourceGenerationBinder]) to the [ContributionSet]. If any validation or combination fails, the set is +// left unmodified (fail-before-mutate) and an [AttributedError] attributing the contributor ID and plane ID is returned. +func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, contributorID string, v P) error { + if s == nil { + return fmt.Errorf("feature: nil ContributionSet") + } + + gp := p.generated.policy + if p.generated.contribute == nil || p.generated.get == nil || gp == nil || gp.planeID != p.ID { + return &AttributedError{ + PluginID: contributorID, + PlaneID: p.ID, + Err: ErrUngeneratedPlane, + } + } + + return contributePolicy(s, gp, p.generated.contribute, p.generated.identity, source, contributorID, v) +} + // Contribute adds a typed contribution from a feature plugin under [SourceFeature] to the [ContributionSet]. // If any validation or combination fails, the set is left unmodified (fail-before-mutate) // and an [AttributedError] attributing the plugin ID and plane ID is returned. diff --git a/pkg/lipsdk/feature/export_test.go b/pkg/lipsdk/feature/export_test.go index e3ebcff3..6935854d 100644 --- a/pkg/lipsdk/feature/export_test.go +++ b/pkg/lipsdk/feature/export_test.go @@ -100,6 +100,18 @@ func BindGeneratedAccessForTest[T any]( return p } +// SetCanonicalValidateIdentityForTest temporarily overrides validateIdentity on a plane's canonical policy. +func SetCanonicalValidateIdentityForTest[T any](p Plane[T], fn func(string) error) func() { + if p.generated.policy == nil { + return func() {} + } + orig := p.generated.policy.validateIdentity + p.generated.policy.validateIdentity = fn + return func() { + p.generated.policy.validateIdentity = orig + } +} + // BindGeneratedTestPlane attaches canonical policy and test eligibility/storage to a Plane[T] for testing. func BindGeneratedTestPlane[T any](p Plane[T]) Plane[T] { return BindGeneratedAccessForTest( diff --git a/pkg/lipsdk/feature/frozen.go b/pkg/lipsdk/feature/frozen.go index 974c4dee..93ef8716 100644 --- a/pkg/lipsdk/feature/frozen.go +++ b/pkg/lipsdk/feature/frozen.go @@ -47,7 +47,7 @@ func materializeRequestSlice[T any]( // For planes bound to generated storage, Get dispatches directly with zero map lookups, // zero reflection, and zero type assertions. func Get[P any](s FrozenPlaneSet, p Plane[P]) P { - if p.generated.get != nil && s.frozen != nil { + if p.generated.get != nil && s.frozen != nil && p.generated.policy != nil && p.generated.policy.planeID == p.ID { return p.generated.get(s.frozen) } var zero P @@ -82,7 +82,7 @@ func FreezeRequestPlanes(in FrozenPlaneSet) FrozenPlaneSet { // FrozenIdentity reads validated cached identity metadata and does not invoke live identity methods. // For planes bound to generated storage, FrozenIdentity dispatches directly with zero map lookups. func FrozenIdentity[P any](s FrozenPlaneSet, p Plane[P]) (string, bool) { - if p.generated.identity != nil && s.frozen != nil { + if p.generated.identity != nil && s.frozen != nil && p.generated.policy != nil && p.generated.policy.planeID == p.ID { return p.generated.identity(s.frozen) } return "", false @@ -128,6 +128,12 @@ func (s FrozenPlaneSet) ContributeCandidateTo(dst *ContributionSet, source Sourc if s.IsZero() || dst == nil || s.frozen == nil { return nil } + if contributorID == "" { + contributorID = "candidate" + } + if err := s.frozen.checkCandidateSourceAdmission(source, contributorID); err != nil { + return err + } staged := dst.Clone() if staged.generated != nil { if err := s.frozen.contributeCandidateTo(staged.generated, source, contributorID); err != nil { @@ -201,6 +207,9 @@ func (s FrozenPlaneSet) ReplaySourceTo(dst *ContributionSet, source SourceKind, Err: fmt.Errorf("%w: source %s requires identity-aware binder operation", ErrUnsupportedReplaySource, source), } } + if err := s.frozen.checkSourceAdmission(source, contributorID); err != nil { + return err + } } if err := s.validateStored(); err != nil { return attributeReplayValidationError(err, contributorID) diff --git a/pkg/lipsdk/feature/plane.go b/pkg/lipsdk/feature/plane.go index a02ef0cb..f45f89f5 100644 --- a/pkg/lipsdk/feature/plane.go +++ b/pkg/lipsdk/feature/plane.go @@ -191,6 +191,28 @@ type generatedPolicy[T any] struct { combine func(SourceKind, T, T) (T, error) identity func(T) (string, bool) exclusiveConflictError error + requestMaterializer func(T) T + requestBorrow bool + hookTarget HookTarget + diagStageID string + diagCoalesceGroup string + diagOrder int + diagMaterialize func(T) []DiagnosticOccupant + diagPrivileges func(T) PrivilegeProjection +} + +func (gp *generatedPolicy[T]) materializeOccupants(v T) []DiagnosticOccupant { + if gp == nil || gp.diagMaterialize == nil { + return nil + } + return gp.diagMaterialize(v) +} + +func (gp *generatedPolicy[T]) projectPrivileges(v T) PrivilegeProjection { + if gp == nil || gp.diagPrivileges == nil { + return PrivilegeProjection{} + } + return gp.diagPrivileges(v) } type generatedAccess[T any] struct { diff --git a/pkg/lipsdk/feature/plane_generated.go b/pkg/lipsdk/feature/plane_generated.go index 76ac5a28..d2a46337 100644 --- a/pkg/lipsdk/feature/plane_generated.go +++ b/pkg/lipsdk/feature/plane_generated.go @@ -237,32 +237,32 @@ func (gf *generatedFrozen) freezeRequest() *generatedFrozen { requestPartHooks: cloneSlice(gf.requestPartHooks), responsePartHooks: cloneSlice(gf.responsePartHooks), toolReactors: cloneSlice(gf.toolReactors), - sessionOpeners: materializeRequestSlice(gf.sessionOpeners, PlaneSessionOpeners.RequestMaterializer), + sessionOpeners: materializeRequestSlice(gf.sessionOpeners, canonicalPlaneSessionOpenersPolicy.requestMaterializer), workspaceResolvers: cloneSlice(gf.workspaceResolvers), toolCatalogFilters: cloneSlice(gf.toolCatalogFilters), - toolCallPolicies: materializeRequestSlice(gf.toolCallPolicies, PlaneToolCallPolicies.RequestMaterializer), - toolCallFinalizers: materializeRequestSlice(gf.toolCallFinalizers, PlaneToolCallFinalizers.RequestMaterializer), + toolCallPolicies: materializeRequestSlice(gf.toolCallPolicies, canonicalPlaneToolCallPoliciesPolicy.requestMaterializer), + toolCallFinalizers: materializeRequestSlice(gf.toolCallFinalizers, canonicalPlaneToolCallFinalizersPolicy.requestMaterializer), toolCallFinalizationMaxArgsBytes: gf.toolCallFinalizationMaxArgsBytes, requestTransforms: cloneSlice(gf.requestTransforms), - preRequestHandlers: materializeRequestSlice(gf.preRequestHandlers, PlanePreRequestHandlers.RequestMaterializer), + preRequestHandlers: materializeRequestSlice(gf.preRequestHandlers, canonicalPlanePreRequestHandlersPolicy.requestMaterializer), routeHintProviders: cloneSlice(gf.routeHintProviders), completionGates: cloneSlice(gf.completionGates), - attemptTransforms: materializeRequestSlice(gf.attemptTransforms, PlaneAttemptTransforms.RequestMaterializer), + attemptTransforms: materializeRequestSlice(gf.attemptTransforms, canonicalPlaneAttemptTransformsPolicy.requestMaterializer), attemptTransformsID: gf.attemptTransformsID, attemptTransformsHasID: gf.attemptTransformsHasID, - streamObserverFactories: materializeRequestSlice(gf.streamObserverFactories, PlaneStreamObserverFactories.RequestMaterializer), + streamObserverFactories: materializeRequestSlice(gf.streamObserverFactories, canonicalPlaneStreamObserverFactoriesPolicy.requestMaterializer), streamObserverFactoriesID: gf.streamObserverFactoriesID, streamObserverFactoriesHasID: gf.streamObserverFactoriesHasID, trafficObservers: cloneSlice(gf.trafficObservers), usageObservers: cloneSlice(gf.usageObservers), rawCaptureSinks: cloneSlice(gf.rawCaptureSinks), - trafficRedactors: materializeRequestSlice(gf.trafficRedactors, PlaneTrafficRedactors.RequestMaterializer), + trafficRedactors: materializeRequestSlice(gf.trafficRedactors, canonicalPlaneTrafficRedactorsPolicy.requestMaterializer), compactionObservers: cloneSlice(gf.compactionObservers), compactionPreservers: cloneSlice(gf.compactionPreservers), compactionPreserversID: gf.compactionPreserversID, compactionPreserversHasID: gf.compactionPreserversHasID, - secretGuards: materializeRequestSlice(gf.secretGuards, PlaneSecretGuards.RequestMaterializer), - localTurnHandlers: materializeRequestSlice(gf.localTurnHandlers, PlaneLocalTurnHandlers.RequestMaterializer), + secretGuards: materializeRequestSlice(gf.secretGuards, canonicalPlaneSecretGuardsPolicy.requestMaterializer), + localTurnHandlers: materializeRequestSlice(gf.localTurnHandlers, canonicalPlaneLocalTurnHandlersPolicy.requestMaterializer), terminalDecisionProvider: gf.terminalDecisionProvider, terminalDecisionProviderID: gf.terminalDecisionProviderID, terminalDecisionProviderHasID: gf.terminalDecisionProviderHasID, @@ -317,232 +317,617 @@ func (gf *generatedFrozen) validate() error { return nil } if gf.submitHooks != nil { - if PlaneSubmitHooks.Validate != nil { - if err := PlaneSubmitHooks.Validate(gf.submitHooks); err != nil { - return newPlaneValidationError(PlaneSubmitHooks.ID, err) + if canonicalPlaneSubmitHooksPolicy.validate != nil { + if err := canonicalPlaneSubmitHooksPolicy.validate(gf.submitHooks); err != nil { + return newPlaneValidationError(canonicalPlaneSubmitHooksPolicy.planeID, err) } } } if gf.requestPartHooks != nil { - if PlaneRequestPartHooks.Validate != nil { - if err := PlaneRequestPartHooks.Validate(gf.requestPartHooks); err != nil { - return newPlaneValidationError(PlaneRequestPartHooks.ID, err) + if canonicalPlaneRequestPartHooksPolicy.validate != nil { + if err := canonicalPlaneRequestPartHooksPolicy.validate(gf.requestPartHooks); err != nil { + return newPlaneValidationError(canonicalPlaneRequestPartHooksPolicy.planeID, err) } } } if gf.responsePartHooks != nil { - if PlaneResponsePartHooks.Validate != nil { - if err := PlaneResponsePartHooks.Validate(gf.responsePartHooks); err != nil { - return newPlaneValidationError(PlaneResponsePartHooks.ID, err) + if canonicalPlaneResponsePartHooksPolicy.validate != nil { + if err := canonicalPlaneResponsePartHooksPolicy.validate(gf.responsePartHooks); err != nil { + return newPlaneValidationError(canonicalPlaneResponsePartHooksPolicy.planeID, err) } } } if gf.toolReactors != nil { - if PlaneToolReactors.Validate != nil { - if err := PlaneToolReactors.Validate(gf.toolReactors); err != nil { - return newPlaneValidationError(PlaneToolReactors.ID, err) + if canonicalPlaneToolReactorsPolicy.validate != nil { + if err := canonicalPlaneToolReactorsPolicy.validate(gf.toolReactors); err != nil { + return newPlaneValidationError(canonicalPlaneToolReactorsPolicy.planeID, err) } } } if gf.sessionOpeners != nil { - if PlaneSessionOpeners.Validate != nil { - if err := PlaneSessionOpeners.Validate(gf.sessionOpeners); err != nil { - return newPlaneValidationError(PlaneSessionOpeners.ID, err) + if canonicalPlaneSessionOpenersPolicy.validate != nil { + if err := canonicalPlaneSessionOpenersPolicy.validate(gf.sessionOpeners); err != nil { + return newPlaneValidationError(canonicalPlaneSessionOpenersPolicy.planeID, err) } } } if gf.workspaceResolvers != nil { - if PlaneWorkspaceResolvers.Validate != nil { - if err := PlaneWorkspaceResolvers.Validate(gf.workspaceResolvers); err != nil { - return newPlaneValidationError(PlaneWorkspaceResolvers.ID, err) + if canonicalPlaneWorkspaceResolversPolicy.validate != nil { + if err := canonicalPlaneWorkspaceResolversPolicy.validate(gf.workspaceResolvers); err != nil { + return newPlaneValidationError(canonicalPlaneWorkspaceResolversPolicy.planeID, err) } } } if gf.toolCatalogFilters != nil { - if PlaneToolCatalogFilters.Validate != nil { - if err := PlaneToolCatalogFilters.Validate(gf.toolCatalogFilters); err != nil { - return newPlaneValidationError(PlaneToolCatalogFilters.ID, err) + if canonicalPlaneToolCatalogFiltersPolicy.validate != nil { + if err := canonicalPlaneToolCatalogFiltersPolicy.validate(gf.toolCatalogFilters); err != nil { + return newPlaneValidationError(canonicalPlaneToolCatalogFiltersPolicy.planeID, err) } } } if gf.toolCallPolicies != nil { - if PlaneToolCallPolicies.Validate != nil { - if err := PlaneToolCallPolicies.Validate(gf.toolCallPolicies); err != nil { - return newPlaneValidationError(PlaneToolCallPolicies.ID, err) + if canonicalPlaneToolCallPoliciesPolicy.validate != nil { + if err := canonicalPlaneToolCallPoliciesPolicy.validate(gf.toolCallPolicies); err != nil { + return newPlaneValidationError(canonicalPlaneToolCallPoliciesPolicy.planeID, err) } } } if gf.toolCallFinalizers != nil { - if PlaneToolCallFinalizers.Validate != nil { - if err := PlaneToolCallFinalizers.Validate(gf.toolCallFinalizers); err != nil { - return newPlaneValidationError(PlaneToolCallFinalizers.ID, err) + if canonicalPlaneToolCallFinalizersPolicy.validate != nil { + if err := canonicalPlaneToolCallFinalizersPolicy.validate(gf.toolCallFinalizers); err != nil { + return newPlaneValidationError(canonicalPlaneToolCallFinalizersPolicy.planeID, err) } } } if gf.toolCallFinalizationMaxArgsBytes < 0 { - return newPlaneValidationError(PlaneToolCallFinalizationMaxArgsBytes.ID, fmt.Errorf("must be >= 0, got %d", gf.toolCallFinalizationMaxArgsBytes)) + return newPlaneValidationError(canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.planeID, fmt.Errorf("must be >= 0, got %d", gf.toolCallFinalizationMaxArgsBytes)) } - if gf.toolCallFinalizationMaxArgsBytes > 0 && PlaneToolCallFinalizationMaxArgsBytes.Validate != nil { - if err := PlaneToolCallFinalizationMaxArgsBytes.Validate(gf.toolCallFinalizationMaxArgsBytes); err != nil { - return newPlaneValidationError(PlaneToolCallFinalizationMaxArgsBytes.ID, err) + if gf.toolCallFinalizationMaxArgsBytes > 0 && canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.validate != nil { + if err := canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.validate(gf.toolCallFinalizationMaxArgsBytes); err != nil { + return newPlaneValidationError(canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.planeID, err) } } if gf.requestTransforms != nil { - if PlaneRequestTransforms.Validate != nil { - if err := PlaneRequestTransforms.Validate(gf.requestTransforms); err != nil { - return newPlaneValidationError(PlaneRequestTransforms.ID, err) + if canonicalPlaneRequestTransformsPolicy.validate != nil { + if err := canonicalPlaneRequestTransformsPolicy.validate(gf.requestTransforms); err != nil { + return newPlaneValidationError(canonicalPlaneRequestTransformsPolicy.planeID, err) } } } if gf.preRequestHandlers != nil { - if PlanePreRequestHandlers.Validate != nil { - if err := PlanePreRequestHandlers.Validate(gf.preRequestHandlers); err != nil { - return newPlaneValidationError(PlanePreRequestHandlers.ID, err) + if canonicalPlanePreRequestHandlersPolicy.validate != nil { + if err := canonicalPlanePreRequestHandlersPolicy.validate(gf.preRequestHandlers); err != nil { + return newPlaneValidationError(canonicalPlanePreRequestHandlersPolicy.planeID, err) } } } if gf.routeHintProviders != nil { - if PlaneRouteHintProviders.Validate != nil { - if err := PlaneRouteHintProviders.Validate(gf.routeHintProviders); err != nil { - return newPlaneValidationError(PlaneRouteHintProviders.ID, err) + if canonicalPlaneRouteHintProvidersPolicy.validate != nil { + if err := canonicalPlaneRouteHintProvidersPolicy.validate(gf.routeHintProviders); err != nil { + return newPlaneValidationError(canonicalPlaneRouteHintProvidersPolicy.planeID, err) } } } if gf.completionGates != nil { - if PlaneCompletionGates.Validate != nil { - if err := PlaneCompletionGates.Validate(gf.completionGates); err != nil { - return newPlaneValidationError(PlaneCompletionGates.ID, err) + if canonicalPlaneCompletionGatesPolicy.validate != nil { + if err := canonicalPlaneCompletionGatesPolicy.validate(gf.completionGates); err != nil { + return newPlaneValidationError(canonicalPlaneCompletionGatesPolicy.planeID, err) } } } if gf.attemptTransforms == nil { if gf.attemptTransformsHasID || gf.attemptTransformsID != "" { - return newPlaneValidationError(PlaneAttemptTransforms.ID, errors.New("malformed metadata without value")) + return newPlaneValidationError(canonicalPlaneAttemptTransformsPolicy.planeID, errors.New("malformed metadata without value")) } } else { - if PlaneAttemptTransforms.Validate != nil { - if err := PlaneAttemptTransforms.Validate(gf.attemptTransforms); err != nil { - return newPlaneValidationError(PlaneAttemptTransforms.ID, err) + if canonicalPlaneAttemptTransformsPolicy.validate != nil { + if err := canonicalPlaneAttemptTransformsPolicy.validate(gf.attemptTransforms); err != nil { + return newPlaneValidationError(canonicalPlaneAttemptTransformsPolicy.planeID, err) } } if !gf.attemptTransformsHasID { if gf.attemptTransformsID != "" || len(gf.attemptTransforms) > 0 { - return newPlaneValidationError(PlaneAttemptTransforms.ID, errors.New("missing cached identity")) + return newPlaneValidationError(canonicalPlaneAttemptTransformsPolicy.planeID, errors.New("missing cached identity")) } } else { if gf.attemptTransformsID == "" { - return newPlaneValidationError(PlaneAttemptTransforms.ID, errors.New("missing cached identity")) + return newPlaneValidationError(canonicalPlaneAttemptTransformsPolicy.planeID, errors.New("missing cached identity")) } - if err := PlaneAttemptTransforms.ValidateIdentity(gf.attemptTransformsID); err != nil { - return newPlaneValidationError(PlaneAttemptTransforms.ID, err) + if err := canonicalPlaneAttemptTransformsPolicy.validateIdentity(gf.attemptTransformsID); err != nil { + return newPlaneValidationError(canonicalPlaneAttemptTransformsPolicy.planeID, err) } } } if gf.streamObserverFactories == nil { if gf.streamObserverFactoriesHasID || gf.streamObserverFactoriesID != "" { - return newPlaneValidationError(PlaneStreamObserverFactories.ID, errors.New("malformed metadata without value")) + return newPlaneValidationError(canonicalPlaneStreamObserverFactoriesPolicy.planeID, errors.New("malformed metadata without value")) } } else { - if PlaneStreamObserverFactories.Validate != nil { - if err := PlaneStreamObserverFactories.Validate(gf.streamObserverFactories); err != nil { - return newPlaneValidationError(PlaneStreamObserverFactories.ID, err) + if canonicalPlaneStreamObserverFactoriesPolicy.validate != nil { + if err := canonicalPlaneStreamObserverFactoriesPolicy.validate(gf.streamObserverFactories); err != nil { + return newPlaneValidationError(canonicalPlaneStreamObserverFactoriesPolicy.planeID, err) } } if !gf.streamObserverFactoriesHasID { if gf.streamObserverFactoriesID != "" || len(gf.streamObserverFactories) > 0 { - return newPlaneValidationError(PlaneStreamObserverFactories.ID, errors.New("missing cached identity")) + return newPlaneValidationError(canonicalPlaneStreamObserverFactoriesPolicy.planeID, errors.New("missing cached identity")) } } else { if gf.streamObserverFactoriesID == "" { - return newPlaneValidationError(PlaneStreamObserverFactories.ID, errors.New("missing cached identity")) + return newPlaneValidationError(canonicalPlaneStreamObserverFactoriesPolicy.planeID, errors.New("missing cached identity")) } - if err := PlaneStreamObserverFactories.ValidateIdentity(gf.streamObserverFactoriesID); err != nil { - return newPlaneValidationError(PlaneStreamObserverFactories.ID, err) + if err := canonicalPlaneStreamObserverFactoriesPolicy.validateIdentity(gf.streamObserverFactoriesID); err != nil { + return newPlaneValidationError(canonicalPlaneStreamObserverFactoriesPolicy.planeID, err) } } } if gf.trafficObservers != nil { - if PlaneTrafficObservers.Validate != nil { - if err := PlaneTrafficObservers.Validate(gf.trafficObservers); err != nil { - return newPlaneValidationError(PlaneTrafficObservers.ID, err) + if canonicalPlaneTrafficObserversPolicy.validate != nil { + if err := canonicalPlaneTrafficObserversPolicy.validate(gf.trafficObservers); err != nil { + return newPlaneValidationError(canonicalPlaneTrafficObserversPolicy.planeID, err) } } } if gf.usageObservers != nil { - if PlaneUsageObservers.Validate != nil { - if err := PlaneUsageObservers.Validate(gf.usageObservers); err != nil { - return newPlaneValidationError(PlaneUsageObservers.ID, err) + if canonicalPlaneUsageObserversPolicy.validate != nil { + if err := canonicalPlaneUsageObserversPolicy.validate(gf.usageObservers); err != nil { + return newPlaneValidationError(canonicalPlaneUsageObserversPolicy.planeID, err) } } } if gf.rawCaptureSinks != nil { - if PlaneRawCaptureSinks.Validate != nil { - if err := PlaneRawCaptureSinks.Validate(gf.rawCaptureSinks); err != nil { - return newPlaneValidationError(PlaneRawCaptureSinks.ID, err) + if canonicalPlaneRawCaptureSinksPolicy.validate != nil { + if err := canonicalPlaneRawCaptureSinksPolicy.validate(gf.rawCaptureSinks); err != nil { + return newPlaneValidationError(canonicalPlaneRawCaptureSinksPolicy.planeID, err) } } } if gf.trafficRedactors != nil { - if PlaneTrafficRedactors.Validate != nil { - if err := PlaneTrafficRedactors.Validate(gf.trafficRedactors); err != nil { - return newPlaneValidationError(PlaneTrafficRedactors.ID, err) + if canonicalPlaneTrafficRedactorsPolicy.validate != nil { + if err := canonicalPlaneTrafficRedactorsPolicy.validate(gf.trafficRedactors); err != nil { + return newPlaneValidationError(canonicalPlaneTrafficRedactorsPolicy.planeID, err) } } } if gf.compactionObservers != nil { - if PlaneCompactionObservers.Validate != nil { - if err := PlaneCompactionObservers.Validate(gf.compactionObservers); err != nil { - return newPlaneValidationError(PlaneCompactionObservers.ID, err) + if canonicalPlaneCompactionObserversPolicy.validate != nil { + if err := canonicalPlaneCompactionObserversPolicy.validate(gf.compactionObservers); err != nil { + return newPlaneValidationError(canonicalPlaneCompactionObserversPolicy.planeID, err) } } } if gf.compactionPreservers == nil { if gf.compactionPreserversHasID || gf.compactionPreserversID != "" { - return newPlaneValidationError(PlaneCompactionPreservers.ID, errors.New("malformed metadata without value")) + return newPlaneValidationError(canonicalPlaneCompactionPreserversPolicy.planeID, errors.New("malformed metadata without value")) } } else { - if PlaneCompactionPreservers.Validate != nil { - if err := PlaneCompactionPreservers.Validate(gf.compactionPreservers); err != nil { - return newPlaneValidationError(PlaneCompactionPreservers.ID, err) + if canonicalPlaneCompactionPreserversPolicy.validate != nil { + if err := canonicalPlaneCompactionPreserversPolicy.validate(gf.compactionPreservers); err != nil { + return newPlaneValidationError(canonicalPlaneCompactionPreserversPolicy.planeID, err) } } if !gf.compactionPreserversHasID { if gf.compactionPreserversID != "" || len(gf.compactionPreservers) > 0 { - return newPlaneValidationError(PlaneCompactionPreservers.ID, errors.New("missing cached identity")) + return newPlaneValidationError(canonicalPlaneCompactionPreserversPolicy.planeID, errors.New("missing cached identity")) } } else { if gf.compactionPreserversID == "" { - return newPlaneValidationError(PlaneCompactionPreservers.ID, errors.New("missing cached identity")) + return newPlaneValidationError(canonicalPlaneCompactionPreserversPolicy.planeID, errors.New("missing cached identity")) } - if err := PlaneCompactionPreservers.ValidateIdentity(gf.compactionPreserversID); err != nil { - return newPlaneValidationError(PlaneCompactionPreservers.ID, err) + if err := canonicalPlaneCompactionPreserversPolicy.validateIdentity(gf.compactionPreserversID); err != nil { + return newPlaneValidationError(canonicalPlaneCompactionPreserversPolicy.planeID, err) } } } if gf.secretGuards != nil { - if PlaneSecretGuards.Validate != nil { - if err := PlaneSecretGuards.Validate(gf.secretGuards); err != nil { - return newPlaneValidationError(PlaneSecretGuards.ID, err) + if canonicalPlaneSecretGuardsPolicy.validate != nil { + if err := canonicalPlaneSecretGuardsPolicy.validate(gf.secretGuards); err != nil { + return newPlaneValidationError(canonicalPlaneSecretGuardsPolicy.planeID, err) } } } if gf.localTurnHandlers != nil { - if PlaneLocalTurnHandlers.Validate != nil { - if err := PlaneLocalTurnHandlers.Validate(gf.localTurnHandlers); err != nil { - return newPlaneValidationError(PlaneLocalTurnHandlers.ID, err) + if canonicalPlaneLocalTurnHandlersPolicy.validate != nil { + if err := canonicalPlaneLocalTurnHandlersPolicy.validate(gf.localTurnHandlers); err != nil { + return newPlaneValidationError(canonicalPlaneLocalTurnHandlersPolicy.planeID, err) } } } if gf.terminalDecisionProvider == nil { if gf.terminalDecisionProviderHasID || gf.terminalDecisionProviderID != "" { - return newPlaneValidationError(PlaneTerminalDecisionProvider.ID, errors.New("malformed metadata without value")) + return newPlaneValidationError(canonicalPlaneTerminalDecisionProviderPolicy.planeID, errors.New("malformed metadata without value")) } } else { if !gf.terminalDecisionProviderHasID || gf.terminalDecisionProviderID == "" { - return newPlaneValidationError(PlaneTerminalDecisionProvider.ID, errors.New("missing cached identity")) + return newPlaneValidationError(canonicalPlaneTerminalDecisionProviderPolicy.planeID, errors.New("missing cached identity")) } - if err := PlaneTerminalDecisionProvider.ValidateIdentity(gf.terminalDecisionProviderID); err != nil { - return newPlaneValidationError(PlaneTerminalDecisionProvider.ID, err) + if err := canonicalPlaneTerminalDecisionProviderPolicy.validateIdentity(gf.terminalDecisionProviderID); err != nil { + return newPlaneValidationError(canonicalPlaneTerminalDecisionProviderPolicy.planeID, err) + } + } + return nil +} + +// checkSourceAdmission checks whether all present planes in gf support source. +func (gf *generatedFrozen) checkSourceAdmission(source SourceKind, contributorID string) error { + if gf == nil { + return nil + } + if gf.submitHooks != nil { + if canonicalPlaneSubmitHooksPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneSubmitHooksPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneSubmitHooksPolicy.planeID), + } + } + } + if gf.requestPartHooks != nil { + if canonicalPlaneRequestPartHooksPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneRequestPartHooksPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneRequestPartHooksPolicy.planeID), + } + } + } + if gf.responsePartHooks != nil { + if canonicalPlaneResponsePartHooksPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneResponsePartHooksPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneResponsePartHooksPolicy.planeID), + } + } + } + if gf.toolReactors != nil { + if canonicalPlaneToolReactorsPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneToolReactorsPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneToolReactorsPolicy.planeID), + } + } + } + if gf.sessionOpeners != nil { + if canonicalPlaneSessionOpenersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneSessionOpenersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneSessionOpenersPolicy.planeID), + } + } + } + if gf.workspaceResolvers != nil { + if canonicalPlaneWorkspaceResolversPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneWorkspaceResolversPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneWorkspaceResolversPolicy.planeID), + } + } + } + if gf.toolCatalogFilters != nil { + if canonicalPlaneToolCatalogFiltersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneToolCatalogFiltersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneToolCatalogFiltersPolicy.planeID), + } + } + } + if gf.toolCallPolicies != nil { + if canonicalPlaneToolCallPoliciesPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneToolCallPoliciesPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneToolCallPoliciesPolicy.planeID), + } + } + } + if gf.toolCallFinalizers != nil { + if canonicalPlaneToolCallFinalizersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneToolCallFinalizersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneToolCallFinalizersPolicy.planeID), + } + } + } + if gf.toolCallFinalizationMaxArgsBytes > 0 { + if canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.planeID), + } + } + } + if gf.requestTransforms != nil { + if canonicalPlaneRequestTransformsPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneRequestTransformsPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneRequestTransformsPolicy.planeID), + } + } + } + if gf.preRequestHandlers != nil { + if canonicalPlanePreRequestHandlersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlanePreRequestHandlersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlanePreRequestHandlersPolicy.planeID), + } + } + } + if gf.routeHintProviders != nil { + if canonicalPlaneRouteHintProvidersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneRouteHintProvidersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneRouteHintProvidersPolicy.planeID), + } + } + } + if gf.completionGates != nil { + if canonicalPlaneCompletionGatesPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneCompletionGatesPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneCompletionGatesPolicy.planeID), + } + } + } + if gf.attemptTransforms != nil { + if canonicalPlaneAttemptTransformsPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneAttemptTransformsPolicy.planeID), + } + } + } + if gf.streamObserverFactories != nil { + if canonicalPlaneStreamObserverFactoriesPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneStreamObserverFactoriesPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneStreamObserverFactoriesPolicy.planeID), + } + } + } + if gf.trafficObservers != nil { + if canonicalPlaneTrafficObserversPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneTrafficObserversPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneTrafficObserversPolicy.planeID), + } + } + } + if gf.usageObservers != nil { + if canonicalPlaneUsageObserversPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneUsageObserversPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneUsageObserversPolicy.planeID), + } + } + } + if gf.rawCaptureSinks != nil { + if canonicalPlaneRawCaptureSinksPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneRawCaptureSinksPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneRawCaptureSinksPolicy.planeID), + } + } + } + if gf.trafficRedactors != nil { + if canonicalPlaneTrafficRedactorsPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneTrafficRedactorsPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneTrafficRedactorsPolicy.planeID), + } + } + } + if gf.compactionObservers != nil { + if canonicalPlaneCompactionObserversPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneCompactionObserversPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneCompactionObserversPolicy.planeID), + } + } + } + if gf.compactionPreservers != nil { + if canonicalPlaneCompactionPreserversPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneCompactionPreserversPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneCompactionPreserversPolicy.planeID), + } + } + } + if gf.secretGuards != nil { + if canonicalPlaneSecretGuardsPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneSecretGuardsPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneSecretGuardsPolicy.planeID), + } + } + } + if gf.localTurnHandlers != nil { + if canonicalPlaneLocalTurnHandlersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneLocalTurnHandlersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneLocalTurnHandlersPolicy.planeID), + } + } + } + if gf.terminalDecisionProvider != nil { + if canonicalPlaneTerminalDecisionProviderPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneTerminalDecisionProviderPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneTerminalDecisionProviderPolicy.planeID), + } + } + } + return nil +} + +// checkCandidateSourceAdmission checks whether all present candidate planes in gf support source. +func (gf *generatedFrozen) checkCandidateSourceAdmission(source SourceKind, contributorID string) error { + if gf == nil { + return nil + } + if gf.sessionOpeners != nil { + if canonicalPlaneSessionOpenersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneSessionOpenersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneSessionOpenersPolicy.planeID), + } + } + } + if gf.workspaceResolvers != nil { + if canonicalPlaneWorkspaceResolversPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneWorkspaceResolversPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneWorkspaceResolversPolicy.planeID), + } + } + } + if gf.toolCatalogFilters != nil { + if canonicalPlaneToolCatalogFiltersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneToolCatalogFiltersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneToolCatalogFiltersPolicy.planeID), + } + } + } + if gf.toolCallPolicies != nil { + if canonicalPlaneToolCallPoliciesPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneToolCallPoliciesPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneToolCallPoliciesPolicy.planeID), + } + } + } + if gf.toolCallFinalizers != nil { + if canonicalPlaneToolCallFinalizersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneToolCallFinalizersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneToolCallFinalizersPolicy.planeID), + } + } + } + if gf.toolCallFinalizationMaxArgsBytes > 0 { + if canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.planeID), + } + } + } + if gf.requestTransforms != nil { + if canonicalPlaneRequestTransformsPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneRequestTransformsPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneRequestTransformsPolicy.planeID), + } + } + } + if gf.preRequestHandlers != nil { + if canonicalPlanePreRequestHandlersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlanePreRequestHandlersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlanePreRequestHandlersPolicy.planeID), + } + } + } + if gf.routeHintProviders != nil { + if canonicalPlaneRouteHintProvidersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneRouteHintProvidersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneRouteHintProvidersPolicy.planeID), + } + } + } + if gf.completionGates != nil { + if canonicalPlaneCompletionGatesPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneCompletionGatesPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneCompletionGatesPolicy.planeID), + } + } + } + if gf.attemptTransforms != nil { + if canonicalPlaneAttemptTransformsPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneAttemptTransformsPolicy.planeID), + } + } + } + if gf.compactionObservers != nil { + if canonicalPlaneCompactionObserversPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneCompactionObserversPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneCompactionObserversPolicy.planeID), + } + } + } + if gf.compactionPreservers != nil { + if canonicalPlaneCompactionPreserversPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneCompactionPreserversPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneCompactionPreserversPolicy.planeID), + } + } + } + if gf.secretGuards != nil { + if canonicalPlaneSecretGuardsPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneSecretGuardsPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneSecretGuardsPolicy.planeID), + } + } + } + if gf.localTurnHandlers != nil { + if canonicalPlaneLocalTurnHandlersPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneLocalTurnHandlersPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneLocalTurnHandlersPolicy.planeID), + } + } + } + if gf.terminalDecisionProvider != nil { + if canonicalPlaneTerminalDecisionProviderPolicy.rules.RuleFor(source) == CombUnsupported { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneTerminalDecisionProviderPolicy.planeID, + Err: fmt.Errorf("%w: source %v is not supported on plane %q", ErrUnsupportedSource, source, canonicalPlaneTerminalDecisionProviderPolicy.planeID), + } } } return nil @@ -552,150 +937,153 @@ func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, sou if gf == nil || gc == nil { return nil } + if err := gf.checkCandidateSourceAdmission(source, contributorID); err != nil { + return err + } if gf.sessionOpeners != nil { - if PlaneSessionOpeners.Validate != nil { - if err := PlaneSessionOpeners.Validate(gf.sessionOpeners); err != nil { + if canonicalPlaneSessionOpenersPolicy.validate != nil { + if err := canonicalPlaneSessionOpenersPolicy.validate(gf.sessionOpeners); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneSessionOpeners.ID, + PlaneID: canonicalPlaneSessionOpenersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneSessionOpeners.generated.contribute(gc, source, contributorID, gf.sessionOpeners); err != nil { + if err := canonicalPlaneSessionOpenersAccess.contribute(gc, source, contributorID, gf.sessionOpeners); err != nil { return err } } if gf.workspaceResolvers != nil { - if PlaneWorkspaceResolvers.Validate != nil { - if err := PlaneWorkspaceResolvers.Validate(gf.workspaceResolvers); err != nil { + if canonicalPlaneWorkspaceResolversPolicy.validate != nil { + if err := canonicalPlaneWorkspaceResolversPolicy.validate(gf.workspaceResolvers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneWorkspaceResolvers.ID, + PlaneID: canonicalPlaneWorkspaceResolversPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneWorkspaceResolvers.generated.contribute(gc, source, contributorID, gf.workspaceResolvers); err != nil { + if err := canonicalPlaneWorkspaceResolversAccess.contribute(gc, source, contributorID, gf.workspaceResolvers); err != nil { return err } } if gf.toolCatalogFilters != nil { - if PlaneToolCatalogFilters.Validate != nil { - if err := PlaneToolCatalogFilters.Validate(gf.toolCatalogFilters); err != nil { + if canonicalPlaneToolCatalogFiltersPolicy.validate != nil { + if err := canonicalPlaneToolCatalogFiltersPolicy.validate(gf.toolCatalogFilters); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolCatalogFilters.ID, + PlaneID: canonicalPlaneToolCatalogFiltersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneToolCatalogFilters.generated.contribute(gc, source, contributorID, gf.toolCatalogFilters); err != nil { + if err := canonicalPlaneToolCatalogFiltersAccess.contribute(gc, source, contributorID, gf.toolCatalogFilters); err != nil { return err } } if gf.toolCallPolicies != nil { - if PlaneToolCallPolicies.Validate != nil { - if err := PlaneToolCallPolicies.Validate(gf.toolCallPolicies); err != nil { + if canonicalPlaneToolCallPoliciesPolicy.validate != nil { + if err := canonicalPlaneToolCallPoliciesPolicy.validate(gf.toolCallPolicies); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolCallPolicies.ID, + PlaneID: canonicalPlaneToolCallPoliciesPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneToolCallPolicies.generated.contribute(gc, source, contributorID, gf.toolCallPolicies); err != nil { + if err := canonicalPlaneToolCallPoliciesAccess.contribute(gc, source, contributorID, gf.toolCallPolicies); err != nil { return err } } if gf.toolCallFinalizers != nil { - if PlaneToolCallFinalizers.Validate != nil { - if err := PlaneToolCallFinalizers.Validate(gf.toolCallFinalizers); err != nil { + if canonicalPlaneToolCallFinalizersPolicy.validate != nil { + if err := canonicalPlaneToolCallFinalizersPolicy.validate(gf.toolCallFinalizers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolCallFinalizers.ID, + PlaneID: canonicalPlaneToolCallFinalizersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneToolCallFinalizers.generated.contribute(gc, source, contributorID, gf.toolCallFinalizers); err != nil { + if err := canonicalPlaneToolCallFinalizersAccess.contribute(gc, source, contributorID, gf.toolCallFinalizers); err != nil { return err } } if gf.toolCallFinalizationMaxArgsBytes < 0 { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolCallFinalizationMaxArgsBytes.ID, + PlaneID: canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.planeID, Err: fmt.Errorf("%w: must be >= 0, got %d", ErrInvalidContribution, gf.toolCallFinalizationMaxArgsBytes), } } if gf.toolCallFinalizationMaxArgsBytes > 0 { - if PlaneToolCallFinalizationMaxArgsBytes.Validate != nil { - if err := PlaneToolCallFinalizationMaxArgsBytes.Validate(gf.toolCallFinalizationMaxArgsBytes); err != nil { + if canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.validate != nil { + if err := canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.validate(gf.toolCallFinalizationMaxArgsBytes); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolCallFinalizationMaxArgsBytes.ID, + PlaneID: canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneToolCallFinalizationMaxArgsBytes.generated.contribute(gc, source, contributorID, gf.toolCallFinalizationMaxArgsBytes); err != nil { + if err := canonicalPlaneToolCallFinalizationMaxArgsBytesAccess.contribute(gc, source, contributorID, gf.toolCallFinalizationMaxArgsBytes); err != nil { return err } } if gf.requestTransforms != nil { - if PlaneRequestTransforms.Validate != nil { - if err := PlaneRequestTransforms.Validate(gf.requestTransforms); err != nil { + if canonicalPlaneRequestTransformsPolicy.validate != nil { + if err := canonicalPlaneRequestTransformsPolicy.validate(gf.requestTransforms); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneRequestTransforms.ID, + PlaneID: canonicalPlaneRequestTransformsPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneRequestTransforms.generated.contribute(gc, source, contributorID, gf.requestTransforms); err != nil { + if err := canonicalPlaneRequestTransformsAccess.contribute(gc, source, contributorID, gf.requestTransforms); err != nil { return err } } if gf.preRequestHandlers != nil { - if PlanePreRequestHandlers.Validate != nil { - if err := PlanePreRequestHandlers.Validate(gf.preRequestHandlers); err != nil { + if canonicalPlanePreRequestHandlersPolicy.validate != nil { + if err := canonicalPlanePreRequestHandlersPolicy.validate(gf.preRequestHandlers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlanePreRequestHandlers.ID, + PlaneID: canonicalPlanePreRequestHandlersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlanePreRequestHandlers.generated.contribute(gc, source, contributorID, gf.preRequestHandlers); err != nil { + if err := canonicalPlanePreRequestHandlersAccess.contribute(gc, source, contributorID, gf.preRequestHandlers); err != nil { return err } } if gf.routeHintProviders != nil { - if PlaneRouteHintProviders.Validate != nil { - if err := PlaneRouteHintProviders.Validate(gf.routeHintProviders); err != nil { + if canonicalPlaneRouteHintProvidersPolicy.validate != nil { + if err := canonicalPlaneRouteHintProvidersPolicy.validate(gf.routeHintProviders); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneRouteHintProviders.ID, + PlaneID: canonicalPlaneRouteHintProvidersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneRouteHintProviders.generated.contribute(gc, source, contributorID, gf.routeHintProviders); err != nil { + if err := canonicalPlaneRouteHintProvidersAccess.contribute(gc, source, contributorID, gf.routeHintProviders); err != nil { return err } } if gf.completionGates != nil { - if PlaneCompletionGates.Validate != nil { - if err := PlaneCompletionGates.Validate(gf.completionGates); err != nil { + if canonicalPlaneCompletionGatesPolicy.validate != nil { + if err := canonicalPlaneCompletionGatesPolicy.validate(gf.completionGates); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompletionGates.ID, + PlaneID: canonicalPlaneCompletionGatesPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneCompletionGates.generated.contribute(gc, source, contributorID, gf.completionGates); err != nil { + if err := canonicalPlaneCompletionGatesAccess.contribute(gc, source, contributorID, gf.completionGates); err != nil { return err } } @@ -703,16 +1091,16 @@ func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, sou if gf.attemptTransformsHasID || gf.attemptTransformsID != "" { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneAttemptTransforms.ID, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, Err: fmt.Errorf("%w: malformed metadata without value", ErrInvalidContribution), } } } else { - if PlaneAttemptTransforms.Validate != nil { - if err := PlaneAttemptTransforms.Validate(gf.attemptTransforms); err != nil { + if canonicalPlaneAttemptTransformsPolicy.validate != nil { + if err := canonicalPlaneAttemptTransformsPolicy.validate(gf.attemptTransforms); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneAttemptTransforms.ID, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } @@ -721,7 +1109,7 @@ func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, sou if gf.attemptTransformsID != "" || len(gf.attemptTransforms) > 0 { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneAttemptTransforms.ID, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, Err: fmt.Errorf("%w: missing cached identity", ErrInvalidContribution), } } @@ -729,33 +1117,58 @@ func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, sou if gf.attemptTransformsID == "" { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneAttemptTransforms.ID, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, Err: fmt.Errorf("%w: missing cached identity", ErrInvalidContribution), } } - if err := PlaneAttemptTransforms.ValidateIdentity(gf.attemptTransformsID); err != nil { + if err := canonicalPlaneAttemptTransformsPolicy.validateIdentity(gf.attemptTransformsID); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneAttemptTransforms.ID, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneAttemptTransforms.generated.contribute(gc, source, contributorID, gf.attemptTransforms); err != nil { - return err + hadDestinationValue := len(gc.attemptTransforms) > 0 + existingID := gc.attemptTransformsID + existingHasID := gc.attemptTransformsHasID + + incoming := cloneSlice(gf.attemptTransforms) + current := cloneSlice(gc.attemptTransforms) + combined, err := canonicalPlaneAttemptTransformsPolicy.combine(source, current, incoming) + if err != nil { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, + Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), + } + } + if (gf.attemptTransforms != nil || gc.attemptTransforms != nil) && combined == nil { + combined = make([]request.AttemptTransform, 0) + } + gc.attemptTransforms = cloneSlice(combined) + if len(gc.attemptTransforms) == 0 { + gc.attemptTransformsID = "" + gc.attemptTransformsHasID = false + } else if hadDestinationValue { + gc.attemptTransformsID = existingID + gc.attemptTransformsHasID = existingHasID + } else { + gc.attemptTransformsID = gf.attemptTransformsID + gc.attemptTransformsHasID = gf.attemptTransformsHasID } } if gf.compactionObservers != nil { - if PlaneCompactionObservers.Validate != nil { - if err := PlaneCompactionObservers.Validate(gf.compactionObservers); err != nil { + if canonicalPlaneCompactionObserversPolicy.validate != nil { + if err := canonicalPlaneCompactionObserversPolicy.validate(gf.compactionObservers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompactionObservers.ID, + PlaneID: canonicalPlaneCompactionObserversPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneCompactionObservers.generated.contribute(gc, source, contributorID, gf.compactionObservers); err != nil { + if err := canonicalPlaneCompactionObserversAccess.contribute(gc, source, contributorID, gf.compactionObservers); err != nil { return err } } @@ -763,16 +1176,16 @@ func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, sou if gf.compactionPreserversHasID || gf.compactionPreserversID != "" { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompactionPreservers.ID, + PlaneID: canonicalPlaneCompactionPreserversPolicy.planeID, Err: fmt.Errorf("%w: malformed metadata without value", ErrInvalidContribution), } } } else { - if PlaneCompactionPreservers.Validate != nil { - if err := PlaneCompactionPreservers.Validate(gf.compactionPreservers); err != nil { + if canonicalPlaneCompactionPreserversPolicy.validate != nil { + if err := canonicalPlaneCompactionPreserversPolicy.validate(gf.compactionPreservers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompactionPreservers.ID, + PlaneID: canonicalPlaneCompactionPreserversPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } @@ -781,7 +1194,7 @@ func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, sou if gf.compactionPreserversID != "" || len(gf.compactionPreservers) > 0 { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompactionPreservers.ID, + PlaneID: canonicalPlaneCompactionPreserversPolicy.planeID, Err: fmt.Errorf("%w: missing cached identity", ErrInvalidContribution), } } @@ -789,47 +1202,72 @@ func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, sou if gf.compactionPreserversID == "" { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompactionPreservers.ID, + PlaneID: canonicalPlaneCompactionPreserversPolicy.planeID, Err: fmt.Errorf("%w: missing cached identity", ErrInvalidContribution), } } - if err := PlaneCompactionPreservers.ValidateIdentity(gf.compactionPreserversID); err != nil { + if err := canonicalPlaneCompactionPreserversPolicy.validateIdentity(gf.compactionPreserversID); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompactionPreservers.ID, + PlaneID: canonicalPlaneCompactionPreserversPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneCompactionPreservers.generated.contribute(gc, source, contributorID, gf.compactionPreservers); err != nil { - return err + hadDestinationValue := len(gc.compactionPreservers) > 0 + existingID := gc.compactionPreserversID + existingHasID := gc.compactionPreserversHasID + + incoming := cloneSlice(gf.compactionPreservers) + current := cloneSlice(gc.compactionPreservers) + combined, err := canonicalPlaneCompactionPreserversPolicy.combine(source, current, incoming) + if err != nil { + return &AttributedError{ + PluginID: contributorID, + PlaneID: canonicalPlaneCompactionPreserversPolicy.planeID, + Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), + } + } + if (gf.compactionPreservers != nil || gc.compactionPreservers != nil) && combined == nil { + combined = make([]compaction.Preserver, 0) + } + gc.compactionPreservers = cloneSlice(combined) + if len(gc.compactionPreservers) == 0 { + gc.compactionPreserversID = "" + gc.compactionPreserversHasID = false + } else if hadDestinationValue { + gc.compactionPreserversID = existingID + gc.compactionPreserversHasID = existingHasID + } else { + gc.compactionPreserversID = gf.compactionPreserversID + gc.compactionPreserversHasID = gf.compactionPreserversHasID } } if gf.secretGuards != nil { - if PlaneSecretGuards.Validate != nil { - if err := PlaneSecretGuards.Validate(gf.secretGuards); err != nil { + if canonicalPlaneSecretGuardsPolicy.validate != nil { + if err := canonicalPlaneSecretGuardsPolicy.validate(gf.secretGuards); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneSecretGuards.ID, + PlaneID: canonicalPlaneSecretGuardsPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneSecretGuards.generated.contribute(gc, source, contributorID, gf.secretGuards); err != nil { + if err := canonicalPlaneSecretGuardsAccess.contribute(gc, source, contributorID, gf.secretGuards); err != nil { return err } } if gf.localTurnHandlers != nil { - if PlaneLocalTurnHandlers.Validate != nil { - if err := PlaneLocalTurnHandlers.Validate(gf.localTurnHandlers); err != nil { + if canonicalPlaneLocalTurnHandlersPolicy.validate != nil { + if err := canonicalPlaneLocalTurnHandlersPolicy.validate(gf.localTurnHandlers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneLocalTurnHandlers.ID, + PlaneID: canonicalPlaneLocalTurnHandlersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneLocalTurnHandlers.generated.contribute(gc, source, contributorID, gf.localTurnHandlers); err != nil { + if err := canonicalPlaneLocalTurnHandlersAccess.contribute(gc, source, contributorID, gf.localTurnHandlers); err != nil { return err } } @@ -837,12 +1275,12 @@ func (gf *generatedFrozen) contributeCandidateTo(gc *generatedContributions, sou if !gf.terminalDecisionProviderHasID || gf.terminalDecisionProviderID == "" { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneTerminalDecisionProvider.ID, + PlaneID: canonicalPlaneTerminalDecisionProviderPolicy.planeID, Err: fmt.Errorf("%w: frozen exclusive identity is missing", ErrInvalidContribution), } } if gc.terminalDecisionProviderHasID { - return makeExclusiveConflictError(contributorID, PlaneTerminalDecisionProvider.ID, PlaneTerminalDecisionProvider.ExclusiveConflictError, gc.terminalDecisionProviderID, gf.terminalDecisionProviderID) + return makeExclusiveConflictError(contributorID, canonicalPlaneTerminalDecisionProviderPolicy.planeID, canonicalPlaneTerminalDecisionProviderPolicy.exclusiveConflictError, gc.terminalDecisionProviderID, gf.terminalDecisionProviderID) } gc.terminalDecisionProvider = gf.terminalDecisionProvider gc.terminalDecisionProviderID = gf.terminalDecisionProviderID @@ -855,199 +1293,202 @@ func (gf *generatedFrozen) replayAllPlanesTo(gc *generatedContributions, source if gf == nil || gc == nil { return nil } + if err := gf.checkSourceAdmission(source, contributorID); err != nil { + return err + } if gf.submitHooks != nil { - if PlaneSubmitHooks.Validate != nil { - if err := PlaneSubmitHooks.Validate(gf.submitHooks); err != nil { + if canonicalPlaneSubmitHooksPolicy.validate != nil { + if err := canonicalPlaneSubmitHooksPolicy.validate(gf.submitHooks); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneSubmitHooks.ID, + PlaneID: canonicalPlaneSubmitHooksPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneSubmitHooks.generated.contribute(gc, source, contributorID, gf.submitHooks); err != nil { + if err := canonicalPlaneSubmitHooksAccess.contribute(gc, source, contributorID, gf.submitHooks); err != nil { return err } } if gf.requestPartHooks != nil { - if PlaneRequestPartHooks.Validate != nil { - if err := PlaneRequestPartHooks.Validate(gf.requestPartHooks); err != nil { + if canonicalPlaneRequestPartHooksPolicy.validate != nil { + if err := canonicalPlaneRequestPartHooksPolicy.validate(gf.requestPartHooks); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneRequestPartHooks.ID, + PlaneID: canonicalPlaneRequestPartHooksPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneRequestPartHooks.generated.contribute(gc, source, contributorID, gf.requestPartHooks); err != nil { + if err := canonicalPlaneRequestPartHooksAccess.contribute(gc, source, contributorID, gf.requestPartHooks); err != nil { return err } } if gf.responsePartHooks != nil { - if PlaneResponsePartHooks.Validate != nil { - if err := PlaneResponsePartHooks.Validate(gf.responsePartHooks); err != nil { + if canonicalPlaneResponsePartHooksPolicy.validate != nil { + if err := canonicalPlaneResponsePartHooksPolicy.validate(gf.responsePartHooks); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneResponsePartHooks.ID, + PlaneID: canonicalPlaneResponsePartHooksPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneResponsePartHooks.generated.contribute(gc, source, contributorID, gf.responsePartHooks); err != nil { + if err := canonicalPlaneResponsePartHooksAccess.contribute(gc, source, contributorID, gf.responsePartHooks); err != nil { return err } } if gf.toolReactors != nil { - if PlaneToolReactors.Validate != nil { - if err := PlaneToolReactors.Validate(gf.toolReactors); err != nil { + if canonicalPlaneToolReactorsPolicy.validate != nil { + if err := canonicalPlaneToolReactorsPolicy.validate(gf.toolReactors); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolReactors.ID, + PlaneID: canonicalPlaneToolReactorsPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneToolReactors.generated.contribute(gc, source, contributorID, gf.toolReactors); err != nil { + if err := canonicalPlaneToolReactorsAccess.contribute(gc, source, contributorID, gf.toolReactors); err != nil { return err } } if gf.sessionOpeners != nil { - if PlaneSessionOpeners.Validate != nil { - if err := PlaneSessionOpeners.Validate(gf.sessionOpeners); err != nil { + if canonicalPlaneSessionOpenersPolicy.validate != nil { + if err := canonicalPlaneSessionOpenersPolicy.validate(gf.sessionOpeners); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneSessionOpeners.ID, + PlaneID: canonicalPlaneSessionOpenersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneSessionOpeners.generated.contribute(gc, source, contributorID, gf.sessionOpeners); err != nil { + if err := canonicalPlaneSessionOpenersAccess.contribute(gc, source, contributorID, gf.sessionOpeners); err != nil { return err } } if gf.workspaceResolvers != nil { - if PlaneWorkspaceResolvers.Validate != nil { - if err := PlaneWorkspaceResolvers.Validate(gf.workspaceResolvers); err != nil { + if canonicalPlaneWorkspaceResolversPolicy.validate != nil { + if err := canonicalPlaneWorkspaceResolversPolicy.validate(gf.workspaceResolvers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneWorkspaceResolvers.ID, + PlaneID: canonicalPlaneWorkspaceResolversPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneWorkspaceResolvers.generated.contribute(gc, source, contributorID, gf.workspaceResolvers); err != nil { + if err := canonicalPlaneWorkspaceResolversAccess.contribute(gc, source, contributorID, gf.workspaceResolvers); err != nil { return err } } if gf.toolCatalogFilters != nil { - if PlaneToolCatalogFilters.Validate != nil { - if err := PlaneToolCatalogFilters.Validate(gf.toolCatalogFilters); err != nil { + if canonicalPlaneToolCatalogFiltersPolicy.validate != nil { + if err := canonicalPlaneToolCatalogFiltersPolicy.validate(gf.toolCatalogFilters); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolCatalogFilters.ID, + PlaneID: canonicalPlaneToolCatalogFiltersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneToolCatalogFilters.generated.contribute(gc, source, contributorID, gf.toolCatalogFilters); err != nil { + if err := canonicalPlaneToolCatalogFiltersAccess.contribute(gc, source, contributorID, gf.toolCatalogFilters); err != nil { return err } } if gf.toolCallPolicies != nil { - if PlaneToolCallPolicies.Validate != nil { - if err := PlaneToolCallPolicies.Validate(gf.toolCallPolicies); err != nil { + if canonicalPlaneToolCallPoliciesPolicy.validate != nil { + if err := canonicalPlaneToolCallPoliciesPolicy.validate(gf.toolCallPolicies); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolCallPolicies.ID, + PlaneID: canonicalPlaneToolCallPoliciesPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneToolCallPolicies.generated.contribute(gc, source, contributorID, gf.toolCallPolicies); err != nil { + if err := canonicalPlaneToolCallPoliciesAccess.contribute(gc, source, contributorID, gf.toolCallPolicies); err != nil { return err } } if gf.toolCallFinalizers != nil { - if PlaneToolCallFinalizers.Validate != nil { - if err := PlaneToolCallFinalizers.Validate(gf.toolCallFinalizers); err != nil { + if canonicalPlaneToolCallFinalizersPolicy.validate != nil { + if err := canonicalPlaneToolCallFinalizersPolicy.validate(gf.toolCallFinalizers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolCallFinalizers.ID, + PlaneID: canonicalPlaneToolCallFinalizersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneToolCallFinalizers.generated.contribute(gc, source, contributorID, gf.toolCallFinalizers); err != nil { + if err := canonicalPlaneToolCallFinalizersAccess.contribute(gc, source, contributorID, gf.toolCallFinalizers); err != nil { return err } } if gf.toolCallFinalizationMaxArgsBytes > 0 { - if PlaneToolCallFinalizationMaxArgsBytes.Validate != nil { - if err := PlaneToolCallFinalizationMaxArgsBytes.Validate(gf.toolCallFinalizationMaxArgsBytes); err != nil { + if canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.validate != nil { + if err := canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.validate(gf.toolCallFinalizationMaxArgsBytes); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneToolCallFinalizationMaxArgsBytes.ID, + PlaneID: canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneToolCallFinalizationMaxArgsBytes.generated.contribute(gc, source, contributorID, gf.toolCallFinalizationMaxArgsBytes); err != nil { + if err := canonicalPlaneToolCallFinalizationMaxArgsBytesAccess.contribute(gc, source, contributorID, gf.toolCallFinalizationMaxArgsBytes); err != nil { return err } } if gf.requestTransforms != nil { - if PlaneRequestTransforms.Validate != nil { - if err := PlaneRequestTransforms.Validate(gf.requestTransforms); err != nil { + if canonicalPlaneRequestTransformsPolicy.validate != nil { + if err := canonicalPlaneRequestTransformsPolicy.validate(gf.requestTransforms); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneRequestTransforms.ID, + PlaneID: canonicalPlaneRequestTransformsPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneRequestTransforms.generated.contribute(gc, source, contributorID, gf.requestTransforms); err != nil { + if err := canonicalPlaneRequestTransformsAccess.contribute(gc, source, contributorID, gf.requestTransforms); err != nil { return err } } if gf.preRequestHandlers != nil { - if PlanePreRequestHandlers.Validate != nil { - if err := PlanePreRequestHandlers.Validate(gf.preRequestHandlers); err != nil { + if canonicalPlanePreRequestHandlersPolicy.validate != nil { + if err := canonicalPlanePreRequestHandlersPolicy.validate(gf.preRequestHandlers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlanePreRequestHandlers.ID, + PlaneID: canonicalPlanePreRequestHandlersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlanePreRequestHandlers.generated.contribute(gc, source, contributorID, gf.preRequestHandlers); err != nil { + if err := canonicalPlanePreRequestHandlersAccess.contribute(gc, source, contributorID, gf.preRequestHandlers); err != nil { return err } } if gf.routeHintProviders != nil { - if PlaneRouteHintProviders.Validate != nil { - if err := PlaneRouteHintProviders.Validate(gf.routeHintProviders); err != nil { + if canonicalPlaneRouteHintProvidersPolicy.validate != nil { + if err := canonicalPlaneRouteHintProvidersPolicy.validate(gf.routeHintProviders); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneRouteHintProviders.ID, + PlaneID: canonicalPlaneRouteHintProvidersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneRouteHintProviders.generated.contribute(gc, source, contributorID, gf.routeHintProviders); err != nil { + if err := canonicalPlaneRouteHintProvidersAccess.contribute(gc, source, contributorID, gf.routeHintProviders); err != nil { return err } } if gf.completionGates != nil { - if PlaneCompletionGates.Validate != nil { - if err := PlaneCompletionGates.Validate(gf.completionGates); err != nil { + if canonicalPlaneCompletionGatesPolicy.validate != nil { + if err := canonicalPlaneCompletionGatesPolicy.validate(gf.completionGates); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompletionGates.ID, + PlaneID: canonicalPlaneCompletionGatesPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneCompletionGates.generated.contribute(gc, source, contributorID, gf.completionGates); err != nil { + if err := canonicalPlaneCompletionGatesAccess.contribute(gc, source, contributorID, gf.completionGates); err != nil { return err } } @@ -1058,11 +1499,11 @@ func (gf *generatedFrozen) replayAllPlanesTo(gc *generatedContributions, source incoming := cloneSlice(gf.attemptTransforms) current := cloneSlice(gc.attemptTransforms) - combined, err := PlaneAttemptTransforms.Combine(source, current, incoming) + combined, err := canonicalPlaneAttemptTransformsPolicy.combine(source, current, incoming) if err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneAttemptTransforms.ID, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } @@ -1088,11 +1529,11 @@ func (gf *generatedFrozen) replayAllPlanesTo(gc *generatedContributions, source incoming := cloneSlice(gf.streamObserverFactories) current := cloneSlice(gc.streamObserverFactories) - combined, err := PlaneStreamObserverFactories.Combine(source, current, incoming) + combined, err := canonicalPlaneStreamObserverFactoriesPolicy.combine(source, current, incoming) if err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneStreamObserverFactories.ID, + PlaneID: canonicalPlaneStreamObserverFactoriesPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } @@ -1112,72 +1553,72 @@ func (gf *generatedFrozen) replayAllPlanesTo(gc *generatedContributions, source } } if gf.trafficObservers != nil { - if PlaneTrafficObservers.Validate != nil { - if err := PlaneTrafficObservers.Validate(gf.trafficObservers); err != nil { + if canonicalPlaneTrafficObserversPolicy.validate != nil { + if err := canonicalPlaneTrafficObserversPolicy.validate(gf.trafficObservers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneTrafficObservers.ID, + PlaneID: canonicalPlaneTrafficObserversPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneTrafficObservers.generated.contribute(gc, source, contributorID, gf.trafficObservers); err != nil { + if err := canonicalPlaneTrafficObserversAccess.contribute(gc, source, contributorID, gf.trafficObservers); err != nil { return err } } if gf.usageObservers != nil { - if PlaneUsageObservers.Validate != nil { - if err := PlaneUsageObservers.Validate(gf.usageObservers); err != nil { + if canonicalPlaneUsageObserversPolicy.validate != nil { + if err := canonicalPlaneUsageObserversPolicy.validate(gf.usageObservers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneUsageObservers.ID, + PlaneID: canonicalPlaneUsageObserversPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneUsageObservers.generated.contribute(gc, source, contributorID, gf.usageObservers); err != nil { + if err := canonicalPlaneUsageObserversAccess.contribute(gc, source, contributorID, gf.usageObservers); err != nil { return err } } if gf.rawCaptureSinks != nil { - if PlaneRawCaptureSinks.Validate != nil { - if err := PlaneRawCaptureSinks.Validate(gf.rawCaptureSinks); err != nil { + if canonicalPlaneRawCaptureSinksPolicy.validate != nil { + if err := canonicalPlaneRawCaptureSinksPolicy.validate(gf.rawCaptureSinks); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneRawCaptureSinks.ID, + PlaneID: canonicalPlaneRawCaptureSinksPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneRawCaptureSinks.generated.contribute(gc, source, contributorID, gf.rawCaptureSinks); err != nil { + if err := canonicalPlaneRawCaptureSinksAccess.contribute(gc, source, contributorID, gf.rawCaptureSinks); err != nil { return err } } if gf.trafficRedactors != nil { - if PlaneTrafficRedactors.Validate != nil { - if err := PlaneTrafficRedactors.Validate(gf.trafficRedactors); err != nil { + if canonicalPlaneTrafficRedactorsPolicy.validate != nil { + if err := canonicalPlaneTrafficRedactorsPolicy.validate(gf.trafficRedactors); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneTrafficRedactors.ID, + PlaneID: canonicalPlaneTrafficRedactorsPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneTrafficRedactors.generated.contribute(gc, source, contributorID, gf.trafficRedactors); err != nil { + if err := canonicalPlaneTrafficRedactorsAccess.contribute(gc, source, contributorID, gf.trafficRedactors); err != nil { return err } } if gf.compactionObservers != nil { - if PlaneCompactionObservers.Validate != nil { - if err := PlaneCompactionObservers.Validate(gf.compactionObservers); err != nil { + if canonicalPlaneCompactionObserversPolicy.validate != nil { + if err := canonicalPlaneCompactionObserversPolicy.validate(gf.compactionObservers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompactionObservers.ID, + PlaneID: canonicalPlaneCompactionObserversPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneCompactionObservers.generated.contribute(gc, source, contributorID, gf.compactionObservers); err != nil { + if err := canonicalPlaneCompactionObserversAccess.contribute(gc, source, contributorID, gf.compactionObservers); err != nil { return err } } @@ -1188,11 +1629,11 @@ func (gf *generatedFrozen) replayAllPlanesTo(gc *generatedContributions, source incoming := cloneSlice(gf.compactionPreservers) current := cloneSlice(gc.compactionPreservers) - combined, err := PlaneCompactionPreservers.Combine(source, current, incoming) + combined, err := canonicalPlaneCompactionPreserversPolicy.combine(source, current, incoming) if err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneCompactionPreservers.ID, + PlaneID: canonicalPlaneCompactionPreserversPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } @@ -1212,30 +1653,30 @@ func (gf *generatedFrozen) replayAllPlanesTo(gc *generatedContributions, source } } if gf.secretGuards != nil { - if PlaneSecretGuards.Validate != nil { - if err := PlaneSecretGuards.Validate(gf.secretGuards); err != nil { + if canonicalPlaneSecretGuardsPolicy.validate != nil { + if err := canonicalPlaneSecretGuardsPolicy.validate(gf.secretGuards); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneSecretGuards.ID, + PlaneID: canonicalPlaneSecretGuardsPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneSecretGuards.generated.contribute(gc, source, contributorID, gf.secretGuards); err != nil { + if err := canonicalPlaneSecretGuardsAccess.contribute(gc, source, contributorID, gf.secretGuards); err != nil { return err } } if gf.localTurnHandlers != nil { - if PlaneLocalTurnHandlers.Validate != nil { - if err := PlaneLocalTurnHandlers.Validate(gf.localTurnHandlers); err != nil { + if canonicalPlaneLocalTurnHandlersPolicy.validate != nil { + if err := canonicalPlaneLocalTurnHandlersPolicy.validate(gf.localTurnHandlers); err != nil { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneLocalTurnHandlers.ID, + PlaneID: canonicalPlaneLocalTurnHandlersPolicy.planeID, Err: fmt.Errorf("%w: %w", ErrInvalidContribution, err), } } } - if err := PlaneLocalTurnHandlers.generated.contribute(gc, source, contributorID, gf.localTurnHandlers); err != nil { + if err := canonicalPlaneLocalTurnHandlersAccess.contribute(gc, source, contributorID, gf.localTurnHandlers); err != nil { return err } } @@ -1243,12 +1684,12 @@ func (gf *generatedFrozen) replayAllPlanesTo(gc *generatedContributions, source if !gf.terminalDecisionProviderHasID || gf.terminalDecisionProviderID == "" { return &AttributedError{ PluginID: contributorID, - PlaneID: PlaneTerminalDecisionProvider.ID, + PlaneID: canonicalPlaneTerminalDecisionProviderPolicy.planeID, Err: fmt.Errorf("%w: frozen exclusive identity is missing", ErrInvalidContribution), } } if gc.terminalDecisionProviderHasID { - return makeExclusiveConflictError(contributorID, PlaneTerminalDecisionProvider.ID, PlaneTerminalDecisionProvider.ExclusiveConflictError, gc.terminalDecisionProviderID, gf.terminalDecisionProviderID) + return makeExclusiveConflictError(contributorID, canonicalPlaneTerminalDecisionProviderPolicy.planeID, canonicalPlaneTerminalDecisionProviderPolicy.exclusiveConflictError, gc.terminalDecisionProviderID, gf.terminalDecisionProviderID) } gc.terminalDecisionProvider = gf.terminalDecisionProvider gc.terminalDecisionProviderID = gf.terminalDecisionProviderID @@ -1263,35 +1704,109 @@ func (gf *generatedFrozen) hasIdentityReplayRule(source SourceKind, rule Combina if gf == nil { return "", false } - if PlaneAttemptTransforms.Rules.RuleFor(source) == rule { + if canonicalPlaneAttemptTransformsPolicy.rules.RuleFor(source) == rule { if len(gf.attemptTransforms) > 0 { - return PlaneAttemptTransforms.ID, true + return canonicalPlaneAttemptTransformsPolicy.planeID, true } } - if PlaneStreamObserverFactories.Rules.RuleFor(source) == rule { + if canonicalPlaneStreamObserverFactoriesPolicy.rules.RuleFor(source) == rule { if len(gf.streamObserverFactories) > 0 { - return PlaneStreamObserverFactories.ID, true + return canonicalPlaneStreamObserverFactoriesPolicy.planeID, true } } - if PlaneCompactionPreservers.Rules.RuleFor(source) == rule { + if canonicalPlaneCompactionPreserversPolicy.rules.RuleFor(source) == rule { if len(gf.compactionPreservers) > 0 { - return PlaneCompactionPreservers.ID, true + return canonicalPlaneCompactionPreserversPolicy.planeID, true } } - if PlaneTerminalDecisionProvider.Rules.RuleFor(source) == rule { + if canonicalPlaneTerminalDecisionProviderPolicy.rules.RuleFor(source) == rule { if !isNilValue(gf.terminalDecisionProvider) { - return PlaneTerminalDecisionProvider.ID, true + return canonicalPlaneTerminalDecisionProviderPolicy.planeID, true } } return "", false } +// Canonical plane policies and access handles captured once at package init. +var ( + canonicalPlaneSubmitHooksPolicy *generatedPolicy[[]hooks.SubmitHook] + canonicalPlaneSubmitHooksAccess generatedAccess[[]hooks.SubmitHook] + canonicalPlaneRequestPartHooksPolicy *generatedPolicy[[]hooks.RequestPartHook] + canonicalPlaneRequestPartHooksAccess generatedAccess[[]hooks.RequestPartHook] + canonicalPlaneResponsePartHooksPolicy *generatedPolicy[[]hooks.ResponsePartHook] + canonicalPlaneResponsePartHooksAccess generatedAccess[[]hooks.ResponsePartHook] + canonicalPlaneToolReactorsPolicy *generatedPolicy[[]hooks.ToolReactor] + canonicalPlaneToolReactorsAccess generatedAccess[[]hooks.ToolReactor] + canonicalPlaneSessionOpenersPolicy *generatedPolicy[[]session.Opener] + canonicalPlaneSessionOpenersAccess generatedAccess[[]session.Opener] + canonicalPlaneWorkspaceResolversPolicy *generatedPolicy[[]workspace.Resolver] + canonicalPlaneWorkspaceResolversAccess generatedAccess[[]workspace.Resolver] + canonicalPlaneToolCatalogFiltersPolicy *generatedPolicy[[]toolcatalog.Filter] + canonicalPlaneToolCatalogFiltersAccess generatedAccess[[]toolcatalog.Filter] + canonicalPlaneToolCallPoliciesPolicy *generatedPolicy[[]toolpolicy.Policy] + canonicalPlaneToolCallPoliciesAccess generatedAccess[[]toolpolicy.Policy] + canonicalPlaneToolCallFinalizersPolicy *generatedPolicy[[]toolcall.Finalizer] + canonicalPlaneToolCallFinalizersAccess generatedAccess[[]toolcall.Finalizer] + canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy *generatedPolicy[int] + canonicalPlaneToolCallFinalizationMaxArgsBytesAccess generatedAccess[int] + canonicalPlaneRequestTransformsPolicy *generatedPolicy[[]request.Transform] + canonicalPlaneRequestTransformsAccess generatedAccess[[]request.Transform] + canonicalPlanePreRequestHandlersPolicy *generatedPolicy[[]prerequest.Handler] + canonicalPlanePreRequestHandlersAccess generatedAccess[[]prerequest.Handler] + canonicalPlaneRouteHintProvidersPolicy *generatedPolicy[[]routehint.Provider] + canonicalPlaneRouteHintProvidersAccess generatedAccess[[]routehint.Provider] + canonicalPlaneCompletionGatesPolicy *generatedPolicy[[]completion.Gate] + canonicalPlaneCompletionGatesAccess generatedAccess[[]completion.Gate] + canonicalPlaneAttemptTransformsPolicy *generatedPolicy[[]request.AttemptTransform] + canonicalPlaneAttemptTransformsAccess generatedAccess[[]request.AttemptTransform] + canonicalPlaneStreamObserverFactoriesPolicy *generatedPolicy[[]response.StreamObserverFactory] + canonicalPlaneStreamObserverFactoriesAccess generatedAccess[[]response.StreamObserverFactory] + canonicalPlaneTrafficObserversPolicy *generatedPolicy[[]traffic.Observer] + canonicalPlaneTrafficObserversAccess generatedAccess[[]traffic.Observer] + canonicalPlaneUsageObserversPolicy *generatedPolicy[[]usage.Observer] + canonicalPlaneUsageObserversAccess generatedAccess[[]usage.Observer] + canonicalPlaneRawCaptureSinksPolicy *generatedPolicy[[]traffic.RawCaptureSink] + canonicalPlaneRawCaptureSinksAccess generatedAccess[[]traffic.RawCaptureSink] + canonicalPlaneTrafficRedactorsPolicy *generatedPolicy[[]traffic.Redactor] + canonicalPlaneTrafficRedactorsAccess generatedAccess[[]traffic.Redactor] + canonicalPlaneCompactionObserversPolicy *generatedPolicy[[]compaction.Observer] + canonicalPlaneCompactionObserversAccess generatedAccess[[]compaction.Observer] + canonicalPlaneCompactionPreserversPolicy *generatedPolicy[[]compaction.Preserver] + canonicalPlaneCompactionPreserversAccess generatedAccess[[]compaction.Preserver] + canonicalPlaneSecretGuardsPolicy *generatedPolicy[[]secretguard.Guard] + canonicalPlaneSecretGuardsAccess generatedAccess[[]secretguard.Guard] + canonicalPlaneLocalTurnHandlersPolicy *generatedPolicy[[]localturn.Handler] + canonicalPlaneLocalTurnHandlersAccess generatedAccess[[]localturn.Handler] + canonicalPlaneTerminalDecisionProviderPolicy *generatedPolicy[terminaldecision.Provider] + canonicalPlaneTerminalDecisionProviderAccess generatedAccess[terminaldecision.Provider] +) + func init() { - PlaneSubmitHooks.generated = generatedAccess[[]hooks.SubmitHook]{ + canonicalPlaneSubmitHooksPolicy = &generatedPolicy[[]hooks.SubmitHook]{ + planeID: PlaneSubmitHooks.ID, + rules: PlaneSubmitHooks.Rules, + nilPolicy: PlaneSubmitHooks.NilPolicy, + isNil: PlaneSubmitHooks.IsNil, + validate: PlaneSubmitHooks.Validate, + validateIdentity: PlaneSubmitHooks.ValidateIdentity, + combine: PlaneSubmitHooks.Combine, + identity: PlaneSubmitHooks.Identity, + exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, + requestMaterializer: PlaneSubmitHooks.RequestMaterializer, + requestBorrow: PlaneSubmitHooks.RequestBorrow, + hookTarget: PlaneSubmitHooks.HookTarget, + diagStageID: PlaneSubmitHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneSubmitHooks.Diagnostics.Order, + diagMaterialize: PlaneSubmitHooks.Diagnostics.Materialize, + diagPrivileges: PlaneSubmitHooks.Diagnostics.Privileges, + } + canonicalPlaneSubmitHooksAccess = generatedAccess[[]hooks.SubmitHook]{ + policy: canonicalPlaneSubmitHooksPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []hooks.SubmitHook) error { incoming := cloneSlice(v) current := cloneSlice(gc.submitHooks) - combined, err := PlaneSubmitHooks.Combine(source, current, incoming) + combined, err := canonicalPlaneSubmitHooksPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1307,23 +1822,34 @@ func init() { } return cloneSlice(gf.submitHooks) }, - policy: &generatedPolicy[[]hooks.SubmitHook]{ - planeID: PlaneSubmitHooks.ID, - rules: PlaneSubmitHooks.Rules, - nilPolicy: PlaneSubmitHooks.NilPolicy, - isNil: PlaneSubmitHooks.IsNil, - validate: PlaneSubmitHooks.Validate, - validateIdentity: PlaneSubmitHooks.ValidateIdentity, - combine: PlaneSubmitHooks.Combine, - identity: PlaneSubmitHooks.Identity, - exclusiveConflictError: PlaneSubmitHooks.ExclusiveConflictError, - }, } - PlaneRequestPartHooks.generated = generatedAccess[[]hooks.RequestPartHook]{ + PlaneSubmitHooks.generated = canonicalPlaneSubmitHooksAccess + + canonicalPlaneRequestPartHooksPolicy = &generatedPolicy[[]hooks.RequestPartHook]{ + planeID: PlaneRequestPartHooks.ID, + rules: PlaneRequestPartHooks.Rules, + nilPolicy: PlaneRequestPartHooks.NilPolicy, + isNil: PlaneRequestPartHooks.IsNil, + validate: PlaneRequestPartHooks.Validate, + validateIdentity: PlaneRequestPartHooks.ValidateIdentity, + combine: PlaneRequestPartHooks.Combine, + identity: PlaneRequestPartHooks.Identity, + exclusiveConflictError: PlaneRequestPartHooks.ExclusiveConflictError, + requestMaterializer: PlaneRequestPartHooks.RequestMaterializer, + requestBorrow: PlaneRequestPartHooks.RequestBorrow, + hookTarget: PlaneRequestPartHooks.HookTarget, + diagStageID: PlaneRequestPartHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneRequestPartHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneRequestPartHooks.Diagnostics.Order, + diagMaterialize: PlaneRequestPartHooks.Diagnostics.Materialize, + diagPrivileges: PlaneRequestPartHooks.Diagnostics.Privileges, + } + canonicalPlaneRequestPartHooksAccess = generatedAccess[[]hooks.RequestPartHook]{ + policy: canonicalPlaneRequestPartHooksPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []hooks.RequestPartHook) error { incoming := cloneSlice(v) current := cloneSlice(gc.requestPartHooks) - combined, err := PlaneRequestPartHooks.Combine(source, current, incoming) + combined, err := canonicalPlaneRequestPartHooksPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1339,23 +1865,34 @@ func init() { } return cloneSlice(gf.requestPartHooks) }, - policy: &generatedPolicy[[]hooks.RequestPartHook]{ - planeID: PlaneRequestPartHooks.ID, - rules: PlaneRequestPartHooks.Rules, - nilPolicy: PlaneRequestPartHooks.NilPolicy, - isNil: PlaneRequestPartHooks.IsNil, - validate: PlaneRequestPartHooks.Validate, - validateIdentity: PlaneRequestPartHooks.ValidateIdentity, - combine: PlaneRequestPartHooks.Combine, - identity: PlaneRequestPartHooks.Identity, - exclusiveConflictError: PlaneRequestPartHooks.ExclusiveConflictError, - }, } - PlaneResponsePartHooks.generated = generatedAccess[[]hooks.ResponsePartHook]{ + PlaneRequestPartHooks.generated = canonicalPlaneRequestPartHooksAccess + + canonicalPlaneResponsePartHooksPolicy = &generatedPolicy[[]hooks.ResponsePartHook]{ + planeID: PlaneResponsePartHooks.ID, + rules: PlaneResponsePartHooks.Rules, + nilPolicy: PlaneResponsePartHooks.NilPolicy, + isNil: PlaneResponsePartHooks.IsNil, + validate: PlaneResponsePartHooks.Validate, + validateIdentity: PlaneResponsePartHooks.ValidateIdentity, + combine: PlaneResponsePartHooks.Combine, + identity: PlaneResponsePartHooks.Identity, + exclusiveConflictError: PlaneResponsePartHooks.ExclusiveConflictError, + requestMaterializer: PlaneResponsePartHooks.RequestMaterializer, + requestBorrow: PlaneResponsePartHooks.RequestBorrow, + hookTarget: PlaneResponsePartHooks.HookTarget, + diagStageID: PlaneResponsePartHooks.Diagnostics.StageID, + diagCoalesceGroup: PlaneResponsePartHooks.Diagnostics.CoalesceGroup, + diagOrder: PlaneResponsePartHooks.Diagnostics.Order, + diagMaterialize: PlaneResponsePartHooks.Diagnostics.Materialize, + diagPrivileges: PlaneResponsePartHooks.Diagnostics.Privileges, + } + canonicalPlaneResponsePartHooksAccess = generatedAccess[[]hooks.ResponsePartHook]{ + policy: canonicalPlaneResponsePartHooksPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []hooks.ResponsePartHook) error { incoming := cloneSlice(v) current := cloneSlice(gc.responsePartHooks) - combined, err := PlaneResponsePartHooks.Combine(source, current, incoming) + combined, err := canonicalPlaneResponsePartHooksPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1371,23 +1908,34 @@ func init() { } return cloneSlice(gf.responsePartHooks) }, - policy: &generatedPolicy[[]hooks.ResponsePartHook]{ - planeID: PlaneResponsePartHooks.ID, - rules: PlaneResponsePartHooks.Rules, - nilPolicy: PlaneResponsePartHooks.NilPolicy, - isNil: PlaneResponsePartHooks.IsNil, - validate: PlaneResponsePartHooks.Validate, - validateIdentity: PlaneResponsePartHooks.ValidateIdentity, - combine: PlaneResponsePartHooks.Combine, - identity: PlaneResponsePartHooks.Identity, - exclusiveConflictError: PlaneResponsePartHooks.ExclusiveConflictError, - }, } - PlaneToolReactors.generated = generatedAccess[[]hooks.ToolReactor]{ + PlaneResponsePartHooks.generated = canonicalPlaneResponsePartHooksAccess + + canonicalPlaneToolReactorsPolicy = &generatedPolicy[[]hooks.ToolReactor]{ + planeID: PlaneToolReactors.ID, + rules: PlaneToolReactors.Rules, + nilPolicy: PlaneToolReactors.NilPolicy, + isNil: PlaneToolReactors.IsNil, + validate: PlaneToolReactors.Validate, + validateIdentity: PlaneToolReactors.ValidateIdentity, + combine: PlaneToolReactors.Combine, + identity: PlaneToolReactors.Identity, + exclusiveConflictError: PlaneToolReactors.ExclusiveConflictError, + requestMaterializer: PlaneToolReactors.RequestMaterializer, + requestBorrow: PlaneToolReactors.RequestBorrow, + hookTarget: PlaneToolReactors.HookTarget, + diagStageID: PlaneToolReactors.Diagnostics.StageID, + diagCoalesceGroup: PlaneToolReactors.Diagnostics.CoalesceGroup, + diagOrder: PlaneToolReactors.Diagnostics.Order, + diagMaterialize: PlaneToolReactors.Diagnostics.Materialize, + diagPrivileges: PlaneToolReactors.Diagnostics.Privileges, + } + canonicalPlaneToolReactorsAccess = generatedAccess[[]hooks.ToolReactor]{ + policy: canonicalPlaneToolReactorsPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []hooks.ToolReactor) error { incoming := cloneSlice(v) current := cloneSlice(gc.toolReactors) - combined, err := PlaneToolReactors.Combine(source, current, incoming) + combined, err := canonicalPlaneToolReactorsPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1403,23 +1951,34 @@ func init() { } return cloneSlice(gf.toolReactors) }, - policy: &generatedPolicy[[]hooks.ToolReactor]{ - planeID: PlaneToolReactors.ID, - rules: PlaneToolReactors.Rules, - nilPolicy: PlaneToolReactors.NilPolicy, - isNil: PlaneToolReactors.IsNil, - validate: PlaneToolReactors.Validate, - validateIdentity: PlaneToolReactors.ValidateIdentity, - combine: PlaneToolReactors.Combine, - identity: PlaneToolReactors.Identity, - exclusiveConflictError: PlaneToolReactors.ExclusiveConflictError, - }, } - PlaneSessionOpeners.generated = generatedAccess[[]session.Opener]{ + PlaneToolReactors.generated = canonicalPlaneToolReactorsAccess + + canonicalPlaneSessionOpenersPolicy = &generatedPolicy[[]session.Opener]{ + planeID: PlaneSessionOpeners.ID, + rules: PlaneSessionOpeners.Rules, + nilPolicy: PlaneSessionOpeners.NilPolicy, + isNil: PlaneSessionOpeners.IsNil, + validate: PlaneSessionOpeners.Validate, + validateIdentity: PlaneSessionOpeners.ValidateIdentity, + combine: PlaneSessionOpeners.Combine, + identity: PlaneSessionOpeners.Identity, + exclusiveConflictError: PlaneSessionOpeners.ExclusiveConflictError, + requestMaterializer: PlaneSessionOpeners.RequestMaterializer, + requestBorrow: PlaneSessionOpeners.RequestBorrow, + hookTarget: PlaneSessionOpeners.HookTarget, + diagStageID: PlaneSessionOpeners.Diagnostics.StageID, + diagCoalesceGroup: PlaneSessionOpeners.Diagnostics.CoalesceGroup, + diagOrder: PlaneSessionOpeners.Diagnostics.Order, + diagMaterialize: PlaneSessionOpeners.Diagnostics.Materialize, + diagPrivileges: PlaneSessionOpeners.Diagnostics.Privileges, + } + canonicalPlaneSessionOpenersAccess = generatedAccess[[]session.Opener]{ + policy: canonicalPlaneSessionOpenersPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []session.Opener) error { incoming := cloneSlice(v) current := cloneSlice(gc.sessionOpeners) - combined, err := PlaneSessionOpeners.Combine(source, current, incoming) + combined, err := canonicalPlaneSessionOpenersPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1435,23 +1994,34 @@ func init() { } return cloneSlice(gf.sessionOpeners) }, - policy: &generatedPolicy[[]session.Opener]{ - planeID: PlaneSessionOpeners.ID, - rules: PlaneSessionOpeners.Rules, - nilPolicy: PlaneSessionOpeners.NilPolicy, - isNil: PlaneSessionOpeners.IsNil, - validate: PlaneSessionOpeners.Validate, - validateIdentity: PlaneSessionOpeners.ValidateIdentity, - combine: PlaneSessionOpeners.Combine, - identity: PlaneSessionOpeners.Identity, - exclusiveConflictError: PlaneSessionOpeners.ExclusiveConflictError, - }, } - PlaneWorkspaceResolvers.generated = generatedAccess[[]workspace.Resolver]{ + PlaneSessionOpeners.generated = canonicalPlaneSessionOpenersAccess + + canonicalPlaneWorkspaceResolversPolicy = &generatedPolicy[[]workspace.Resolver]{ + planeID: PlaneWorkspaceResolvers.ID, + rules: PlaneWorkspaceResolvers.Rules, + nilPolicy: PlaneWorkspaceResolvers.NilPolicy, + isNil: PlaneWorkspaceResolvers.IsNil, + validate: PlaneWorkspaceResolvers.Validate, + validateIdentity: PlaneWorkspaceResolvers.ValidateIdentity, + combine: PlaneWorkspaceResolvers.Combine, + identity: PlaneWorkspaceResolvers.Identity, + exclusiveConflictError: PlaneWorkspaceResolvers.ExclusiveConflictError, + requestMaterializer: PlaneWorkspaceResolvers.RequestMaterializer, + requestBorrow: PlaneWorkspaceResolvers.RequestBorrow, + hookTarget: PlaneWorkspaceResolvers.HookTarget, + diagStageID: PlaneWorkspaceResolvers.Diagnostics.StageID, + diagCoalesceGroup: PlaneWorkspaceResolvers.Diagnostics.CoalesceGroup, + diagOrder: PlaneWorkspaceResolvers.Diagnostics.Order, + diagMaterialize: PlaneWorkspaceResolvers.Diagnostics.Materialize, + diagPrivileges: PlaneWorkspaceResolvers.Diagnostics.Privileges, + } + canonicalPlaneWorkspaceResolversAccess = generatedAccess[[]workspace.Resolver]{ + policy: canonicalPlaneWorkspaceResolversPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []workspace.Resolver) error { incoming := cloneSlice(v) current := cloneSlice(gc.workspaceResolvers) - combined, err := PlaneWorkspaceResolvers.Combine(source, current, incoming) + combined, err := canonicalPlaneWorkspaceResolversPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1467,23 +2037,34 @@ func init() { } return cloneSlice(gf.workspaceResolvers) }, - policy: &generatedPolicy[[]workspace.Resolver]{ - planeID: PlaneWorkspaceResolvers.ID, - rules: PlaneWorkspaceResolvers.Rules, - nilPolicy: PlaneWorkspaceResolvers.NilPolicy, - isNil: PlaneWorkspaceResolvers.IsNil, - validate: PlaneWorkspaceResolvers.Validate, - validateIdentity: PlaneWorkspaceResolvers.ValidateIdentity, - combine: PlaneWorkspaceResolvers.Combine, - identity: PlaneWorkspaceResolvers.Identity, - exclusiveConflictError: PlaneWorkspaceResolvers.ExclusiveConflictError, - }, } - PlaneToolCatalogFilters.generated = generatedAccess[[]toolcatalog.Filter]{ + PlaneWorkspaceResolvers.generated = canonicalPlaneWorkspaceResolversAccess + + canonicalPlaneToolCatalogFiltersPolicy = &generatedPolicy[[]toolcatalog.Filter]{ + planeID: PlaneToolCatalogFilters.ID, + rules: PlaneToolCatalogFilters.Rules, + nilPolicy: PlaneToolCatalogFilters.NilPolicy, + isNil: PlaneToolCatalogFilters.IsNil, + validate: PlaneToolCatalogFilters.Validate, + validateIdentity: PlaneToolCatalogFilters.ValidateIdentity, + combine: PlaneToolCatalogFilters.Combine, + identity: PlaneToolCatalogFilters.Identity, + exclusiveConflictError: PlaneToolCatalogFilters.ExclusiveConflictError, + requestMaterializer: PlaneToolCatalogFilters.RequestMaterializer, + requestBorrow: PlaneToolCatalogFilters.RequestBorrow, + hookTarget: PlaneToolCatalogFilters.HookTarget, + diagStageID: PlaneToolCatalogFilters.Diagnostics.StageID, + diagCoalesceGroup: PlaneToolCatalogFilters.Diagnostics.CoalesceGroup, + diagOrder: PlaneToolCatalogFilters.Diagnostics.Order, + diagMaterialize: PlaneToolCatalogFilters.Diagnostics.Materialize, + diagPrivileges: PlaneToolCatalogFilters.Diagnostics.Privileges, + } + canonicalPlaneToolCatalogFiltersAccess = generatedAccess[[]toolcatalog.Filter]{ + policy: canonicalPlaneToolCatalogFiltersPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []toolcatalog.Filter) error { incoming := cloneSlice(v) current := cloneSlice(gc.toolCatalogFilters) - combined, err := PlaneToolCatalogFilters.Combine(source, current, incoming) + combined, err := canonicalPlaneToolCatalogFiltersPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1499,23 +2080,34 @@ func init() { } return cloneSlice(gf.toolCatalogFilters) }, - policy: &generatedPolicy[[]toolcatalog.Filter]{ - planeID: PlaneToolCatalogFilters.ID, - rules: PlaneToolCatalogFilters.Rules, - nilPolicy: PlaneToolCatalogFilters.NilPolicy, - isNil: PlaneToolCatalogFilters.IsNil, - validate: PlaneToolCatalogFilters.Validate, - validateIdentity: PlaneToolCatalogFilters.ValidateIdentity, - combine: PlaneToolCatalogFilters.Combine, - identity: PlaneToolCatalogFilters.Identity, - exclusiveConflictError: PlaneToolCatalogFilters.ExclusiveConflictError, - }, } - PlaneToolCallPolicies.generated = generatedAccess[[]toolpolicy.Policy]{ + PlaneToolCatalogFilters.generated = canonicalPlaneToolCatalogFiltersAccess + + canonicalPlaneToolCallPoliciesPolicy = &generatedPolicy[[]toolpolicy.Policy]{ + planeID: PlaneToolCallPolicies.ID, + rules: PlaneToolCallPolicies.Rules, + nilPolicy: PlaneToolCallPolicies.NilPolicy, + isNil: PlaneToolCallPolicies.IsNil, + validate: PlaneToolCallPolicies.Validate, + validateIdentity: PlaneToolCallPolicies.ValidateIdentity, + combine: PlaneToolCallPolicies.Combine, + identity: PlaneToolCallPolicies.Identity, + exclusiveConflictError: PlaneToolCallPolicies.ExclusiveConflictError, + requestMaterializer: PlaneToolCallPolicies.RequestMaterializer, + requestBorrow: PlaneToolCallPolicies.RequestBorrow, + hookTarget: PlaneToolCallPolicies.HookTarget, + diagStageID: PlaneToolCallPolicies.Diagnostics.StageID, + diagCoalesceGroup: PlaneToolCallPolicies.Diagnostics.CoalesceGroup, + diagOrder: PlaneToolCallPolicies.Diagnostics.Order, + diagMaterialize: PlaneToolCallPolicies.Diagnostics.Materialize, + diagPrivileges: PlaneToolCallPolicies.Diagnostics.Privileges, + } + canonicalPlaneToolCallPoliciesAccess = generatedAccess[[]toolpolicy.Policy]{ + policy: canonicalPlaneToolCallPoliciesPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []toolpolicy.Policy) error { incoming := cloneSlice(v) current := cloneSlice(gc.toolCallPolicies) - combined, err := PlaneToolCallPolicies.Combine(source, current, incoming) + combined, err := canonicalPlaneToolCallPoliciesPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1531,23 +2123,34 @@ func init() { } return cloneSlice(gf.toolCallPolicies) }, - policy: &generatedPolicy[[]toolpolicy.Policy]{ - planeID: PlaneToolCallPolicies.ID, - rules: PlaneToolCallPolicies.Rules, - nilPolicy: PlaneToolCallPolicies.NilPolicy, - isNil: PlaneToolCallPolicies.IsNil, - validate: PlaneToolCallPolicies.Validate, - validateIdentity: PlaneToolCallPolicies.ValidateIdentity, - combine: PlaneToolCallPolicies.Combine, - identity: PlaneToolCallPolicies.Identity, - exclusiveConflictError: PlaneToolCallPolicies.ExclusiveConflictError, - }, } - PlaneToolCallFinalizers.generated = generatedAccess[[]toolcall.Finalizer]{ + PlaneToolCallPolicies.generated = canonicalPlaneToolCallPoliciesAccess + + canonicalPlaneToolCallFinalizersPolicy = &generatedPolicy[[]toolcall.Finalizer]{ + planeID: PlaneToolCallFinalizers.ID, + rules: PlaneToolCallFinalizers.Rules, + nilPolicy: PlaneToolCallFinalizers.NilPolicy, + isNil: PlaneToolCallFinalizers.IsNil, + validate: PlaneToolCallFinalizers.Validate, + validateIdentity: PlaneToolCallFinalizers.ValidateIdentity, + combine: PlaneToolCallFinalizers.Combine, + identity: PlaneToolCallFinalizers.Identity, + exclusiveConflictError: PlaneToolCallFinalizers.ExclusiveConflictError, + requestMaterializer: PlaneToolCallFinalizers.RequestMaterializer, + requestBorrow: PlaneToolCallFinalizers.RequestBorrow, + hookTarget: PlaneToolCallFinalizers.HookTarget, + diagStageID: PlaneToolCallFinalizers.Diagnostics.StageID, + diagCoalesceGroup: PlaneToolCallFinalizers.Diagnostics.CoalesceGroup, + diagOrder: PlaneToolCallFinalizers.Diagnostics.Order, + diagMaterialize: PlaneToolCallFinalizers.Diagnostics.Materialize, + diagPrivileges: PlaneToolCallFinalizers.Diagnostics.Privileges, + } + canonicalPlaneToolCallFinalizersAccess = generatedAccess[[]toolcall.Finalizer]{ + policy: canonicalPlaneToolCallFinalizersPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []toolcall.Finalizer) error { incoming := cloneSlice(v) current := cloneSlice(gc.toolCallFinalizers) - combined, err := PlaneToolCallFinalizers.Combine(source, current, incoming) + combined, err := canonicalPlaneToolCallFinalizersPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1563,21 +2166,32 @@ func init() { } return cloneSlice(gf.toolCallFinalizers) }, - policy: &generatedPolicy[[]toolcall.Finalizer]{ - planeID: PlaneToolCallFinalizers.ID, - rules: PlaneToolCallFinalizers.Rules, - nilPolicy: PlaneToolCallFinalizers.NilPolicy, - isNil: PlaneToolCallFinalizers.IsNil, - validate: PlaneToolCallFinalizers.Validate, - validateIdentity: PlaneToolCallFinalizers.ValidateIdentity, - combine: PlaneToolCallFinalizers.Combine, - identity: PlaneToolCallFinalizers.Identity, - exclusiveConflictError: PlaneToolCallFinalizers.ExclusiveConflictError, - }, } - PlaneToolCallFinalizationMaxArgsBytes.generated = generatedAccess[int]{ + PlaneToolCallFinalizers.generated = canonicalPlaneToolCallFinalizersAccess + + canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy = &generatedPolicy[int]{ + planeID: PlaneToolCallFinalizationMaxArgsBytes.ID, + rules: PlaneToolCallFinalizationMaxArgsBytes.Rules, + nilPolicy: PlaneToolCallFinalizationMaxArgsBytes.NilPolicy, + isNil: PlaneToolCallFinalizationMaxArgsBytes.IsNil, + validate: PlaneToolCallFinalizationMaxArgsBytes.Validate, + validateIdentity: PlaneToolCallFinalizationMaxArgsBytes.ValidateIdentity, + combine: PlaneToolCallFinalizationMaxArgsBytes.Combine, + identity: PlaneToolCallFinalizationMaxArgsBytes.Identity, + exclusiveConflictError: PlaneToolCallFinalizationMaxArgsBytes.ExclusiveConflictError, + requestMaterializer: PlaneToolCallFinalizationMaxArgsBytes.RequestMaterializer, + requestBorrow: PlaneToolCallFinalizationMaxArgsBytes.RequestBorrow, + hookTarget: PlaneToolCallFinalizationMaxArgsBytes.HookTarget, + diagStageID: PlaneToolCallFinalizationMaxArgsBytes.Diagnostics.StageID, + diagCoalesceGroup: PlaneToolCallFinalizationMaxArgsBytes.Diagnostics.CoalesceGroup, + diagOrder: PlaneToolCallFinalizationMaxArgsBytes.Diagnostics.Order, + diagMaterialize: PlaneToolCallFinalizationMaxArgsBytes.Diagnostics.Materialize, + diagPrivileges: PlaneToolCallFinalizationMaxArgsBytes.Diagnostics.Privileges, + } + canonicalPlaneToolCallFinalizationMaxArgsBytesAccess = generatedAccess[int]{ + policy: canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v int) error { - combined, err := PlaneToolCallFinalizationMaxArgsBytes.Combine(source, gc.toolCallFinalizationMaxArgsBytes, v) + combined, err := canonicalPlaneToolCallFinalizationMaxArgsBytesPolicy.combine(source, gc.toolCallFinalizationMaxArgsBytes, v) if err != nil { return err } @@ -1590,23 +2204,34 @@ func init() { } return gf.toolCallFinalizationMaxArgsBytes }, - policy: &generatedPolicy[int]{ - planeID: PlaneToolCallFinalizationMaxArgsBytes.ID, - rules: PlaneToolCallFinalizationMaxArgsBytes.Rules, - nilPolicy: PlaneToolCallFinalizationMaxArgsBytes.NilPolicy, - isNil: PlaneToolCallFinalizationMaxArgsBytes.IsNil, - validate: PlaneToolCallFinalizationMaxArgsBytes.Validate, - validateIdentity: PlaneToolCallFinalizationMaxArgsBytes.ValidateIdentity, - combine: PlaneToolCallFinalizationMaxArgsBytes.Combine, - identity: PlaneToolCallFinalizationMaxArgsBytes.Identity, - exclusiveConflictError: PlaneToolCallFinalizationMaxArgsBytes.ExclusiveConflictError, - }, } - PlaneRequestTransforms.generated = generatedAccess[[]request.Transform]{ + PlaneToolCallFinalizationMaxArgsBytes.generated = canonicalPlaneToolCallFinalizationMaxArgsBytesAccess + + canonicalPlaneRequestTransformsPolicy = &generatedPolicy[[]request.Transform]{ + planeID: PlaneRequestTransforms.ID, + rules: PlaneRequestTransforms.Rules, + nilPolicy: PlaneRequestTransforms.NilPolicy, + isNil: PlaneRequestTransforms.IsNil, + validate: PlaneRequestTransforms.Validate, + validateIdentity: PlaneRequestTransforms.ValidateIdentity, + combine: PlaneRequestTransforms.Combine, + identity: PlaneRequestTransforms.Identity, + exclusiveConflictError: PlaneRequestTransforms.ExclusiveConflictError, + requestMaterializer: PlaneRequestTransforms.RequestMaterializer, + requestBorrow: PlaneRequestTransforms.RequestBorrow, + hookTarget: PlaneRequestTransforms.HookTarget, + diagStageID: PlaneRequestTransforms.Diagnostics.StageID, + diagCoalesceGroup: PlaneRequestTransforms.Diagnostics.CoalesceGroup, + diagOrder: PlaneRequestTransforms.Diagnostics.Order, + diagMaterialize: PlaneRequestTransforms.Diagnostics.Materialize, + diagPrivileges: PlaneRequestTransforms.Diagnostics.Privileges, + } + canonicalPlaneRequestTransformsAccess = generatedAccess[[]request.Transform]{ + policy: canonicalPlaneRequestTransformsPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []request.Transform) error { incoming := cloneSlice(v) current := cloneSlice(gc.requestTransforms) - combined, err := PlaneRequestTransforms.Combine(source, current, incoming) + combined, err := canonicalPlaneRequestTransformsPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1622,23 +2247,34 @@ func init() { } return cloneSlice(gf.requestTransforms) }, - policy: &generatedPolicy[[]request.Transform]{ - planeID: PlaneRequestTransforms.ID, - rules: PlaneRequestTransforms.Rules, - nilPolicy: PlaneRequestTransforms.NilPolicy, - isNil: PlaneRequestTransforms.IsNil, - validate: PlaneRequestTransforms.Validate, - validateIdentity: PlaneRequestTransforms.ValidateIdentity, - combine: PlaneRequestTransforms.Combine, - identity: PlaneRequestTransforms.Identity, - exclusiveConflictError: PlaneRequestTransforms.ExclusiveConflictError, - }, } - PlanePreRequestHandlers.generated = generatedAccess[[]prerequest.Handler]{ + PlaneRequestTransforms.generated = canonicalPlaneRequestTransformsAccess + + canonicalPlanePreRequestHandlersPolicy = &generatedPolicy[[]prerequest.Handler]{ + planeID: PlanePreRequestHandlers.ID, + rules: PlanePreRequestHandlers.Rules, + nilPolicy: PlanePreRequestHandlers.NilPolicy, + isNil: PlanePreRequestHandlers.IsNil, + validate: PlanePreRequestHandlers.Validate, + validateIdentity: PlanePreRequestHandlers.ValidateIdentity, + combine: PlanePreRequestHandlers.Combine, + identity: PlanePreRequestHandlers.Identity, + exclusiveConflictError: PlanePreRequestHandlers.ExclusiveConflictError, + requestMaterializer: PlanePreRequestHandlers.RequestMaterializer, + requestBorrow: PlanePreRequestHandlers.RequestBorrow, + hookTarget: PlanePreRequestHandlers.HookTarget, + diagStageID: PlanePreRequestHandlers.Diagnostics.StageID, + diagCoalesceGroup: PlanePreRequestHandlers.Diagnostics.CoalesceGroup, + diagOrder: PlanePreRequestHandlers.Diagnostics.Order, + diagMaterialize: PlanePreRequestHandlers.Diagnostics.Materialize, + diagPrivileges: PlanePreRequestHandlers.Diagnostics.Privileges, + } + canonicalPlanePreRequestHandlersAccess = generatedAccess[[]prerequest.Handler]{ + policy: canonicalPlanePreRequestHandlersPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []prerequest.Handler) error { incoming := cloneSlice(v) current := cloneSlice(gc.preRequestHandlers) - combined, err := PlanePreRequestHandlers.Combine(source, current, incoming) + combined, err := canonicalPlanePreRequestHandlersPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1654,23 +2290,34 @@ func init() { } return cloneSlice(gf.preRequestHandlers) }, - policy: &generatedPolicy[[]prerequest.Handler]{ - planeID: PlanePreRequestHandlers.ID, - rules: PlanePreRequestHandlers.Rules, - nilPolicy: PlanePreRequestHandlers.NilPolicy, - isNil: PlanePreRequestHandlers.IsNil, - validate: PlanePreRequestHandlers.Validate, - validateIdentity: PlanePreRequestHandlers.ValidateIdentity, - combine: PlanePreRequestHandlers.Combine, - identity: PlanePreRequestHandlers.Identity, - exclusiveConflictError: PlanePreRequestHandlers.ExclusiveConflictError, - }, } - PlaneRouteHintProviders.generated = generatedAccess[[]routehint.Provider]{ + PlanePreRequestHandlers.generated = canonicalPlanePreRequestHandlersAccess + + canonicalPlaneRouteHintProvidersPolicy = &generatedPolicy[[]routehint.Provider]{ + planeID: PlaneRouteHintProviders.ID, + rules: PlaneRouteHintProviders.Rules, + nilPolicy: PlaneRouteHintProviders.NilPolicy, + isNil: PlaneRouteHintProviders.IsNil, + validate: PlaneRouteHintProviders.Validate, + validateIdentity: PlaneRouteHintProviders.ValidateIdentity, + combine: PlaneRouteHintProviders.Combine, + identity: PlaneRouteHintProviders.Identity, + exclusiveConflictError: PlaneRouteHintProviders.ExclusiveConflictError, + requestMaterializer: PlaneRouteHintProviders.RequestMaterializer, + requestBorrow: PlaneRouteHintProviders.RequestBorrow, + hookTarget: PlaneRouteHintProviders.HookTarget, + diagStageID: PlaneRouteHintProviders.Diagnostics.StageID, + diagCoalesceGroup: PlaneRouteHintProviders.Diagnostics.CoalesceGroup, + diagOrder: PlaneRouteHintProviders.Diagnostics.Order, + diagMaterialize: PlaneRouteHintProviders.Diagnostics.Materialize, + diagPrivileges: PlaneRouteHintProviders.Diagnostics.Privileges, + } + canonicalPlaneRouteHintProvidersAccess = generatedAccess[[]routehint.Provider]{ + policy: canonicalPlaneRouteHintProvidersPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []routehint.Provider) error { incoming := cloneSlice(v) current := cloneSlice(gc.routeHintProviders) - combined, err := PlaneRouteHintProviders.Combine(source, current, incoming) + combined, err := canonicalPlaneRouteHintProvidersPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1686,23 +2333,34 @@ func init() { } return cloneSlice(gf.routeHintProviders) }, - policy: &generatedPolicy[[]routehint.Provider]{ - planeID: PlaneRouteHintProviders.ID, - rules: PlaneRouteHintProviders.Rules, - nilPolicy: PlaneRouteHintProviders.NilPolicy, - isNil: PlaneRouteHintProviders.IsNil, - validate: PlaneRouteHintProviders.Validate, - validateIdentity: PlaneRouteHintProviders.ValidateIdentity, - combine: PlaneRouteHintProviders.Combine, - identity: PlaneRouteHintProviders.Identity, - exclusiveConflictError: PlaneRouteHintProviders.ExclusiveConflictError, - }, } - PlaneCompletionGates.generated = generatedAccess[[]completion.Gate]{ + PlaneRouteHintProviders.generated = canonicalPlaneRouteHintProvidersAccess + + canonicalPlaneCompletionGatesPolicy = &generatedPolicy[[]completion.Gate]{ + planeID: PlaneCompletionGates.ID, + rules: PlaneCompletionGates.Rules, + nilPolicy: PlaneCompletionGates.NilPolicy, + isNil: PlaneCompletionGates.IsNil, + validate: PlaneCompletionGates.Validate, + validateIdentity: PlaneCompletionGates.ValidateIdentity, + combine: PlaneCompletionGates.Combine, + identity: PlaneCompletionGates.Identity, + exclusiveConflictError: PlaneCompletionGates.ExclusiveConflictError, + requestMaterializer: PlaneCompletionGates.RequestMaterializer, + requestBorrow: PlaneCompletionGates.RequestBorrow, + hookTarget: PlaneCompletionGates.HookTarget, + diagStageID: PlaneCompletionGates.Diagnostics.StageID, + diagCoalesceGroup: PlaneCompletionGates.Diagnostics.CoalesceGroup, + diagOrder: PlaneCompletionGates.Diagnostics.Order, + diagMaterialize: PlaneCompletionGates.Diagnostics.Materialize, + diagPrivileges: PlaneCompletionGates.Diagnostics.Privileges, + } + canonicalPlaneCompletionGatesAccess = generatedAccess[[]completion.Gate]{ + policy: canonicalPlaneCompletionGatesPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []completion.Gate) error { incoming := cloneSlice(v) current := cloneSlice(gc.completionGates) - combined, err := PlaneCompletionGates.Combine(source, current, incoming) + combined, err := canonicalPlaneCompletionGatesPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1718,23 +2376,34 @@ func init() { } return cloneSlice(gf.completionGates) }, - policy: &generatedPolicy[[]completion.Gate]{ - planeID: PlaneCompletionGates.ID, - rules: PlaneCompletionGates.Rules, - nilPolicy: PlaneCompletionGates.NilPolicy, - isNil: PlaneCompletionGates.IsNil, - validate: PlaneCompletionGates.Validate, - validateIdentity: PlaneCompletionGates.ValidateIdentity, - combine: PlaneCompletionGates.Combine, - identity: PlaneCompletionGates.Identity, - exclusiveConflictError: PlaneCompletionGates.ExclusiveConflictError, - }, } - PlaneAttemptTransforms.generated = generatedAccess[[]request.AttemptTransform]{ + PlaneCompletionGates.generated = canonicalPlaneCompletionGatesAccess + + canonicalPlaneAttemptTransformsPolicy = &generatedPolicy[[]request.AttemptTransform]{ + planeID: PlaneAttemptTransforms.ID, + rules: PlaneAttemptTransforms.Rules, + nilPolicy: PlaneAttemptTransforms.NilPolicy, + isNil: PlaneAttemptTransforms.IsNil, + validate: PlaneAttemptTransforms.Validate, + validateIdentity: PlaneAttemptTransforms.ValidateIdentity, + combine: PlaneAttemptTransforms.Combine, + identity: PlaneAttemptTransforms.Identity, + exclusiveConflictError: PlaneAttemptTransforms.ExclusiveConflictError, + requestMaterializer: PlaneAttemptTransforms.RequestMaterializer, + requestBorrow: PlaneAttemptTransforms.RequestBorrow, + hookTarget: PlaneAttemptTransforms.HookTarget, + diagStageID: PlaneAttemptTransforms.Diagnostics.StageID, + diagCoalesceGroup: PlaneAttemptTransforms.Diagnostics.CoalesceGroup, + diagOrder: PlaneAttemptTransforms.Diagnostics.Order, + diagMaterialize: PlaneAttemptTransforms.Diagnostics.Materialize, + diagPrivileges: PlaneAttemptTransforms.Diagnostics.Privileges, + } + canonicalPlaneAttemptTransformsAccess = generatedAccess[[]request.AttemptTransform]{ + policy: canonicalPlaneAttemptTransformsPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []request.AttemptTransform) error { incoming := cloneSlice(v) current := cloneSlice(gc.attemptTransforms) - combined, err := PlaneAttemptTransforms.Combine(source, current, incoming) + combined, err := canonicalPlaneAttemptTransformsPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1742,7 +2411,7 @@ func init() { combined = make([]request.AttemptTransform, 0) } gc.attemptTransforms = cloneSlice(combined) - id, hasID := PlaneAttemptTransforms.Identity(gc.attemptTransforms) + id, hasID := canonicalPlaneAttemptTransformsPolicy.identity(gc.attemptTransforms) gc.attemptTransformsID = id gc.attemptTransformsHasID = hasID return nil @@ -1759,23 +2428,34 @@ func init() { } return gf.attemptTransformsID, gf.attemptTransformsHasID }, - policy: &generatedPolicy[[]request.AttemptTransform]{ - planeID: PlaneAttemptTransforms.ID, - rules: PlaneAttemptTransforms.Rules, - nilPolicy: PlaneAttemptTransforms.NilPolicy, - isNil: PlaneAttemptTransforms.IsNil, - validate: PlaneAttemptTransforms.Validate, - validateIdentity: PlaneAttemptTransforms.ValidateIdentity, - combine: PlaneAttemptTransforms.Combine, - identity: PlaneAttemptTransforms.Identity, - exclusiveConflictError: PlaneAttemptTransforms.ExclusiveConflictError, - }, } - PlaneStreamObserverFactories.generated = generatedAccess[[]response.StreamObserverFactory]{ + PlaneAttemptTransforms.generated = canonicalPlaneAttemptTransformsAccess + + canonicalPlaneStreamObserverFactoriesPolicy = &generatedPolicy[[]response.StreamObserverFactory]{ + planeID: PlaneStreamObserverFactories.ID, + rules: PlaneStreamObserverFactories.Rules, + nilPolicy: PlaneStreamObserverFactories.NilPolicy, + isNil: PlaneStreamObserverFactories.IsNil, + validate: PlaneStreamObserverFactories.Validate, + validateIdentity: PlaneStreamObserverFactories.ValidateIdentity, + combine: PlaneStreamObserverFactories.Combine, + identity: PlaneStreamObserverFactories.Identity, + exclusiveConflictError: PlaneStreamObserverFactories.ExclusiveConflictError, + requestMaterializer: PlaneStreamObserverFactories.RequestMaterializer, + requestBorrow: PlaneStreamObserverFactories.RequestBorrow, + hookTarget: PlaneStreamObserverFactories.HookTarget, + diagStageID: PlaneStreamObserverFactories.Diagnostics.StageID, + diagCoalesceGroup: PlaneStreamObserverFactories.Diagnostics.CoalesceGroup, + diagOrder: PlaneStreamObserverFactories.Diagnostics.Order, + diagMaterialize: PlaneStreamObserverFactories.Diagnostics.Materialize, + diagPrivileges: PlaneStreamObserverFactories.Diagnostics.Privileges, + } + canonicalPlaneStreamObserverFactoriesAccess = generatedAccess[[]response.StreamObserverFactory]{ + policy: canonicalPlaneStreamObserverFactoriesPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []response.StreamObserverFactory) error { incoming := cloneSlice(v) current := cloneSlice(gc.streamObserverFactories) - combined, err := PlaneStreamObserverFactories.Combine(source, current, incoming) + combined, err := canonicalPlaneStreamObserverFactoriesPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1783,7 +2463,7 @@ func init() { combined = make([]response.StreamObserverFactory, 0) } gc.streamObserverFactories = cloneSlice(combined) - id, hasID := PlaneStreamObserverFactories.Identity(gc.streamObserverFactories) + id, hasID := canonicalPlaneStreamObserverFactoriesPolicy.identity(gc.streamObserverFactories) gc.streamObserverFactoriesID = id gc.streamObserverFactoriesHasID = hasID return nil @@ -1800,23 +2480,34 @@ func init() { } return gf.streamObserverFactoriesID, gf.streamObserverFactoriesHasID }, - policy: &generatedPolicy[[]response.StreamObserverFactory]{ - planeID: PlaneStreamObserverFactories.ID, - rules: PlaneStreamObserverFactories.Rules, - nilPolicy: PlaneStreamObserverFactories.NilPolicy, - isNil: PlaneStreamObserverFactories.IsNil, - validate: PlaneStreamObserverFactories.Validate, - validateIdentity: PlaneStreamObserverFactories.ValidateIdentity, - combine: PlaneStreamObserverFactories.Combine, - identity: PlaneStreamObserverFactories.Identity, - exclusiveConflictError: PlaneStreamObserverFactories.ExclusiveConflictError, - }, } - PlaneTrafficObservers.generated = generatedAccess[[]traffic.Observer]{ + PlaneStreamObserverFactories.generated = canonicalPlaneStreamObserverFactoriesAccess + + canonicalPlaneTrafficObserversPolicy = &generatedPolicy[[]traffic.Observer]{ + planeID: PlaneTrafficObservers.ID, + rules: PlaneTrafficObservers.Rules, + nilPolicy: PlaneTrafficObservers.NilPolicy, + isNil: PlaneTrafficObservers.IsNil, + validate: PlaneTrafficObservers.Validate, + validateIdentity: PlaneTrafficObservers.ValidateIdentity, + combine: PlaneTrafficObservers.Combine, + identity: PlaneTrafficObservers.Identity, + exclusiveConflictError: PlaneTrafficObservers.ExclusiveConflictError, + requestMaterializer: PlaneTrafficObservers.RequestMaterializer, + requestBorrow: PlaneTrafficObservers.RequestBorrow, + hookTarget: PlaneTrafficObservers.HookTarget, + diagStageID: PlaneTrafficObservers.Diagnostics.StageID, + diagCoalesceGroup: PlaneTrafficObservers.Diagnostics.CoalesceGroup, + diagOrder: PlaneTrafficObservers.Diagnostics.Order, + diagMaterialize: PlaneTrafficObservers.Diagnostics.Materialize, + diagPrivileges: PlaneTrafficObservers.Diagnostics.Privileges, + } + canonicalPlaneTrafficObserversAccess = generatedAccess[[]traffic.Observer]{ + policy: canonicalPlaneTrafficObserversPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []traffic.Observer) error { incoming := cloneSlice(v) current := cloneSlice(gc.trafficObservers) - combined, err := PlaneTrafficObservers.Combine(source, current, incoming) + combined, err := canonicalPlaneTrafficObserversPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1832,23 +2523,34 @@ func init() { } return cloneSlice(gf.trafficObservers) }, - policy: &generatedPolicy[[]traffic.Observer]{ - planeID: PlaneTrafficObservers.ID, - rules: PlaneTrafficObservers.Rules, - nilPolicy: PlaneTrafficObservers.NilPolicy, - isNil: PlaneTrafficObservers.IsNil, - validate: PlaneTrafficObservers.Validate, - validateIdentity: PlaneTrafficObservers.ValidateIdentity, - combine: PlaneTrafficObservers.Combine, - identity: PlaneTrafficObservers.Identity, - exclusiveConflictError: PlaneTrafficObservers.ExclusiveConflictError, - }, } - PlaneUsageObservers.generated = generatedAccess[[]usage.Observer]{ + PlaneTrafficObservers.generated = canonicalPlaneTrafficObserversAccess + + canonicalPlaneUsageObserversPolicy = &generatedPolicy[[]usage.Observer]{ + planeID: PlaneUsageObservers.ID, + rules: PlaneUsageObservers.Rules, + nilPolicy: PlaneUsageObservers.NilPolicy, + isNil: PlaneUsageObservers.IsNil, + validate: PlaneUsageObservers.Validate, + validateIdentity: PlaneUsageObservers.ValidateIdentity, + combine: PlaneUsageObservers.Combine, + identity: PlaneUsageObservers.Identity, + exclusiveConflictError: PlaneUsageObservers.ExclusiveConflictError, + requestMaterializer: PlaneUsageObservers.RequestMaterializer, + requestBorrow: PlaneUsageObservers.RequestBorrow, + hookTarget: PlaneUsageObservers.HookTarget, + diagStageID: PlaneUsageObservers.Diagnostics.StageID, + diagCoalesceGroup: PlaneUsageObservers.Diagnostics.CoalesceGroup, + diagOrder: PlaneUsageObservers.Diagnostics.Order, + diagMaterialize: PlaneUsageObservers.Diagnostics.Materialize, + diagPrivileges: PlaneUsageObservers.Diagnostics.Privileges, + } + canonicalPlaneUsageObserversAccess = generatedAccess[[]usage.Observer]{ + policy: canonicalPlaneUsageObserversPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []usage.Observer) error { incoming := cloneSlice(v) current := cloneSlice(gc.usageObservers) - combined, err := PlaneUsageObservers.Combine(source, current, incoming) + combined, err := canonicalPlaneUsageObserversPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1864,23 +2566,34 @@ func init() { } return cloneSlice(gf.usageObservers) }, - policy: &generatedPolicy[[]usage.Observer]{ - planeID: PlaneUsageObservers.ID, - rules: PlaneUsageObservers.Rules, - nilPolicy: PlaneUsageObservers.NilPolicy, - isNil: PlaneUsageObservers.IsNil, - validate: PlaneUsageObservers.Validate, - validateIdentity: PlaneUsageObservers.ValidateIdentity, - combine: PlaneUsageObservers.Combine, - identity: PlaneUsageObservers.Identity, - exclusiveConflictError: PlaneUsageObservers.ExclusiveConflictError, - }, } - PlaneRawCaptureSinks.generated = generatedAccess[[]traffic.RawCaptureSink]{ + PlaneUsageObservers.generated = canonicalPlaneUsageObserversAccess + + canonicalPlaneRawCaptureSinksPolicy = &generatedPolicy[[]traffic.RawCaptureSink]{ + planeID: PlaneRawCaptureSinks.ID, + rules: PlaneRawCaptureSinks.Rules, + nilPolicy: PlaneRawCaptureSinks.NilPolicy, + isNil: PlaneRawCaptureSinks.IsNil, + validate: PlaneRawCaptureSinks.Validate, + validateIdentity: PlaneRawCaptureSinks.ValidateIdentity, + combine: PlaneRawCaptureSinks.Combine, + identity: PlaneRawCaptureSinks.Identity, + exclusiveConflictError: PlaneRawCaptureSinks.ExclusiveConflictError, + requestMaterializer: PlaneRawCaptureSinks.RequestMaterializer, + requestBorrow: PlaneRawCaptureSinks.RequestBorrow, + hookTarget: PlaneRawCaptureSinks.HookTarget, + diagStageID: PlaneRawCaptureSinks.Diagnostics.StageID, + diagCoalesceGroup: PlaneRawCaptureSinks.Diagnostics.CoalesceGroup, + diagOrder: PlaneRawCaptureSinks.Diagnostics.Order, + diagMaterialize: PlaneRawCaptureSinks.Diagnostics.Materialize, + diagPrivileges: PlaneRawCaptureSinks.Diagnostics.Privileges, + } + canonicalPlaneRawCaptureSinksAccess = generatedAccess[[]traffic.RawCaptureSink]{ + policy: canonicalPlaneRawCaptureSinksPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []traffic.RawCaptureSink) error { incoming := cloneSlice(v) current := cloneSlice(gc.rawCaptureSinks) - combined, err := PlaneRawCaptureSinks.Combine(source, current, incoming) + combined, err := canonicalPlaneRawCaptureSinksPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1896,23 +2609,34 @@ func init() { } return cloneSlice(gf.rawCaptureSinks) }, - policy: &generatedPolicy[[]traffic.RawCaptureSink]{ - planeID: PlaneRawCaptureSinks.ID, - rules: PlaneRawCaptureSinks.Rules, - nilPolicy: PlaneRawCaptureSinks.NilPolicy, - isNil: PlaneRawCaptureSinks.IsNil, - validate: PlaneRawCaptureSinks.Validate, - validateIdentity: PlaneRawCaptureSinks.ValidateIdentity, - combine: PlaneRawCaptureSinks.Combine, - identity: PlaneRawCaptureSinks.Identity, - exclusiveConflictError: PlaneRawCaptureSinks.ExclusiveConflictError, - }, } - PlaneTrafficRedactors.generated = generatedAccess[[]traffic.Redactor]{ + PlaneRawCaptureSinks.generated = canonicalPlaneRawCaptureSinksAccess + + canonicalPlaneTrafficRedactorsPolicy = &generatedPolicy[[]traffic.Redactor]{ + planeID: PlaneTrafficRedactors.ID, + rules: PlaneTrafficRedactors.Rules, + nilPolicy: PlaneTrafficRedactors.NilPolicy, + isNil: PlaneTrafficRedactors.IsNil, + validate: PlaneTrafficRedactors.Validate, + validateIdentity: PlaneTrafficRedactors.ValidateIdentity, + combine: PlaneTrafficRedactors.Combine, + identity: PlaneTrafficRedactors.Identity, + exclusiveConflictError: PlaneTrafficRedactors.ExclusiveConflictError, + requestMaterializer: PlaneTrafficRedactors.RequestMaterializer, + requestBorrow: PlaneTrafficRedactors.RequestBorrow, + hookTarget: PlaneTrafficRedactors.HookTarget, + diagStageID: PlaneTrafficRedactors.Diagnostics.StageID, + diagCoalesceGroup: PlaneTrafficRedactors.Diagnostics.CoalesceGroup, + diagOrder: PlaneTrafficRedactors.Diagnostics.Order, + diagMaterialize: PlaneTrafficRedactors.Diagnostics.Materialize, + diagPrivileges: PlaneTrafficRedactors.Diagnostics.Privileges, + } + canonicalPlaneTrafficRedactorsAccess = generatedAccess[[]traffic.Redactor]{ + policy: canonicalPlaneTrafficRedactorsPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []traffic.Redactor) error { incoming := cloneSlice(v) current := cloneSlice(gc.trafficRedactors) - combined, err := PlaneTrafficRedactors.Combine(source, current, incoming) + combined, err := canonicalPlaneTrafficRedactorsPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1928,23 +2652,34 @@ func init() { } return cloneSlice(gf.trafficRedactors) }, - policy: &generatedPolicy[[]traffic.Redactor]{ - planeID: PlaneTrafficRedactors.ID, - rules: PlaneTrafficRedactors.Rules, - nilPolicy: PlaneTrafficRedactors.NilPolicy, - isNil: PlaneTrafficRedactors.IsNil, - validate: PlaneTrafficRedactors.Validate, - validateIdentity: PlaneTrafficRedactors.ValidateIdentity, - combine: PlaneTrafficRedactors.Combine, - identity: PlaneTrafficRedactors.Identity, - exclusiveConflictError: PlaneTrafficRedactors.ExclusiveConflictError, - }, } - PlaneCompactionObservers.generated = generatedAccess[[]compaction.Observer]{ + PlaneTrafficRedactors.generated = canonicalPlaneTrafficRedactorsAccess + + canonicalPlaneCompactionObserversPolicy = &generatedPolicy[[]compaction.Observer]{ + planeID: PlaneCompactionObservers.ID, + rules: PlaneCompactionObservers.Rules, + nilPolicy: PlaneCompactionObservers.NilPolicy, + isNil: PlaneCompactionObservers.IsNil, + validate: PlaneCompactionObservers.Validate, + validateIdentity: PlaneCompactionObservers.ValidateIdentity, + combine: PlaneCompactionObservers.Combine, + identity: PlaneCompactionObservers.Identity, + exclusiveConflictError: PlaneCompactionObservers.ExclusiveConflictError, + requestMaterializer: PlaneCompactionObservers.RequestMaterializer, + requestBorrow: PlaneCompactionObservers.RequestBorrow, + hookTarget: PlaneCompactionObservers.HookTarget, + diagStageID: PlaneCompactionObservers.Diagnostics.StageID, + diagCoalesceGroup: PlaneCompactionObservers.Diagnostics.CoalesceGroup, + diagOrder: PlaneCompactionObservers.Diagnostics.Order, + diagMaterialize: PlaneCompactionObservers.Diagnostics.Materialize, + diagPrivileges: PlaneCompactionObservers.Diagnostics.Privileges, + } + canonicalPlaneCompactionObserversAccess = generatedAccess[[]compaction.Observer]{ + policy: canonicalPlaneCompactionObserversPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []compaction.Observer) error { incoming := cloneSlice(v) current := cloneSlice(gc.compactionObservers) - combined, err := PlaneCompactionObservers.Combine(source, current, incoming) + combined, err := canonicalPlaneCompactionObserversPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1960,23 +2695,34 @@ func init() { } return cloneSlice(gf.compactionObservers) }, - policy: &generatedPolicy[[]compaction.Observer]{ - planeID: PlaneCompactionObservers.ID, - rules: PlaneCompactionObservers.Rules, - nilPolicy: PlaneCompactionObservers.NilPolicy, - isNil: PlaneCompactionObservers.IsNil, - validate: PlaneCompactionObservers.Validate, - validateIdentity: PlaneCompactionObservers.ValidateIdentity, - combine: PlaneCompactionObservers.Combine, - identity: PlaneCompactionObservers.Identity, - exclusiveConflictError: PlaneCompactionObservers.ExclusiveConflictError, - }, } - PlaneCompactionPreservers.generated = generatedAccess[[]compaction.Preserver]{ + PlaneCompactionObservers.generated = canonicalPlaneCompactionObserversAccess + + canonicalPlaneCompactionPreserversPolicy = &generatedPolicy[[]compaction.Preserver]{ + planeID: PlaneCompactionPreservers.ID, + rules: PlaneCompactionPreservers.Rules, + nilPolicy: PlaneCompactionPreservers.NilPolicy, + isNil: PlaneCompactionPreservers.IsNil, + validate: PlaneCompactionPreservers.Validate, + validateIdentity: PlaneCompactionPreservers.ValidateIdentity, + combine: PlaneCompactionPreservers.Combine, + identity: PlaneCompactionPreservers.Identity, + exclusiveConflictError: PlaneCompactionPreservers.ExclusiveConflictError, + requestMaterializer: PlaneCompactionPreservers.RequestMaterializer, + requestBorrow: PlaneCompactionPreservers.RequestBorrow, + hookTarget: PlaneCompactionPreservers.HookTarget, + diagStageID: PlaneCompactionPreservers.Diagnostics.StageID, + diagCoalesceGroup: PlaneCompactionPreservers.Diagnostics.CoalesceGroup, + diagOrder: PlaneCompactionPreservers.Diagnostics.Order, + diagMaterialize: PlaneCompactionPreservers.Diagnostics.Materialize, + diagPrivileges: PlaneCompactionPreservers.Diagnostics.Privileges, + } + canonicalPlaneCompactionPreserversAccess = generatedAccess[[]compaction.Preserver]{ + policy: canonicalPlaneCompactionPreserversPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []compaction.Preserver) error { incoming := cloneSlice(v) current := cloneSlice(gc.compactionPreservers) - combined, err := PlaneCompactionPreservers.Combine(source, current, incoming) + combined, err := canonicalPlaneCompactionPreserversPolicy.combine(source, current, incoming) if err != nil { return err } @@ -1984,7 +2730,7 @@ func init() { combined = make([]compaction.Preserver, 0) } gc.compactionPreservers = cloneSlice(combined) - id, hasID := PlaneCompactionPreservers.Identity(gc.compactionPreservers) + id, hasID := canonicalPlaneCompactionPreserversPolicy.identity(gc.compactionPreservers) gc.compactionPreserversID = id gc.compactionPreserversHasID = hasID return nil @@ -2001,23 +2747,34 @@ func init() { } return gf.compactionPreserversID, gf.compactionPreserversHasID }, - policy: &generatedPolicy[[]compaction.Preserver]{ - planeID: PlaneCompactionPreservers.ID, - rules: PlaneCompactionPreservers.Rules, - nilPolicy: PlaneCompactionPreservers.NilPolicy, - isNil: PlaneCompactionPreservers.IsNil, - validate: PlaneCompactionPreservers.Validate, - validateIdentity: PlaneCompactionPreservers.ValidateIdentity, - combine: PlaneCompactionPreservers.Combine, - identity: PlaneCompactionPreservers.Identity, - exclusiveConflictError: PlaneCompactionPreservers.ExclusiveConflictError, - }, } - PlaneSecretGuards.generated = generatedAccess[[]secretguard.Guard]{ + PlaneCompactionPreservers.generated = canonicalPlaneCompactionPreserversAccess + + canonicalPlaneSecretGuardsPolicy = &generatedPolicy[[]secretguard.Guard]{ + planeID: PlaneSecretGuards.ID, + rules: PlaneSecretGuards.Rules, + nilPolicy: PlaneSecretGuards.NilPolicy, + isNil: PlaneSecretGuards.IsNil, + validate: PlaneSecretGuards.Validate, + validateIdentity: PlaneSecretGuards.ValidateIdentity, + combine: PlaneSecretGuards.Combine, + identity: PlaneSecretGuards.Identity, + exclusiveConflictError: PlaneSecretGuards.ExclusiveConflictError, + requestMaterializer: PlaneSecretGuards.RequestMaterializer, + requestBorrow: PlaneSecretGuards.RequestBorrow, + hookTarget: PlaneSecretGuards.HookTarget, + diagStageID: PlaneSecretGuards.Diagnostics.StageID, + diagCoalesceGroup: PlaneSecretGuards.Diagnostics.CoalesceGroup, + diagOrder: PlaneSecretGuards.Diagnostics.Order, + diagMaterialize: PlaneSecretGuards.Diagnostics.Materialize, + diagPrivileges: PlaneSecretGuards.Diagnostics.Privileges, + } + canonicalPlaneSecretGuardsAccess = generatedAccess[[]secretguard.Guard]{ + policy: canonicalPlaneSecretGuardsPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []secretguard.Guard) error { incoming := cloneSlice(v) current := cloneSlice(gc.secretGuards) - combined, err := PlaneSecretGuards.Combine(source, current, incoming) + combined, err := canonicalPlaneSecretGuardsPolicy.combine(source, current, incoming) if err != nil { return err } @@ -2033,23 +2790,34 @@ func init() { } return cloneSlice(gf.secretGuards) }, - policy: &generatedPolicy[[]secretguard.Guard]{ - planeID: PlaneSecretGuards.ID, - rules: PlaneSecretGuards.Rules, - nilPolicy: PlaneSecretGuards.NilPolicy, - isNil: PlaneSecretGuards.IsNil, - validate: PlaneSecretGuards.Validate, - validateIdentity: PlaneSecretGuards.ValidateIdentity, - combine: PlaneSecretGuards.Combine, - identity: PlaneSecretGuards.Identity, - exclusiveConflictError: PlaneSecretGuards.ExclusiveConflictError, - }, } - PlaneLocalTurnHandlers.generated = generatedAccess[[]localturn.Handler]{ + PlaneSecretGuards.generated = canonicalPlaneSecretGuardsAccess + + canonicalPlaneLocalTurnHandlersPolicy = &generatedPolicy[[]localturn.Handler]{ + planeID: PlaneLocalTurnHandlers.ID, + rules: PlaneLocalTurnHandlers.Rules, + nilPolicy: PlaneLocalTurnHandlers.NilPolicy, + isNil: PlaneLocalTurnHandlers.IsNil, + validate: PlaneLocalTurnHandlers.Validate, + validateIdentity: PlaneLocalTurnHandlers.ValidateIdentity, + combine: PlaneLocalTurnHandlers.Combine, + identity: PlaneLocalTurnHandlers.Identity, + exclusiveConflictError: PlaneLocalTurnHandlers.ExclusiveConflictError, + requestMaterializer: PlaneLocalTurnHandlers.RequestMaterializer, + requestBorrow: PlaneLocalTurnHandlers.RequestBorrow, + hookTarget: PlaneLocalTurnHandlers.HookTarget, + diagStageID: PlaneLocalTurnHandlers.Diagnostics.StageID, + diagCoalesceGroup: PlaneLocalTurnHandlers.Diagnostics.CoalesceGroup, + diagOrder: PlaneLocalTurnHandlers.Diagnostics.Order, + diagMaterialize: PlaneLocalTurnHandlers.Diagnostics.Materialize, + diagPrivileges: PlaneLocalTurnHandlers.Diagnostics.Privileges, + } + canonicalPlaneLocalTurnHandlersAccess = generatedAccess[[]localturn.Handler]{ + policy: canonicalPlaneLocalTurnHandlersPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v []localturn.Handler) error { incoming := cloneSlice(v) current := cloneSlice(gc.localTurnHandlers) - combined, err := PlaneLocalTurnHandlers.Combine(source, current, incoming) + combined, err := canonicalPlaneLocalTurnHandlersPolicy.combine(source, current, incoming) if err != nil { return err } @@ -2065,26 +2833,37 @@ func init() { } return cloneSlice(gf.localTurnHandlers) }, - policy: &generatedPolicy[[]localturn.Handler]{ - planeID: PlaneLocalTurnHandlers.ID, - rules: PlaneLocalTurnHandlers.Rules, - nilPolicy: PlaneLocalTurnHandlers.NilPolicy, - isNil: PlaneLocalTurnHandlers.IsNil, - validate: PlaneLocalTurnHandlers.Validate, - validateIdentity: PlaneLocalTurnHandlers.ValidateIdentity, - combine: PlaneLocalTurnHandlers.Combine, - identity: PlaneLocalTurnHandlers.Identity, - exclusiveConflictError: PlaneLocalTurnHandlers.ExclusiveConflictError, - }, } - PlaneTerminalDecisionProvider.generated = generatedAccess[terminaldecision.Provider]{ + PlaneLocalTurnHandlers.generated = canonicalPlaneLocalTurnHandlersAccess + + canonicalPlaneTerminalDecisionProviderPolicy = &generatedPolicy[terminaldecision.Provider]{ + planeID: PlaneTerminalDecisionProvider.ID, + rules: PlaneTerminalDecisionProvider.Rules, + nilPolicy: PlaneTerminalDecisionProvider.NilPolicy, + isNil: PlaneTerminalDecisionProvider.IsNil, + validate: PlaneTerminalDecisionProvider.Validate, + validateIdentity: PlaneTerminalDecisionProvider.ValidateIdentity, + combine: PlaneTerminalDecisionProvider.Combine, + identity: PlaneTerminalDecisionProvider.Identity, + exclusiveConflictError: PlaneTerminalDecisionProvider.ExclusiveConflictError, + requestMaterializer: PlaneTerminalDecisionProvider.RequestMaterializer, + requestBorrow: PlaneTerminalDecisionProvider.RequestBorrow, + hookTarget: PlaneTerminalDecisionProvider.HookTarget, + diagStageID: PlaneTerminalDecisionProvider.Diagnostics.StageID, + diagCoalesceGroup: PlaneTerminalDecisionProvider.Diagnostics.CoalesceGroup, + diagOrder: PlaneTerminalDecisionProvider.Diagnostics.Order, + diagMaterialize: PlaneTerminalDecisionProvider.Diagnostics.Materialize, + diagPrivileges: PlaneTerminalDecisionProvider.Diagnostics.Privileges, + } + canonicalPlaneTerminalDecisionProviderAccess = generatedAccess[terminaldecision.Provider]{ + policy: canonicalPlaneTerminalDecisionProviderPolicy, contribute: func(gc *generatedContributions, source SourceKind, pluginID string, v terminaldecision.Provider) error { - combined, err := PlaneTerminalDecisionProvider.Combine(source, gc.terminalDecisionProvider, v) + combined, err := canonicalPlaneTerminalDecisionProviderPolicy.combine(source, gc.terminalDecisionProvider, v) if err != nil { return err } gc.terminalDecisionProvider = combined - id, hasID := PlaneTerminalDecisionProvider.Identity(gc.terminalDecisionProvider) + id, hasID := canonicalPlaneTerminalDecisionProviderPolicy.identity(gc.terminalDecisionProvider) gc.terminalDecisionProviderID = id gc.terminalDecisionProviderHasID = hasID return nil @@ -2101,18 +2880,9 @@ func init() { } return gf.terminalDecisionProviderID, gf.terminalDecisionProviderHasID }, - policy: &generatedPolicy[terminaldecision.Provider]{ - planeID: PlaneTerminalDecisionProvider.ID, - rules: PlaneTerminalDecisionProvider.Rules, - nilPolicy: PlaneTerminalDecisionProvider.NilPolicy, - isNil: PlaneTerminalDecisionProvider.IsNil, - validate: PlaneTerminalDecisionProvider.Validate, - validateIdentity: PlaneTerminalDecisionProvider.ValidateIdentity, - combine: PlaneTerminalDecisionProvider.Combine, - identity: PlaneTerminalDecisionProvider.Identity, - exclusiveConflictError: PlaneTerminalDecisionProvider.ExclusiveConflictError, - }, } + PlaneTerminalDecisionProvider.generated = canonicalPlaneTerminalDecisionProviderAccess + } // HookConfig contains the projected hook slices and error policy for core execution. @@ -2127,10 +2897,10 @@ type HookConfig struct { // ProjectHookConfig projects a FrozenPlaneSet into typed HookConfig. func ProjectHookConfig(frozen FrozenPlaneSet, policy hooks.ToolReactorErrorPolicy) HookConfig { return HookConfig{ - SubmitHooks: Get(frozen, PlaneSubmitHooks), - RequestPartHooks: Get(frozen, PlaneRequestPartHooks), - ResponsePartHooks: Get(frozen, PlaneResponsePartHooks), - ToolReactors: Get(frozen, PlaneToolReactors), + SubmitHooks: canonicalPlaneSubmitHooksAccess.get(frozen.frozen), + RequestPartHooks: canonicalPlaneRequestPartHooksAccess.get(frozen.frozen), + ResponsePartHooks: canonicalPlaneResponsePartHooksAccess.get(frozen.frozen), + ToolReactors: canonicalPlaneToolReactorsAccess.get(frozen.frozen), ToolReactorErrorPolicy: policy, } } @@ -2184,32 +2954,32 @@ func (v RequestExecutionView) LocalTurnHandlers() []localturn.Handler { // BindAttemptTransforms replaces AttemptTransforms under SourceGenerationBinder semantics. func (s *ContributionSet) BindAttemptTransforms(contributorID string, v []request.AttemptTransform) error { - return ContributeSource(s, PlaneAttemptTransforms, SourceGenerationBinder, contributorID, v) + return contributePolicy(s, canonicalPlaneAttemptTransformsPolicy, canonicalPlaneAttemptTransformsAccess.contribute, canonicalPlaneAttemptTransformsAccess.identity, SourceGenerationBinder, contributorID, v) } // ReplaceAttemptTransforms replaces AttemptTransforms under SourceGenerationBinder semantics. func (s *ContributionSet) ReplaceAttemptTransforms(contributorID string, v []request.AttemptTransform) error { - return ContributeSource(s, PlaneAttemptTransforms, SourceGenerationBinder, contributorID, v) + return contributePolicy(s, canonicalPlaneAttemptTransformsPolicy, canonicalPlaneAttemptTransformsAccess.contribute, canonicalPlaneAttemptTransformsAccess.identity, SourceGenerationBinder, contributorID, v) } // BindStreamObserverFactories replaces StreamObserverFactories under SourceGenerationBinder semantics. func (s *ContributionSet) BindStreamObserverFactories(contributorID string, v []response.StreamObserverFactory) error { - return ContributeSource(s, PlaneStreamObserverFactories, SourceGenerationBinder, contributorID, v) + return contributePolicy(s, canonicalPlaneStreamObserverFactoriesPolicy, canonicalPlaneStreamObserverFactoriesAccess.contribute, canonicalPlaneStreamObserverFactoriesAccess.identity, SourceGenerationBinder, contributorID, v) } // ReplaceStreamObserverFactories replaces StreamObserverFactories under SourceGenerationBinder semantics. func (s *ContributionSet) ReplaceStreamObserverFactories(contributorID string, v []response.StreamObserverFactory) error { - return ContributeSource(s, PlaneStreamObserverFactories, SourceGenerationBinder, contributorID, v) + return contributePolicy(s, canonicalPlaneStreamObserverFactoriesPolicy, canonicalPlaneStreamObserverFactoriesAccess.contribute, canonicalPlaneStreamObserverFactoriesAccess.identity, SourceGenerationBinder, contributorID, v) } // BindCompactionPreservers replaces CompactionPreservers under SourceGenerationBinder semantics. func (s *ContributionSet) BindCompactionPreservers(contributorID string, v []compaction.Preserver) error { - return ContributeSource(s, PlaneCompactionPreservers, SourceGenerationBinder, contributorID, v) + return contributePolicy(s, canonicalPlaneCompactionPreserversPolicy, canonicalPlaneCompactionPreserversAccess.contribute, canonicalPlaneCompactionPreserversAccess.identity, SourceGenerationBinder, contributorID, v) } // ReplaceCompactionPreservers replaces CompactionPreservers under SourceGenerationBinder semantics. func (s *ContributionSet) ReplaceCompactionPreservers(contributorID string, v []compaction.Preserver) error { - return ContributeSource(s, PlaneCompactionPreservers, SourceGenerationBinder, contributorID, v) + return contributePolicy(s, canonicalPlaneCompactionPreserversPolicy, canonicalPlaneCompactionPreserversAccess.contribute, canonicalPlaneCompactionPreserversAccess.identity, SourceGenerationBinder, contributorID, v) } // ProjectDiagnostics projects diagnostic occupants and privileges from a frozen plane set. @@ -2226,8 +2996,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneSubmitHooks { val := gf.submitHooks - occ := PlaneSubmitHooks.MaterializeOccupants(val) - priv := PlaneSubmitHooks.ProjectPrivileges(val) + occ := canonicalPlaneSubmitHooksPolicy.materializeOccupants(val) + priv := canonicalPlaneSubmitHooksPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2250,10 +3020,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneSubmitHooks.ID, - StageID: PlaneSubmitHooks.Diagnostics.StageID, - CoalesceGroup: PlaneSubmitHooks.Diagnostics.CoalesceGroup, - Order: PlaneSubmitHooks.Diagnostics.Order, + PlaneID: canonicalPlaneSubmitHooksPolicy.planeID, + StageID: canonicalPlaneSubmitHooksPolicy.diagStageID, + CoalesceGroup: canonicalPlaneSubmitHooksPolicy.diagCoalesceGroup, + Order: canonicalPlaneSubmitHooksPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2263,8 +3033,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneRequestPartHooks { val := gf.requestPartHooks - occ := PlaneRequestPartHooks.MaterializeOccupants(val) - priv := PlaneRequestPartHooks.ProjectPrivileges(val) + occ := canonicalPlaneRequestPartHooksPolicy.materializeOccupants(val) + priv := canonicalPlaneRequestPartHooksPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2287,10 +3057,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneRequestPartHooks.ID, - StageID: PlaneRequestPartHooks.Diagnostics.StageID, - CoalesceGroup: PlaneRequestPartHooks.Diagnostics.CoalesceGroup, - Order: PlaneRequestPartHooks.Diagnostics.Order, + PlaneID: canonicalPlaneRequestPartHooksPolicy.planeID, + StageID: canonicalPlaneRequestPartHooksPolicy.diagStageID, + CoalesceGroup: canonicalPlaneRequestPartHooksPolicy.diagCoalesceGroup, + Order: canonicalPlaneRequestPartHooksPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2300,8 +3070,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneResponsePartHooks { val := gf.responsePartHooks - occ := PlaneResponsePartHooks.MaterializeOccupants(val) - priv := PlaneResponsePartHooks.ProjectPrivileges(val) + occ := canonicalPlaneResponsePartHooksPolicy.materializeOccupants(val) + priv := canonicalPlaneResponsePartHooksPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2324,10 +3094,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneResponsePartHooks.ID, - StageID: PlaneResponsePartHooks.Diagnostics.StageID, - CoalesceGroup: PlaneResponsePartHooks.Diagnostics.CoalesceGroup, - Order: PlaneResponsePartHooks.Diagnostics.Order, + PlaneID: canonicalPlaneResponsePartHooksPolicy.planeID, + StageID: canonicalPlaneResponsePartHooksPolicy.diagStageID, + CoalesceGroup: canonicalPlaneResponsePartHooksPolicy.diagCoalesceGroup, + Order: canonicalPlaneResponsePartHooksPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2337,8 +3107,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneToolReactors { val := gf.toolReactors - occ := PlaneToolReactors.MaterializeOccupants(val) - priv := PlaneToolReactors.ProjectPrivileges(val) + occ := canonicalPlaneToolReactorsPolicy.materializeOccupants(val) + priv := canonicalPlaneToolReactorsPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2361,10 +3131,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneToolReactors.ID, - StageID: PlaneToolReactors.Diagnostics.StageID, - CoalesceGroup: PlaneToolReactors.Diagnostics.CoalesceGroup, - Order: PlaneToolReactors.Diagnostics.Order, + PlaneID: canonicalPlaneToolReactorsPolicy.planeID, + StageID: canonicalPlaneToolReactorsPolicy.diagStageID, + CoalesceGroup: canonicalPlaneToolReactorsPolicy.diagCoalesceGroup, + Order: canonicalPlaneToolReactorsPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2374,8 +3144,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneSessionOpeners { val := gf.sessionOpeners - occ := PlaneSessionOpeners.MaterializeOccupants(val) - priv := PlaneSessionOpeners.ProjectPrivileges(val) + occ := canonicalPlaneSessionOpenersPolicy.materializeOccupants(val) + priv := canonicalPlaneSessionOpenersPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2398,10 +3168,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneSessionOpeners.ID, - StageID: PlaneSessionOpeners.Diagnostics.StageID, - CoalesceGroup: PlaneSessionOpeners.Diagnostics.CoalesceGroup, - Order: PlaneSessionOpeners.Diagnostics.Order, + PlaneID: canonicalPlaneSessionOpenersPolicy.planeID, + StageID: canonicalPlaneSessionOpenersPolicy.diagStageID, + CoalesceGroup: canonicalPlaneSessionOpenersPolicy.diagCoalesceGroup, + Order: canonicalPlaneSessionOpenersPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2411,8 +3181,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneWorkspaceResolvers { val := gf.workspaceResolvers - occ := PlaneWorkspaceResolvers.MaterializeOccupants(val) - priv := PlaneWorkspaceResolvers.ProjectPrivileges(val) + occ := canonicalPlaneWorkspaceResolversPolicy.materializeOccupants(val) + priv := canonicalPlaneWorkspaceResolversPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2435,10 +3205,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneWorkspaceResolvers.ID, - StageID: PlaneWorkspaceResolvers.Diagnostics.StageID, - CoalesceGroup: PlaneWorkspaceResolvers.Diagnostics.CoalesceGroup, - Order: PlaneWorkspaceResolvers.Diagnostics.Order, + PlaneID: canonicalPlaneWorkspaceResolversPolicy.planeID, + StageID: canonicalPlaneWorkspaceResolversPolicy.diagStageID, + CoalesceGroup: canonicalPlaneWorkspaceResolversPolicy.diagCoalesceGroup, + Order: canonicalPlaneWorkspaceResolversPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2448,8 +3218,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneToolCatalogFilters { val := gf.toolCatalogFilters - occ := PlaneToolCatalogFilters.MaterializeOccupants(val) - priv := PlaneToolCatalogFilters.ProjectPrivileges(val) + occ := canonicalPlaneToolCatalogFiltersPolicy.materializeOccupants(val) + priv := canonicalPlaneToolCatalogFiltersPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2472,10 +3242,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneToolCatalogFilters.ID, - StageID: PlaneToolCatalogFilters.Diagnostics.StageID, - CoalesceGroup: PlaneToolCatalogFilters.Diagnostics.CoalesceGroup, - Order: PlaneToolCatalogFilters.Diagnostics.Order, + PlaneID: canonicalPlaneToolCatalogFiltersPolicy.planeID, + StageID: canonicalPlaneToolCatalogFiltersPolicy.diagStageID, + CoalesceGroup: canonicalPlaneToolCatalogFiltersPolicy.diagCoalesceGroup, + Order: canonicalPlaneToolCatalogFiltersPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2485,8 +3255,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneToolCallPolicies { val := gf.toolCallPolicies - occ := PlaneToolCallPolicies.MaterializeOccupants(val) - priv := PlaneToolCallPolicies.ProjectPrivileges(val) + occ := canonicalPlaneToolCallPoliciesPolicy.materializeOccupants(val) + priv := canonicalPlaneToolCallPoliciesPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2509,10 +3279,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneToolCallPolicies.ID, - StageID: PlaneToolCallPolicies.Diagnostics.StageID, - CoalesceGroup: PlaneToolCallPolicies.Diagnostics.CoalesceGroup, - Order: PlaneToolCallPolicies.Diagnostics.Order, + PlaneID: canonicalPlaneToolCallPoliciesPolicy.planeID, + StageID: canonicalPlaneToolCallPoliciesPolicy.diagStageID, + CoalesceGroup: canonicalPlaneToolCallPoliciesPolicy.diagCoalesceGroup, + Order: canonicalPlaneToolCallPoliciesPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2522,8 +3292,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneToolCallFinalizers { val := gf.toolCallFinalizers - occ := PlaneToolCallFinalizers.MaterializeOccupants(val) - priv := PlaneToolCallFinalizers.ProjectPrivileges(val) + occ := canonicalPlaneToolCallFinalizersPolicy.materializeOccupants(val) + priv := canonicalPlaneToolCallFinalizersPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2546,10 +3316,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneToolCallFinalizers.ID, - StageID: PlaneToolCallFinalizers.Diagnostics.StageID, - CoalesceGroup: PlaneToolCallFinalizers.Diagnostics.CoalesceGroup, - Order: PlaneToolCallFinalizers.Diagnostics.Order, + PlaneID: canonicalPlaneToolCallFinalizersPolicy.planeID, + StageID: canonicalPlaneToolCallFinalizersPolicy.diagStageID, + CoalesceGroup: canonicalPlaneToolCallFinalizersPolicy.diagCoalesceGroup, + Order: canonicalPlaneToolCallFinalizersPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2559,8 +3329,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneRequestTransforms { val := gf.requestTransforms - occ := PlaneRequestTransforms.MaterializeOccupants(val) - priv := PlaneRequestTransforms.ProjectPrivileges(val) + occ := canonicalPlaneRequestTransformsPolicy.materializeOccupants(val) + priv := canonicalPlaneRequestTransformsPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2583,10 +3353,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneRequestTransforms.ID, - StageID: PlaneRequestTransforms.Diagnostics.StageID, - CoalesceGroup: PlaneRequestTransforms.Diagnostics.CoalesceGroup, - Order: PlaneRequestTransforms.Diagnostics.Order, + PlaneID: canonicalPlaneRequestTransformsPolicy.planeID, + StageID: canonicalPlaneRequestTransformsPolicy.diagStageID, + CoalesceGroup: canonicalPlaneRequestTransformsPolicy.diagCoalesceGroup, + Order: canonicalPlaneRequestTransformsPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2596,8 +3366,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlanePreRequestHandlers { val := gf.preRequestHandlers - occ := PlanePreRequestHandlers.MaterializeOccupants(val) - priv := PlanePreRequestHandlers.ProjectPrivileges(val) + occ := canonicalPlanePreRequestHandlersPolicy.materializeOccupants(val) + priv := canonicalPlanePreRequestHandlersPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2620,10 +3390,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlanePreRequestHandlers.ID, - StageID: PlanePreRequestHandlers.Diagnostics.StageID, - CoalesceGroup: PlanePreRequestHandlers.Diagnostics.CoalesceGroup, - Order: PlanePreRequestHandlers.Diagnostics.Order, + PlaneID: canonicalPlanePreRequestHandlersPolicy.planeID, + StageID: canonicalPlanePreRequestHandlersPolicy.diagStageID, + CoalesceGroup: canonicalPlanePreRequestHandlersPolicy.diagCoalesceGroup, + Order: canonicalPlanePreRequestHandlersPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2633,8 +3403,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneRouteHintProviders { val := gf.routeHintProviders - occ := PlaneRouteHintProviders.MaterializeOccupants(val) - priv := PlaneRouteHintProviders.ProjectPrivileges(val) + occ := canonicalPlaneRouteHintProvidersPolicy.materializeOccupants(val) + priv := canonicalPlaneRouteHintProvidersPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2657,10 +3427,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneRouteHintProviders.ID, - StageID: PlaneRouteHintProviders.Diagnostics.StageID, - CoalesceGroup: PlaneRouteHintProviders.Diagnostics.CoalesceGroup, - Order: PlaneRouteHintProviders.Diagnostics.Order, + PlaneID: canonicalPlaneRouteHintProvidersPolicy.planeID, + StageID: canonicalPlaneRouteHintProvidersPolicy.diagStageID, + CoalesceGroup: canonicalPlaneRouteHintProvidersPolicy.diagCoalesceGroup, + Order: canonicalPlaneRouteHintProvidersPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2670,8 +3440,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneCompletionGates { val := gf.completionGates - occ := PlaneCompletionGates.MaterializeOccupants(val) - priv := PlaneCompletionGates.ProjectPrivileges(val) + occ := canonicalPlaneCompletionGatesPolicy.materializeOccupants(val) + priv := canonicalPlaneCompletionGatesPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2694,10 +3464,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneCompletionGates.ID, - StageID: PlaneCompletionGates.Diagnostics.StageID, - CoalesceGroup: PlaneCompletionGates.Diagnostics.CoalesceGroup, - Order: PlaneCompletionGates.Diagnostics.Order, + PlaneID: canonicalPlaneCompletionGatesPolicy.planeID, + StageID: canonicalPlaneCompletionGatesPolicy.diagStageID, + CoalesceGroup: canonicalPlaneCompletionGatesPolicy.diagCoalesceGroup, + Order: canonicalPlaneCompletionGatesPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2707,8 +3477,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneAttemptTransforms { val := gf.attemptTransforms - occ := PlaneAttemptTransforms.MaterializeOccupants(val) - priv := PlaneAttemptTransforms.ProjectPrivileges(val) + occ := canonicalPlaneAttemptTransformsPolicy.materializeOccupants(val) + priv := canonicalPlaneAttemptTransformsPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2731,10 +3501,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneAttemptTransforms.ID, - StageID: PlaneAttemptTransforms.Diagnostics.StageID, - CoalesceGroup: PlaneAttemptTransforms.Diagnostics.CoalesceGroup, - Order: PlaneAttemptTransforms.Diagnostics.Order, + PlaneID: canonicalPlaneAttemptTransformsPolicy.planeID, + StageID: canonicalPlaneAttemptTransformsPolicy.diagStageID, + CoalesceGroup: canonicalPlaneAttemptTransformsPolicy.diagCoalesceGroup, + Order: canonicalPlaneAttemptTransformsPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2744,8 +3514,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneStreamObserverFactories { val := gf.streamObserverFactories - occ := PlaneStreamObserverFactories.MaterializeOccupants(val) - priv := PlaneStreamObserverFactories.ProjectPrivileges(val) + occ := canonicalPlaneStreamObserverFactoriesPolicy.materializeOccupants(val) + priv := canonicalPlaneStreamObserverFactoriesPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2768,10 +3538,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneStreamObserverFactories.ID, - StageID: PlaneStreamObserverFactories.Diagnostics.StageID, - CoalesceGroup: PlaneStreamObserverFactories.Diagnostics.CoalesceGroup, - Order: PlaneStreamObserverFactories.Diagnostics.Order, + PlaneID: canonicalPlaneStreamObserverFactoriesPolicy.planeID, + StageID: canonicalPlaneStreamObserverFactoriesPolicy.diagStageID, + CoalesceGroup: canonicalPlaneStreamObserverFactoriesPolicy.diagCoalesceGroup, + Order: canonicalPlaneStreamObserverFactoriesPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2781,8 +3551,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneTrafficObservers { val := gf.trafficObservers - occ := PlaneTrafficObservers.MaterializeOccupants(val) - priv := PlaneTrafficObservers.ProjectPrivileges(val) + occ := canonicalPlaneTrafficObserversPolicy.materializeOccupants(val) + priv := canonicalPlaneTrafficObserversPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2805,10 +3575,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneTrafficObservers.ID, - StageID: PlaneTrafficObservers.Diagnostics.StageID, - CoalesceGroup: PlaneTrafficObservers.Diagnostics.CoalesceGroup, - Order: PlaneTrafficObservers.Diagnostics.Order, + PlaneID: canonicalPlaneTrafficObserversPolicy.planeID, + StageID: canonicalPlaneTrafficObserversPolicy.diagStageID, + CoalesceGroup: canonicalPlaneTrafficObserversPolicy.diagCoalesceGroup, + Order: canonicalPlaneTrafficObserversPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2818,8 +3588,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneUsageObservers { val := gf.usageObservers - occ := PlaneUsageObservers.MaterializeOccupants(val) - priv := PlaneUsageObservers.ProjectPrivileges(val) + occ := canonicalPlaneUsageObserversPolicy.materializeOccupants(val) + priv := canonicalPlaneUsageObserversPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2842,10 +3612,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneUsageObservers.ID, - StageID: PlaneUsageObservers.Diagnostics.StageID, - CoalesceGroup: PlaneUsageObservers.Diagnostics.CoalesceGroup, - Order: PlaneUsageObservers.Diagnostics.Order, + PlaneID: canonicalPlaneUsageObserversPolicy.planeID, + StageID: canonicalPlaneUsageObserversPolicy.diagStageID, + CoalesceGroup: canonicalPlaneUsageObserversPolicy.diagCoalesceGroup, + Order: canonicalPlaneUsageObserversPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2855,8 +3625,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneRawCaptureSinks { val := gf.rawCaptureSinks - occ := PlaneRawCaptureSinks.MaterializeOccupants(val) - priv := PlaneRawCaptureSinks.ProjectPrivileges(val) + occ := canonicalPlaneRawCaptureSinksPolicy.materializeOccupants(val) + priv := canonicalPlaneRawCaptureSinksPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2879,10 +3649,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneRawCaptureSinks.ID, - StageID: PlaneRawCaptureSinks.Diagnostics.StageID, - CoalesceGroup: PlaneRawCaptureSinks.Diagnostics.CoalesceGroup, - Order: PlaneRawCaptureSinks.Diagnostics.Order, + PlaneID: canonicalPlaneRawCaptureSinksPolicy.planeID, + StageID: canonicalPlaneRawCaptureSinksPolicy.diagStageID, + CoalesceGroup: canonicalPlaneRawCaptureSinksPolicy.diagCoalesceGroup, + Order: canonicalPlaneRawCaptureSinksPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2892,8 +3662,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneTrafficRedactors { val := gf.trafficRedactors - occ := PlaneTrafficRedactors.MaterializeOccupants(val) - priv := PlaneTrafficRedactors.ProjectPrivileges(val) + occ := canonicalPlaneTrafficRedactorsPolicy.materializeOccupants(val) + priv := canonicalPlaneTrafficRedactorsPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2916,10 +3686,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneTrafficRedactors.ID, - StageID: PlaneTrafficRedactors.Diagnostics.StageID, - CoalesceGroup: PlaneTrafficRedactors.Diagnostics.CoalesceGroup, - Order: PlaneTrafficRedactors.Diagnostics.Order, + PlaneID: canonicalPlaneTrafficRedactorsPolicy.planeID, + StageID: canonicalPlaneTrafficRedactorsPolicy.diagStageID, + CoalesceGroup: canonicalPlaneTrafficRedactorsPolicy.diagCoalesceGroup, + Order: canonicalPlaneTrafficRedactorsPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2929,8 +3699,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneSecretGuards { val := gf.secretGuards - occ := PlaneSecretGuards.MaterializeOccupants(val) - priv := PlaneSecretGuards.ProjectPrivileges(val) + occ := canonicalPlaneSecretGuardsPolicy.materializeOccupants(val) + priv := canonicalPlaneSecretGuardsPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2953,10 +3723,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneSecretGuards.ID, - StageID: PlaneSecretGuards.Diagnostics.StageID, - CoalesceGroup: PlaneSecretGuards.Diagnostics.CoalesceGroup, - Order: PlaneSecretGuards.Diagnostics.Order, + PlaneID: canonicalPlaneSecretGuardsPolicy.planeID, + StageID: canonicalPlaneSecretGuardsPolicy.diagStageID, + CoalesceGroup: canonicalPlaneSecretGuardsPolicy.diagCoalesceGroup, + Order: canonicalPlaneSecretGuardsPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) @@ -2966,8 +3736,8 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { // Project PlaneLocalTurnHandlers { val := gf.localTurnHandlers - occ := PlaneLocalTurnHandlers.MaterializeOccupants(val) - priv := PlaneLocalTurnHandlers.ProjectPrivileges(val) + occ := canonicalPlaneLocalTurnHandlersPolicy.materializeOccupants(val) + priv := canonicalPlaneLocalTurnHandlersPolicy.projectPrivileges(val) if len(occ) > 0 || len(priv.Flags) > 0 { var occCopy []DiagnosticOccupant if len(occ) > 0 { @@ -2990,10 +3760,10 @@ func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection { privCopy = append([]string(nil), priv.Flags...) } projections = append(projections, DiagnosticPlaneProjection{ - PlaneID: PlaneLocalTurnHandlers.ID, - StageID: PlaneLocalTurnHandlers.Diagnostics.StageID, - CoalesceGroup: PlaneLocalTurnHandlers.Diagnostics.CoalesceGroup, - Order: PlaneLocalTurnHandlers.Diagnostics.Order, + PlaneID: canonicalPlaneLocalTurnHandlersPolicy.planeID, + StageID: canonicalPlaneLocalTurnHandlersPolicy.diagStageID, + CoalesceGroup: canonicalPlaneLocalTurnHandlersPolicy.diagCoalesceGroup, + Order: canonicalPlaneLocalTurnHandlersPolicy.diagOrder, Occupants: occCopy, Privileges: PrivilegeProjection{Flags: privCopy}, }) diff --git a/pkg/lipsdk/feature/plane_manifest_test.go b/pkg/lipsdk/feature/plane_manifest_test.go index d7070293..9d518f68 100644 --- a/pkg/lipsdk/feature/plane_manifest_test.go +++ b/pkg/lipsdk/feature/plane_manifest_test.go @@ -152,7 +152,7 @@ func TestStandardCandidatePlanes_GeneratedDispatchCurrency(t *testing.T) { parts[i] = strings.ToUpper(part[:1]) + part[1:] } } - varRef := "Plane" + strings.Join(parts, "") + ".ID" + varRef := "canonicalPlane" + strings.Join(parts, "") + "Policy.planeID" assert.True(t, strings.Contains(methodBody, varRef), "contributeCandidateTo must check candidate plane %s (%q)", varRef, candID) } diff --git a/pkg/lipsdk/feature/plane_replay_identity_test.go b/pkg/lipsdk/feature/plane_replay_identity_test.go index 1bec2c5f..e86df177 100644 --- a/pkg/lipsdk/feature/plane_replay_identity_test.go +++ b/pkg/lipsdk/feature/plane_replay_identity_test.go @@ -443,13 +443,16 @@ func TestOrderedIdentityPlanes_ValidatorInvocationProof(t *testing.T) { //nolint t.Run("PlaneAttemptTransforms", func(t *testing.T) { //nolint:paralleltest // mutates package-level plane ValidateIdentity globals origValidator := feature.PlaneAttemptTransforms.ValidateIdentity validatorCalls := 0 - feature.PlaneAttemptTransforms.ValidateIdentity = func(id string) error { + validateFn := func(id string) error { validatorCalls++ require.Equal(t, wantID, id) return errValidator } + feature.PlaneAttemptTransforms.ValidateIdentity = validateFn + restoreCanonical := feature.SetCanonicalValidateIdentityForTest(feature.PlaneAttemptTransforms, validateFn) t.Cleanup(func() { feature.PlaneAttemptTransforms.ValidateIdentity = origValidator + restoreCanonical() }) calls := 0 @@ -486,13 +489,16 @@ func TestOrderedIdentityPlanes_ValidatorInvocationProof(t *testing.T) { //nolint t.Run("PlaneStreamObserverFactories", func(t *testing.T) { //nolint:paralleltest // mutates package-level plane ValidateIdentity globals origValidator := feature.PlaneStreamObserverFactories.ValidateIdentity validatorCalls := 0 - feature.PlaneStreamObserverFactories.ValidateIdentity = func(id string) error { + validateFn := func(id string) error { validatorCalls++ require.Equal(t, wantID, id) return errValidator } + feature.PlaneStreamObserverFactories.ValidateIdentity = validateFn + restoreCanonical := feature.SetCanonicalValidateIdentityForTest(feature.PlaneStreamObserverFactories, validateFn) t.Cleanup(func() { feature.PlaneStreamObserverFactories.ValidateIdentity = origValidator + restoreCanonical() }) calls := 0 @@ -526,13 +532,16 @@ func TestOrderedIdentityPlanes_ValidatorInvocationProof(t *testing.T) { //nolint t.Run("PlaneCompactionPreservers", func(t *testing.T) { //nolint:paralleltest // mutates package-level plane ValidateIdentity globals origValidator := feature.PlaneCompactionPreservers.ValidateIdentity validatorCalls := 0 - feature.PlaneCompactionPreservers.ValidateIdentity = func(id string) error { + validateFn := func(id string) error { validatorCalls++ require.Equal(t, wantID, id) return errValidator } + feature.PlaneCompactionPreservers.ValidateIdentity = validateFn + restoreCanonical := feature.SetCanonicalValidateIdentityForTest(feature.PlaneCompactionPreservers, validateFn) t.Cleanup(func() { feature.PlaneCompactionPreservers.ValidateIdentity = origValidator + restoreCanonical() }) calls := 0 @@ -706,3 +715,204 @@ func TestOrderedIdentityPlanes_GenerationBinderReplayRejected(t *testing.T) { assert.False(t, errors.Is(err, feature.ErrUnsupportedReplaySource)) }) } + +func TestOrderedIdentityPlanes_CandidateReplay_ZeroLiveIDCalls_Generated(t *testing.T) { + t.Parallel() + + t.Run("PlaneAttemptTransforms_EmptyDestination", func(t *testing.T) { + t.Parallel() + calls := 0 + xform := callCountingAttemptTransform{id: "cand-at-1", calls: &calls} + + candCS := feature.NewContributionSet() + require.NoError(t, feature.Contribute(candCS, feature.PlaneAttemptTransforms, "plugin-cand", []request.AttemptTransform{xform})) + assert.Equal(t, 1, calls, "after candidate contribution") + + candFrozen := candCS.Freeze() + assert.Equal(t, 1, calls, "after candidate freeze") + + dst := feature.NewContributionSet() + require.NoError(t, candFrozen.ContributeCandidateTo(dst, feature.SourceFeature, "candidate")) + assert.Equal(t, 1, calls, "candidate replay into empty destination must not invoke live ID()") + + dstFrozen := dst.Freeze() + assert.Equal(t, 1, calls, "after destination freeze") + + id, ok := feature.FrozenIdentity(dstFrozen, feature.PlaneAttemptTransforms) + assert.True(t, ok) + assert.Equal(t, "cand-at-1", id) + assert.Equal(t, 1, calls, "after destination FrozenIdentity") + }) + + t.Run("PlaneAttemptTransforms_NonEmptyDestination", func(t *testing.T) { + t.Parallel() + dstCalls := 0 + dstXform := callCountingAttemptTransform{id: "dst-at-1", calls: &dstCalls} + dst := feature.NewContributionSet() + require.NoError(t, feature.Contribute(dst, feature.PlaneAttemptTransforms, "plugin-dst", []request.AttemptTransform{dstXform})) + assert.Equal(t, 1, dstCalls) + + candCalls := 0 + candXform := callCountingAttemptTransform{id: "cand-at-2", calls: &candCalls} + candCS := feature.NewContributionSet() + require.NoError(t, feature.Contribute(candCS, feature.PlaneAttemptTransforms, "plugin-cand", []request.AttemptTransform{candXform})) + assert.Equal(t, 1, candCalls) + + candFrozen := candCS.Freeze() + assert.Equal(t, 1, candCalls) + + require.NoError(t, candFrozen.ContributeCandidateTo(dst, feature.SourceFeature, "candidate")) + assert.Equal(t, 1, dstCalls, "destination ID() must not be called during candidate replay") + assert.Equal(t, 1, candCalls, "candidate ID() must not be called during candidate replay") + + dstFrozen := dst.Freeze() + assert.Equal(t, 1, dstCalls) + assert.Equal(t, 1, candCalls) + + retained := feature.Get(dstFrozen, feature.PlaneAttemptTransforms) + require.Len(t, retained, 2) + assert.Equal(t, "dst-at-1", retained[0].ID()) + assert.Equal(t, "cand-at-2", retained[1].ID()) + + id, ok := feature.FrozenIdentity(dstFrozen, feature.PlaneAttemptTransforms) + assert.True(t, ok) + assert.Equal(t, "dst-at-1", id) + }) + + t.Run("PlaneStreamObserverFactories_CandidateReplayIgnored_ZeroLiveIDCalls", func(t *testing.T) { + t.Parallel() + calls := 0 + sof := callCountingStreamObserverFactory{id: "cand-sof-1", calls: &calls} + + candCS := feature.NewContributionSet() + require.NoError(t, feature.Contribute(candCS, feature.PlaneStreamObserverFactories, "plugin-cand", []response.StreamObserverFactory{sof})) + assert.Equal(t, 1, calls) + + candFrozen := candCS.Freeze() + assert.Equal(t, 1, calls) + + dst := feature.NewContributionSet() + require.NoError(t, candFrozen.ContributeCandidateTo(dst, feature.SourceFeature, "candidate")) + assert.Equal(t, 1, calls, "candidate replay must not invoke live ID()") + + dstFrozen := dst.Freeze() + assert.Equal(t, 1, calls) + assert.Empty(t, feature.Get(dstFrozen, feature.PlaneStreamObserverFactories)) + }) + + t.Run("PlaneCompactionPreservers_EmptyDestination", func(t *testing.T) { + t.Parallel() + calls := 0 + cp := callCountingCompactionPreserver{stubPreserver: stubPreserver{id: "cand-cp-1"}, calls: &calls} + + candCS := feature.NewContributionSet() + require.NoError(t, feature.Contribute(candCS, feature.PlaneCompactionPreservers, "plugin-cand", []compaction.Preserver{cp})) + assert.Equal(t, 1, calls) + + candFrozen := candCS.Freeze() + assert.Equal(t, 1, calls) + + dst := feature.NewContributionSet() + require.NoError(t, candFrozen.ContributeCandidateTo(dst, feature.SourceFeature, "candidate")) + assert.Equal(t, 1, calls, "candidate replay into empty destination must not invoke live ID()") + + dstFrozen := dst.Freeze() + assert.Equal(t, 1, calls) + + id, ok := feature.FrozenIdentity(dstFrozen, feature.PlaneCompactionPreservers) + assert.True(t, ok) + assert.Equal(t, "cand-cp-1", id) + assert.Equal(t, 1, calls) + }) + + t.Run("PlaneCompactionPreservers_NonEmptyDestination", func(t *testing.T) { + t.Parallel() + dstCalls := 0 + dstCP := callCountingCompactionPreserver{stubPreserver: stubPreserver{id: "dst-cp-1"}, calls: &dstCalls} + dst := feature.NewContributionSet() + require.NoError(t, feature.Contribute(dst, feature.PlaneCompactionPreservers, "plugin-dst", []compaction.Preserver{dstCP})) + assert.Equal(t, 1, dstCalls) + + candCalls := 0 + candCP := callCountingCompactionPreserver{stubPreserver: stubPreserver{id: "cand-cp-2"}, calls: &candCalls} + candCS := feature.NewContributionSet() + require.NoError(t, feature.Contribute(candCS, feature.PlaneCompactionPreservers, "plugin-cand", []compaction.Preserver{candCP})) + assert.Equal(t, 1, candCalls) + + candFrozen := candCS.Freeze() + assert.Equal(t, 1, candCalls) + + require.NoError(t, candFrozen.ContributeCandidateTo(dst, feature.SourceFeature, "candidate")) + assert.Equal(t, 1, dstCalls, "destination ID() must not be called during candidate replay") + assert.Equal(t, 1, candCalls, "candidate ID() must not be called during candidate replay") + + dstFrozen := dst.Freeze() + assert.Equal(t, 1, dstCalls) + assert.Equal(t, 1, candCalls) + + retained := feature.Get(dstFrozen, feature.PlaneCompactionPreservers) + require.Len(t, retained, 2) + assert.Equal(t, "dst-cp-1", retained[0].ID()) + assert.Equal(t, "cand-cp-2", retained[1].ID()) + + id, ok := feature.FrozenIdentity(dstFrozen, feature.PlaneCompactionPreservers) + assert.True(t, ok) + assert.Equal(t, "dst-cp-1", id) + }) +} + +func TestReplay_SourceAdmission_FailBeforeMutate(t *testing.T) { + t.Parallel() + + t.Run("ReplaySourceTo_UnsupportedSource_RejectsBeforeMutatingDestination", func(t *testing.T) { + t.Parallel() + + src := feature.NewContributionSet() + require.NoError(t, feature.Contribute(src, feature.PlaneSubmitHooks, "plugin-src", []hooks.SubmitHook{ + dummySubmitHook{id: "hook-src", ord: 1}, + })) + frozenSrc := src.Freeze() + + dst := feature.NewContributionSet() + require.NoError(t, feature.Contribute(dst, feature.PlaneSubmitHooks, "plugin-dst", []hooks.SubmitHook{ + dummySubmitHook{id: "hook-dst", ord: 10}, + })) + + err := frozenSrc.ReplaySourceTo(dst, feature.SourceHost, "host-replayer") + require.Error(t, err) + assert.True(t, errors.Is(err, feature.ErrUnsupportedSource), "must satisfy errors.Is(err, ErrUnsupportedSource)") + + var attrErr *feature.AttributedError + require.True(t, errors.As(err, &attrErr), "must be *AttributedError") + assert.Equal(t, "host-replayer", attrErr.PluginID) + assert.Equal(t, feature.PlaneSubmitHooks.ID, attrErr.PlaneID) + + // Destination must remain unchanged (fail-before-mutate) + retained := feature.Get(dst.Freeze(), feature.PlaneSubmitHooks) + require.Len(t, retained, 1) + assert.Equal(t, "hook-dst", retained[0].ID()) + }) + + t.Run("ContributeCandidateTo_UnsupportedSource_RejectsBeforeMutatingDestination", func(t *testing.T) { + t.Parallel() + + src := feature.NewContributionSet() + require.NoError(t, feature.Contribute(src, feature.PlaneToolCallFinalizationMaxArgsBytes, "plugin-cand", 1024)) + frozenCand := src.Freeze() + + dst := feature.NewContributionSet() + require.NoError(t, feature.Contribute(dst, feature.PlaneToolCallFinalizationMaxArgsBytes, "plugin-dst", 512)) + + err := frozenCand.ContributeCandidateTo(dst, feature.SourceHost, "candidate-actor") + require.Error(t, err) + assert.True(t, errors.Is(err, feature.ErrUnsupportedSource)) + + var attrErr *feature.AttributedError + require.True(t, errors.As(err, &attrErr)) + assert.Equal(t, "candidate-actor", attrErr.PluginID) + assert.Equal(t, feature.PlaneToolCallFinalizationMaxArgsBytes.ID, attrErr.PlaneID) + + // Destination must remain unchanged (fail-before-mutate) + assert.Equal(t, 512, feature.Get(dst.Freeze(), feature.PlaneToolCallFinalizationMaxArgsBytes)) + }) +}