package packs

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"sort"
	"strings"

	"github.com/nexuscrm/shared/pkg/models"
	"github.com/pingcap-inc/nexuscrm-controlplane/internal/offlinecandidateauthority"
)

type runtimeStartupShallowLiveRow struct {
	key        string
	customized bool
}

type runtimeStartupShallowPermissionProjection struct {
	APIName     string `json:"apiName"`
	Label       string `json:"label"`
	Category    string `json:"category"`
	Description string `json:"description,omitempty"`
	Requires    string `json:"requires,omitempty"`
	OwnerPack   string `json:"ownerPack"`
	IsSystem    bool   `json:"isSystem"`
	IsActive    bool   `json:"isActive"`
}

type runtimeStartupShallowValidationRuleProjection struct {
	ObjectAPIName     string                                  `json:"objectApiName"`
	Name              string                                  `json:"name"`
	Description       *string                                 `json:"description,omitempty"`
	Active            bool                                    `json:"active"`
	Condition         string                                  `json:"condition"`
	ErrorMessage      string                                  `json:"errorMessage"`
	ErrorDisplayField *string                                 `json:"errorDisplayField,omitempty"`
	RecordSetBindings []models.ValidationRuleRecordSetBinding `json:"recordSetBindings,omitempty"`
	OwnerPack         string                                  `json:"ownerPack"`
}

type runtimeStartupShallowListFieldsProjection struct {
	ObjectAPIName string   `json:"objectApiName"`
	Fields        []string `json:"fields"`
}

var resolveInstalledPackForStartupShallowCompat = ResolveInstalledPack

type runtimeStartupShallowInstalledSourceIdentity struct {
	appliedPayloadHash    sql.NullString
	manifestFormatVersion sql.NullString
	sourceKind            sql.NullString
	sourceURI             sql.NullString
	sourceRevision        sql.NullString
}

type runtimeStartupShallowSourceBackedPackCache struct {
	loaded bool
	pack   *SourceBackedPack
}

func unmarshalRuntimeStartupShallowDeclaredRows(raw string) ([]runtimeStartupShallowDeclaredRow, error) {
	if strings.TrimSpace(raw) == "" {
		return nil, fmt.Errorf("missing persisted startup shallow declaration")
	}
	var rows []runtimeStartupShallowDeclaredRow
	if err := unmarshalJSONRequiredArray(raw, &rows); err != nil {
		return nil, err
	}
	return normalizeRuntimeStartupShallowDeclaredRows(rows), nil
}

// VerifyInstalledPersistedRuntimeShallowByName checks the persisted startup-shallow
// declaration cache against live pack-owned non-object-spec rows without resolving
// the pack source. This is the ordinary startup/readiness read path for
// RuntimeStartupShallowDeclarations.
func VerifyInstalledPersistedRuntimeShallowByName(ctx context.Context, db *sql.DB, ownerPack string, category Category) error {
	return verifyInstalledPersistedRuntimeShallowByName(ctx, db, ownerPack, category, nil)
}

// VerifyInstalledPersistedRuntimeShallowByNameWithComponentKindRegistrationSet
// carries one distribution-owned registration snapshot through the source
// fallbacks used to verify legacy persisted startup-shallow declarations.
func VerifyInstalledPersistedRuntimeShallowByNameWithComponentKindRegistrationSet(ctx context.Context, db *sql.DB, ownerPack string, category Category, registrations ComponentKindRegistrationSet) error {
	return verifyInstalledPersistedRuntimeShallowByName(ctx, db, ownerPack, category, &registrations)
}

