package run

import (
	"strings"
	"time"

	"github.com/tidbcloud/AgentTeam/internal/core/identifiers"
	"github.com/tidbcloud/AgentTeam/internal/workflow/eventcontract"
	runkernel "github.com/tidbcloud/AgentTeam/internal/workflow/run"
)

// Required ID prefixes for the reviewed event/effect envelope fields (bare
// producer prefixes; the validators append `_`). A persisted value must carry
// the matching prefix to be a valid identifier; any other value (prose, a
// secret, a different prefix) fails closed. The suffix grammar is per-generator-
// family: wfx/btn are StableChildID/notification hex (32 lowercase hex), usr/agt
// are NewEntityID base36 (exactly 14), and member ids are the raw NewMemberID
// form (12 base36, NO mem_ prefix).
const (
	validEffectIDPrefix       = "wfx"
	validAgentIDPrefix        = "agt"
	validUserIDPrefix         = "usr"
	validNotificationIDPrefix = "btn"
)

// authoritativePlanPortPattern is the exact grammar for a compiled/authored
// Plan output port. It is the single authoritative port grammar used wherever a
// port projects (event schemas, EffectResult projection, dispatch events).
const authoritativePlanPortPattern = `^[a-z][a-z0-9_-]{0,63}$`

// envelopeFieldPlanPort validates one authored/compiled Plan output port against
// the authoritative Plan port grammar ^[a-z][a-z0-9_-]{0,63}$. The value is
// validated byte-for-byte through the shared exact Plan port validator: a
// spaced/malformed/secret-bearing/oversized/punctuation-prefixed value fails
// closed and is never trimmed or sanitized into a different valid identity.
func envelopeFieldPlanPort(raw any) (any, bool) {
	text := readFailureString(raw)
	if _, ok := runkernel.PublicPlanPort(text); !ok {
		return nil, false
	}
	return text, true
}

// validPlanPort reports whether value is an exact authoritative Plan port:
// a lowercase letter, then up to 63 lowercase letters/digits/underscore/dash.
func validPlanPort(value string) bool {
	_, ok := runkernel.PublicPlanPort(value)
	return ok
}

// readIdentityString reads a string field WITHOUT any TrimSpace / ToValidUTF8
// normalization. Identity-bearing and closed-vocabulary fields are validated
// byte-for-byte: a whitespace-padded, invalid-UTF-8 (post JSON-decoding U+FFFD),
// case/punctuation/token-bearing, or wrong-family value fails the exact grammar
// below and is NEVER normalized into a different accepted identity. Bounded
// normalization is preserved ONLY for documented public prose
// (envelopeFieldCancelReason) and timestamps (envelopeFieldRFC3339).
func readIdentityString(raw any) string {
	if raw == nil {
		return ""
	}
	return readFailureString(raw)
}

// envelopeFieldKernelActivationID validates a kernel logical activation ID.
// The reducer allocates kernel logical activation IDs as `a` + 20 zero-padded
// digits (fmt.Sprintf("a%020d", seq)). The dispatcher and reducer events carry
// this kernel logical id, NOT the persisted `wra_` child id. A malformed,
// secret-bearing, or non-`a`-leading value fails closed. The length is exact
// (1 + 20 digits), never a loose upper bound.
func envelopeFieldKernelActivationID(maxRunes int) func(any) (any, bool) {
	return func(raw any) (any, bool) {
		text := readIdentityString(raw)
		if text == "" || text[0] != 'a' {
			return nil, false
		}
		if len(text) != 21 || len(text) > maxRunes {
			// Exactly `a` + 20 digits. A shorter/longer value is never a kernel
			// logical activation id.
			return nil, false
		}
		for index := 1; index < len(text); index++ {
			character := text[index]
			if character >= '0' && character <= '9' {
				continue
			}
			return nil, false
		}
		return text, true
	}
}

