"""M20 Knowledge Oracle lab for Project P06. Uses synthetic data and runs offline.""" import argparse from datetime import date import json from pathlib import Path import re AS_OF = date(2026, 6, 1) DEFAULT_BUDGET = 600 TOPICS = ("mural booking", "archive badge", "kiln training", "equipment roster") NO_ANSWER = "I can't verify an answer from the available sources." CASES = { "supported": ("What is the mural booking deadline?", "north", 600, False), "unsupported": ("Where is the astronomy guide?", "north", 600, False), "restricted": ("Where is the equipment roster?", "north", 600, False), "stale-only": ("When is kiln training?", "north", 600, False), "conflict": ("Where do I collect an archive badge?", "north", 600, False), "budget": ("What is the mural booking deadline?", "north", 120, False), "budget-conflict": ("Where do I collect an archive badge?", "north", 190, False), "citation-fault": ("What is the mural booking deadline?", "north", 600, True), "south-supported": ("What is the mural booking deadline?", "south", 600, False), } def words(text): return set(re.findall(r"[a-z0-9]+", text.lower())) def load_corpus(): """Read the synthetic workshop corpus shipped with the lab.""" return json.loads(Path(__file__).with_name("corpus.json").read_text(encoding="utf-8")) def retrieve(corpus, question_words, topic, tenant, as_of): """Filter by tenant and validity before lexical ranking.""" eligible = [ row for row in corpus if row["tenant"] == tenant and date.fromisoformat(row["valid_from"]) <= as_of < date.fromisoformat(row["valid_until"]) ] ranked = [] for row in eligible: if row["topic"] == topic: score = len(question_words & words(row["text"])) if score: ranked.append((score, row)) ranked.sort(key=lambda result: (-result[0], result[1]["citation"])) return [ {"citation": row["citation"], "excerpt": row["text"], "fact": row["fact"]} for _, row in ranked ] def compose_fact(policy, *, simulate_bad_citation): """Model stand-in. Copies a pre-reviewed fact without reading passage text.""" citation = policy["citation"] if simulate_bad_citation: citation = "mural-studio@1#notice" # Intentional composition bug. return {"fact": policy["fact"], "citation": citation} def ask(corpus, question, *, tenant, as_of=AS_OF, budget=DEFAULT_BUDGET, simulate_bad_citation=False): """Return a public result and a teaching trace scoped to authorized rows.""" trace = { "retrieved": [], "in_context": [], "packet_chars": 0, "budget_chars": budget, "draft_citation": None, "reason": None, } result = {"answer": NO_ANSWER, "citations": [], "trace": trace} query_words = words(question) topics = [topic for topic in TOPICS if words(topic) <= query_words] if len(topics) != 1: trace["reason"] = "unsupported_or_ambiguous_topic" return result candidates = retrieve(corpus, query_words, topics[0], tenant, as_of) trace["retrieved"] = [item["citation"] for item in candidates] if not candidates: trace["reason"] = "no_eligible_evidence" return result packet = json.dumps(candidates, ensure_ascii=False, separators=(",", ":")) trace["packet_chars"] = len(packet) if len(packet) > budget: # A clipped set could hide a conflicting policy. Decline the whole packet. trace["reason"] = "context_budget" return result trace["in_context"] = [item["citation"] for item in candidates] policies = [item for item in candidates if item["fact"] is not None] if not policies: trace["reason"] = "no_policy_fact" return result if len({item["fact"] for item in policies}) > 1: trace["reason"] = "conflicting_policy" return result draft = compose_fact(policies[0], simulate_bad_citation=simulate_bad_citation) trace["draft_citation"] = draft["citation"] cited = next((item for item in candidates if item["citation"] == draft["citation"]), None) if cited is None or cited["fact"] != draft["fact"]: trace["reason"] = "invalid_draft_citation" return result trace["reason"] = "grounded_fact" return {"answer": draft["fact"], "citations": [cited["citation"]], "trace": trace} def run_case(corpus, name): question, tenant, budget, fault = CASES[name] return ask(corpus, question, tenant=tenant, budget=budget, simulate_bad_citation=fault) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--case", choices=CASES, default="supported") args = parser.parse_args() print(json.dumps(run_case(load_corpus(), args.case), indent=2)) if __name__ == "__main__": main()