core/tests/test_teaching_grounding.py
Shay 51aad0c2cd feat(adr-0065): OOV cliff → five-tier honesty gradient (Phase 2.1 + 2.2)
Replaces the flat "I don't know — insufficient grounding" disclosure
with a deterministic gradient that names specific vocabulary gaps
and gives operators concrete next steps.

P2.1 — OOV "teach me" surface (chat/oov_surface.py).

  When the intent classifier extracts a clean subject lemma but that
  lemma is not resident in any mounted lexicon pack, the runtime now
  emits a deterministic learning-invitation surface tagged
  ``grounding_source="oov"`` instead of the universal disclosure.

  Surface format (fixed template):

    "I haven't learned '{token}' yet (intent: {intent}).
     Mounted lexicon packs: {pack_list}.
     Teach me via a reviewed PackMutationProposal."

  The OOV token passes through ``core._safe_display.safe_display``
  before persistence — user-input sanitization at the trust boundary.
  No vocabulary is invented; no domain is inferred.  Honours the
  ADR-0027 proposal-only invariant: the surface invites a reviewed
  pack mutation, never silently mutates any pack.

  Refactored ``_maybe_pack_grounded_surface`` so every existing
  intent branch (COMPARISON / CAUSE / VERIFICATION / CORRECTION /
  PROCEDURE / DEFINITION+RECALL) falls through on a None composer
  result instead of early-returning.  The OOV invitation is the
  deterministic fall-through for any clean-subject prompt whose
  subject doesn't resolve.

P2.2 — Partial-grounding tier (chat/partial_surface.py).

  When exactly one of two COMPARISON lemmas resolves, the runtime
  emits a hedged surface that grounds the known side verbatim and
  disclaims the OOV side explicitly:

    "Whatever '{oov}' is, I can ground '{known}' — pack-grounded
     ({pack_id}): {d1}; {d2}.  I cannot ground the comparison
     without learning '{oov}' — teach me via a reviewed
     PackMutationProposal."

  Tagged ``grounding_source="partial"``.  Falls through to OOV
  invitation when both lemmas are OOV, and to full pack-grounded
  COMPARISON when both resolve — partial is the middle tier in the
  five-tier gradient.

  Also normalises trailing sentence punctuation on
  intent.secondary_subject at the COMPARISON boundary so prompts
  like "Compare A and B." (with the period) still resolve B
  correctly.

Five-tier gradient (vault → teaching → pack → partial → oov → none).

Test debt retired: four pre-existing tests asserted "OOV → universal
disclosure", which is exactly the contract P2.1/P2.2 inverted.
Rewritten to the new contract.  Plus test_procedure_surface.py
gained a test for the OOV gradient on procedure intents.

Verification:
  tests/test_oov_surface.py                       22 passed
  tests/test_partial_surface.py                   16 passed
  Cognition eval byte-identical:
    public  100% / 100% / 91.7% / 100%
    holdout 100% / 100% / 83.3% / 100%
  Curated lanes all green.
2026-05-18 16:41:45 -07:00

220 lines
8.3 KiB
Python