// envelopeFieldMessageID validates a real app-facing message identifier. The
// current producer (core/identifiers.NewMessageID) returns a raw 32-hex string
// with NO prefix. Legacy durable rows may carry a `msg_`-prefixed bounded
// identifier (a prior accepted form). Accept exactly those two producer
// contracts: raw 32 lowercase hex, OR `msg_` + lowercase word chars. A prose,
// secret-bearing, or malformed value fails closed.
func envelopeFieldMessageID(maxRunes int) func(any) (any, bool) {
	return func(raw any) (any, bool) {
		text := readIdentityString(raw)
		if text == "" || len(text) > maxRunes {
			return nil, false
		}
		if identifiers.ValidMessageID(text) {
			return text, true
		}
		prefixed := strings.HasPrefix(text, "msg_")
		if prefixed && len(text) > len("msg_") {
			for index := len("msg_"); index < len(text); index++ {
				character := text[index]
				if (character >= 'a' && character <= 'z') || (character >= '0' && character <= '9') || character == '_' {
					continue
				}
				prefixed = false
				break
			}
		} else {
			prefixed = false
		}
		if prefixed {
			return text, true
		}
		return nil, false
	}
}

// envelopeFieldRevision validates a non-negative int64 receipt revision (for
// example the approval notificationRevision producer field).
func envelopeFieldRevision(raw any) (any, bool) {
	value, ok := readFailureInteger(raw)
	if !ok || value < 0 {
		return nil, false
	}
	return value, true
}

// envelopeFieldCompletedAt validates the completion timestamp receipt field.
// The producer writes an RFC3339 UTC timestamp (a *time.Time marshaled to
// RFC3339Nano). A malformed or secret-bearing value fails closed.
func envelopeFieldCompletedAt(raw any) (any, bool) {
	return envelopeFieldRFC3339(raw)
}

// envelopeFieldCancelReason validates the run_canceled reason field: a bounded
// UTF-8-safe string preserved through the authoritative 2048-byte limit. The
// producer trims the reason and caps it at maxCancelReasonBytes (2048). Arbitrary
// authored prose is preserved exactly (trimmed); a secret is preserved as prose
// only because the reason is user-authored output, not an identity.
func envelopeFieldCancelReason(raw any) (any, bool) {
	text := strings.TrimSpace(strings.ToValidUTF8(readFailureString(raw), "�"))
	if text == "" || len([]byte(text)) > maxCancelReasonReadBytes {
		return nil, false
	}
	return text, true
}

// maxCancelReasonReadBytes mirrors the producer's authoritative 2048-byte bound
// for a Run cancellation reason.
const maxCancelReasonReadBytes = 2048

// envelopeFieldActor validates the run_canceled actor provenance object against
// its exact producer contract: {type, id, memberId} where type is the closed
// actor vocabulary (human/agent), id is the exact NewEntityID id (usr_/agt_ + 14
// base36), and memberId is the exact raw NewMemberID (12 base36, NO mem_ prefix).
// The object must contain exactly these three keys with the right JSON types and
// exact input bytes: a token-bearing `usr_token=SECRET`, a prefixed
// `mem_token=SECRET`, punctuation, whitespace, invalid UTF-8, an oversized
// value, or any extra/unknown key fails closed (dropped).
func envelopeFieldActor(raw any) (any, bool) {
	object, ok := raw.(map[string]any)
	if !ok {
		return nil, false
	}
	// Closed key set: exactly type, id, memberId. Any other key fails closed.
	for key := range object {
		if key != "type" && key != "id" && key != "memberId" {
			return nil, false
		}
	}
	actorType := readIdentityString(object["type"])
	if actorType != "human" && actorType != "agent" {
		return nil, false
	}
	// Exact producer id forms; the trimmed/UTF8-replaced text must equal the raw
	// input bytes so a token/punctuation/whitespace/invalid-UTF8 lookalike is
	// rejected rather than silently normalized into a different identity.
	id := readFailureString(object["id"])
	switch actorType {
	case "human":
		if !identifiers.ValidNewEntityIDForm(id, "usr") {
			return nil, false
		}
	case "agent":
		if !identifiers.ValidNewEntityIDForm(id, "agt") {
			return nil, false
		}
	}
	memberID := readFailureString(object["memberId"])
	if !identifiers.ValidMemberIDRaw(memberID) {
		return nil, false
	}
	return map[string]any{"type": actorType, "id": id, "memberId": memberID}, true
}

