diff --git a/docs/operations/nesy-reinforcement/NS-03-neural-readiness.adoc b/docs/operations/nesy-reinforcement/NS-03-neural-readiness.adoc new file mode 100644 index 000000000..c07b593b5 --- /dev/null +++ b/docs/operations/nesy-reinforcement/NS-03-neural-readiness.adoc @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += NS-03: truthful neural contribution and local readiness +:toc: +:toclevels: 2 + +Date: 2026-11-23. Base revision: `d158aed87f76b93e4f291e995bef9f26559c7fb2`. +Scope: the coordinator confidence calculation and its consumption by +`PatternAnalyzer`. This is a reinforcement of the existing advisory path, not +a Kautz-level acceptance result or an autonomous-capability promotion. + +== Problem and implemented boundary + +The previous calculation counted the GNN's fixed interaction score and the +sequence model's last-observation heuristic in its weighted mean. A VAE result +with a missing or false `placeholder` label also counted. Presence of an entry +was enough to admit other untrained outputs. Downstream, an aggregate outside +`0.70..0.76` was interpreted as evidence of training. + +The coordinator now consults its own component state, inside the existing +source-store/cohort transaction. Only an eligible component with local +training bookkeeping and a numeric output in `[0, 1]` contributes. The same +eligibility decision controls its numerator and denominator weight. Changing +a trace's `trained`, `model_trained` or `placeholder` label cannot create +training state. + +Removing placeholder weights can raise an honest aggregate above `0.95`. +That arithmetic change is not permission to activate automatic execution. +The only readiness contract implemented here is advisory: the coordinator +retains the honest `confidence` and `raw_strategy` diagnostics, then limits +the strategy to at most `:review` before applying the existing outcome-maturity +gate. `PatternAnalyzer` independently enforces the same ceiling. There is no +configuration switch or caller-supplied qualification flag that bypasses it. +A future promotion requires a separately reviewed capability contract and +evaluation evidence. + +== Contributor contract + +[cols="1,3,1,3",options="header"] +|=== +|Component |Local state required |Weight |Limits +|MoE +|A `MixtureOfExperts` state with a training timestamp and positive training +counts for every selected, registered expert. Missing or repeated selections +do not qualify. +|0.35 +|Training another expert does not qualify the experts used for this finding. +This is local bookkeeping, including legitimately restored bookkeeping. +|RBF +|The actual coordinator-owned RBF state has `trained: true`. +|0.20 +|The consumed value remains the existing distance-based similarity. It is +not a calibrated probability of a repair succeeding. +|LSM +|The actual coordinator-owned LSM state has `trained: true`. +|0.15 +|Reservoir activity alone is not training. This patch does not add a +production caller for its training function. +|ESN +|The actual coordinator-owned ESN state has `trained: true`. +|0.15 +|The existing train/serve signal mismatch is not repaired by this status. +|GNN +|Not eligible: current interaction score is a placeholder. +|0 +|Graph diagnostics remain visible. +|VAE +|Not eligible: current interpretation is a placeholder. +|0 +|Changing or omitting the placeholder label has no effect. +|Sequence +|Not eligible: current prediction is a last-observation heuristic. +|0 +|The diagnostic identity is `:heuristic`; stored weights are not used by +the current inference implementation. +|PageRank / trust graph +|Not a learned confidence contributor. +|0 +|Trust routing remains separately available. +|=== + +Weights are fixed, then renormalized over eligible contributors. They are +not an adaptive learned mixture. Missing, malformed or out-of-range outputs +have zero weight even when the associated model's local state is trained. +If no component contributes, the numeric fallback is `0.5`, readiness is +false and the coordinator's raw strategy is `:report_only`. The fallback is +an explicitly unready diagnostic value, not neural evidence. + +The legacy undocumented `Coordinator.derive_confidence/1` has no model-state +argument and therefore returns that conservative fallback. The production +server calls `confidence_assessment/2` with its own state after its existing +source checks. Its two-argument helper is a pure policy seam for testing; +it does not authenticate arbitrary caller-created state or traces. + +== Returned metadata and consumer behavior + +Both `Coordinator.analyze/2` and `dispatch_recommendation/3` add +`confidence_readiness`. A representative shape is: + +[source,elixir] +---- +%{ + scope: :local_training_state, + ready: true, + contributing_models: [:rbf, :esn], + components: %{ + moe: :untrained, + rbf: :contributing, + lsm: :untrained, + esn: :contributing, + gnn: :placeholder, + vae: :placeholder, + sequence: :heuristic, + pagerank: :trust_routing + } +} +---- + +Here, `ready` means at least one locally trained component supplied a valid +score in this round. It does not mean that all consulted subsystems are +trained. `network_count` / `networks_consulted` continue to count eight +consulted subsystems. The explicit contributor list supplies the narrower +count relevant to the aggregate. + +`confidence_ready?/1` recognizes the complete local contract: scope, boolean +readiness, a nonempty and nonrepeated contributor list, consistent component +statuses, and the fixed diagnostic classifications. A bare `ready: true` or +`trained: true` is insufficient. This is structural contract checking, not +a signature or independent attestation of model provenance. + +`PatternAnalyzer.apply_neural_recommendation/2` is the actual pure production +composition used by the analysis pipeline and the regression tests. It: + +. Preserves novel and report-only refusals. +. Applies an advisory review ceiling, including to complete local-readiness + recommendations that claim `:auto_execute`. +. Caps missing, malformed or legacy readiness conservatively before invoking + the existing dispatch guard, preserving the original recipe confidence for + the audit trail. +. Uses a valid local prediction only to lower the recipe confidence. A + trained value of `0.73` is usable; an untrained value outside the former + numerical band is not interpreted as training. +. Records the effective boolean `"neural_confidence_ready"` and the supplied + `"neural_confidence_readiness"` metadata alongside the retained recipe, or + on a control-tier pattern. The supplied metadata is diagnostic; the + effective boolean records whether this consumer accepted its contract. + +Dispatch recommendations now distinguish two clamps: + +* `advisory_clamped`: the raw strategy exceeded the local-readiness advisory + ceiling. +* `annealing_clamped`: the outcome-maturity gate lowered the already + advisory-capped strategy. + +The reason text identifies an advisory clamp explicitly. This avoids +misreporting the new ceiling as an outcome-maturity decision. + +== Verification + +The regression checks use synthetic fixtures and isolated test stores. They +do not dispatch repairs or establish effectiveness on a deployed corpus. +The runtime is Elixir `1.19.4` on OTP `27.3.4.19`, matching the repository pin. + +Before the implementation, the three revised placeholder tests ran against +the base production source and all three failed: a trace with no component +state scored approximately `0.99`, and a placeholder-only graph result scored +`1.0`. These are confidence-calculation counterexamples, not evidence that a +production actuator executed a repair. + +The focused suite exercises: + +* Exact numerator/denominator exclusion and invariance under placeholder + presence, namespace, value and label changes. +* Empty, malformed, missing-state and placeholder-only fallbacks. +* Selected-expert MoE readiness, invalid outputs, trained-in-band and + untrained-outside-band converse controls. +* The actual PatternAnalyzer composition, including prior-confidence audit, + demote-only behavior, legacy metadata, novelty and unavailable-coordinator + refusals. +* A real fitted RBF at high similarity, a mature recipe with 71 qualified + synthetic outcomes, the actual source-bound coordinator and the production + consumer: raw `:auto_execute` remains effective `:review`. Removing the + fixture maturity history restricts further to `:report_only`; the two clamp + flags identify their different causes. +* Real cohort state before and after training, RBF restoration, cold ESN/LSM + after restart, and the existing source-lifecycle refusal tests. + +[source,shell] +---- +MIX_ENV=test mix compile --warnings-as-errors +MIX_ENV=test mix test \ + test/placeholder_network_test.exs \ + test/neural_readiness_test.exs \ + test/neural_dispatch_guard_test.exs \ + test/novelty_fail_closed_test.exs \ + test/neural_source_store_lifecycle_test.exs \ + test/neural_training_qualification_test.exs \ + test/neural_trust_restart_test.exs +---- + +At this change, compilation with warnings as errors passed and the focused +suite passed 82 tests with zero failures. The three failed-before controls +were rerun as part of that suite. The focused result and any subsequent +combined-suite result belong to their specific reviewed revision. The default +test helper excludes several tagged +external-data/integration suites; this command is not a claim that those +suites or a live deployment were qualified. + +The coordinator subsequently combined the independently reviewed NS-01 and +NS-03 source patches in a separate checkout of the same base. Compilation +with warnings as errors and repository-wide formatting passed. With the +CI-pinned Nickel 1.11.0 validator available, `mix test --seed 0` reported +`3742 tests, 0 failures (246 excluded)` and no skips. README claims, the +no-active-Logtalk check and diff whitespace checks also passed. This is a +local result for the combined source; it does not substitute for hosted CI, +the excluded suites, a held-out neural benchmark or deployment evidence. + +== Remaining obligations + +This patch changes no model algorithm, learned-parameter persistence schema, +training admission, source lifecycle or outcome qualification. It grants no +additional actuator permission. ESN/LSM remain cold after restart because their persistence +is summary-only. Local restored flags and counters are not proof of the +contents or quality of a training corpus. + +Content-bound model provenance, reproducible corpus splits, train/serve +parity, calibration, held-out utility and ablations, online-learning receipts +and operational promotion remain separate work. Source-store identity is +still pathname identity, not content attestation. The patch improves the +truthfulness and conservatism of the existing path; it earns no additional +Kautz level by itself. diff --git a/lib/neural/coordinator.ex b/lib/neural/coordinator.ex index 2817b6bf2..369000cee 100644 --- a/lib/neural/coordinator.ex +++ b/lib/neural/coordinator.ex @@ -13,8 +13,8 @@ defmodule Hypatia.Neural.Coordinator do @moduledoc """ Neural Network Coordinator for Hypatia (blackboard architecture). - Orchestrates 8 neural network subsystems through 6 execution phases, - coordinated via a shared ETS blackboard. Each network reads accumulated + Orchestrates 8 subsystems through 6 execution phases, coordinated via a + shared ETS blackboard. Each subsystem reads accumulated context before computing and writes its results for downstream phases. ## Networks (8 total) @@ -23,12 +23,12 @@ defmodule Hypatia.Neural.Coordinator do |-----------|-------|-------------------------------------------| | RBF | 1 | Novelty detection -- novel vs known | | PageRank | 2 | Trust-weighted routing over graph | - | GNN | 2 | Agent interaction graph structure | + | GNN | 2 | Graph diagnostics; confidence placeholder | | MoE | 3 | Domain-specific confidence estimation | | ESN | 4 | Confidence trajectory forecasting | | LSM | 4 | Temporal anomaly detection | - | VAE | 5 | Hermeneutic interpretation clustering | - | Sequence | 6 | Choreography trace prediction | + | VAE | 5 | Interpretation placeholder | + | Sequence | 6 | Last-observation heuristic | ## Phase execution order @@ -42,8 +42,19 @@ defmodule Hypatia.Neural.Coordinator do ## Architecture change Previous: hub-and-spoke with fixed weights (0.6 MoE + 0.25 RBF + 0.15 LSM). - Current: blackboard with phased execution. Confidence derives from the full - reasoning trace, not a hardcoded weighted sum. + Current: blackboard with phased execution. Confidence is a fixed weighted + mean over valid outputs from locally trained MoE/RBF/LSM/ESN components. + Weights are renormalized over contributors. GNN/VAE placeholders, the + sequence heuristic and trust routing have no confidence weight. + + `confidence_readiness` describes local training bookkeeping for this round, + checked against coordinator-owned model state. It does not attest corpus + identity, calibration, held-out evaluation or operational qualification. + This contract is advisory: even a high raw score is capped at review before + the existing outcome-maturity gate. A future capability-promotion contract + requires its own evidence and review; no caller flag bypasses this ceiling. + `network_count` and `networks_consulted` count consulted subsystems, not + trained or experimentally qualified models. """ use GenServer @@ -82,6 +93,27 @@ defmodule Hypatia.Neural.Coordinator do @network_count 8 @phase_count 6 + @confidence_components [ + {:moe, :domain_confidence, :confidence, 0.35}, + {:rbf, :novelty_result, :similarity, 0.20}, + {:lsm, :temporal_result, :score, 0.15}, + {:esn, :trajectory_result, :predicted_next, 0.15} + ] + @diagnostic_components %{ + gnn: :placeholder, + vae: :placeholder, + sequence: :heuristic, + pagerank: :trust_routing + } + @component_statuses [ + :contributing, + :untrained, + :untrained_selected_experts, + :missing_expert_selection, + :missing_model_state, + :missing_output, + :invalid_output + ] # ── GenServer API ─────────────────────────────────────── @@ -458,6 +490,7 @@ defmodule Hypatia.Neural.Coordinator do SourceStore.reply(state, source, fn -> ensure_cohort!(state) {trace, updated_state} = run_phased_analysis(finding, state) + assessment = confidence_assessment(trace, updated_state) analysis = %{ # Legacy fields for backward compatibility @@ -469,8 +502,9 @@ defmodule Hypatia.Neural.Coordinator do gnn: trace_field(trace, :gnn, :graph_metrics), vae: trace_field(trace, :vae, :interpretation), sequence: trace_field(trace, :sequence, :prediction), - # Derived confidence from full reasoning trace - aggregated_confidence: derive_confidence(trace), + # Only locally trained components with valid outputs contribute. + aggregated_confidence: assessment.confidence, + confidence_readiness: assessment.readiness, is_novel: is_novel?(trace), # Blackboard metadata round: trace.round, @@ -489,14 +523,24 @@ defmodule Hypatia.Neural.Coordinator do ensure_cohort!(state) {trace, updated_state} = run_phased_analysis(finding, state) - confidence = derive_confidence(trace) + assessment = confidence_assessment(trace, updated_state) + confidence = assessment.confidence novel = is_novel?(trace) # Trust graph: find best bots trusted_bots = GraphOfTrust.trusted_bots(state.trust_graph) trusted_recipes = GraphOfTrust.trusted_recipes(state.trust_graph) - raw_strategy = raw_strategy(novel, confidence) + raw_strategy = + if confidence_ready?(assessment.readiness), + do: raw_strategy(novel, confidence), + else: :report_only + + # Local training bookkeeping cannot promote an autonomous capability. + # Removing placeholder weights may raise the honest aggregate above 0.95; + # keep that raw diagnostic while preserving an advisory review ceiling. + advisory_strategy = if raw_strategy == :auto_execute, do: :review, else: raw_strategy + advisory_clamped = advisory_strategy != raw_strategy # Annealing gate: clamp strategy based on recipe's outcome maturity. # A recipe with only 3 outcomes cannot reach :auto_execute regardless @@ -506,17 +550,26 @@ defmodule Hypatia.Neural.Coordinator do |> Enum.find("unknown", fn id -> is_binary(id) and byte_size(id) > 0 end) strategy = - Hypatia.OutcomeTracker.annealed_strategy_from_store(recipe_id, raw_strategy, source) + Hypatia.OutcomeTracker.annealed_strategy_from_store(recipe_id, advisory_strategy, source) recommendation = %{ strategy: strategy, raw_strategy: raw_strategy, confidence: confidence, + confidence_readiness: assessment.readiness, preferred_bots: Enum.take(trusted_bots, 3), preferred_recipes: Enum.take(trusted_recipes, 5), is_novel: novel, - reason: dispatch_reason(strategy, confidence, novel, novelty_untrained?(trace)), - annealing_clamped: strategy != raw_strategy, + reason: + dispatch_reason( + strategy, + confidence, + novel, + novelty_untrained?(trace), + advisory_clamped + ), + advisory_clamped: advisory_clamped, + annealing_clamped: strategy != advisory_strategy, architecture: :blackboard, networks_consulted: @network_count } @@ -913,129 +966,144 @@ defmodule Hypatia.Neural.Coordinator do # ── Confidence Derivation ─────────────────────────────── @doc false - def derive_confidence(trace) do - # Derive confidence from the full reasoning trace rather than - # hardcoded fixed weights. Each network contributes evidence. - networks = trace.networks || %{} - - # Extract individual confidence signals - moe_conf = - extract_confidence(networks, :moe, :domain_confidence, fn r -> r.confidence end, 0.5) - - rbf_conf = extract_confidence(networks, :rbf, :novelty_result, fn r -> r.similarity end, 0.0) - lsm_score = extract_confidence(networks, :lsm, :temporal_result, fn r -> r.score end, 0.5) - - esn_pred = - extract_confidence(networks, :esn, :trajectory_result, fn r -> r.predicted_next end, 0.5) - - # Adaptive weighting: if a network contributed, its weight counts. - # Networks that didn't contribute get zero weight. - weights = [ - {moe_conf, if(has_network?(networks, :moe), do: 0.35, else: 0.0)}, - {rbf_conf, if(has_network?(networks, :rbf), do: 0.20, else: 0.0)}, - {lsm_score, if(has_network?(networks, :lsm), do: 0.15, else: 0.0)}, - {esn_pred, if(has_network?(networks, :esn), do: 0.15, else: 0.0)}, - # New networks contribute smaller initial weights (they're untrained) - {gnn_confidence(networks), if(has_network?(networks, :gnn), do: 0.05, else: 0.0)}, - # A network that returns a fixed placeholder adds nothing (E0-23). - {vae_confidence(networks), - if(has_network?(networks, :vae) and not placeholder?(networks, :vae, :interpretation), - do: 0.05, - else: 0.0 - )}, - {seq_confidence(networks), if(has_network?(networks, :sequence), do: 0.05, else: 0.0)} - ] + # Legacy trace-only callers cannot establish model state. Production uses + # confidence_assessment/2 after SourceStore and cohort checks, in the server. + def derive_confidence(trace, state \\ nil), do: confidence_assessment(trace, state).confidence - total_weight = weights |> Enum.map(&elem(&1, 1)) |> Enum.sum() - - if total_weight > 0 do - weighted_sum = - weights - |> Enum.map(fn {val, w} -> val * w end) - |> Enum.sum() - - (weighted_sum / total_weight) - |> max(0.0) - |> min(1.0) - else - 0.5 - end - end + @doc false + def confidence_assessment(trace, state) do + networks = + case trace do + %{networks: networks} when is_map(networks) -> networks + _ -> %{} + end - defp extract_confidence(networks, network_key, entry_key, extractor, default) do - case Map.get(networks, network_key) do - entries when is_list(entries) -> - case Enum.find(entries, fn e -> e.key == entry_key end) do - %{value: value} -> - try do - extractor.(value) - rescue - _ -> default + contributions = + Enum.map(@confidence_components, fn {network, entry, field, weight} -> + case confidence_result(networks, network, entry) do + {:ok, result} -> + case training_status(state, network, result) do + :trained -> + case Map.get(result, field) do + score when is_number(score) and score >= 0.0 and score <= 1.0 -> + {network, :contributing, score, weight} + + _ -> + {network, :invalid_output, 0.0, 0.0} + end + + status -> + {network, status, 0.0, 0.0} end - nil -> - default + :missing -> + {network, :missing_output, 0.0, 0.0} end + end) - _ -> - default - end + total_weight = Enum.reduce(contributions, 0.0, fn {_, _, _, weight}, acc -> acc + weight end) + + weighted_sum = + Enum.reduce(contributions, 0.0, fn {_, _, score, weight}, acc -> acc + score * weight end) + + contributors = for {network, :contributing, _, _} <- contributions, do: network + + components = + contributions + |> Map.new(fn {network, status, _, _} -> {network, status} end) + |> Map.merge(@diagnostic_components) + + %{ + confidence: if(total_weight > 0.0, do: weighted_sum / total_weight, else: 0.5), + readiness: %{ + scope: :local_training_state, + ready: contributors != [], + contributing_models: contributors, + components: components + } + } + end + + @doc false + # Recognize the complete local bookkeeping contract, not a proof of training + # data, calibration or operational qualification. A bare ready/trained label + # is insufficient. This does not authenticate an arbitrary caller's map. + def confidence_ready?(%{ + scope: :local_training_state, + ready: true, + contributing_models: contributors, + components: components + }) + when is_list(contributors) and is_map(components) do + models = Enum.map(@confidence_components, &elem(&1, 0)) + recorded = Enum.filter(models, &(Map.get(components, &1) == :contributing)) + + contributors != [] and Enum.uniq(contributors) == contributors and + Enum.sort(contributors) == Enum.sort(recorded) and + Enum.all?(models, &(Map.get(components, &1) in @component_statuses)) and + Enum.all?(@diagnostic_components, fn {network, kind} -> + Map.get(components, network) == kind + end) end - defp has_network?(networks, key), do: Map.has_key?(networks, key) + def confidence_ready?(_missing_or_unready), do: false - # Does the entry say that it is a placeholder? Only the mark `placeholder: true` - # does: an entry with no mark, or with `placeholder: false`, is evidence. - defp placeholder?(networks, network_key, entry_key) do - case Map.get(networks, network_key) do + defp confidence_result(networks, network, entry) do + case Map.get(networks, network) do entries when is_list(entries) -> - match?( - %{value: %{placeholder: true}}, - Enum.find(entries, fn e -> e.key == entry_key end) - ) + Enum.find_value(entries, :missing, fn + %{key: ^entry, value: result} when is_map(result) -> {:ok, result} + _ -> nil + end) _ -> - false + :missing end end - defp gnn_confidence(networks) do - extract_confidence( - networks, - :gnn, - :graph_metrics, - fn r -> - Map.get(r, :interaction_strength, 0.5) - end, - 0.5 - ) + # Every expert used for this prediction must have local training history. + # Training a different expert does not qualify the selected default experts. + defp training_status( + %__MODULE__{moe: %MixtureOfExperts{last_trained: %DateTime{}} = moe}, + :moe, + %{experts: [_ | _] = experts} + ) + when is_map(moe.experts) and is_map(moe.expert_stats) do + if Enum.uniq(experts) == experts and + Enum.all?(experts, fn domain -> + Map.has_key?(moe.experts, domain) and + match?( + %{total: total} when is_integer(total) and total > 0, + moe.expert_stats[domain] + ) + end), + do: :trained, + else: :untrained_selected_experts end - defp vae_confidence(networks) do - extract_confidence( - networks, - :vae, - :interpretation, - fn r -> - # VAE doesn't produce a confidence directly; use cluster coherence - if r.cluster_id != nil, do: 0.6, else: 0.3 - end, - 0.3 - ) - end + defp training_status(%__MODULE__{moe: %MixtureOfExperts{}}, :moe, %{experts: [_ | _]}), + do: :untrained - defp seq_confidence(networks) do - extract_confidence( - networks, - :sequence, - :prediction, - fn r -> - Map.get(r, :confidence, 0.0) - end, - 0.0 - ) + defp training_status(%__MODULE__{moe: %MixtureOfExperts{}}, :moe, _), + do: :missing_expert_selection + + defp training_status(%__MODULE__{} = state, network, _) when network in [:rbf, :lsm, :esn] do + module = + case network do + :rbf -> RadialNeuralNetwork + :lsm -> LiquidStateMachine + :esn -> EchoStateNetwork + end + + case Map.get(state, network) do + %{__struct__: ^module, trained: true} -> :trained + %{__struct__: ^module, trained: false} -> :untrained + _ -> :missing_model_state + end end + defp training_status(_missing_state, _network, _result), do: :missing_model_state + defp is_novel?(trace) do case Map.get(trace.networks || %{}, :rbf) do entries when is_list(entries) -> @@ -1095,12 +1163,12 @@ defmodule Hypatia.Neural.Coordinator do end end - defp dispatch_reason(strategy, confidence, novel, untrained?) do + defp dispatch_reason(strategy, confidence, novel, untrained?, advisory_clamped) do base = case strategy do :auto_execute -> "High confidence (#{Float.round(confidence, 3)})" - :review -> "Moderate confidence (#{Float.round(confidence, 3)}), needs human review" - :report_only -> "Low confidence (#{Float.round(confidence, 3)})" + :review -> "Confidence (#{Float.round(confidence, 3)}), needs human review" + :report_only -> "Confidence (#{Float.round(confidence, 3)}), report only" end cond do @@ -1110,6 +1178,9 @@ defmodule Hypatia.Neural.Coordinator do novel -> base <> "; NOVEL finding forced to report_only" + advisory_clamped -> + base <> "; local training state is advisory and permits at most review" + true -> base end diff --git a/lib/pattern_analyzer.ex b/lib/pattern_analyzer.ex index 645cf0134..3941fc171 100644 --- a/lib/pattern_analyzer.ex +++ b/lib/pattern_analyzer.ex @@ -80,7 +80,7 @@ defmodule Hypatia.PatternAnalyzer do # Step 4: Enhance dispatch decisions with neural intelligence. # The coordinator provides novelty detection, trust-weighted routing, - # and aggregated confidence from all 5 neural networks. + # and confidence from locally trained components with valid outputs. routed = enhance_with_neural(routed) # Steps 5-6: Dispatch routed actions to the fleet and write the dispatch @@ -276,7 +276,8 @@ defmodule Hypatia.PatternAnalyzer do # Enhance routed actions with neural intelligence. Consults the Neural.Coordinator # for each finding to get novelty detection, trust-weighted bot preferences, and - # aggregated confidence from all 5 networks (MoE, RBF, LSM, ESN, Graph of Trust). + # confidence from locally trained MoE/RBF/LSM/ESN components. Readiness here + # describes local model bookkeeping, not corpus or deployment qualification. # # Novel findings are demoted to :control (report_only) regardless of recipe confidence. # For non-novel findings, the neural aggregated confidence can override the recipe's @@ -287,15 +288,11 @@ defmodule Hypatia.PatternAnalyzer do case neural_recommendation(pattern) do {:ok, rec} -> - # Guard the original action first so its original recipe confidence - # survives in the audit trail, before a conservative neural adjustment. - action - |> DispatchGuard.enforce(rec) - |> apply_neural_recommendation(rec) + apply_neural_recommendation(action, rec) :unavailable -> # Missing neural checks must not leave auto-execution eligible. - DispatchGuard.enforce(action, :unavailable) + apply_neural_recommendation(action, :unavailable) end end) end @@ -313,10 +310,38 @@ defmodule Hypatia.PatternAnalyzer do end end - # Apply neural recommendation to a routed action. + @doc false + # The production composition is also a pure regression-test seam. Check + # local readiness before DispatchGuard so legacy auto-shaped replies cannot + # preserve automatic eligibility, and the original confidence is audited once. + # The only implemented readiness contract is advisory. A complete local + # contract also cannot authorise automatic execution without a separately + # reviewed capability-promotion contract; no reply flag bypasses this ceiling. + def apply_neural_recommendation(action, rec) when is_map(rec) do + ready = NeuralCoordinator.confidence_ready?(Map.get(rec, :confidence_readiness)) + + guarded_rec = + cond do + Map.get(rec, :is_novel) == true -> rec + Map.get(rec, :strategy) == :report_only -> rec + Map.get(rec, :strategy) == :auto_execute -> Map.put(rec, :strategy, :review) + not ready -> Map.put(rec, :strategy, :review) + true -> rec + end + + action + |> DispatchGuard.enforce(guarded_rec) + |> apply_neural_adjustment(rec, ready) + |> record_neural_readiness(rec, ready) + end + + def apply_neural_recommendation(action, _unavailable), + do: DispatchGuard.enforce(action, :unavailable) + + # Apply the confidence adjustment after the dispatch/readiness ceilings. # - Novel findings: demote to :control (human review required) - # - Non-novel: adjust confidence downward if neural prediction is lower (conservative) - defp apply_neural_recommendation(action, %{is_novel: true} = _rec) do + # - Non-novel: only ready local predictions can lower recipe confidence. + defp apply_neural_adjustment(action, %{is_novel: true} = _rec, _ready) do # Novel finding -- force to control tier for human review pattern = extract_pattern(action) @@ -327,20 +352,17 @@ defmodule Hypatia.PatternAnalyzer do {:control, Map.put(pattern, "neural_novel", true)} end - defp apply_neural_recommendation( + defp apply_neural_adjustment( {:eliminate, recipe, pattern}, - %{confidence: neural_conf} = rec + %{confidence: neural_conf} = rec, + ready ) when is_number(neural_conf) and neural_conf >= 0.0 and neural_conf <= 1.0 do recipe_conf = Map.get(recipe, "confidence", 0.0) prior_conf = Map.get(recipe, "neural_prior_confidence", recipe_conf) - # Only let neural confidence override if it's meaningfully trained. - # Untrained MoE returns sigmoid(1.0) ~= 0.73 -- don't let that drag down - # a proven recipe at 0.99. Neural override kicks in once confidence - # diverges from the default sigmoid output (i.e., the network has learned). - neural_is_trained = neural_conf < 0.70 or neural_conf > 0.76 - effective_conf = if neural_is_trained, do: min(recipe_conf, neural_conf), else: recipe_conf + # A score's magnitude does not establish training. This remains demote-only. + effective_conf = if ready, do: min(recipe_conf, neural_conf), else: recipe_conf updated_recipe = recipe @@ -352,9 +374,10 @@ defmodule Hypatia.PatternAnalyzer do {:eliminate, updated_recipe, pattern} end - defp apply_neural_recommendation( + defp apply_neural_adjustment( {:substitute, recipe, pattern}, - %{confidence: neural_conf} = rec + %{confidence: neural_conf} = rec, + _ready ) do updated_recipe = recipe @@ -364,7 +387,21 @@ defmodule Hypatia.PatternAnalyzer do {:substitute, updated_recipe, pattern} end - defp apply_neural_recommendation(action, _rec), do: action + defp apply_neural_adjustment(action, _rec, _ready), do: action + + defp record_neural_readiness({tier, recipe, pattern}, rec, ready) + when tier in [:eliminate, :substitute] do + {tier, readiness_audit(recipe, rec, ready), pattern} + end + + defp record_neural_readiness({:control, pattern}, rec, ready), + do: {:control, readiness_audit(pattern, rec, ready)} + + defp readiness_audit(record, rec, ready) do + record + |> Map.put("neural_confidence_ready", ready) + |> Map.put("neural_confidence_readiness", Map.get(rec, :confidence_readiness)) + end defp extract_pattern({:eliminate, _recipe, pattern}), do: pattern defp extract_pattern({:substitute, _recipe, pattern}), do: pattern diff --git a/test/neural_readiness_test.exs b/test/neural_readiness_test.exs new file mode 100644 index 000000000..f81039296 --- /dev/null +++ b/test/neural_readiness_test.exs @@ -0,0 +1,315 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +defmodule Hypatia.Neural.ReadinessTest do + use ExUnit.Case, async: true + + alias Hypatia.Neural.{ + Coordinator, + EchoStateNetwork, + LiquidStateMachine, + MixtureOfExperts, + RadialNeuralNetwork + } + + alias Hypatia.{PatternAnalyzer, TriangleRouter} + + @pattern %{"id" => "PA-readiness", "routed_repo" => "fixture/repo"} + @selected [:security, :quality] + + defp entry(key, value), do: %{key: key, value: value} + + defp trace(overrides \\ %{}) do + %{ + networks: + Map.merge( + %{ + moe: [entry(:domain_confidence, %{confidence: 0.80, experts: @selected})], + rbf: [entry(:novelty_result, %{similarity: 0.70})], + lsm: [entry(:temporal_result, %{score: 0.60})], + esn: [entry(:trajectory_result, %{predicted_next: 0.65})] + }, + overrides + ) + } + end + + # Synthetic local bookkeeping exercises the readiness policy. The real + # training/restore path is checked by SourceStoreLifecycleTest, not attested + # by these controlled flags or the supplied trace scores. + defp state(trained? \\ true) do + moe = MixtureOfExperts.init() + + moe = + if trained? do + stats = Map.new(moe.expert_stats, fn {domain, stat} -> {domain, %{stat | total: 1}} end) + %{moe | expert_stats: stats, last_trained: ~U[2026-11-23 00:00:00Z]} + else + moe + end + + %Coordinator{ + moe: moe, + rbf: %RadialNeuralNetwork{trained: trained?}, + lsm: %LiquidStateMachine{trained: trained?}, + esn: %EchoStateNetwork{trained: trained?} + } + end + + defp action(confidence \\ 0.99), + do: {:eliminate, %{"id" => "recipe-readiness", "confidence" => confidence}, @pattern} + + defp recommendation(overrides \\ %{}) do + Map.merge( + %{ + strategy: :auto_execute, + confidence: 0.98, + confidence_readiness: Coordinator.confidence_assessment(trace(), state()).readiness, + is_novel: false, + architecture: :blackboard, + networks_consulted: 8, + annealing_clamped: false + }, + overrides + ) + end + + test "only state-ready outputs enter both parts of the weighted mean" do + assessment = Coordinator.confidence_assessment(trace(), state()) + expected = (0.80 * 0.35 + 0.70 * 0.20 + 0.60 * 0.15 + 0.65 * 0.15) / 0.85 + + assert_in_delta assessment.confidence, expected, 1.0e-12 + assert assessment.readiness.scope == :local_training_state + assert assessment.readiness.contributing_models == [:moe, :rbf, :lsm, :esn] + assert Coordinator.confidence_ready?(assessment.readiness) + assert assessment.readiness.components.gnn == :placeholder + assert assessment.readiness.components.vae == :placeholder + assert assessment.readiness.components.sequence == :heuristic + assert assessment.readiness.components.pagerank == :trust_routing + end + + test "placeholder names, scores and labels change neither a ready aggregate nor its decision" do + baseline = Coordinator.confidence_assessment(trace(), state()) + + for namespace <- [:gnn, :vae, :sequence, :unrecognised, "gnn"], + score <- [nil, -1.0, 0.0, 0.99, 1.0, 9.0], + placeholder <- [true, false, nil] do + # Supplying every familiar field does not turn these namespaces into a + # locally trained contributor, even when a caller changes their labels. + value = %{ + confidence: score, + interaction_strength: score, + cluster_id: score, + placeholder: placeholder, + trained: true, + model_trained: true + } + + extra = %{ + namespace => Enum.map([:graph_metrics, :interpretation, :prediction], &entry(&1, value)) + } + + assessment = Coordinator.confidence_assessment(trace(extra), state()) + assert assessment == baseline + + assert Coordinator.raw_strategy(false, assessment.confidence) == + Coordinator.raw_strategy(false, baseline.confidence) + end + end + + test "trace claims and out-of-band scores cannot qualify untrained or missing model state" do + high = %{ + networks: %{ + moe: [entry(:domain_confidence, %{confidence: 0.99, experts: @selected, trained: true})], + rbf: [entry(:novelty_result, %{similarity: 0.99, trained: true})], + lsm: [entry(:temporal_result, %{score: 0.99, status: :trained})], + esn: [entry(:trajectory_result, %{predicted_next: 0.99, trained: true})] + } + } + + for model_state <- [state(false), nil, %{rbf: %{trained: true}}] do + assessment = Coordinator.confidence_assessment(high, model_state) + assert assessment.confidence == 0.5 + refute assessment.readiness.ready + assert assessment.readiness.contributing_models == [] + refute Coordinator.confidence_ready?(assessment.readiness) + end + end + + test "training another MoE expert does not qualify the selected experts" do + model_state = state() + partial = put_in(model_state.moe.expert_stats.quality.total, 0) + only_moe = %{networks: %{moe: trace().networks.moe}} + + assessment = Coordinator.confidence_assessment(only_moe, partial) + refute assessment.readiness.ready + assert assessment.readiness.components.moe == :untrained_selected_experts + assert assessment.confidence == 0.5 + + assert Coordinator.confidence_assessment(only_moe, model_state).readiness.ready + + no_selection = %{networks: %{moe: [entry(:domain_confidence, %{confidence: 0.99})]}} + refute Coordinator.confidence_assessment(no_selection, model_state).readiness.ready + + no_training_time = %{model_state | moe: %{model_state.moe | last_trained: nil}} + refute Coordinator.confidence_assessment(only_moe, no_training_time).readiness.ready + end + + test "missing or malformed scores have no numerator or denominator even with trained state" do + for score <- [nil, "0.99", -0.1, 1.1] do + input = %{ + networks: %{ + moe: [entry(:domain_confidence, %{confidence: score, experts: @selected})], + rbf: [entry(:novelty_result, %{similarity: 0.8})], + lsm: :malformed, + esn: [nil, %{}, entry(:trajectory_result, %{})] + } + } + + assessment = Coordinator.confidence_assessment(input, state()) + assert_in_delta assessment.confidence, 0.8, 1.0e-12 + assert assessment.readiness.contributing_models == [:rbf] + assert assessment.readiness.components.moe == :invalid_output + assert assessment.readiness.components.lsm == :missing_output + assert assessment.readiness.components.esn == :invalid_output + end + end + + test "empty and placeholder-only traces remain unready even when unrelated models are trained" do + for networks <- [ + %{}, + %{gnn: [entry(:graph_metrics, %{interaction_strength: 1.0, trained: true})]}, + %{sequence: [entry(:prediction, %{confidence: 1.0, model_trained: true})]}, + %{vae: [entry(:interpretation, %{cluster_id: 0, placeholder: false})]} + ] do + assessment = Coordinator.confidence_assessment(%{networks: networks}, state()) + assert assessment.confidence == 0.5 + refute assessment.readiness.ready + assert Coordinator.raw_strategy(false, assessment.confidence) == :report_only + end + end + + test "renormalization can cross the raw auto boundary without granting automatic eligibility" do + input = %{ + networks: %{ + rbf: [entry(:novelty_result, %{similarity: 0.99, trained: true, is_novel: false})], + gnn: [entry(:graph_metrics, %{interaction_strength: 0.5, placeholder: false})], + sequence: [entry(:prediction, %{confidence: 0.3, model_trained: true})] + } + } + + # The former placeholder weights would depress this below the boundary. + assert (0.99 * 0.20 + 0.5 * 0.05 + 0.3 * 0.05) / 0.30 < 0.95 + ready = Coordinator.confidence_assessment(input, state()) + assert Coordinator.confidence_ready?(ready.readiness) + assert_in_delta ready.confidence, 0.99, 1.0e-12 + assert Coordinator.raw_strategy(false, ready.confidence) == :auto_execute + + unready = Coordinator.confidence_assessment(input, state(false)) + assert unready.confidence == 0.5 + refute unready.readiness.ready + assert Coordinator.raw_strategy(false, unready.confidence) == :report_only + + # Novelty and the advisory ceiling still take precedence. Do not supply a + # pre-clamped review reply: exercise the actual composition on an auto-shaped + # reply whose local metadata is complete and whose annealing is not clamped. + assert Coordinator.raw_strategy(true, ready.confidence) == :report_only + + rec = + recommendation(%{confidence: ready.confidence, confidence_readiness: ready.readiness}) + + assert {:eliminate, recipe, _} = PatternAnalyzer.apply_neural_recommendation(action(), rec) + assert recipe["confidence"] == 0.94 + assert recipe["neural_prior_confidence"] == 0.99 + assert recipe["neural_confidence_ready"] + end + + test "a ready score inside the former magic band is used for demotion" do + input = %{networks: %{rbf: [entry(:novelty_result, %{similarity: 0.73})]}} + assessment = Coordinator.confidence_assessment(input, state()) + assert Coordinator.confidence_ready?(assessment.readiness) + + rec = + recommendation(%{ + strategy: :review, + confidence: assessment.confidence, + confidence_readiness: assessment.readiness + }) + + assert {:eliminate, recipe, _} = PatternAnalyzer.apply_neural_recommendation(action(), rec) + assert_in_delta recipe["confidence"], 0.73, 1.0e-12 + assert recipe["neural_prior_confidence"] == 0.99 + assert recipe["neural_confidence_ready"] + end + + test "unready scores outside the former band do not imply learning or allow auto execution" do + unready = Coordinator.confidence_assessment(trace(), state(false)).readiness + + for score <- [0.2, 0.99] do + rec = recommendation(%{confidence: score, confidence_readiness: unready}) + assert {:eliminate, recipe, _} = PatternAnalyzer.apply_neural_recommendation(action(), rec) + assert recipe["confidence"] == 0.94 + assert recipe["neural_prior_confidence"] == 0.99 + refute recipe["neural_confidence_ready"] + assert TriangleRouter.dispatch_strategy(recipe["confidence"]) == :review + end + end + + test "missing, legacy or malformed metadata cannot preserve an auto-shaped recommendation" do + metadata = recommendation().confidence_readiness + + invalid = [ + nil, + true, + %{trained: true}, + %{ready: true}, + Map.delete(metadata, :scope), + Map.put(metadata, :scope, :operational_qualification), + Map.put(metadata, :ready, "true"), + Map.put(metadata, :contributing_models, []), + Map.put(metadata, :contributing_models, [:gnn]), + Map.put(metadata, :contributing_models, [:moe, :moe]), + Map.put(metadata, :components, %{rbf: :contributing}), + put_in(metadata.components.gnn, :contributing) + ] + + recs = + [Map.delete(recommendation(), :confidence_readiness)] ++ + Enum.map(invalid, &recommendation(%{confidence_readiness: &1})) + + for rec <- recs do + assert {:eliminate, recipe, _} = PatternAnalyzer.apply_neural_recommendation(action(), rec) + assert recipe["confidence"] == 0.94 + assert recipe["neural_prior_confidence"] == 0.99 + refute recipe["neural_confidence_ready"] + end + end + + test "readiness never promotes a recipe and retains its prior confidence" do + for prior <- [0.70, 0.99] do + assert {:eliminate, recipe, _} = + PatternAnalyzer.apply_neural_recommendation(action(prior), recommendation()) + + assert recipe["confidence"] == min(prior, 0.94) + assert recipe["neural_prior_confidence"] == prior + assert recipe["neural_confidence_ready"] + end + end + + test "novel and report-only refusals survive absent readiness metadata" do + for overrides <- [%{is_novel: true}, %{strategy: :report_only}] do + rec = recommendation(overrides) |> Map.delete(:confidence_readiness) + assert {:control, pattern} = PatternAnalyzer.apply_neural_recommendation(action(), rec) + refute pattern["neural_confidence_ready"] + end + end + + test "unavailable coordinator keeps the dispatch guard's ceiling" do + assert {:eliminate, recipe, _} = + PatternAnalyzer.apply_neural_recommendation(action(), :unavailable) + + assert recipe["confidence"] == 0.94 + assert recipe["neural_prior_confidence"] == 0.99 + assert recipe["neural_dispatch_guard"] == "unavailable" + end +end diff --git a/test/neural_source_store_lifecycle_test.exs b/test/neural_source_store_lifecycle_test.exs index 6beca9fef..138923db5 100644 --- a/test/neural_source_store_lifecycle_test.exs +++ b/test/neural_source_store_lifecycle_test.exs @@ -4,7 +4,14 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do use ExUnit.Case, async: false - alias Hypatia.{FleetDispatcher, LearningScheduler, OutcomeTracker} + alias Hypatia.{ + FleetDispatcher, + LearningScheduler, + OutcomeTracker, + PatternAnalyzer, + TriangleRouter + } + alias Hypatia.Diagnostics.Monitor alias Hypatia.Kin.Gate alias Hypatia.Watcher.AnomalyDetector @@ -16,6 +23,7 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do GraphOfTrust, LiquidStateMachine, Persistence, + RadialNeuralNetwork, SourceStore, SequenceModel, TrainingPipeline @@ -116,13 +124,23 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do {server, _cohort} = coordinator() refute :sys.get_state(server).rbf.trained - assert %{rbf: %{novelty: :untrained, is_novel: true}, is_novel: true} = + assert %{ + rbf: %{novelty: :untrained, is_novel: true}, + is_novel: true, + aggregated_confidence: 0.5, + confidence_readiness: %{scope: :local_training_state, ready: false} = readiness + } = Coordinator.analyze(@finding, server) + assert readiness.contributing_models == [] + assert readiness.components.sequence == :heuristic + assert readiness.components.gnn == :placeholder + assert %{ is_novel: true, strategy: :report_only, raw_strategy: :report_only, + confidence_readiness: %{ready: false}, reason: reason } = Coordinator.dispatch_recommendation(@finding, server) @@ -139,9 +157,17 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do analysis = Coordinator.analyze(@finding, server) assert analysis.rbf.novelty != :untrained assert analysis.is_novel == match?({:novel, _}, analysis.rbf.novelty) + assert Coordinator.confidence_ready?(analysis.confidence_readiness) + assert :rbf in analysis.confidence_readiness.contributing_models + assert :esn in analysis.confidence_readiness.contributing_models + refute :lsm in analysis.confidence_readiness.contributing_models + refute :gnn in analysis.confidence_readiness.contributing_models + refute :vae in analysis.confidence_readiness.contributing_models + refute :sequence in analysis.confidence_readiness.contributing_models rec = Coordinator.dispatch_recommendation(@finding, server) refute rec.reason =~ "untrained" + assert Coordinator.confidence_ready?(rec.confidence_readiness) end test "an actual ready cohort can analyze, train and persist its own source", ctx do @@ -171,6 +197,64 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do refute File.exists?(Path.join(ctx.second, "neural-states")) end + test "a mature recipe and high learned similarity remain advisory through actual composition", + ctx do + write_training_store(ctx.first) + {server, _cohort} = coordinator() + + # Fit the real RBF on a bounded synthetic fixture at this finding. The + # resulting similarity is high, but is not a calibration/evaluation receipt. + vector = RadialNeuralNetwork.finding_to_vector(@finding) + + rbf = + RadialNeuralNetwork.init(num_centers: 1) + |> RadialNeuralNetwork.train(List.duplicate(vector, 5), List.duplicate(1.0, 5)) + + assert rbf.trained + :sys.replace_state(server, fn state -> %{state | rbf: rbf} end) + + # Confirm this is the boundary where the existing maturity gate alone + # would permit auto execution; do not manufacture a pre-clamped reply. + assert OutcomeTracker.annealed_strategy_from_store( + @finding["recipe_id"], + :auto_execute, + ctx.first + ) == :auto_execute + + rec = Coordinator.dispatch_recommendation(@finding, server) + assert_in_delta rec.confidence, 1.0, 1.0e-12 + assert rec.raw_strategy == :auto_execute + assert rec.strategy == :review + assert rec.advisory_clamped + refute rec.annealing_clamped + assert rec.confidence_readiness.contributing_models == [:rbf] + assert rec.reason =~ "local training state is advisory" + + action = {:eliminate, %{"id" => @finding["recipe_id"], "confidence" => 0.99}, @finding} + + # The consumer independently retains the ceiling even if a legacy or + # relabelled reply tries to turn the honest raw strategy into authority. + for recommendation <- [rec, %{rec | strategy: :auto_execute, advisory_clamped: false}] do + assert {:eliminate, recipe, _} = + PatternAnalyzer.apply_neural_recommendation(action, recommendation) + + assert recipe["confidence"] == 0.94 + assert recipe["neural_prior_confidence"] == 0.99 + assert recipe["neural_confidence_ready"] + assert TriangleRouter.dispatch_strategy(recipe["confidence"]) == :review + end + + # A missing maturity history still restricts further. Its clamp remains + # distinguishable from the independent advisory ceiling. + File.write!(Path.join([ctx.first, "outcomes", "fixture.jsonl"]), "") + immature = Coordinator.dispatch_recommendation(@finding, server) + assert immature.raw_strategy == :auto_execute + assert immature.strategy == :report_only + assert immature.advisory_clamped + assert immature.annealing_clamped + assert {:control, _} = PatternAnalyzer.apply_neural_recommendation(action, immature) + end + # E0-23: the autoencoder encodes nothing yet (an all-zero latent, cluster 0). Its # result says so, and the coordinator gives it no weight in the derived confidence. test "the autoencoder's result is marked as a placeholder", ctx do @@ -424,6 +508,14 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do assert :sys.get_state(restored).rbf.trained assert :sys.get_state(restored).rbf.output_weights == bound["output_weights"] + restored_readiness = Coordinator.analyze(@finding, restored).confidence_readiness + assert Coordinator.confidence_ready?(restored_readiness) + assert :rbf in restored_readiness.contributing_models + # ESN/LSM snapshots are summaries; a restart still leaves their actual + # local readouts cold. A saved "trained" flag is not their runtime state. + refute :esn in restored_readiness.contributing_models + refute :lsm in restored_readiness.contributing_models + for diagnostic <- [ Map.drop(bound, ["source_schema", "source_store", "source_status"]), Map.put(bound, "source_store", ctx.second), @@ -434,6 +526,7 @@ defmodule Hypatia.Neural.SourceStoreLifecycleTest do bytes = File.read!(path) {cold, _cohort} = coordinator() refute :sys.get_state(cold).rbf.trained + refute Coordinator.analyze(@finding, cold).confidence_readiness.ready assert {:ok, ^diagnostic} = Persistence.load_all(ctx.first).rbf assert File.read!(path) == bytes end diff --git a/test/placeholder_network_test.exs b/test/placeholder_network_test.exs index c763f209c..964e0ab7c 100644 --- a/test/placeholder_network_test.exs +++ b/test/placeholder_network_test.exs @@ -3,70 +3,57 @@ defmodule Hypatia.PlaceholderNetworkTest do @moduledoc """ - E0-23: a network that returns a fixed placeholder adds nothing to the derived - confidence, and its result says that it is a placeholder (design of 2026-11-14 on - merge honesty, decision 4). The autoencoder encodes nothing yet: its latent vector is - all zeros and its cluster is always 0, and the coordinator used to weigh that at 0.05. - The mark on the result is `placeholder: true`; the end-to-end check is in - `neural_source_store_lifecycle_test.exs`. + NS-03 extends E0-23: current GNN/VAE placeholders and the sequence + last-observation heuristic have no confidence weight. Trace labels alone + cannot establish that a model has learned. Real cohort checks also live in + neural_source_store_lifecycle_test.exs. """ use ExUnit.Case, async: true alias Hypatia.Neural.Coordinator - # A reasoning trace, in the shape the coordinator reads: networks -> entries. defp entry(key, value), do: %{key: key, value: value} defp trace(extra) do base = %{ - moe: [entry(:domain_confidence, %{confidence: 0.80})], - rbf: [entry(:novelty_result, %{similarity: 0.70})], - lsm: [entry(:temporal_result, %{score: 0.60})], - esn: [entry(:trajectory_result, %{predicted_next: 0.65})], - gnn: [entry(:graph_metrics, %{interaction_strength: 0.5})], - sequence: [entry(:prediction, %{confidence: 0.3})] + moe: [entry(:domain_confidence, %{confidence: 0.99, trained: true})], + rbf: [entry(:novelty_result, %{similarity: 0.99, trained: true})], + lsm: [entry(:temporal_result, %{score: 0.99, status: :trained})], + esn: [entry(:trajectory_result, %{predicted_next: 0.99, trained: true})] } %{networks: Map.merge(base, extra)} end - defp vae(fields), - do: %{vae: [entry(:interpretation, Map.merge(%{cluster_id: 0, latent: [0.0]}, fields))]} - - test "a placeholder autoencoder changes nothing in the derived confidence of 1 finding" do - without = Coordinator.derive_confidence(trace(%{})) - placeholder = Coordinator.derive_confidence(trace(vae(%{placeholder: true}))) - - assert placeholder == without + test "a legacy trace with no actual component state is unqualified at every score" do + assert Coordinator.derive_confidence(trace(%{})) == 0.5 + assert Coordinator.derive_confidence(%{networks: %{}}) == 0.5 end - test "the same holds whatever the placeholder's cluster would have been worth" do - without = Coordinator.derive_confidence(trace(%{})) + test "placeholder and heuristic labels cannot alter an unqualified aggregate" do + for placeholder <- [true, false, nil], score <- [0.0, 0.3, 0.99, 1.0] do + extra = %{ + gnn: [entry(:graph_metrics, %{interaction_strength: score, placeholder: placeholder})], + vae: [entry(:interpretation, %{cluster_id: 7, placeholder: placeholder})], + sequence: [entry(:prediction, %{confidence: score, model_trained: true})] + } - for cluster_id <- [0, 1, 7, nil] do - assert Coordinator.derive_confidence( - trace(vae(%{placeholder: true, cluster_id: cluster_id})) - ) == without + assert Coordinator.derive_confidence(trace(extra)) == 0.5 end end - test "an autoencoder that is not marked as a placeholder still counts, at its weight" do - without = Coordinator.derive_confidence(trace(%{})) - counted = Coordinator.derive_confidence(trace(vae(%{placeholder: false}))) - - assert counted != without - - # cluster 0 is worth 0.6 at weight 0.05; the others weigh 0.35 + 0.20 + 0.15 + 0.15 + 0.05 + 0.05. - expected = - (0.80 * 0.35 + 0.70 * 0.20 + 0.60 * 0.15 + 0.65 * 0.15 + 0.5 * 0.05 + 0.3 * 0.05 + - 0.6 * 0.05) / - 1.0 - - assert_in_delta counted, expected, 1.0e-9 - end - - test "an autoencoder result with no mark is not mistaken for a placeholder" do - assert Coordinator.derive_confidence(trace(vae(%{}))) != - Coordinator.derive_confidence(trace(%{})) + test "a placeholder-only or heuristic-only trace cannot supply learned confidence" do + traces = [ + %{gnn: [entry(:graph_metrics, %{interaction_strength: 1.0, placeholder: false})]}, + %{vae: [entry(:interpretation, %{cluster_id: 0, placeholder: false})]}, + %{sequence: [entry(:prediction, %{confidence: 1.0, model_trained: true})]}, + %{other_network: [entry(:domain_confidence, %{confidence: 1.0, trained: true})]} + ] + + for networks <- traces do + confidence = Coordinator.derive_confidence(%{networks: networks}) + assert confidence == 0.5 + assert Coordinator.raw_strategy(false, confidence) == :report_only + end end end