func verifyInstalledPersistedRuntimeShallowByName(ctx context.Context, db *sql.DB, ownerPack string, category Category, registrations *ComponentKindRegistrationSet) error {
	if db == nil {
		return fmt.Errorf("database is required")
	}
	ownerPack = strings.TrimSpace(ownerPack)
	if ownerPack == "" {
		return fmt.Errorf("owner pack is required")
	}

	var raw sql.NullString
	if err := db.QueryRowContext(ctx, `
SELECT RuntimeStartupShallowDeclarations
  FROM _System_InstalledPack
 WHERE Name = ?
   AND Status = 'active'
   AND COALESCE(IsDeleted, 0) = 0
 LIMIT 1`, ownerPack).Scan(&raw); err != nil {
		return fmt.Errorf("query persisted startup shallow declaration for pack %s: %w", ownerPack, err)
	}
	if !raw.Valid {
		return fmt.Errorf("installed pack %s is missing persisted startup shallow declaration; run setup apply", ownerPack)
	}
	declared, err := unmarshalRuntimeStartupShallowDeclaredRows(raw.String)
	if err != nil {
		return fmt.Errorf("parse persisted startup shallow declaration for pack %s: %w", ownerPack, err)
	}
	retained := declared[:0]
	for _, row := range declared {
		if row.Kind != ComponentKindApprovalProcess {
			retained = append(retained, row)
		}
	}
	declared = retained

	declaredKinds := make(map[ComponentKind]struct{}, len(declared))
	for _, row := range declared {
		declaredKinds[row.Kind] = struct{}{}
	}
	_, recordTypeDeclaredInPersisted := declaredKinds[ComponentKindRecordType]

	var ownedObjects []string
	if category == AppPack {
		ownedObjects, err = loadPersistedRuntimeOwnedObjectNamesByName(ctx, db, ownerPack)
		if err != nil {
			return err
		}
	}

	liveByKind, err := loadRuntimeStartupShallowLiveRowsByKind(ctx, db, ownerPack, category, declared, declaredKinds, ownedObjects)
	if err != nil {
		return err
	}

	var sourceDecl *runtimeDeclaration
	var sourcePack runtimeStartupShallowSourceBackedPackCache
	declaredByKind := map[ComponentKind]map[string]struct{}{}
	var errs []string
	for _, want := range declared {
		if want.Kind == ComponentKindConnectorPushContract ||
			want.Kind == componentKindConnectorPushRecoverySourceEligibility {
			// These component-level rows are immutable generation projections.
			// Existing per-mapping shallow keys still verify the live mapping
			// table; the component rows have no corresponding live key.
			if _, _, err := normalizeRuntimeStartupShallowDeclaredProjection(want); err != nil {
				errs = append(errs, fmt.Sprintf("%s %s projection invalid: %v", want.Kind, want.BusinessKey, err))
			}
			continue
		}
		if want.Kind == ComponentKindConnectorFieldMapping {
			// BusinessKey owner matching is case-insensitive at pack validation,
			// but the persisted mapping Source must remain byte-exactly bound to
			// the installed pack owner used by Runtime and Catalog admission.
			if _, err := normalizePersistedConnectorFieldMappingProjectionForOwner(want, ownerPack); err != nil {
				errs = append(errs, fmt.Sprintf("%s %s projection invalid: %v", want.Kind, want.BusinessKey, err))
			}
			continue
		}
		if want.Kind == ComponentKindInvocableAction {
			if err := verifyDeclaredInvocableActionStartupShallow(ctx, db, ownerPack, want.BusinessKey); err != nil {
				errs = append(errs, err.Error())
			}
			kindDeclared := declaredByKind[want.Kind]
			if kindDeclared == nil {
				kindDeclared = map[string]struct{}{}
				declaredByKind[want.Kind] = kindDeclared
			}
			kindDeclared[want.BusinessKey] = struct{}{}
			continue
		}
		if want.Kind == ComponentKindStandardFlow {
			if err := verifyDeclaredStandardFlowStartupShallow(ctx, db, ownerPack, want.BusinessKey, liveByKind[want.Kind][want.BusinessKey]); err != nil {
				errs = append(errs, err.Error())
			}
			kindDeclared := declaredByKind[want.Kind]
			if kindDeclared == nil {
				kindDeclared = map[string]struct{}{}
				declaredByKind[want.Kind] = kindDeclared
			}
			kindDeclared[want.BusinessKey] = struct{}{}
			continue
		}
		if want.Kind == ComponentKindValidationRule {
			if err := verifyDeclaredValidationRuleStartupShallow(ctx, db, ownerPack, want.BusinessKey); err != nil {
				errs = append(errs, err.Error())
				kindDeclared := declaredByKind[want.Kind]
				if kindDeclared == nil {
					kindDeclared = map[string]struct{}{}
					declaredByKind[want.Kind] = kindDeclared
				}
				kindDeclared[want.BusinessKey] = struct{}{}
				continue
			}
		}
		if want.Kind == ComponentKindHrefRewriteFields {
			kindDeclared := declaredByKind[want.Kind]
			if kindDeclared == nil {
				kindDeclared = map[string]struct{}{}
				declaredByKind[want.Kind] = kindDeclared
			}
			kindDeclared[want.BusinessKey] = struct{}{}
			if _, _, err := normalizeRuntimeStartupShallowDeclaredProjection(want); err != nil {
				errs = append(errs, fmt.Sprintf("%s %s projection invalid: %v", want.Kind, want.BusinessKey, err))
			}
			continue
		}
		// Auto-number counters are runtime state keyed by live ScopeKey, not a stable
		// startup-shallow authority surface for ordinary readiness verification.
		if want.Kind == ComponentKindAutoNumberCounter {
			continue
		}
		kindDeclared := declaredByKind[want.Kind]
		if kindDeclared == nil {
			kindDeclared = map[string]struct{}{}
			declaredByKind[want.Kind] = kindDeclared
		}
		kindDeclared[want.BusinessKey] = struct{}{}
		rows := liveByKind[want.Kind][want.BusinessKey]
		if want.Kind != ComponentKindValidationRule && len(rows) == 0 {
			if want.Kind != ComponentKindRecordType {
				errs = append(errs, fmt.Sprintf("%s %s is missing", want.Kind, want.BusinessKey))
				continue
			}
		}
		if len(rows) > 1 {
			errs = append(errs, fmt.Sprintf("%s %s has duplicate live business keys: %s", want.Kind, want.BusinessKey, strings.Join(runtimeStartupShallowLiveRowSamples(rows), ", ")))
		}
		declaredProjection, legacyBlankProjection, err := normalizeRuntimeStartupShallowDeclaredProjection(want)
		if err != nil {
			errs = append(errs, fmt.Sprintf("%s %s projection invalid: %v", want.Kind, want.BusinessKey, err))
			continue
		}
		if legacyBlankProjection {
			if err := verifyLegacyStartupShallowProjectionFromSource(ctx, db, ownerPack, category, want, &sourceDecl, registrations); err != nil {
				errs = append(errs, fmt.Sprintf("%s %s projection drift: %v", want.Kind, want.BusinessKey, err))
			}
			continue
		}
		if declaredProjection != "" {
			liveProjection, err := loadRuntimeStartupShallowLiveProjection(ctx, db, ownerPack, category, want, declaredProjection, &sourcePack, registrations)
			if err != nil {
				errs = append(errs, fmt.Sprintf("%s %s projection load failed: %v", want.Kind, want.BusinessKey, err))
				continue
			}
			if liveProjection != declaredProjection {
				errs = append(errs, fmt.Sprintf("%s %s projection drift", want.Kind, want.BusinessKey))
			}
		}
	}
	for kind, byKey := range liveByKind {
		if kind == ComponentKindAutoNumberCounter {
			continue
		}
		declaredKeys := declaredByKind[kind]
		for businessKey, rows := range byKey {
			if _, ok := declaredKeys[businessKey]; ok {
				continue
			}
			if runtimeStartupShallowAllRowsCustomized(rows) {
				if kind != ComponentKindListFields {
					continue
				}
				overrideAllowed, err := runtimeStartupShallowListFieldsLiveOverrideAllowed(ctx, db, ownerPack, category, businessKey, &sourcePack, registrations)
				if err != nil {
					errs = append(errs, fmt.Sprintf("%s %s ownership load failed: %v", kind, businessKey, err))
					continue
				}
				if overrideAllowed {
					continue
				}
			}
			if kind == ComponentKindRecordType && !recordTypeDeclaredInPersisted {
				legacyRow := runtimeStartupShallowDeclaredRow{Kind: kind, BusinessKey: businessKey}
				if err := verifyLegacyStartupShallowProjectionFromSource(ctx, db, ownerPack, category, legacyRow, &sourceDecl, registrations); err == nil {
					continue
				} else {
					errs = append(errs, fmt.Sprintf("%s %s legacy omission drift: %v", kind, businessKey, err))
					continue
				}
			}
			errs = append(errs, fmt.Sprintf("%s %s is undeclared", kind, businessKey))
			if len(rows) > 1 {
				errs = append(errs, fmt.Sprintf("%s %s has duplicate live business keys: %s", kind, businessKey, strings.Join(runtimeStartupShallowLiveRowSamples(rows), ", ")))
			}
		}
	}
	if len(errs) > 0 {
		sort.Strings(errs)
		return fmt.Errorf("installed pack %s startup shallow declaration drift: %s", ownerPack, strings.Join(errs, "; "))
	}
	return nil
}

func marshalRuntimeStartupShallowProjection(v any) (string, error) {
	if v == nil {
		return "", nil
	}
	raw, err := json.Marshal(v)
	if err != nil {
		return "", err
	}
	return string(raw), nil
}

func runtimeStartupShallowSupportsSemanticProjection(kind ComponentKind) bool {
	switch kind {
	case ComponentKindListFields, ComponentKindPermission, ComponentKindValidationRule,
		ComponentKindRecordType, ComponentKindFlowActionCallHandler,
		ComponentKindHrefRewriteFields, ComponentKindConnectorPushContract,
		componentKindConnectorPushRecoverySourceEligibility,
		ComponentKindConnectorFieldMapping, ComponentKindConnectorCalloutProfile:
		return true
	default:
		return false
	}
}

func runtimeStartupShallowAllowsLegacyBlankProjection(kind ComponentKind) bool {
	switch kind {
	case ComponentKindListFields, ComponentKindPermission, ComponentKindValidationRule:
		return true
	default:
		return false
	}
}

func normalizeRuntimeStartupShallowDeclaredProjection(row runtimeStartupShallowDeclaredRow) (string, bool, error) {
	if strings.TrimSpace(row.Projection) == "" {
		if runtimeStartupShallowAllowsLegacyBlankProjection(row.Kind) {
			return "", true, nil
		}
		if runtimeStartupShallowSupportsSemanticProjection(row.Kind) {
			return "", false, fmt.Errorf("projection is required")
		}
	}
	switch row.Kind {
	case ComponentKindListFields:
		var p runtimeStartupShallowListFieldsProjection
		if err := json.Unmarshal([]byte(row.Projection), &p); err != nil {
			return "", false, err
		}
		if strings.TrimSpace(p.ObjectAPIName) != row.BusinessKey {
			return "", false, fmt.Errorf("objectApiName %q does not match business key %q", strings.TrimSpace(p.ObjectAPIName), row.BusinessKey)
		}
		p.Fields = sourceBackedNormalizeStringSlice(p.Fields)
		normalized, err := marshalRuntimeStartupShallowProjection(p)
		return normalized, false, err
	case ComponentKindPermission:
		var p runtimeStartupShallowPermissionProjection
		if err := json.Unmarshal([]byte(row.Projection), &p); err != nil {
			return "", false, err
		}
		if strings.TrimSpace(p.APIName) != row.BusinessKey {
			return "", false, fmt.Errorf("apiName %q does not match business key %q", strings.TrimSpace(p.APIName), row.BusinessKey)
		}
		normalized, err := marshalRuntimeStartupShallowProjection(p)
		return normalized, false, err
	case ComponentKindValidationRule:
		var p runtimeStartupShallowValidationRuleProjection
		if err := json.Unmarshal([]byte(row.Projection), &p); err != nil {
			return "", false, err
		}
		if JoinComponentBusinessKey(strings.TrimSpace(p.ObjectAPIName), strings.TrimSpace(p.Name)) != row.BusinessKey {
			return "", false, fmt.Errorf(
				"objectApiName/name %q/%q does not match business key %q",
				strings.TrimSpace(p.ObjectAPIName),
				strings.TrimSpace(p.Name),
				row.BusinessKey,
			)
		}
		normalized, err := marshalRuntimeStartupShallowProjection(p)
		return normalized, false, err
	case ComponentKindRecordType:
		p, err := runtimeStartupShallowRecordTypeLookupProjection(row, row.Projection)
		if err != nil {
			return "", false, err
		}
		normalized, err := marshalRuntimeStartupShallowProjection(p)
		return normalized, false, err
	case ComponentKindFlowActionCallHandler:
		p, err := runtimeStartupShallowFlowActionCallHandlerLookupProjection(row, row.Projection)
		if err != nil {
			return "", false, err
		}
		normalized, err := marshalRuntimeStartupShallowProjection(p)
		return normalized, false, err
	case ComponentKindHrefRewriteFields:
		p, err := runtimeStartupShallowHrefRewriteFieldLookupProjection(row, row.Projection)
		if err != nil {
			return "", false, err
		}
		normalized, err := marshalRuntimeStartupShallowProjection(p)
		return normalized, false, err
	case ComponentKindConnectorPushContract:
		normalized, err := normalizePersistedConnectorPushContractProjection(row)
		return normalized, false, err
	case componentKindConnectorPushRecoverySourceEligibility:
		normalized, err := normalizePersistedConnectorPushRecoverySourceEligibilityProjection(row)
		return normalized, false, err
	case ComponentKindConnectorFieldMapping:
		normalized, err := normalizePersistedConnectorFieldMappingProjection(row)
		return normalized, false, err
	case ComponentKindConnectorCalloutProfile:
		normalized, err := normalizePersistedConnectorCalloutProfileFinalizationProjection(row)
		return normalized, false, err
	default:
		return strings.TrimSpace(row.Projection), false, nil
	}
}