// Closed enums for the reviewed envelope fields.
var (
	// eventEnvelopeKindValues is the closed vocabulary for the envelope `kind`
	// field. Dispatcher events carry the intent kind (send_message/wait/
	// request_approval); reducer/engine events carry the event kind name
	// (run_failed, fan_out_item_failed, ...).
	eventEnvelopeKindValues = stringSet(
		// Intent kinds.
		"send_message", "wait", "request_approval",
		// Event kinds.
		"run_accepted", "run_started", "run_succeeded", "run_canceled", "run_cancel_replayed", "run_failed",
		"activation_started", "activation_created", "activation_completed", "activation_failed",
		"branch_arrived", "branch_failed", "fan_out_opened", "fan_out_item_arrived",
		"fan_out_item_started", "fan_out_item_responder_activated", "fan_out_item_blocked",
		"fan_out_item_failed", "fan_out_resolved", "loop_opened", "loop_continued",
		"loop_completed", "loop_broken", "parallel_opened", "parallel_resolved",
		"effect_requested", "effect_waiting_for_responder_capacity", "effect_responder_selected", "effect_responder_promoted",
		"wait_requested", "approval_requested",
		"wait_completed", "message_sent", "message_callback_awaiting", "message_callback_completed",
		"approval_awaiting", "approval_decided",
		"effect_failed", "effect_retry_scheduled", "effect_timed_out",
		"callback_responder_observed", "callback_task_watch_projection_restored", "completion_replayed",
	)

	// eventEnvelopeDecisionValues is the closed approval decision vocabulary.
	eventEnvelopeDecisionValues = stringSet("approved", "rejected")

	// eventEnvelopeWaitingReasonValues is the closed machine vocabulary for
	// capacity waits. Candidate identities and pool details never enter this
	// public event field.
	eventEnvelopeWaitingReasonValues = stringSet("responder_capacity")

	// eventEnvelopeScopeKindValues is the closed message-scope kind vocabulary.
	eventEnvelopeScopeKindValues = stringSet("channel", "thread", "dm", "task")

	// eventEnvelopeStatusValues is the closed run/effect/activation status
	// vocabulary carried on non-failure event rows.
	eventEnvelopeStatusValues = stringSet(
		"queued", "running", "waiting", "succeeded", "failed", "canceled",
		"pending", "dispatching", "delivered", "awaiting", "queued_for_agent",
		"waiting_for_responder", "completed",
	)
)

func stringSet(values ...string) map[string]struct{} {
	set := make(map[string]struct{}, len(values))
	for _, value := range values {
		set[value] = struct{}{}
	}
	return set
}

// envelopeFieldStableChildID validates a workflow Run child id family
// (effectId/activationId/notificationId) against the exact producer grammar:
// `prefix + "_" + 32 lowercase hex` (orchestrator.StableChildID for wfx_/wra_;
// deterministicAppNotificationID for btn_). A base36, prefixed-punctuation,
// token-bearing, oversized, or invalid-UTF8 value fails closed.
func envelopeFieldStableChildID(prefix string, maxRunes int) func(any) (any, bool) {
	return func(raw any) (any, bool) {
		text := readIdentityString(raw)
		if text == "" || len(text) > maxRunes {
			return nil, false
		}
		if !identifiers.ValidStableChildID(text, prefix) {
			return nil, false
		}
		return text, true
	}
}

// envelopeFieldEntityID validates a NewEntityID-family id (usr_/agt_ and any
// other NewEntityID caller) against the exact producer grammar:
// `prefix + "_" + exactly 14 base36 lowercase`. A hex suffix, punctuation,
// token-bearing, oversized, or invalid-UTF8 value fails closed.
func envelopeFieldEntityID(prefix string, maxRunes int) func(any) (any, bool) {
	return func(raw any) (any, bool) {
		text := readIdentityString(raw)
		if text == "" || len(text) > maxRunes {
			return nil, false
		}
		if !identifiers.ValidNewEntityIDForm(text, prefix) {
			return nil, false
		}
		return text, true
	}
}

