defmodule TradeMachine.GMGradeV2.Grader do @moduledoc """ Pure end-to-end AVC GM grader. Pillars and plausibility retain full precision. Display rounding occurs only when `TradeMachine.GMGradeV2.Result.GradeResult.finalize/1` is called. """ alias TradeMachine.GMGradeV2.CapState alias TradeMachine.GMGradeV2.ChallengeSnapshot alias TradeMachine.GMGradeV2.ComparableState alias TradeMachine.GMGradeV2.ModelVersion alias TradeMachine.GMGradeV2.MoveSummary alias TradeMachine.GMGradeV2.Narrative alias TradeMachine.GMGradeV2.Plausibility alias TradeMachine.GMGradeV2.Progression alias TradeMachine.GMGradeV2.Pillars.AssetManagement alias TradeMachine.GMGradeV2.Pillars.CapFlexibility alias TradeMachine.GMGradeV2.Pillars.CompetitiveStrength alias TradeMachine.GMGradeV2.Pillars.ContractHealth alias TradeMachine.GMGradeV2.Pillars.RosterConstruction alias TradeMachine.GMGradeV2.Pillars.TimelineAlignment alias TradeMachine.GMGradeV2.Result.GradeResult alias TradeMachine.GMGradeV2.ResolvedModel alias TradeMachine.GMGradeV2.Result.PillarResult @weight_tolerance 1.0e-9 @pillar_order [ :competitive_strength, :roster_construction, :contract_health, :cap_flexibility, :asset_management, :timeline_alignment ] @doc """ Runs all six pillar aggregators and returns an unrounded grade. The assembled state must include `:asset_metric_results`; callers that begin with a persisted scenario should use `ScenarioAssembly.grade/2`. """ @spec grade(map(), ChallengeSnapshot.t(), struct()) :: GradeResult.t() def grade(scenario_state, %ChallengeSnapshot{} = snapshot, mandate_profile) do grade(scenario_state, snapshot, mandate_profile, []) end @doc """ Grades with optional lab-only `:constants_override` values. `:resolved_model` is the parameter document this grade is scored and stamped under. Supplied, it decides all 64 phase-1 R0 parameters: each pillar's four metric weights, the mandate's six pillar weights, and the four plausibility magnitudes — and the grade-version string the result cites. Omitted, every one of those falls back to the module attribute it has always come from, which is what every caller does until the orchestration boundaries resolve one. It must already be a `%ResolvedModel{}` — this module is pure, so resolving an id would mean reading the database from the scorer. Orchestration boundaries (`ScenarioAssembly`, `Challenges`, `Lab`) resolve once and pass the struct down. """ @spec grade(map(), ChallengeSnapshot.t(), struct(), keyword()) :: GradeResult.t() def grade(scenario_state, %ChallengeSnapshot{} = snapshot, mandate_profile, opts) when is_list(opts) do resolved_model = resolved_model!(opts) scenario_state = Map.put( scenario_state, :constants_override, Keyword.get(opts, :constants_override, %{}) ) pillar_results = score_pillars(scenario_state, snapshot, resolved_model) aggregate(pillar_results, scenario_state, snapshot, mandate_profile, resolved_model) end @doc """ Aggregates already-computed pillar results. This is the narrow unit-test seam for the final arithmetic; production uses `grade/3`, which always computes the six pillars. """ @spec aggregate( [PillarResult.t()], map(), ChallengeSnapshot.t(), struct(), ResolvedModel.t() | nil ) :: GradeResult.t() def aggregate(pillar_results, scenario_state, snapshot, mandate_profile, resolved_model \\ nil) when is_list(pillar_results) do weights = mandate_pillar_weights(resolved_model, mandate_profile) base_score = composite_score(pillar_results, weights) moves = build_moves([scenario_state]) plausibility = scenario_state |> Plausibility.assess(snapshot, pillar_results, magnitudes(resolved_model)) |> Plausibility.integrate_moves(moves) final_score = apply_plausibility(base_score, plausibility) result = %GradeResult{ model_version: grade_version(resolved_model), mandate_key: mandate_profile.key, mandate_profile_version: mandate_profile.version, pillar_results: pillar_results, pillar_weights: weights, base_score: base_score, plausibility: plausibility, final_score: final_score, validation_status: validation_status(pillar_results, scenario_state), snapshot_refs: snapshot_refs(snapshot, mandate_profile, scenario_state, resolved_model) } %{ result | narrative: Narrative.build(result, effective_profile(mandate_profile, weights), moves) } end @doc "Applies penalty, then the minimum cap, and clamps once at full precision." @spec apply_plausibility(number(), %{penalty: number(), cap: number() | nil}) :: float() def apply_plausibility(base_score, plausibility) when is_number(base_score) do base_score |> Kernel.-(Map.fetch!(plausibility, :penalty)) |> min(Map.get(plausibility, :cap) || 100.0) |> max(0.0) |> min(100.0) |> Kernel.*(1.0) end @doc """ Computes the canonical mandate-weighted composite for six pillar results. This is also the reusable arithmetic boundary for projections that retain AVC's pillar weights while deliberately omitting the plausibility layer. """ @spec composite_score([PillarResult.t()], %{atom() => number()}) :: float() def composite_score(pillar_results, weights) when is_list(pillar_results) and is_map(weights) do assert_weights!(weights) # On the list, before it becomes a map: a key given twice is refused here, # where the map would quietly keep one of them. assert_pillars!(Enum.map(pillar_results, & &1.key), weights) pillar_results |> Map.new(&{&1.key, &1.score}) |> composite_from_scores(weights) end @doc """ `composite_score/2`'s arithmetic on a map of category key to score: the same canonical order, the same assertions, the same float. `composite_score/2` calls it, so there is one copy of the sum. It exists for scores that are not `%PillarResult{}` structs, such as a stored grade's starting category scores, whose composite is the starting overall: `composite_from_scores(grade["starting"], grade["pillar_weights"])`. Keys are the category atoms (as the grader's own weights are) or their strings (as a stored grade's are), the same kind in both maps. Raises `ArgumentError` when the weights do not sum to 1.0 or the two maps do not name exactly the same categories. """ @spec composite_from_scores( %{(atom() | String.t()) => number()}, %{(atom() | String.t()) => number()} ) :: float() def composite_from_scores(scores, weights) when is_map(scores) and is_map(weights) do assert_weights!(weights) assert_pillars!(Map.keys(scores), weights) scores |> Enum.sort_by(fn {key, _score} -> pillar_order!(key) end) |> Enum.reduce(0.0, fn {key, score}, total -> total + score * Map.fetch!(weights, key) end) |> Kernel.*(1.0) end @doc """ Grades starting and final states against identical frozen evidence. The returned result is the final grade. Starting scores and pillar/metric deltas are explanatory fields and never enter the composite. """ @spec grade_pair(map(), map(), ChallengeSnapshot.t(), struct()) :: GradeResult.t() def grade_pair(starting_state, final_state, snapshot, mandate_profile) do grade_pair(starting_state, final_state, snapshot, mandate_profile, []) end @doc """ Grades a state pair with optional lab-only overrides. The separately versioned Progression result is opt-in shadow data. Pass `progression?: true` from an explicitly authorized orchestration boundary; the canonical grade is identical either way. """ @spec grade_pair(map(), map(), ChallengeSnapshot.t(), struct(), keyword()) :: GradeResult.t() def grade_pair(starting_state, final_state, snapshot, mandate_profile, opts) when is_list(opts) do starting = grade(starting_state, snapshot, mandate_profile, opts) final = grade(final_state, snapshot, mandate_profile, opts) starting_by_key = Map.new(starting.pillar_results, &{&1.key, &1}) pillar_results = Enum.map(final.pillar_results, fn result -> starting_result = Map.fetch!(starting_by_key, result.key) %{ result | starting_score: starting_result.score, delta: result.score - starting_result.score } end) starting_scores = Map.new(starting.pillar_results, &{&1.key, &1.score}) deltas = Map.new(pillar_results, fn result -> starting_result = Map.fetch!(starting_by_key, result.key) {result.key, %{ score: result.delta, metrics: metric_deltas(starting_result, result) }} end) progression = if Keyword.get(opts, :progression?, false) do progression(starting, final, mandate_profile, opts) end result = %{ final | pillar_results: pillar_results, starting: starting_scores, deltas: deltas, progression: progression } %{ result | narrative: build_narrative(result, mandate_profile, [starting_state, final_state]) } end # `result.pillar_weights` is whatever `aggregate/5` composited with, so the # narrative here is substituted from the result rather than re-derived from # the model — the two cannot drift. defp build_narrative(result, mandate_profile, states) do profile = effective_profile(mandate_profile, result.pillar_weights) Narrative.build(result, profile, build_moves(states)) end defp build_moves(states) do final_state = List.last(states) || %{} final_state |> Map.get(:modifications, %{}) |> MoveSummary.build(players_by_id(states)) end defp players_by_id(states) do states |> Enum.flat_map(&Map.get(&1, :roster, [])) |> Enum.reduce(%{}, fn player, players -> case Map.get(player, :id) || Map.get(player, "id") do nil -> players id -> Map.put(players, id, player) end end) end defp progression(starting, final, mandate_profile, opts) do progression_opts = [model_override: Keyword.get(opts, :progression_override, %{})] progression_opts = case Keyword.get(opts, :progression_policy) do nil -> progression_opts policy -> Keyword.put(progression_opts, :comparison_policy, policy) end # The same resolved model the canonical pair was scored under, so Asset # Management's neutral-AEV re-aggregation cannot be weighted differently # from the grade it is compared against (plan §5.1's seventh call site). case ComparableState.project_pair(starting, final, resolved_model!(opts)) do {:ok, comparable} -> Progression.evaluate( mandate_profile.key, comparable.baseline.score, comparable.final.score, final.final_score, progression_opts ++ [ pillar_deltas: comparable.pillar_deltas, metric_deltas: comparable.metric_deltas ] ) {:error, reason} -> Progression.unavailable( mandate_profile.key, final.final_score, reason, progression_opts ) end end defp score_pillars(state, snapshot, resolved_model) do unless Map.has_key?(state, :asset_metric_results) do raise ArgumentError, "Grader.grade/3 requires an assembled state with :asset_metric_results; " <> "use ScenarioAssembly.grade/2 for persisted scenarios" end cap_state = Map.get_lazy(state, :cap_state, fn -> CapState.build(state, season_start!(snapshot)) end) asset_results = Map.fetch!(state, :asset_metric_results) weights = pillar_metric_weights(resolved_model) [ CompetitiveStrength.score(state, snapshot, weights.competitive_strength), RosterConstruction.score(state, snapshot, weights.roster_construction), ContractHealth.score(state, snapshot, weights.contract_health), CapFlexibility.score(cap_state, weights.cap_flexibility), AssetManagement.score(asset_results, weights.asset_management), TimelineAlignment.score(state, snapshot, weights.timeline_alignment) ] end # Six weight sets resolved up front, so the pillar list above reads the same # whether or not a model was supplied. `nil` is every caller today: each # pillar's published attribute, read through its own public accessor rather # than restated here. Asset Management's are the *full* four — it derives its # provisional set itself (plan §3.4 item 8). defp pillar_metric_weights(nil) do %{ competitive_strength: CompetitiveStrength.metric_weights(), roster_construction: RosterConstruction.metric_weights(), contract_health: ContractHealth.metric_weights(), cap_flexibility: CapFlexibility.metric_weights(), asset_management: AssetManagement.full_weights(), timeline_alignment: TimelineAlignment.metric_weights() } end defp pillar_metric_weights(%ResolvedModel{} = model) do Map.new(@pillar_order, &{&1, ResolvedModel.metric_weights_for(model, &1)}) end # The mandate still *selects* the weight set; the model says what the six # numbers in it are. A `nil` model keeps the profile's own, which is the # hardcoded path every caller is on until the orchestration boundaries # resolve one. defp mandate_pillar_weights(nil, mandate_profile), do: mandate_profile.pillar_weights defp mandate_pillar_weights(%ResolvedModel{} = model, mandate_profile) do ResolvedModel.pillar_weights_for(model, mandate_profile) end defp magnitudes(nil), do: Plausibility.default_magnitudes() defp magnitudes(%ResolvedModel{} = model), do: ResolvedModel.plausibility_magnitudes(model) # `Narrative` picks the highlighted pillar and the recommended next step from # the *profile's* `pillar_weights` (`narrative.ex:446,451`), not from the # result's. Left alone, a published document would move the score while the # recommendations still followed the old priorities — and because the seeded # model reproduces the hardcoded weights exactly, parity would never catch it # (B8). So the narrative is handed a profile whose weights are the ones the # composite actually used. Everything else about the mandate — its key, label # and Timeline Alignment targets — is untouched, because only the weights are # phase-1 parameters. defp effective_profile(mandate_profile, weights) do %{mandate_profile | pillar_weights: weights} end defp season_start!(snapshot) do snapshot |> ChallengeSnapshot.section(:season) |> Map.fetch!("start_date") |> Date.from_iso8601!() end defp assert_weights!(weights) do sum = weights |> Map.values() |> Enum.sum() if abs(sum - 1.0) > @weight_tolerance do raise ArgumentError, "mandate pillar weights sum to #{sum}, not 1.0" end end defp assert_pillars!(keys, weights) do result_keys = MapSet.new(keys) weight_keys = weights |> Map.keys() |> MapSet.new() if length(keys) != map_size(weights) or result_keys != weight_keys do raise ArgumentError, "pillar results must contain exactly #{inspect(Map.keys(weights))}; got " <> inspect(keys) end end # The one place the grade-version string is chosen. `nil` is the whole of # production today: nothing resolves a model until the orchestration # boundaries do, and until then a grade cites the version the code is at. defp grade_version(nil), do: ModelVersion.model_version() defp grade_version(%ResolvedModel{} = model), do: ResolvedModel.grade_version(model) # A model id or a `%GradingModel{}` would have to be read from the database to # become weights, and this module is pure. Refusing loudly beats resolving it # here or — far worse — ignoring it and grading against the defaults while the # caller believes it selected a model. defp resolved_model!(opts) do case Keyword.get(opts, :resolved_model) do nil -> nil %ResolvedModel{} = model -> model other -> raise ArgumentError, ":resolved_model must be a %ResolvedModel{} resolved by the caller, got: " <> inspect(other) end end defp validation_status(results, state) do if Enum.any?(results, & &1.provisional?) or Map.get(state, :provisional_player_ids, []) != [] do :provisional else :ok end end # `evidence_source` is `nil` for a hand-assembled state, which is the honest # answer: nothing accounted for where its evidence came from. Only # `ScenarioAssembly` can say, and it always does. defp snapshot_refs(snapshot, profile, state, resolved_model) do benchmark = snapshot.benchmark %{ benchmark_id: benchmark.id, benchmark_version: benchmark.version, snapshot_id: snapshot.id, # The same string as the result's own `model_version` above, from the same # resolved model, because a grade that disagreed with its own provenance # would make both unreadable. It was independently hardcoded here before # (B5), which is exactly how that disagreement would have arrived. model_version: grade_version(resolved_model), model_versions: ChallengeSnapshot.section(snapshot, :model_versions), mandate_key: profile.key, mandate_profile_version: profile.version, provisional_player_ids: Map.get(state, :provisional_player_ids, []), starting_rotation_fallback: Map.get(state, :starting_rotation_fallback), evidence_source: Map.get(state, :evidence_source), live_evidence: Map.get(state, :live_evidence, []) } end defp metric_deltas(starting, final) do starting_metrics = Map.new(starting.metric_results, &{&1.key, &1.score}) Map.new(final.metric_results, fn metric -> delta = case Map.fetch(starting_metrics, metric.key) do {:ok, starting_score} -> metric.score - starting_score :error -> nil end {metric.key, delta} end) end # A category key's place in `@pillar_order`, as an atom or its string. defp pillar_order!(key) do case Enum.find_index(@pillar_order, &(&1 == key or Atom.to_string(&1) == key)) do nil -> raise ArgumentError, "unknown pillar key #{inspect(key)}" index -> index end end end