func verifyLegacyStartupShallowProjectionFromSource(ctx context.Context, db *sql.DB, ownerPack string, category Category, row runtimeStartupShallowDeclaredRow, sourceDecl **runtimeDeclaration, registrations *ComponentKindRegistrationSet) error {
	if !runtimeStartupShallowSupportsSemanticProjection(row.Kind) {
		return fmt.Errorf("legacy projection compatibility unsupported for %s", row.Kind)
	}
	if sourceDecl == nil {
		return fmt.Errorf("missing source declaration cache")
	}
	if *sourceDecl == nil {
		identity, err := loadRuntimeStartupShallowInstalledSourceIdentity(ctx, db, ownerPack)
		if err != nil {
			return err
		}
		appliedPayloadHash := strings.TrimSpace(identity.appliedPayloadHash.String)
		sourceKind := strings.TrimSpace(identity.sourceKind.String)
		sourceURI := strings.TrimSpace(identity.sourceURI.String)
		if sourceKind == "" || sourceURI == "" {
			return fmt.Errorf("source identity missing required source locator fields")
		}
		if (row.Kind == ComponentKindListFields || row.Kind == ComponentKindRecordType) && appliedPayloadHash == "" {
			return fmt.Errorf("source identity missing required hash-gated fields")
		}
		pack, err := resolveInstalledPackForStartupShallowCompat(InstalledPackResolverInput{
			Name:                  ownerPack,
			Category:              category,
			AppliedPayloadHash:    appliedPayloadHash,
			ManifestFormatVersion: identity.manifestFormatVersion.String,
			SourceKind:            sourceKind,
			SourceURI:             sourceURI,
			SourceRevision:        identity.sourceRevision.String,
		}, InstalledPackResolverOptions{
			AllowBundledFallback:         false,
			ObjectSchemaResolver:         sourceBackedVerifySchemaFallback(ctx, VerifyDeps{DB: db}),
			ComponentKindRegistrationSet: registrations,
		})
		if err != nil {
			return fmt.Errorf("resolve source identity: %w", err)
		}
		decl := buildRuntimeDeclaration(pack)
		*sourceDecl = &decl
	}
	var sourceRow *runtimeStartupShallowDeclaredRow
	for i := range (*sourceDecl).startupShallowRows {
		candidate := &(*sourceDecl).startupShallowRows[i]
		if candidate.Kind == row.Kind && candidate.BusinessKey == row.BusinessKey {
			sourceRow = candidate
			break
		}
	}
	if sourceRow == nil {
		return fmt.Errorf("source identity missing declared projection")
	}
	sourceProjection, legacyBlankProjection, err := normalizeRuntimeStartupShallowDeclaredProjection(*sourceRow)
	if err != nil {
		return fmt.Errorf("source identity projection invalid: %w", err)
	}
	if legacyBlankProjection || sourceProjection == "" {
		return fmt.Errorf("source identity missing declared projection")
	}
	var sourcePack runtimeStartupShallowSourceBackedPackCache
	liveProjection, err := loadRuntimeStartupShallowLiveProjection(ctx, db, ownerPack, category, row, sourceProjection, &sourcePack, registrations)
	if err != nil {
		return fmt.Errorf("live projection load failed: %w", err)
	}
	if liveProjection != sourceProjection {
		return fmt.Errorf("source identity mismatch")
	}
	return nil
}

func loadRuntimeStartupShallowInstalledSourceIdentity(ctx context.Context, db *sql.DB, ownerPack string) (runtimeStartupShallowInstalledSourceIdentity, error) {
	var out runtimeStartupShallowInstalledSourceIdentity
	if err := db.QueryRowContext(ctx, `
SELECT AppliedPayloadHash, ManifestFormatVersion, SourceKind, SourceURI, SourceRevision
  FROM _System_InstalledPack
 WHERE Name = ?
   AND Status = 'active'
   AND COALESCE(IsDeleted, 0) = 0
 LIMIT 1`, ownerPack).Scan(
		&out.appliedPayloadHash,
		&out.manifestFormatVersion,
		&out.sourceKind,
		&out.sourceURI,
		&out.sourceRevision,
	); err != nil {
		return runtimeStartupShallowInstalledSourceIdentity{}, fmt.Errorf("query source identity for pack %s: %w", ownerPack, err)
	}
	return out, nil
}