// envelopeFieldRawMemberID validates a persisted workspace member id against the
// exact producer grammar: a RAW identifiers.NewMemberID (exactly 12 base36
// lowercase) with NO `mem_` prefix. The workspace bootstrap persists the raw
// member id; any prefixed/punctuation/token/oversized/invalid-UTF8 lookalike
// fails closed. Only evidence-backed historical forms (a real migration/read
// producer) would be added; none currently exist.
func envelopeFieldRawMemberID(maxRunes int) func(any) (any, bool) {
	return func(raw any) (any, bool) {
		text := readIdentityString(raw)
		if text == "" || len(text) > maxRunes {
			return nil, false
		}
		if !identifiers.ValidMemberIDRaw(text) {
			return nil, false
		}
		return text, true
	}
}

// envelopeFieldIdentifier validates a bounded identifier (word chars
// and dashes, no spaces, no punctuation, no secrets). It is used for nodeId and
// scopeId, which are runtime-generated (wnd_/wsc_ prefixed) or author-named plan
// node ids (word chars). Authored output ports are validated separately by the
// authoritative Plan port grammar (validPlanPort).
func envelopeFieldIdentifier(maxRunes int) func(any) (any, bool) {
	return func(raw any) (any, bool) {
		text := readIdentityString(raw)
		if text == "" || len(text) > maxRunes {
			return nil, false
		}
		for _, character := range text {
			if (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') ||
				(character >= '0' && character <= '9') || character == '_' || character == '-' {
				continue
			}
			return nil, false
		}
		return text, true
	}
}

// envelopeFieldEnum validates membership in a closed enum set.
func envelopeFieldEnum(values map[string]struct{}) func(any) (any, bool) {
	return func(raw any) (any, bool) {
		text := readIdentityString(raw)
		if text == "" {
			return nil, false
		}
		if _, ok := values[text]; !ok {
			return nil, false
		}
		return text, true
	}
}

// envelopeFieldRFC3339 validates that the value is an RFC3339 timestamp and
// returns the normalized UTC form.
func envelopeFieldRFC3339(raw any) (any, bool) {
	text := strings.TrimSpace(strings.ToValidUTF8(readFailureString(raw), "�"))
	if text == "" {
		return nil, false
	}
	parsed, err := time.Parse(time.RFC3339, text)
	if err != nil {
		return nil, false
	}
	return parsed.UTC().Format(time.RFC3339Nano), true
}

// envelopeFieldScope validates a {kind, scopeId} message-scope object against
// the closed scope-kind enum and a valid scopeId (bounded word chars).
func envelopeFieldScope(raw any) (any, bool) {
	object, ok := raw.(map[string]any)
	if !ok {
		return nil, false
	}
	kind := readIdentityString(object["kind"])
	if _, ok := eventEnvelopeScopeKindValues[kind]; !ok {
		return nil, false
	}
	scopeID := readIdentityString(object["scopeId"])
	if scopeID == "" || len(scopeID) > readEnvelopeIDRunes {
		return nil, false
	}
	for _, character := range scopeID {
		if (character >= 'a' && character <= 'z') || (character >= '0' && character <= '9') || character == '_' {
			continue
		}
		return nil, false
	}
	return map[string]any{
		"kind":    kind,
		"scopeId": scopeID,
	}, true
}

// envelopeFieldAgentIDList validates a list of valid agent IDs at both item
// count and item length. Each item must be the exact NewEntityID agent form
// (`agt_` + 14 base36); a prefixed/token/oversize/invalid-UTF8 item is dropped.
func envelopeFieldAgentIDList(maxRunes, maxItems int) func(any) (any, bool) {
	validAgent := envelopeFieldEntityID(validAgentIDPrefix, maxRunes)
	return func(raw any) (any, bool) {
		list, ok := raw.([]any)
		if !ok {
			return nil, false
		}
		projected := make([]any, 0, len(list))
		for _, item := range list {
			if len(projected) >= maxItems {
				break
			}
			if value, ok := validAgent(item); ok {
				projected = append(projected, value)
			}
		}
		if len(projected) == 0 {
			return nil, false
		}
		return projected, true
	}
}

// eventEnvelopeSchema is the closed typed public schema for one Run event kind.
type eventEnvelopeSchema struct {
	// context is the allowlist of non-failure context fields with typed
	// validators.
	context map[string]func(any) (any, bool)
	// failureAllowed reports whether the event kind may carry a failure
	// contract.
	failureAllowed bool
}

// sharedEventEnvelopeContext is the reviewed typed allowlist of event context
// fields shared across event kinds. Each field is validated against its
// required prefix / enum / timestamp / scope / list grammar.
var sharedEventEnvelopeContext = map[string]func(any) (any, bool){
	"effectId":                 envelopeFieldStableChildID(validEffectIDPrefix, readEnvelopeIDRunes),
	"activationId":             envelopeFieldKernelActivationID(readEnvelopeIDRunes),
	"agentId":                  envelopeFieldEntityID(validAgentIDPrefix, readEnvelopeIDRunes),
	"nodeId":                   envelopeFieldIdentifier(readEnvelopeIDRunes),
	"scopeId":                  envelopeFieldIdentifier(readEnvelopeIDRunes),
	"kind":                     envelopeFieldEnum(eventEnvelopeKindValues),
	"port":                     envelopeFieldPlanPort,
	"messageId":                envelopeFieldMessageID(readEnvelopeIDRunes),
	"notificationId":           envelopeFieldStableChildID(validNotificationIDPrefix, readEnvelopeIDRunes),
	"decision":                 envelopeFieldEnum(eventEnvelopeDecisionValues),
	"decidedByMemberId":        envelopeFieldRawMemberID(readEnvelopeIDRunes),
	"assigneeMemberId":         envelopeFieldRawMemberID(readEnvelopeIDRunes),
	"callbackResponderAgentId": envelopeFieldEntityID(validAgentIDPrefix, readEnvelopeIDRunes),
	"retryAt":                  envelopeFieldRFC3339,
	"receiptRecovery":          envelopeFieldBool,
	"wakeAgentIds":             envelopeFieldAgentIDList(readEnvelopeIDRunes, readEnvelopeListCap),
	"deliveryScope":            envelopeFieldScope,
	"threadScope":              envelopeFieldScope,
	"status":                   envelopeFieldEnum(eventEnvelopeStatusValues),
	"waitingReason":            envelopeFieldEnum(eventEnvelopeWaitingReasonValues),
	"reason":                   envelopeFieldCancelReason,
	"actor":                    envelopeFieldActor,
}

// eventEnvelopeSchemas is the per-event-kind closed public schema. Every event
// kind produced by the kernel, dispatcher, callback, approval, retry/timeout,
// task-watch, parallel, branch, loop, and fan-out producers is represented here;
// a missing kind fails closed to an empty object.
var eventEnvelopeSchemas = map[string]eventEnvelopeSchema{
	// Run lifecycle.
	"run_accepted": {context: contextFields("status")},
	"run_started":  {context: contextFields("kind")},
	"run_succeeded": {context: contextFields(
		"kind", "activationId", "nodeId"),
	},
	"run_canceled": {context: contextFields(
		"kind", "reason", "actor"),
	},
	"run_cancel_replayed": {context: contextFields(
		"kind"),
	},
	"run_failed": {context: contextFields(
		"kind", "activationId", "nodeId"), failureAllowed: true,
	},
	// Activation lifecycle.
	"activation_started": {context: contextFields(
		"kind", "activationId"),
	},
	"activation_created": {context: contextFields(
		"kind", "activationId", "nodeId", "scopeId"),
	},
	"activation_completed": {context: contextFields(
		"kind", "activationId", "nodeId", "port"),
	},
	"activation_failed": {context: contextFields(
		"kind", "activationId", "nodeId"), failureAllowed: true,
	},
	// Branch / parallel / loop / fan-out scope events.
	"branch_arrived": {context: contextFields(
		"kind", "scopeId", "port"),
	},
	"branch_failed": {context: contextFields(
		"kind", "activationId", "nodeId", "scopeId"), failureAllowed: true,
	},
	"parallel_opened": {context: contextFields(
		"kind", "activationId", "scopeId"),
	},
	"parallel_resolved": {context: contextFields(
		"kind", "scopeId", "port"),
	},
	"loop_opened": {context: contextFields(
		"kind", "activationId", "scopeId"),
	},
	"loop_continued": {context: contextFields(
		"kind", "activationId", "scopeId"),
	},
	"loop_completed": {context: contextFields(
		"kind", "activationId", "scopeId"),
	},
	"loop_broken": {context: contextFields(
		"kind", "activationId", "scopeId"),
	},
	"fan_out_opened": {context: contextFields(
		"kind", "activationId", "nodeId", "scopeId"),
	},
	"fan_out_item_arrived": {context: contextFields(
		"kind", "scopeId"),
	},
	"fan_out_item_started": {context: contextFields(
		"kind", "scopeId"),
	},
	"fan_out_item_responder_activated": {context: contextFields(
		"kind", "activationId", "nodeId", "agentId", "scopeId"),
	},
	"fan_out_item_blocked": {context: contextFields(
		"kind", "scopeId"), failureAllowed: true,
	},
	"fan_out_item_failed": {context: contextFields(
		"kind", "scopeId"), failureAllowed: true,
	},
	"fan_out_resolved": {context: contextFields(
		"kind", "scopeId", "port"),
	},
	// Effect request events.
	"effect_requested": {context: contextFields(
		"kind", "activationId", "nodeId"),
	},
	"effect_waiting_for_responder_capacity": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind", "waitingReason"),
	},
	"effect_responder_selected": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind", "waitingReason"),
	},
	"effect_responder_promoted": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind", "waitingReason"),
	},
	"wait_requested": {context: contextFields(
		"kind", "activationId", "nodeId"),
	},
	"approval_requested": {context: contextFields(
		"kind", "activationId", "nodeId"),
	},
	// Dispatcher events carry the effect context plus their delivery/approval
	// specific fields.
	"wait_completed": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind"),
	},
	"message_sent": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind", "messageId",
		"deliveryScope", "threadScope"),
	},
	"message_callback_awaiting": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind", "messageId",
		"wakeAgentIds", "callbackResponderAgentId", "deliveryScope"),
	},
	"message_callback_completed": {context: contextFields(
		"effectId", "activationId", "nodeId", "agentId", "port"), failureAllowed: true,
	},
	"approval_awaiting": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind", "notificationId",
		"assigneeMemberId"),
	},
	"approval_decided": {context: contextFields(
		"effectId", "activationId", "nodeId", "notificationId",
		"decision", "decidedByMemberId"),
	},
	// Failure effect events carry the effect context plus the failure contract.
	"effect_failed": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind"), failureAllowed: true,
	},
	"effect_retry_scheduled": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind", "retryAt", "messageId",
		"receiptRecovery"), failureAllowed: true,
	},
	"effect_timed_out": {context: contextFields(
		"effectId", "activationId", "nodeId", "kind"), failureAllowed: true,
	},
	// Task-watch / completion-replay events.
	"callback_responder_observed": {context: contextFields(
		"kind", "activationId", "nodeId", "agentId"),
	},
	"callback_task_watch_projection_restored": {context: contextFields(
		"kind", "activationId", "nodeId"),
	},
	"completion_replayed": {context: contextFields(
		"kind", "activationId", "port"),
	},
}