"""ADR-0052 — teaching-grounded CAUSE / VERIFICATION surface tests.
Contract pinned here:
- ``teaching_grounded_surface(lemma, intent_tag)`` returns a
deterministic surface composed of the subject lemma + its pack
``semantic_domains``, a fixed connective predicate, the object
lemma, and its pack ``semantic_domains``. No synthesis.
- Returns ``None`` when:
* the lemma is empty or absent from the corpus,
* the intent is not ``CAUSE`` or ``VERIFICATION``,
* the chain references lemmas missing from the ratified pack.
- The runtime wiring engages only when:
* the gate fires with ``source="empty_vault"``,
* ``output_language == "en"``,
* intent is ``CAUSE`` or ``VERIFICATION``,
* the subject lemma has a reviewed chain.
- ``ChatResponse.grounding_source`` and ``TurnEvent.grounding_source``
both carry ``"teaching"`` on this branch.
- Refusal still takes priority — teaching-grounded surfaces never
bypass safety / ethics verdict refusal.
"""
from __future__ import annotations
import pytest
from chat.pack_grounding import PACK_ID, _pack_index
from chat.runtime import ChatRuntime, _UNKNOWN_DOMAIN_SURFACE
from chat.teaching_grounding import (
TEACHING_CORPUS_ID,
has_teaching_chain,
teaching_grounded_surface,
)
from generate.intent import IntentTag
# ---------------------------------------------------------------------------
# teaching_grounded_surface — pure-function contracts
# ---------------------------------------------------------------------------
def test_cause_light_chain_produces_surface() -> None:
surface = teaching_grounded_surface("light", IntentTag.CAUSE)
assert surface is not None
assert "light" in surface
assert "truth" in surface
assert "reveals" in surface
assert TEACHING_CORPUS_ID in surface
assert "teaching-grounded" in surface
assert "No session evidence yet." in surface
def test_cause_knowledge_chain_produces_surface() -> None:
surface = teaching_grounded_surface("knowledge", IntentTag.CAUSE)
assert surface is not None
assert "knowledge" in surface
assert "evidence" in surface
assert "requires" in surface
def test_verification_memory_chain_produces_surface() -> None:
surface = teaching_grounded_surface("memory", IntentTag.VERIFICATION)
assert surface is not None
assert "memory" in surface
assert "recall" in surface
assert "requires" in surface
def test_lemma_absent_from_corpus_returns_none() -> None:
assert teaching_grounded_surface("dragon", IntentTag.CAUSE) is None
def test_subject_in_corpus_wrong_intent_returns_none() -> None:
"""``memory`` has a VERIFICATION chain but not a CAUSE chain."""
assert teaching_grounded_surface("memory", IntentTag.CAUSE) is None
def test_definition_intent_returns_none() -> None:
"""Teaching grounding is scoped to CAUSE / VERIFICATION only."""
assert teaching_grounded_surface("light", IntentTag.DEFINITION) is None
assert teaching_grounded_surface("light", IntentTag.RECALL) is None
assert teaching_grounded_surface("light", IntentTag.COMPARISON) is None
assert teaching_grounded_surface("light", IntentTag.UNKNOWN) is None
@pytest.mark.parametrize("bad", ["", " ", None])
def test_empty_or_invalid_lemma_returns_none(bad) -> None:
assert teaching_grounded_surface(bad, IntentTag.CAUSE) is None # type: ignore[arg-type]
def test_surface_is_deterministic() -> None:
"""Same input must produce byte-identical surface on repeat."""
a = teaching_grounded_surface("memory", IntentTag.VERIFICATION)
b = teaching_grounded_surface("memory", IntentTag.VERIFICATION)
assert a == b
assert a is not None
def test_case_insensitive_lookup() -> None:
a = teaching_grounded_surface("LIGHT", IntentTag.CAUSE)
b = teaching_grounded_surface("light", IntentTag.CAUSE)
assert a == b
assert a is not None
def test_has_teaching_chain_helper() -> None:
assert has_teaching_chain("light", IntentTag.CAUSE) is True
assert has_teaching_chain("knowledge", IntentTag.CAUSE) is True
assert has_teaching_chain("memory", IntentTag.VERIFICATION) is True
assert has_teaching_chain("memory", IntentTag.CAUSE) is False
assert has_teaching_chain("dragon", IntentTag.CAUSE) is False
assert has_teaching_chain("light", IntentTag.DEFINITION) is False
assert has_teaching_chain("", IntentTag.CAUSE) is False
# ---------------------------------------------------------------------------
# Doctrine — every atom verbatim from pack or fixed template
# ---------------------------------------------------------------------------
def test_surface_atoms_are_verbatim_from_pack() -> None:
"""Every visible non-template descriptor must be a verbatim
``semantic_domains`` string from the ratified pack — no rewording."""
surface = teaching_grounded_surface("knowledge", IntentTag.CAUSE)
assert surface is not None
index = _pack_index()
# Subject domains (first 2 by corpus config)
for domain in index["knowledge"][:2]:
assert domain in surface
# Object domain (first 1)
for domain in index["evidence"][:1]:
assert domain in surface
# Fixed-template tokens
assert "teaching-grounded" in surface
assert "No session evidence yet." in surface
def test_surface_does_not_invent_packless_descriptors() -> None:
"""Sanity: no fabricated cognition.* domain that isn't in the pack."""
surface = teaching_grounded_surface("memory", IntentTag.VERIFICATION)
assert surface is not None
index = _pack_index()
all_pack_domains: set[str] = set()
for domains in index.values():
all_pack_domains.update(domains)
# Every "<word>.<word>" looking descriptor in the surface must be a
# real pack domain. Crude but effective at catching fabrication.
import re
for match in re.findall(r"\b[a-z]+\.[a-z]+\b", surface):
assert match in all_pack_domains, f"non-pack descriptor: {match}"
# ---------------------------------------------------------------------------
# ChatRuntime integration — cold-start CAUSE / VERIFICATION path
# ---------------------------------------------------------------------------
def test_cold_start_cause_light_returns_teaching_surface() -> None:
rt = ChatRuntime()
resp = rt.chat("Why does light exist?")
assert resp.grounding_source == "teaching"
assert "light" in resp.surface
assert "truth" in resp.surface
assert "teaching-grounded" in resp.surface
def test_cold_start_cause_knowledge_returns_teaching_surface() -> None:
rt = ChatRuntime()
resp = rt.chat("Why does knowledge require evidence?")
assert resp.grounding_source == "teaching"
assert "knowledge" in resp.surface
assert "evidence" in resp.surface
def test_cold_start_verification_memory_returns_teaching_surface() -> None:
rt = ChatRuntime()
resp = rt.chat("Does memory require recall?")
assert resp.grounding_source == "teaching"
assert "memory" in resp.surface
assert "recall" in resp.surface
def test_cold_start_cause_unknown_subject_routes_to_oov_invitation() -> None:
"""ADR-0065 / P2.1 — CAUSE on an OOV subject routes through the
OOV invitation surface (subject is OOV → no chain → fall-through
to OOV). Pre-P2.1 this returned the universal disclosure."""
rt = ChatRuntime()
resp = rt.chat("Why does dragon exist?")
assert resp.grounding_source == "oov"
assert "dragon" in resp.surface
def test_turn_event_carries_grounding_source_teaching() -> None:
rt = ChatRuntime()
rt.chat("Why does light exist?")
last_event = rt.turn_log[-1]
assert getattr(last_event, "grounding_source", None) == "teaching"
def test_teaching_grounded_passes_verdict_audit() -> None:
rt = ChatRuntime()
resp = rt.chat("Why does light exist?")
assert resp.safety_verdict is not None
assert resp.ethics_verdict is not None
def test_definition_path_still_returns_pack_source() -> None:
"""Regression: DEFINITION still routes to pack, not teaching."""
rt = ChatRuntime()
resp = rt.chat("What is light?")
assert resp.grounding_source == "pack"
assert PACK_ID in resp.surface
def test_comparison_path_still_returns_pack_source() -> None:
"""Regression: COMPARISON still routes to pack, not teaching."""
rt = ChatRuntime()
resp = rt.chat("Compare memory and recall")
assert resp.grounding_source == "pack"