func loadRuntimeStartupShallowLiveProjection(ctx context.Context, db *sql.DB, ownerPack string, category Category, row runtimeStartupShallowDeclaredRow, declaredProjection string, sourcePack *runtimeStartupShallowSourceBackedPackCache, registrations *ComponentKindRegistrationSet) (string, error) {
	switch row.Kind {
	case ComponentKindListFields:
		objectAPIName, err := runtimeStartupShallowListFieldsLookupObject(row, declaredProjection)
		if err != nil {
			return "", err
		}
		var raw sql.NullString
		var customized bool
		if err := db.QueryRowContext(ctx, `
SELECT ListFields, ListFieldsCustomized
  FROM _System_Object
 WHERE ApiName = ?
   AND COALESCE(IsDeleted, 0) = 0
 LIMIT 1`, objectAPIName).Scan(&raw, &customized); err != nil {
			return "", err
		}
		if customized {
			overrideAllowed, err := runtimeStartupShallowListFieldsLiveOverrideAllowed(ctx, db, ownerPack, category, objectAPIName, sourcePack, registrations)
			if err != nil {
				return "", err
			}
			if !overrideAllowed {
				goto compareLiveListFields
			}
			return declaredProjection, nil
		}
	compareLiveListFields:
		var fields []string
		if raw.Valid && strings.TrimSpace(raw.String) != "" {
			if err := json.Unmarshal([]byte(raw.String), &fields); err != nil {
				return "", fmt.Errorf("%s ListFields is not JSON array: %w", row.BusinessKey, err)
			}
		}
		return marshalRuntimeStartupShallowProjection(runtimeStartupShallowListFieldsProjection{
			ObjectAPIName: objectAPIName,
			Fields:        sourceBackedNormalizeStringSlice(fields),
		})
	case ComponentKindPermission:
		apiName, err := runtimeStartupShallowPermissionLookupAPIName(row, declaredProjection)
		if err != nil {
			return "", err
		}
		var p runtimeStartupShallowPermissionProjection
		var isSystem, isActive int
		if err := db.QueryRowContext(ctx, `
SELECT ApiName, Label, Category, COALESCE(Description, ''), COALESCE(RequiresPermission, ''), COALESCE(OwnerPack, ''), IsSystem, IsActive
  FROM _System_Permission
 WHERE ApiName = ?
 LIMIT 1`, apiName).Scan(&p.APIName, &p.Label, &p.Category, &p.Description, &p.Requires, &p.OwnerPack, &isSystem, &isActive); err != nil {
			return "", err
		}
		p.IsSystem = isSystem != 0
		p.IsActive = isActive != 0
		return marshalRuntimeStartupShallowProjection(p)
	case ComponentKindValidationRule:
		objectAPIName, ruleName, err := runtimeStartupShallowValidationRuleLookupKey(row, declaredProjection)
		if err != nil {
			return "", err
		}
		rowPredicate, err := validationRuleStartupShallowDeclaredRowPredicate(ctx, db)
		if err != nil {
			return "", err
		}
		var p runtimeStartupShallowValidationRuleProjection
		var description, errorDisplayField, recordSetBindings, gotOwner sql.NullString
		var isCustomized bool
		if err := db.QueryRowContext(ctx, `
SELECT ObjectApiName, Name, Description, Active, `+"`Condition`"+`, ErrorMessage, ErrorDisplayField, RecordSetBindings, IsCustomized, OwnerPack
  FROM _System_ValidationRule
 WHERE COALESCE(OwnerPack, '') = ?
   AND ObjectApiName = ?
   AND Name = ?
   AND `+rowPredicate+`
 LIMIT 1`, ownerPack, objectAPIName, ruleName).Scan(
			&p.ObjectAPIName,
			&p.Name,
			&description,
			&p.Active,
			&p.Condition,
			&p.ErrorMessage,
			&errorDisplayField,
			&recordSetBindings,
			&isCustomized,
			&gotOwner,
		); err != nil {
			return "", err
		}
		if isCustomized {
			return declaredProjection, nil
		}
		p.Description = sourceBackedNullStringPtr(description)
		p.ErrorDisplayField = sourceBackedNullStringPtr(errorDisplayField)
		if recordSetBindings.Valid && strings.TrimSpace(recordSetBindings.String) != "" {
			if err := json.Unmarshal([]byte(recordSetBindings.String), &p.RecordSetBindings); err != nil {
				return "", fmt.Errorf("parse validation_rule %s recordSetBindings: %w", row.BusinessKey, err)
			}
		}
		p.OwnerPack = gotOwner.String
		return marshalRuntimeStartupShallowProjection(p)
	case ComponentKindRecordType:
		p, err := runtimeStartupShallowRecordTypeLookupProjection(row, declaredProjection)
		if err != nil {
			return "", err
		}
		var got sourceBackedRecordTypeRow
		var gotOwner, code, businessProcessID sql.NullString
		var isDeleted bool
		err = db.QueryRowContext(ctx, `
SELECT o.ApiName, rt.Name, COALESCE(rt.DeveloperName, ''), COALESCE(rt.SobjectType, ''), rt.record_type_code, rt.IsActive, rt.IsMaster, rt.BusinessProcessId, COALESCE(rt.OwnerPack, ''), rt.IsDeleted
  FROM _System_RecordType rt
  JOIN _System_Object o ON o.Id = rt.ObjectId
 WHERE o.ApiName = ?
   AND (rt.DeveloperName = ? OR (COALESCE(rt.DeveloperName, '') = '' AND rt.Name = ?))
 ORDER BY CASE WHEN rt.DeveloperName = ? THEN 0 ELSE 1 END, rt.Id
 LIMIT 1`, p.ObjectAPIName, p.DeveloperName, p.Name, p.DeveloperName).Scan(
			&got.ObjectAPIName,
			&got.Name,
			&got.DeveloperName,
			&got.SobjectType,
			&code,
			&got.IsActive,
			&got.IsMaster,
			&businessProcessID,
			&gotOwner,
			&isDeleted,
		)
		if err == sql.ErrNoRows {
			return "", fmt.Errorf("record type %s/%s is missing", p.ObjectAPIName, p.DeveloperName)
		}
		if err != nil {
			return "", err
		}
		if isDeleted {
			return "", fmt.Errorf("record type %s/%s is deleted", p.ObjectAPIName, p.DeveloperName)
		}
		if p.Code != nil && code.Valid {
			got.Code = trimmedStringPtr(&code.String)
		}
		if businessProcessID.Valid {
			got.BusinessProcessID = trimmedStringPtr(&businessProcessID.String)
		}
		got.DeveloperName = canonicalSourceBackedRecordTypeDeveloperName(got.Name, got.DeveloperName)
		got.SobjectType = canonicalSourceBackedRecordTypeSobjectType(got.ObjectAPIName, got.SobjectType)
		got.OwnerPack = gotOwner.String
		return marshalRuntimeStartupShallowProjection(normalizeRuntimeStartupShallowRecordTypeProjection(got))
	case ComponentKindFlowActionCallHandler:
		p, err := runtimeStartupShallowFlowActionCallHandlerLookupProjection(row, declaredProjection)
		if err != nil {
			return "", err
		}
		live, err := liveSourceBackedFlowActionCallHandlerProjection(ctx, db, p.OwnerPack, p.ActionType)
		if err != nil {
			return "", err
		}
		opts := DefaultPackSourceOptions()
		registrations, err := flowActionCallRegistrationsForProjection(live, opts.FlowActionCallRegistrations, opts.FlowActionCallHandlerImplementations)
		if err != nil {
			return "", err
		}
		if err := validateFlowActionCallHandlerRuntimeRegistration(live, registrations...); err != nil {
			return "", err
		}
		return marshalRuntimeStartupShallowProjection(live)
	case ComponentKindConnectorCalloutProfile:
		declared, err := decodePersistedConnectorCalloutProfileFinalization(row)
		if err != nil {
			return "", err
		}
		packInstallationID, candidate := offlinecandidateauthority.StoppedSourceSetPackInstallID(ctx, ownerPack)
		if !candidate {
			if err := db.QueryRowContext(ctx, `
SELECT PackInstallId
  FROM _System_InstalledPack
 WHERE Name = ?
   AND Status = 'active'
   AND COALESCE(IsDeleted, 0) = 0
	 LIMIT 1`, ownerPack).Scan(&packInstallationID); err != nil {
				return "", err
			}
		}
		live, err := liveConnectorCalloutProfileProjection(
			ctx,
			db,
			ownerPack,
			packInstallationID,
			declared.ProfileName,
		)
		if err != nil {
			return "", err
		}
		profile, ok := live.(connectorCalloutProfileProjectionRow)
		if !ok {
			return "", fmt.Errorf(
				"connector callout profile %s/%s returned projection %T",
				ownerPack,
				declared.ProfileName,
				live,
			)
		}
		return marshalConnectorCalloutProfileFinalizationProjection(
			connectorCalloutProfileFinalizationProjectionFromRow(profile),
		)
	default:
		return "", fmt.Errorf("unsupported startup shallow projection kind %s", row.Kind)
	}
}

func runtimeStartupShallowListFieldsLiveOverrideAllowed(ctx context.Context, db *sql.DB, ownerPack string, category Category, objectAPIName string, cache *runtimeStartupShallowSourceBackedPackCache, registrations *ComponentKindRegistrationSet) (bool, error) {
	if cache == nil {
		return true, nil
	}
	if !cache.loaded {
		sourcePack, err := loadRuntimeStartupShallowSourceBackedPack(ctx, db, ownerPack, category, registrations)
		if err != nil {
			return false, err
		}
		cache.pack = sourcePack
		cache.loaded = true
	}
	if cache.pack == nil {
		return true, nil
	}
	allowed, known := sourceBackedPackListFieldsLiveOverrideAllowed(cache.pack, objectAPIName)
	if !known {
		return true, nil
	}
	return allowed, nil
}

