# -*- coding: utf-8 -*- """Adaptive study-design contracts shared by SmartPaper quantitative/qualitative paths. The LLM may propose a candidate design, but this module owns deterministic normalization, identity, validation, and scope semantics. It deliberately contains no provider/model routing logic. """ from __future__ import annotations import hashlib import json import re from typing import Any STUDY_DESIGN_CONTRACT_VERSION = "smartpaper-adaptive-study-design-contract-v1" _QUANT_ROLES = {"predictor", "mediator", "moderator", "outcome", "control", "covariate"} _QUANT_RELATIONS = {"direct_association", "moderation", "control_effect"} _QUAL_SOURCE_FAMILIES = { "interview", "focus_group", "observation", "document", "log", "artifact", "digital_trace", "field_note", "other", } def _clean(value: Any, maximum: int = 240) -> str: text = re.sub(r"\s+", " ", str(value or "")).strip(" \t\r\n,;:.-") return text[:maximum] def _keywords(value: Any) -> list[str]: raw = value if isinstance(value, (list, tuple)) else re.split(r"[,;\n|]+", str(value or "")) out: list[str] = [] seen: set[str] = set() for item in raw: text = _clean(item, 100) key = text.casefold() if text and key not in seen: out.append(text) seen.add(key) return out[:16] def _stable_hash(payload: dict[str, Any]) -> str: encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") return hashlib.sha256(encoded).hexdigest() def _finalize(contract: dict[str, Any]) -> dict[str, Any]: value = dict(contract) value.pop("contract_sha256", None) value.pop("contract_id", None) digest = _stable_hash(value) value["contract_id"] = digest[:20] value["contract_sha256"] = digest return value def _normalize_quant_relation_type(value: Any) -> str: text = _clean(value, 80).casefold().replace("-", "_").replace(" ", "_") aliases = { "association": "direct_association", "direct": "direct_association", "direct_effect": "direct_association", "direct_association": "direct_association", "path": "direct_association", "mediation_path": "direct_association", "moderator": "moderation", "moderation": "moderation", "interaction": "moderation", "interaction_effect": "moderation", "control": "control_effect", "control_effect": "control_effect", } return aliases.get(text, text) def _normalize_roles(value: Any) -> list[str]: raw = value if isinstance(value, (list, tuple)) else [value] out: list[str] = [] for item in raw: role = _clean(item, 40).casefold().replace(" ", "_") if role in _QUANT_ROLES and role not in out: out.append(role) return out def _legacy_quant_candidate(constructs: list[str], context: str = "") -> dict[str, Any]: values = [_clean(item, 80) for item in constructs if _clean(item, 80)] if len(values) != 3: values = ["Focal Predictor", "Focal Mediator", "Focal Outcome"] p, m, o = values return { "constructs": [ {"label": p, "roles": ["predictor"]}, {"label": m, "roles": ["mediator"]}, {"label": o, "roles": ["outcome"]}, ], "relations": [ {"source": p, "target": o, "type": "direct_association", "hypothesis_order": 1}, {"source": p, "target": m, "type": "direct_association", "hypothesis_order": 2}, {"source": m, "target": o, "type": "direct_association", "hypothesis_order": 3}, ], "indirect_effects": [{"path": [p, m, o], "kind": "simple", "numbered_hypothesis": False}], "research_context": context, "background_concepts": [], } def build_quantitative_contract( topic: str, keywords: Any, candidate: Any, *, source_type: str = "system_generated", policy_version: str = "adaptive-quantitative-v1", ) -> dict[str, Any]: """Normalize a model-proposed quantitative graph into deterministic authority.""" raw = dict(candidate or {}) if isinstance(candidate, dict) else {} raw_constructs = raw.get("constructs") or [] if raw_constructs and all(not isinstance(item, dict) for item in raw_constructs): raw = _legacy_quant_candidate(list(raw_constructs), _clean(raw.get("research_context"))) raw_constructs = raw["constructs"] constructs: list[dict[str, Any]] = [] label_to_id: dict[str, str] = {} for item in raw_constructs[:8]: if not isinstance(item, dict): continue label = _clean(item.get("label") or item.get("name"), 80) if not label or label.casefold() in label_to_id: continue roles = _normalize_roles(item.get("roles") or item.get("role")) if not roles: continue cid = f"C{len(constructs) + 1:03d}" row = { "construct_id": cid, "label": label, "roles": roles, "measurement_model": _clean(item.get("measurement_model") or "reflective", 40).casefold() or "reflective", "measurement_allowed": bool(item.get("measurement_allowed", True)), } constructs.append(row) label_to_id[label.casefold()] = cid # Safe compatibility fallback; importantly this is a fallback, not the normal schema. if len(constructs) < 2: raw = _legacy_quant_candidate(["Focal Predictor", "Focal Mediator", "Focal Outcome"], _clean(raw.get("research_context"))) return build_quantitative_contract(topic, keywords, raw, source_type=source_type, policy_version=policy_version) by_id = {row["construct_id"]: row for row in constructs} def resolve(ref: Any) -> str: text = _clean(ref, 80) if text in by_id: return text return label_to_id.get(text.casefold(), "") relations: list[dict[str, Any]] = [] rejected: list[dict[str, Any]] = [] for item in (raw.get("relations") or [])[:24]: if not isinstance(item, dict): continue rtype = _normalize_quant_relation_type(item.get("type")) source = resolve(item.get("source")) target = resolve(item.get("target")) moderator = resolve(item.get("moderator")) if item.get("moderator") else "" if rtype not in _QUANT_RELATIONS or not source or not target or source == target: rejected.append({"reason": "invalid_or_unsupported_relation", "raw": {k: item.get(k) for k in ("type", "source", "target", "moderator")}}) continue if rtype == "moderation" and (not moderator or moderator in {source, target}): rejected.append({"reason": "moderation_requires_distinct_moderator", "raw": {k: item.get(k) for k in ("type", "source", "target", "moderator")}}) continue relation = { "relation_id": f"R{len(relations) + 1:03d}", "type": rtype, "source": source, "target": target, "moderator": moderator or None, "analysis_target": bool(item.get("analysis_target", True)), "numbered_hypothesis": bool(item.get("numbered_hypothesis", rtype != "control_effect")), } try: relation["hypothesis_order"] = int(item.get("hypothesis_order")) if item.get("hypothesis_order") is not None else None except Exception: relation["hypothesis_order"] = None relations.append(relation) # If the interpreter omitted relations but roles make a parsimonious graph unambiguous, # compile a safe role-derived graph rather than silently returning an empty model. if not relations: predictors = [x["construct_id"] for x in constructs if "predictor" in x["roles"]] mediators = [x["construct_id"] for x in constructs if "mediator" in x["roles"]] outcomes = [x["construct_id"] for x in constructs if "outcome" in x["roles"]] moderators = [x["construct_id"] for x in constructs if "moderator" in x["roles"]] if predictors and outcomes: p, o = predictors[0], outcomes[0] if mediators: m = mediators[0] relations.extend([ {"relation_id":"R001","type":"direct_association","source":p,"target":o,"moderator":None,"analysis_target":True,"numbered_hypothesis":True,"hypothesis_order":1}, {"relation_id":"R002","type":"direct_association","source":p,"target":m,"moderator":None,"analysis_target":True,"numbered_hypothesis":True,"hypothesis_order":2}, {"relation_id":"R003","type":"direct_association","source":m,"target":o,"moderator":None,"analysis_target":True,"numbered_hypothesis":True,"hypothesis_order":3}, ]) else: relations.append({"relation_id":"R001","type":"direct_association","source":p,"target":o,"moderator":None,"analysis_target":True,"numbered_hypothesis":True,"hypothesis_order":1}) if moderators: relations.append({"relation_id":f"R{len(relations)+1:03d}","type":"moderation","source":p,"target":o,"moderator":moderators[0],"analysis_target":True,"numbered_hypothesis":True,"hypothesis_order":len(relations)+1}) direct_pairs = {(r["source"], r["target"]): r["relation_id"] for r in relations if r["type"] == "direct_association"} indirect_effects: list[dict[str, Any]] = [] raw_indirect = raw.get("indirect_effects") or [] for item in raw_indirect[:12]: if not isinstance(item, dict): continue path = [resolve(x) for x in (item.get("path") or [])] path = [x for x in path if x] if len(path) < 3 or any((a, b) not in direct_pairs for a, b in zip(path, path[1:])): rejected.append({"reason":"invalid_indirect_path","raw":{"path": item.get("path")}}) continue indirect_effects.append({ "effect_id": f"I{len(indirect_effects)+1:03d}", "path": path, "kind": _clean(item.get("kind") or ("simple" if len(path)==3 else "serial"), 30).casefold(), "numbered_hypothesis": bool(item.get("numbered_hypothesis", False)), }) if not indirect_effects: # Infer valid mediator chains from role identity and existing path edges. predictors = [x["construct_id"] for x in constructs if "predictor" in x["roles"]] mediators = [x["construct_id"] for x in constructs if "mediator" in x["roles"]] outcomes = [x["construct_id"] for x in constructs if "outcome" in x["roles"]] for p in predictors: for m in mediators: for o in outcomes: if (p, m) in direct_pairs and (m, o) in direct_pairs: indirect_effects.append({"effect_id":f"I{len(indirect_effects)+1:03d}","path":[p,m,o],"kind":"simple","numbered_hypothesis":False}) controls = [x["construct_id"] for x in constructs if set(x["roles"]) & {"control", "covariate"}] outcomes = [x["construct_id"] for x in constructs if "outcome" in x["roles"]] if not outcomes: targeted = {r["target"] for r in relations if r["type"] != "control_effect"} outcomes = sorted(targeted) analysis_plan = ["measurement_assessment"] if any(r["type"] == "direct_association" for r in relations): analysis_plan.append("direct_association") if indirect_effects: analysis_plan.append("indirect_effect") if any(r["type"] == "moderation" for r in relations): analysis_plan.extend(["interaction_test", "simple_slopes"]) analysis_plan.append("robustness") # Legacy profile is used only to preserve exact prior H ordering and validators. role_map = {role: [x for x in constructs if role in x["roles"]] for role in ("predictor","mediator","outcome")} legacy_profile = ( len(constructs) == 3 and all(len(role_map[r]) == 1 for r in role_map) and not any("moderator" in x["roles"] or set(x["roles"]) & {"control","covariate"} for x in constructs) and len([r for r in relations if r["type"] == "direct_association"]) == 3 ) unsupported = _keywords(raw.get("background_concepts") or raw.get("unsupported_seed_concepts") or []) context = _clean(raw.get("research_context") or "respondents with experience relevant to the focal management phenomenon", 240) contract = { "version": STUDY_DESIGN_CONTRACT_VERSION, "mode": "quantitative", "source_type": _clean(source_type, 40) or "system_generated", "source_topic": _clean(topic, 500), "source_keywords": _keywords(keywords), "research_problem": _clean(raw.get("research_problem"), 500), "research_questions": _keywords(raw.get("research_questions") or []), "design_family": "cross_sectional_observational_survey", "evidence_strength": { "causal_identification": False, "allowed_inference": ["association", "estimated_indirect_association", "interaction_association"], "forbidden_inference": ["causal_effect", "causal_mediation_identification"], }, "context": {"research_context": context}, "quantitative": { "constructs": constructs, "relations": relations, "indirect_effects": indirect_effects, "controls": controls, "outcomes": outcomes, "analysis_plan": analysis_plan, "legacy_three_construct_profile": legacy_profile, }, "qualitative": None, "unsupported_seed_concepts": unsupported, "compiler_decisions": rejected, "policy_version": policy_version, } return _finalize(contract) def validate_quantitative_contract(contract: dict[str, Any]) -> list[str]: issues: list[str] = [] record = dict(contract or {}) if record.get("version") != STUDY_DESIGN_CONTRACT_VERSION or record.get("mode") != "quantitative": return ["invalid_contract_identity"] quant = dict(record.get("quantitative") or {}) constructs = [x for x in (quant.get("constructs") or []) if isinstance(x, dict)] ids = {x.get("construct_id") for x in constructs} if len(ids) != len(constructs) or len(constructs) < 2: issues.append("invalid_construct_identity") for r in quant.get("relations") or []: if not isinstance(r, dict): issues.append("invalid_relation_record"); continue if r.get("source") not in ids or r.get("target") not in ids: issues.append("relation_references_unknown_construct") if r.get("type") == "moderation" and r.get("moderator") not in ids: issues.append("moderation_references_unknown_moderator") return list(dict.fromkeys(issues)) def compile_quantitative_hypothesis_ledger(contract: dict[str, Any], *, version: str) -> dict[str, Any]: quant = dict((contract or {}).get("quantitative") or {}) constructs = {x.get("construct_id"): x for x in (quant.get("constructs") or []) if isinstance(x, dict)} rels = [dict(r) for r in (quant.get("relations") or []) if isinstance(r, dict) and r.get("numbered_hypothesis")] rels.sort(key=lambda r: (r.get("hypothesis_order") is None, r.get("hypothesis_order") or 999, r.get("relation_id") or "")) items: list[dict[str, Any]] = [] for r in rels: source = constructs.get(r.get("source"), {}).get("label") target = constructs.get(r.get("target"), {}).get("label") moderator = constructs.get(r.get("moderator"), {}).get("label") if r.get("moderator") else None if not source or not target: continue row = { "hypothesis_id": f"H{len(items)+1}", "predictor": source, "outcome": target, "relation": "moderation" if r.get("type") == "moderation" else "association", "relation_id": r.get("relation_id"), } if moderator: row["moderator"] = moderator items.append(row) indirect_rows = [] for effect in quant.get("indirect_effects") or []: if not isinstance(effect, dict): continue labels = [constructs.get(cid, {}).get("label") for cid in effect.get("path") or []] labels = [x for x in labels if x] if len(labels) >= 3: indirect_rows.append({ "effect_id": effect.get("effect_id"), "path": labels, "predictor": labels[0], "mediator": " -> ".join(labels[1:-1]), "outcome": labels[-1], "numbered_hypothesis": bool(effect.get("numbered_hypothesis", False)), "relation": "estimated_indirect_association", }) ledger = {"version": version, "items": items, "indirect_analyses": indirect_rows} # Exact compatibility key for the historical single-mediator profile. if len(indirect_rows) == 1 and len(indirect_rows[0].get("path") or []) == 3: p = indirect_rows[0] ledger["indirect_analysis"] = { "predictor": p["path"][0], "mediator": p["path"][1], "outcome": p["path"][2], "numbered_hypothesis": p["numbered_hypothesis"], "relation": p["relation"], } return ledger def build_quantitative_front_matter_contract(contract: dict[str, Any], *, version: str) -> dict[str, Any]: quant = dict((contract or {}).get("quantitative") or {}) items = [dict(x) for x in (quant.get("constructs") or []) if isinstance(x, dict)] # Preserve legacy role map where a role is singular, while adding an extensible item list. role_map: dict[str, str] = {} for role in ("predictor", "mediator", "moderator", "outcome", "control", "covariate"): values = [x.get("label") for x in items if role in (x.get("roles") or []) and x.get("label")] if len(values) == 1: role_map[role] = values[0] construct_roles = [r for r in ("predictor","mediator","moderator","outcome","control","covariate") if r in role_map] return { "version": version, "policy": "adaptive_study_design_frozen_semantic_authority", "source_topic": str((contract or {}).get("source_topic") or ""), "source_keywords": list((contract or {}).get("source_keywords") or []), "construct_roles": construct_roles, "constructs": role_map, "construct_items": items, "relations": list(quant.get("relations") or []), "unsupported_seed_concepts": list((contract or {}).get("unsupported_seed_concepts") or []), "study_design_contract_sha256": str((contract or {}).get("contract_sha256") or ""), } def build_qualitative_contract(topic: str, keywords: Any, metadata: dict[str, Any], *, policy_version: str = "adaptive-qualitative-v1") -> dict[str, Any]: meta = dict(metadata or {}) facts = dict(meta.get("study_facts") or {}) sources = [] for index, raw in enumerate(facts.get("data_sources") or [], start=1): label = _clean(raw, 120) folded = label.casefold() family = ( "interview" if "interview" in folded else "focus_group" if "focus" in folded and "group" in folded else "observation" if "observ" in folded else "log" if "log" in folded else "document" if any(x in folded for x in ("document","archiv","record")) else "digital_trace" if any(x in folded for x in ("digital trace","clickstream","platform trace")) else "field_note" if "field note" in folded else "artifact" if "artifact" in folded else "other" ) sources.append({"source_id":f"D{index:03d}","label":label,"family":family,"semantic_descriptor":label if family=="other" else ""}) actors = [] seen = set() for row in facts.get("data_source_roles") or []: if not isinstance(row, dict): continue label = _clean(row.get("actor_role"), 100) if label and label.casefold() not in seen: actors.append({"actor_id":f"A{len(actors)+1:03d}","label":label}); seen.add(label.casefold()) themes = [] for item in meta.get("themes") or []: if not isinstance(item, dict): continue themes.append({ "theme_id": _clean(item.get("theme_id"), 40), "title": _clean(item.get("title"), 160), "stages": [_clean(x,80) for x in (item.get("stages") or []) if _clean(x,80)], "has_deviant_evidence": bool(item.get("has_deviant_evidence")), }) design = _clean(facts.get("analytic_design") or facts.get("analysis_method"), 120) temporal = _clean(facts.get("temporal_structure"), 160) case_structure = _clean(facts.get("case_structure"), 160) contract = { "version": STUDY_DESIGN_CONTRACT_VERSION, "mode": "qualitative", "source_type": _clean(meta.get("source_type"),40), "source_topic": _clean(topic,500), "source_keywords": _keywords(keywords), "research_problem": "", "research_questions": [], "design_family": design or "Iterative thematic/process analysis", "evidence_strength": {"causal_identification":False,"allowed_inference":["theme","process_pattern","interpretive_mechanism"],"forbidden_inference":["causal_effect"]}, "context": {"research_setting": _clean(facts.get("research_setting"),240)}, "quantitative": None, "qualitative": { "phenomenon": _clean(topic,300), "organizational_puzzle": "", "research_questions": [], "design_tradition": design or "Iterative thematic/process analysis", "units_of_analysis": [{"unit_id":"U001","label":case_structure or "study participants/organizational setting","level":"other"}], "actor_groups": actors, "data_sources": sources, "sampling": {"participant_count": facts.get("participant_count"), "interview_count": facts.get("interview_count")}, "temporal_scope": {"description": temporal or "Not specified"}, "analysis_strategy": [design] if design else [], "themes": themes, "process_model": [], "trustworthiness_procedures": list(facts.get("trustworthiness_procedures") or []), "ethics_procedures": list(facts.get("ethics_procedures") or []), "reflexivity_procedures": list(facts.get("reflexivity_procedures") or []), }, "unsupported_seed_concepts": [], "compiler_decisions": [], "policy_version": policy_version, } return _finalize(contract) def _study_owned_sentence(sentence: str) -> bool: text = str(sentence or "") if re.search(r"\bCITE-\d+\b", text, flags=re.I): return False if re.search(r"\((?=[^()\n]*(?:19|20)\d{2})[^()\n]+\)", text): return False if re.search(r"(?i)\b(?:prior|previous|existing|earlier)\s+(?:research|stud(?:y|ies)|literature)\b", text): return False return bool(re.search(r"(?i)\b(?:we|our\s+study|this\s+study|the\s+present\s+study|the\s+study|our\s+analysis|our\s+results|our\s+findings|we\s+(?:examine|investigate|test|analy[sz]e|explore|study))\b", text)) def inspect_study_design_scope(text: str, contract: dict[str, Any], *, section_name: str = "") -> list[dict[str, Any]]: """High-confidence whole-manuscript scope guard for both modes.""" value = str(text or "") rows: list[dict[str, Any]] = [] mode = str((contract or {}).get("mode") or "") sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+|\n+", value) if s.strip()] if mode == "quantitative": quant = dict((contract or {}).get("quantitative") or {}) constructs = [x for x in (quant.get("constructs") or []) if isinstance(x, dict)] allowed_labels = {str(x.get("label") or "").casefold() for x in constructs if x.get("label")} has_moderation = any(r.get("type") == "moderation" for r in (quant.get("relations") or []) if isinstance(r, dict)) has_indirect = bool(quant.get("indirect_effects")) unsupported = [str(x) for x in (contract or {}).get("unsupported_seed_concepts") or [] if str(x).strip()] for sentence in sentences: if not _study_owned_sentence(sentence): continue folded = sentence.casefold() if re.search(r"\bmoderat(?:e|es|ed|ing|or|ion)\b|\binteraction\s+(?:effect|term)\b", folded) and not has_moderation: rows.append({"type":"unsupported_moderation_claim","preview":sentence[:260],"reason":"The frozen study-design graph contains no moderation/interaction analysis target."}) if re.search(r"\bmediat(?:e|es|ed|ing|or|ion)\b|\bindirect\s+(?:effect|association)\b", folded) and not has_indirect: rows.append({"type":"unsupported_mediation_claim","preview":sentence[:260],"reason":"The frozen study-design graph contains no indirect-effect analysis target."}) for concept in unsupported: if concept.casefold() in folded and re.search(r"(?i)\b(?:examine|investigate|test|model|measure|assess|estimate)\b", sentence): rows.append({"type":"unsupported_focal_construct","construct":concept,"preview":sentence[:260],"reason":"The concept is background-only under the frozen study-design contract."}) elif mode == "qualitative": qual = dict((contract or {}).get("qualitative") or {}) design = str(qual.get("design_tradition") or "").casefold() temporal = str(dict(qual.get("temporal_scope") or {}).get("description") or "").casefold() families = {str(x.get("family") or "") for x in (qual.get("data_sources") or []) if isinstance(x, dict)} unit_label = " ".join(str(x.get("label") or "") for x in (qual.get("units_of_analysis") or []) if isinstance(x, dict)).casefold() for sentence in sentences: if not _study_owned_sentence(sentence): continue folded = sentence.casefold() if "longitudinal" in folded and "longitudinal" not in temporal and "longitudinal" not in design: rows.append({"type":"unsupported_temporal_scope","preview":sentence[:260],"reason":"The frozen qualitative design does not establish longitudinal evidence."}) if "ethnograph" in folded and "ethnograph" not in design: rows.append({"type":"unsupported_design_tradition","preview":sentence[:260],"reason":"Ethnography is not the frozen qualitative design tradition."}) if "grounded theory" in folded and "grounded theory" not in design: rows.append({"type":"unsupported_design_tradition","preview":sentence[:260],"reason":"Grounded theory is not the frozen qualitative design tradition."}) if "triangulat" in folded and len({x for x in families if x}) < 2: rows.append({"type":"unsupported_data_source_claim","preview":sentence[:260],"reason":"Triangulation requires at least two frozen evidence-source families."}) if re.search(r"\b(?:multi|multiple)[- ]case\b|\bcomparative case\b", folded) and not any(x in (design + " " + unit_label) for x in ("comparative", "multiple", "multi-case")): rows.append({"type":"unsupported_unit_of_analysis","preview":sentence[:260],"reason":"The frozen qualitative contract does not establish a multi-case comparison."}) return rows[:8]