// contextFields builds a context-field allowlist referencing the shared typed
// validators.
func contextFields(names ...string) map[string]func(any) (any, bool) {
	result := make(map[string]func(any) (any, bool), len(names))
	for _, name := range names {
		if validator, ok := sharedEventEnvelopeContext[name]; ok {
			result[name] = validator
		}
	}
	return result
}

// eventKindSchema returns the closed schema for an event kind, or nil when the
// kind is unknown. It enforces the cross-package bijection against the
// producer-owned contract: a producer-declared kind must have a public schema
// (so a producer addition cannot silently project to an empty object), and the
// public schema's failureAllowed must equal the producer's FailureCapable (so
// failure-capability drift fails closed). Unknown (non-producer) kinds still
// return nil and fail closed to the scrubbed empty object.
func eventKindSchema(kind string) *eventEnvelopeSchema {
	kind = strings.TrimSpace(kind)
	schema, ok := eventEnvelopeSchemas[kind]
	if !ok {
		return nil
	}
	if producer := eventcontract.Lookup(kind); producer != nil {
		if producer.FailureCapable != schema.failureAllowed {
			// Drift: the producer declares a different failure capability than the
			// public schema. Fail the projection closed (treat as unknown) so a
			// stale schema cannot project a failure contract incorrectly.
			return nil
		}
	}
	return &schema
}