func loadRuntimeStartupShallowSourceBackedPack(ctx context.Context, db *sql.DB, ownerPack string, category Category, registrations *ComponentKindRegistrationSet) (*SourceBackedPack, error) {
	identity, err := loadRuntimeStartupShallowInstalledSourceIdentity(ctx, db, ownerPack)
	if err != nil {
		return nil, err
	}
	appliedPayloadHash := strings.TrimSpace(identity.appliedPayloadHash.String)
	sourceKind := strings.TrimSpace(identity.sourceKind.String)
	sourceURI := strings.TrimSpace(identity.sourceURI.String)
	if sourceKind == "" || sourceURI == "" || appliedPayloadHash == "" {
		return nil, fmt.Errorf("source identity missing required list_fields ownership fields")
	}
	pack, err := resolveInstalledPackForStartupShallowCompat(InstalledPackResolverInput{
		Name:                  ownerPack,
		Category:              category,
		AppliedPayloadHash:    appliedPayloadHash,
		ManifestFormatVersion: identity.manifestFormatVersion.String,
		SourceKind:            sourceKind,
		SourceURI:             sourceURI,
		SourceRevision:        identity.sourceRevision.String,
	}, InstalledPackResolverOptions{
		AllowBundledFallback:         false,
		ObjectSchemaResolver:         sourceBackedVerifySchemaFallback(ctx, VerifyDeps{DB: db}),
		ComponentKindRegistrationSet: registrations,
	})
	if err != nil {
		return nil, fmt.Errorf("resolve source identity: %w", err)
	}
	sourcePack, ok := pack.(*SourceBackedPack)
	if !ok {
		return nil, nil
	}
	return sourcePack, nil
}

func sourceBackedPackListFieldsLiveOverrideAllowed(pack *SourceBackedPack, objectAPIName string) (bool, bool) {
	if pack == nil {
		return true, false
	}
	objectAPIName = strings.TrimSpace(objectAPIName)
	if objectAPIName == "" {
		return true, false
	}
	for _, component := range pack.components {
		objectComponent, ok := component.(*sourceBackedObjectSpecComponent)
		if !ok || objectComponent == nil || objectComponent.Manageability() != ManageabilityLocked {
			continue
		}
		for _, spec := range objectComponent.specs {
			if spec.ListFields != nil && strings.EqualFold(strings.TrimSpace(spec.APIName), objectAPIName) {
				return false, true
			}
		}
	}
	for _, component := range pack.components {
		if component == nil || component.Kind() != ComponentKindListFields {
			continue
		}
		payload, err := component.ExpectedPayload()
		if err != nil {
			continue
		}
		rows, err := sourceBackedListFieldsProjection(payload, fmt.Sprintf("%s %s", component.Kind(), component.BusinessKey()))
		if err != nil {
			continue
		}
		for _, row := range rows {
			if strings.EqualFold(strings.TrimSpace(row.ObjectAPIName), objectAPIName) {
				return ResolveListFieldsValueOwnership(component.Manageability(), true) == ObjectSpecValueLiveOverrideAllowed, true
			}
		}
	}
	for _, component := range pack.components {
		objectComponent, ok := component.(*sourceBackedObjectSpecComponent)
		if !ok || objectComponent == nil {
			continue
		}
		for _, spec := range objectComponent.specs {
			if strings.EqualFold(strings.TrimSpace(spec.APIName), objectAPIName) {
				return ResolveListFieldsValueOwnership(objectComponent.Manageability(), true) == ObjectSpecValueLiveOverrideAllowed, true
			}
		}
	}
	return true, false
}

func runtimeStartupShallowListFieldsLookupObject(row runtimeStartupShallowDeclaredRow, declaredProjection string) (string, error) {
	var p runtimeStartupShallowListFieldsProjection
	if err := json.Unmarshal([]byte(declaredProjection), &p); err != nil {
		return "", err
	}
	objectAPIName := strings.TrimSpace(p.ObjectAPIName)
	if objectAPIName != row.BusinessKey {
		return "", fmt.Errorf("objectApiName %q does not match business key %q", objectAPIName, row.BusinessKey)
	}
	return p.ObjectAPIName, nil
}

func runtimeStartupShallowPermissionLookupAPIName(row runtimeStartupShallowDeclaredRow, declaredProjection string) (string, error) {
	var p runtimeStartupShallowPermissionProjection
	if err := json.Unmarshal([]byte(declaredProjection), &p); err != nil {
		return "", err
	}
	if strings.TrimSpace(p.APIName) != row.BusinessKey {
		return "", fmt.Errorf("apiName %q does not match business key %q", strings.TrimSpace(p.APIName), row.BusinessKey)
	}
	return p.APIName, nil
}

func runtimeStartupShallowValidationRuleLookupKey(row runtimeStartupShallowDeclaredRow, declaredProjection string) (string, string, error) {
	var p runtimeStartupShallowValidationRuleProjection
	if err := json.Unmarshal([]byte(declaredProjection), &p); err != nil {
		return "", "", err
	}
	objectAPIName := strings.TrimSpace(p.ObjectAPIName)
	name := strings.TrimSpace(p.Name)
	if JoinComponentBusinessKey(objectAPIName, name) != row.BusinessKey {
		return "", "", fmt.Errorf("objectApiName/name %q/%q does not match business key %q", objectAPIName, name, row.BusinessKey)
	}
	return p.ObjectAPIName, p.Name, nil
}

func runtimeStartupShallowRecordTypeLookupProjection(row runtimeStartupShallowDeclaredRow, declaredProjection string) (sourceBackedRecordTypeRow, error) {
	var p sourceBackedRecordTypeRow
	if err := json.Unmarshal([]byte(declaredProjection), &p); err != nil {
		return sourceBackedRecordTypeRow{}, err
	}
	p = normalizeRuntimeStartupShallowRecordTypeProjection(p)
	if JoinComponentBusinessKey(p.ObjectAPIName, p.DeveloperName) != row.BusinessKey {
		return sourceBackedRecordTypeRow{}, fmt.Errorf("objectApiName/developerName %q/%q does not match business key %q", p.ObjectAPIName, p.DeveloperName, row.BusinessKey)
	}
	return p, nil
}

func normalizeRuntimeStartupShallowRecordTypeProjection(p sourceBackedRecordTypeRow) sourceBackedRecordTypeRow {
	p.ObjectAPIName = strings.TrimSpace(p.ObjectAPIName)
	p.Name = strings.TrimSpace(p.Name)
	p.DeveloperName = canonicalSourceBackedRecordTypeDeveloperName(p.Name, p.DeveloperName)
	p.SobjectType = canonicalSourceBackedRecordTypeSobjectType(p.ObjectAPIName, p.SobjectType)
	p.OwnerPack = strings.TrimSpace(p.OwnerPack)
	p.Code = trimmedStringPtr(p.Code)
	p.BusinessProcessID = trimmedStringPtr(p.BusinessProcessID)
	return p
}

func loadPersistedRuntimeOwnedObjectNamesByName(ctx context.Context, db *sql.DB, ownerPack string) ([]string, error) {
	var raw sql.NullString
	if err := db.QueryRowContext(ctx, `
SELECT RuntimeObjectSpecDeclarations
  FROM _System_InstalledPack
 WHERE Name = ?
   AND Status = 'active'
   AND COALESCE(IsDeleted, 0) = 0
 LIMIT 1`, ownerPack).Scan(&raw); err != nil {
		return nil, fmt.Errorf("query persisted runtime object declarations for pack %s: %w", ownerPack, err)
	}
	if !raw.Valid {
		return nil, fmt.Errorf("installed pack %s is missing persisted runtime object declaration; run setup apply", ownerPack)
	}
	payloads, err := unmarshalRuntimeObjectSpecPayloads(raw.String)
	if err != nil {
		return nil, fmt.Errorf("parse persisted runtime object declarations for pack %s: %w", ownerPack, err)
	}
	ownedObjects, err := persistedRuntimeDeclaredObjectNamesFromPayloads(payloads, "persisted-runtime-declaration")
	if err != nil {
		return nil, fmt.Errorf("derive persisted runtime owned objects for pack %s: %w", ownerPack, err)
	}
	return ownedObjects, nil
}

func loadRuntimeStartupShallowLiveRowsByKind(ctx context.Context, db *sql.DB, ownerPack string, category Category, declared []runtimeStartupShallowDeclaredRow, declaredKinds map[ComponentKind]struct{}, ownedObjectNames []string) (map[ComponentKind]map[string][]runtimeStartupShallowLiveRow, error) {
	out := map[ComponentKind]map[string][]runtimeStartupShallowLiveRow{}
	hasKind := func(kind ComponentKind) bool {
		if kind == ComponentKindAutoNumberCounter {
			return false
		}
		if _, ok := declaredKinds[kind]; ok {
			return true
		}
		return runtimeStartupShallowKindSupportedForCategory(category, kind)
	}
	add := func(kind ComponentKind, row runtimeStartupShallowLiveRow) {
		row.key = strings.TrimSpace(row.key)
		if row.key == "" {
			return
		}
		byKey := out[kind]
		if byKey == nil {
			byKey = map[string][]runtimeStartupShallowLiveRow{}
			out[kind] = byKey
		}
		byKey[row.key] = append(byKey[row.key], row)
	}
	appendRows := func(kind ComponentKind, query string, scan func(*sql.Rows) (runtimeStartupShallowLiveRow, error), args ...any) error {
		rows, err := db.QueryContext(ctx, query, args...)
		if err != nil {
			return err
		}
		defer rows.Close()
		for rows.Next() {
			row, err := scan(rows)
			if err != nil {
				return err
			}
			add(kind, row)
		}
		return rows.Err()
	}
	declaredBusinessKeys := func(kind ComponentKind) []string {
		keys := make([]string, 0, len(declared))
		seen := map[string]struct{}{}
		for _, row := range declared {
			if row.Kind != kind {
				continue
			}
			key := strings.TrimSpace(row.BusinessKey)
			if key == "" {
				continue
			}
			if _, ok := seen[key]; ok {
				continue
			}
			seen[key] = struct{}{}
			keys = append(keys, key)
		}
		return keys
	}

	if category == AppPack {
		if hasKind(ComponentKindPermission) {
			if err := appendRows(ComponentKindPermission, `
SELECT ApiName
  FROM _System_Permission
 WHERE COALESCE(OwnerPack, '') = ?
   AND COALESCE(IsActive, 1) = 1
 ORDER BY ApiName`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var apiName string
				if err := rows.Scan(&apiName); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: apiName}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query permission startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindListFields) {
			objectAPINameKeys := declaredBusinessKeys(ComponentKindListFields)
			if len(objectAPINameKeys) > 0 {
				placeholders := make([]string, 0, len(objectAPINameKeys))
				args := make([]any, 0, len(objectAPINameKeys))
				for _, objectAPIName := range objectAPINameKeys {
					placeholders = append(placeholders, "?")
					args = append(args, objectAPIName)
				}
				if err := appendRows(ComponentKindListFields, `
SELECT ApiName, ListFields, COALESCE(ListFieldsCustomized, 0)
  FROM _System_Object
 WHERE COALESCE(IsDeleted, 0) = 0
   AND ApiName IN (`+strings.Join(placeholders, ",")+`)
 ORDER BY ApiName`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
					var objectAPIName string
					var raw sql.NullString
					var customized bool
					if err := rows.Scan(&objectAPIName, &raw, &customized); err != nil {
						return runtimeStartupShallowLiveRow{}, err
					}
					if !customized && strings.TrimSpace(objectAPIName) == "" {
						return runtimeStartupShallowLiveRow{}, nil
					}
					return runtimeStartupShallowLiveRow{key: objectAPIName, customized: customized}, nil
				}, args...); err != nil {
					return nil, fmt.Errorf("query list_fields startup shallow rows for pack %s: %w", ownerPack, err)
				}
			}
			undeclaredOwnedObjectNames := make([]string, 0, len(ownedObjectNames))
			declaredListFieldsKeys := map[string]struct{}{}
			for _, objectAPIName := range objectAPINameKeys {
				declaredListFieldsKeys[objectAPIName] = struct{}{}
			}
			for _, objectAPIName := range ownedObjectNames {
				objectAPIName = strings.TrimSpace(objectAPIName)
				if objectAPIName == "" {
					continue
				}
				if _, ok := declaredListFieldsKeys[objectAPIName]; ok {
					continue
				}
				undeclaredOwnedObjectNames = append(undeclaredOwnedObjectNames, objectAPIName)
			}
			if len(undeclaredOwnedObjectNames) > 0 {
				placeholders := make([]string, 0, len(undeclaredOwnedObjectNames))
				args := make([]any, 0, len(undeclaredOwnedObjectNames))
				for _, objectAPIName := range undeclaredOwnedObjectNames {
					placeholders = append(placeholders, "?")
					args = append(args, objectAPIName)
				}
				if err := appendRows(ComponentKindListFields, `
SELECT ApiName, COALESCE(ListFieldsCustomized, 0)
  FROM _System_Object
 WHERE COALESCE(IsDeleted, 0) = 0
   AND ListFields IS NOT NULL
   AND ApiName IN (`+strings.Join(placeholders, ",")+`)
 ORDER BY ApiName`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
					var objectAPIName string
					var customized bool
					if err := rows.Scan(&objectAPIName, &customized); err != nil {
						return runtimeStartupShallowLiveRow{}, err
					}
					return runtimeStartupShallowLiveRow{key: objectAPIName, customized: customized}, nil
				}, args...); err != nil {
					return nil, fmt.Errorf("query orphan list_fields startup shallow rows for pack %s: %w", ownerPack, err)
				}
			}
		}
		if hasKind(ComponentKindValidationRule) {
			validationRuleWhere, err := sourceLessValidationRuleLiveRowsPredicate(ctx, db)
			if err != nil {
				return nil, err
			}
			if err := appendRows(ComponentKindValidationRule, `
SELECT ObjectApiName, Name, COALESCE(IsCustomized, 0)
  FROM _System_ValidationRule
 WHERE COALESCE(OwnerPack, '') = ?
   AND `+validationRuleWhere+`
 ORDER BY ObjectApiName, Name`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var objectAPIName, name string
				var customized bool
				if err := rows.Scan(&objectAPIName, &name, &customized); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{
					key:        JoinComponentBusinessKey(objectAPIName, name),
					customized: customized,
				}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query validation_rule startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindInvocableAction) {
			if err := appendRows(ComponentKindInvocableAction, `
SELECT Name, COALESCE(IsCustomized, 0)
  FROM _System_StandardAction
 WHERE COALESCE(OwnerPack, '') = ?
   AND COALESCE(IsActive, 1) = 1
   AND COALESCE(IsDeleted, 0) = 0
   AND (IsCustomized = 0 OR IsCustomized IS NULL)
 ORDER BY Name`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var name string
				var customized bool
				if err := rows.Scan(&name, &customized); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: name, customized: customized}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query invocable_action startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindFlowActionCallHandler) {
			if err := appendRows(ComponentKindFlowActionCallHandler, `
SELECT ActionType
  FROM _System_FlowActionCallHandler
 WHERE COALESCE(OwnerPack, '') = ?
   AND COALESCE(IsActive, 1) = 1
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY ActionType`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var actionType string
				if err := rows.Scan(&actionType); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: normalizeFlowActionCallHandlerActionType(actionType)}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query flow_action_call_handler startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindReportType) {
			if err := appendRows(ComponentKindReportType, `
SELECT FullName
  FROM _System_ReportType
 WHERE COALESCE(OwnerPack, '') = ?
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY FullName`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var fullName string
				if err := rows.Scan(&fullName); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: fullName}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query report_type startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindUIAction) {
			if err := appendRows(ComponentKindUIAction, `
SELECT ObjectApiName, Name
  FROM _System_Action
 WHERE COALESCE(OwnerPack, '') = ?
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY ObjectApiName, Name`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var objectAPIName, name string
				if err := rows.Scan(&objectAPIName, &name); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{
					key:        JoinComponentBusinessKey(objectAPIName, name),
					customized: false, // _System_Action has no IsCustomized column.
				}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query ui_action startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindStandardFlow) {
			if err := appendRows(ComponentKindStandardFlow, `
SELECT DISTINCT fd.DeveloperName, COALESCE(fd.IsCustomized, 0)
  FROM FlowDefinition fd
  JOIN Flow f ON f.DefinitionId = fd.Id
 WHERE COALESCE(fd.OwnerPack, '') = ?
   AND COALESCE(fd.IsDeleted, 0) = 0
   AND COALESCE(f.IsDeleted, 0) = 0
 ORDER BY fd.DeveloperName`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var developerName string
				var customized bool
				if err := rows.Scan(&developerName, &customized); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: developerName, customized: customized}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query standard_flow startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindFieldMapping) {
			if err := appendRows(ComponentKindFieldMapping, `
SELECT SourceObject, TargetObject, ActionType, SourceField, COALESCE(Direction, ''), COALESCE(IsCustomized, 0)
  FROM _System_ObjectFieldMapping
 WHERE COALESCE(Source, '') = ?
   AND COALESCE(IsActive, 0) = 1
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY SourceObject, TargetObject, ActionType, SourceField, Direction`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var sourceObject, targetObject, actionType, sourceField, direction string
				var customized bool
				if err := rows.Scan(&sourceObject, &targetObject, &actionType, &sourceField, &direction, &customized); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{
					key:        fieldMappingStartupShallowBusinessKey(sourceObject, targetObject, actionType, sourceField, direction),
					customized: customized,
				}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query field_mapping startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindAutoNumberFormat) {
			if err := appendRows(ComponentKindAutoNumberFormat, `
SELECT o.ApiName, f.ApiName
  FROM _System_Field f
  JOIN _System_Object o ON o.Id = f.ObjectId
 WHERE COALESCE(f.OwnerPack, '') = ?
   AND COALESCE(f.IsDeleted, 0) = 0
   AND COALESCE(f.auto_number_format, '') <> ''
 ORDER BY o.ApiName, f.ApiName`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var objectAPIName, fieldAPIName string
				if err := rows.Scan(&objectAPIName, &fieldAPIName); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: JoinComponentBusinessKey(objectAPIName, fieldAPIName)}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query autonumber_format startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindRecordType) {
			if err := appendRows(ComponentKindRecordType, `
SELECT o.ApiName, rt.Name, COALESCE(rt.DeveloperName, '')
  FROM _System_RecordType rt
  JOIN _System_Object o ON o.Id = rt.ObjectId
 WHERE COALESCE(rt.OwnerPack, '') = ?
   AND COALESCE(rt.IsActive, 1) = 1
   AND COALESCE(rt.IsDeleted, 0) = 0
 ORDER BY o.ApiName, rt.DeveloperName, rt.Name`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var objectAPIName, name, developerName string
				if err := rows.Scan(&objectAPIName, &name, &developerName); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{
					key: JoinComponentBusinessKey(
						objectAPIName,
						canonicalSourceBackedRecordTypeDeveloperName(name, developerName),
					),
				}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query record_type startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindAutoNumberCounter) {
			if err := appendRows(ComponentKindAutoNumberCounter, `
SELECT COALESCE(o.ApiName, ''), COALESCE(f.ApiName, ''), COALESCE(c.ScopeKey, '')
  FROM _System_AutoNumberCounter c
  LEFT JOIN _System_Field f ON f.Id = c.FieldId
  LEFT JOIN _System_Object o ON o.Id = f.ObjectId
 WHERE COALESCE(f.OwnerPack, '') = ?
   AND COALESCE(f.IsDeleted, 0) = 0
   AND COALESCE(f.auto_number_format, '') <> ''
 ORDER BY o.ApiName, f.ApiName, c.ScopeKey`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var objectAPIName, fieldAPIName, scopeKey string
				if err := rows.Scan(&objectAPIName, &fieldAPIName, &scopeKey); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: JoinComponentBusinessKey(objectAPIName, fieldAPIName, scopeKey)}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query autonumber_counter startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}
	}

	if category == ConnectorPack {
		if hasKind(ComponentKindConnectorCapability) {
			if err := appendRows(ComponentKindConnectorCapability, `
SELECT Namespace, Kind
  FROM _System_ConnectorCapabilityDeclaration
 WHERE InstalledPackName = ?
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY Namespace, Kind`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var namespace, kind string
				if err := rows.Scan(&namespace, &kind); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: strings.TrimSpace(namespace) + ":" + strings.TrimSpace(kind)}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query connector_capability startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindWebhookSecret) {
			if err := appendRows(ComponentKindWebhookSecret, `
SELECT Name
  FROM _System_WebhookSecret
 WHERE OwnerPack = ?
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY Name`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var name string
				if err := rows.Scan(&name); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: name}, nil
			}, strings.ToLower(ownerPack)); err != nil {
				return nil, fmt.Errorf("query webhook_secret startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindConnectorRateLimit) {
			if err := appendRows(ComponentKindConnectorRateLimit, `
SELECT EndpointClass
  FROM _System_ConnectorRateLimit
 WHERE OwnerPack = ?
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY EndpointClass`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var endpointClass string
				if err := rows.Scan(&endpointClass); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: endpointClass}, nil
			}, strings.ToLower(ownerPack)); err != nil {
				return nil, fmt.Errorf("query connector_rate_limit startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindConnectorCalloutProfile) {
			if err := appendRows(ComponentKindConnectorCalloutProfile, `
SELECT ProfileName
  FROM _System_ConnectorCalloutProfile
 WHERE OwnerPack = ?
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY ProfileName`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var profileName string
				if err := rows.Scan(&profileName); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: profileName}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query connector_callout_profile startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindConnectorInboundHandlerConfig) {
			if err := appendRows(ComponentKindConnectorInboundHandlerConfig, `
SELECT CapabilityKind
  FROM _System_ConnectorInboundHandlerConfig
 WHERE Namespace = ?
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY CapabilityKind`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var capabilityKind string
				if err := rows.Scan(&capabilityKind); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: strings.TrimSpace(capabilityKind)}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query connector_inbound_handler_config startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindConnectorInboundRoute) {
			if err := appendRows(ComponentKindConnectorInboundRoute, `
SELECT r.EventKind
  FROM _System_ConnectorInboundRoute r
  JOIN _System_InstalledPack p ON p.PackInstallId = r.InstalledPackId
 WHERE r.Namespace = ?
   AND COALESCE(r.IsDeleted, 0) = 0
   AND COALESCE(r.IsCurrent, 1) = 1
   AND p.Name = ?
   AND p.Status = 'active'
   AND COALESCE(p.IsDeleted, 0) = 0
   AND COALESCE(p.PackInstallId, '') <> ''
 ORDER BY r.EventKind`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var eventKind string
				if err := rows.Scan(&eventKind); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{key: strings.TrimSpace(eventKind)}, nil
			}, ownerPack, ownerPack); err != nil {
				return nil, fmt.Errorf("query connector_inbound_route startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}

		if hasKind(ComponentKindFieldMapping) {
			if err := appendRows(ComponentKindFieldMapping, `
SELECT SourceObject, TargetObject, ActionType, SourceField, COALESCE(Direction, ''), COALESCE(IsCustomized, 0)
  FROM _System_ObjectFieldMapping
 WHERE COALESCE(Source, '') = ?
   AND COALESCE(IsActive, 0) = 1
   AND COALESCE(IsDeleted, 0) = 0
 ORDER BY SourceObject, TargetObject, ActionType, SourceField, Direction`, func(rows *sql.Rows) (runtimeStartupShallowLiveRow, error) {
				var sourceObject, targetObject, actionType, sourceField, direction string
				var customized bool
				if err := rows.Scan(&sourceObject, &targetObject, &actionType, &sourceField, &direction, &customized); err != nil {
					return runtimeStartupShallowLiveRow{}, err
				}
				return runtimeStartupShallowLiveRow{
					key:        fieldMappingStartupShallowBusinessKey(sourceObject, targetObject, actionType, sourceField, direction),
					customized: customized,
				}, nil
			}, ownerPack); err != nil {
				return nil, fmt.Errorf("query field_mapping startup shallow rows for pack %s: %w", ownerPack, err)
			}
		}
	}

	return out, nil
}

func fieldMappingStartupShallowBusinessKey(sourceObject, targetObject, actionType, sourceField, direction string) string {
	direction = strings.TrimSpace(direction)
	if direction == "" || strings.EqualFold(direction, "legacy") {
		return JoinComponentBusinessKey(sourceObject, targetObject, actionType, sourceField)
	}
	return JoinComponentBusinessKey(sourceObject, targetObject, actionType, sourceField, direction)
}

func runtimeStartupShallowAllRowsCustomized(rows []runtimeStartupShallowLiveRow) bool {
	if len(rows) == 0 {
		return false
	}
	for _, row := range rows {
		if !row.customized {
			return false
		}
	}
	return true
}

func runtimeStartupShallowLiveRowSamples(rows []runtimeStartupShallowLiveRow) []string {
	samples := make([]string, 0, len(rows))
	for _, row := range rows {
		samples = append(samples, row.key)
	}
	return samples
}

func verifyDeclaredInvocableActionStartupShallow(ctx context.Context, db *sql.DB, ownerPack, businessKey string) error {
	businessKey = strings.TrimSpace(businessKey)
	if businessKey == "" {
		return fmt.Errorf("%s %s is missing", ComponentKindInvocableAction, businessKey)
	}
	var isDeleted bool
	err := db.QueryRowContext(ctx, `
SELECT COALESCE(IsDeleted, 0)
  FROM _System_StandardAction
 WHERE COALESCE(OwnerPack, '') = ?
   AND Name = ?
 LIMIT 1`, ownerPack, businessKey).Scan(&isDeleted)
	if err == sql.ErrNoRows {
		return fmt.Errorf("%s %s is missing", ComponentKindInvocableAction, businessKey)
	}
	if err != nil {
		return fmt.Errorf("query invocable_action startup shallow row for %s: %w", businessKey, err)
	}
	if isDeleted {
		return fmt.Errorf("%s %s is missing", ComponentKindInvocableAction, businessKey)
	}
	return nil
}

func verifyDeclaredValidationRuleStartupShallow(ctx context.Context, db *sql.DB, ownerPack, businessKey string) error {
	objectAPIName, name, ok := splitStartupShallowBusinessKey(businessKey)
	if !ok {
		return fmt.Errorf("%s %s is invalid", ComponentKindValidationRule, businessKey)
	}
	rowPredicate, err := validationRuleStartupShallowDeclaredRowPredicate(ctx, db)
	if err != nil {
		return err
	}
	var found int
	err = db.QueryRowContext(ctx, `
SELECT 1
  FROM _System_ValidationRule
 WHERE COALESCE(OwnerPack, '') = ?
   AND ObjectApiName = ?
   AND Name = ?
   AND `+rowPredicate+`
 LIMIT 1`, ownerPack, objectAPIName, name).Scan(&found)
	if err == sql.ErrNoRows {
		return fmt.Errorf("%s %s is missing", ComponentKindValidationRule, businessKey)
	}
	if err != nil {
		return fmt.Errorf("query validation_rule startup shallow row for %s: %w", businessKey, err)
	}
	return nil
}

func verifyDeclaredStandardFlowStartupShallow(ctx context.Context, db *sql.DB, ownerPack, businessKey string, liveRows []runtimeStartupShallowLiveRow) error {
	businessKey = strings.TrimSpace(businessKey)
	if businessKey == "" {
		return fmt.Errorf("%s %s is missing", ComponentKindStandardFlow, businessKey)
	}
	if len(liveRows) > 0 {
		if len(liveRows) > 1 {
			return fmt.Errorf("%s %s has duplicate live business keys: %s", ComponentKindStandardFlow, businessKey, strings.Join(runtimeStartupShallowLiveRowSamples(liveRows), ", "))
		}
		return nil
	}
	var customized bool
	err := db.QueryRowContext(ctx, `
SELECT COALESCE(IsCustomized, 0)
  FROM FlowDefinition
 WHERE COALESCE(OwnerPack, '') = ?
   AND DeveloperName = ?
   AND COALESCE(IsDeleted, 0) = 0
 LIMIT 1`, ownerPack, businessKey).Scan(&customized)
	if err == sql.ErrNoRows {
		return fmt.Errorf("%s %s is missing", ComponentKindStandardFlow, businessKey)
	}
	if err != nil {
		return fmt.Errorf("query standard_flow startup shallow row for %s: %w", businessKey, err)
	}
	if customized {
		return nil
	}
	return fmt.Errorf("%s %s is missing", ComponentKindStandardFlow, businessKey)
}

func runtimeStartupShallowKindSupportedForCategory(category Category, kind ComponentKind) bool {
	switch category {
	case AppPack:
		switch kind {
		case ComponentKindPermission,
			ComponentKindListFields,
			ComponentKindValidationRule,
			ComponentKindInvocableAction,
			ComponentKindReportType,
			ComponentKindUIAction,
			ComponentKindStandardFlow,
			ComponentKindFieldMapping,
			ComponentKindAutoNumberFormat,
			ComponentKindRecordType,
			ComponentKindFlowActionCallHandler:
			return true
		}
	case ConnectorPack:
		switch kind {
		case ComponentKindConnectorCapability,
			ComponentKindWebhookSecret,
			ComponentKindConnectorRateLimit,
			ComponentKindConnectorCalloutProfile,
			ComponentKindConnectorInboundHandlerConfig,
			ComponentKindConnectorInboundRoute:
			return true
		}
	}
	return false
}

func splitStartupShallowBusinessKey(businessKey string) (string, string, bool) {
	parts := strings.SplitN(strings.TrimSpace(businessKey), "/", 2)
	if len(parts) != 2 {
		return "", "", false
	}
	objectAPIName := strings.TrimSpace(parts[0])
	name := strings.TrimSpace(parts[1])
	if objectAPIName == "" || name == "" {
		return "", "", false
	}
	return objectAPIName, name, true
}

func sourceLessValidationRuleLiveRowsPredicate(ctx context.Context, db *sql.DB) (string, error) {
	hasActiveColumn, err := sourceLessTableHasColumn(ctx, db, "_System_ValidationRule", "Active")
	if err != nil {
		return "", err
	}
	if hasActiveColumn {
		// Startup-shallow must observe the same retained customized rows the
		// per-key declaration check accepts, otherwise the live scan and
		// declared-key verifier stop being source-free comparable.
		return "(COALESCE(Active, 0) = 1 OR COALESCE(IsCustomized, 0) = 1)", nil
	}
	hasColumn, err := sourceLessTableHasColumn(ctx, db, "_System_ValidationRule", "IsDeleted")
	if err != nil {
		return "", err
	}
	if hasColumn {
		return "(COALESCE(IsDeleted, 0) = 0 OR COALESCE(IsCustomized, 0) = 1)", nil
	}
	return "1 = 1", nil
}

func validationRuleStartupShallowDeclaredRowPredicate(ctx context.Context, db *sql.DB) (string, error) {
	hasActiveColumn, err := sourceLessTableHasColumn(ctx, db, "_System_ValidationRule", "Active")
	if err != nil {
		return "", err
	}
	if hasActiveColumn {
		// Active-backed installs must still verify declared inactive rows.
		return "1 = 1", nil
	}
	hasIsDeletedColumn, err := sourceLessTableHasColumn(ctx, db, "_System_ValidationRule", "IsDeleted")
	if err != nil {
		return "", err
	}
	if hasIsDeletedColumn {
		// Legacy compatibility must keep retained customized rows addressable
		// while still failing closed for truly deleted non-customized rows.
		return "(COALESCE(IsDeleted, 0) = 0 OR COALESCE(IsCustomized, 0) = 1)", nil
	}
	return "1 = 1", nil
}

func sourceLessTableHasColumn(ctx context.Context, db *sql.DB, tableName, columnName string) (bool, error) {
	var count int
	if err := db.QueryRowContext(ctx, `
		SELECT COUNT(*)
		  FROM information_schema.columns
		 WHERE table_schema = DATABASE()
		   AND table_name = ?
		   AND column_name = ?`,
		tableName, columnName,
	).Scan(&count); err != nil {
		return false, fmt.Errorf("check column %s.%s: %w", tableName, columnName, err)
	}
	return count > 0, nil
}
