NEO.K / MSSP FIELD LAB019-applicability-is-part-of-the-answer
編號019-applicability-is-part-of-the-answer
語言python
版本v1.0
日期2026-08-19
行數643
執行python src/main.py

019 — A measurement has to say when it does not apply

candidate. Example 018 wrote this into its own limitations: its incentive number read 0 both for a unit that declared nothing and for a unit whose declaration could not be suppressed. This is that limitation gone.

What this program does

It runs example 018's counterfactual again and refuses to hand back a value it did not compute.

python src/main.py             # the run under the policy SCL names
python src/main.py --control   # the same units under a policy that ignores declarations
python src/main.py --total     # ask for a total across all three
python src/main.py --strict    # exit 1 on an unmeasurable unit or a contradicted assumption
python src/island_test.py      # 52 checks across 8 sections, and it prints the count itself
  unit              suppressed   declared   incentive   reading
  baked-in          -            6          n/a         NOT MEASURED: the declaration is not a
                                                        separable field - suppressing it would also
                                                        remove a record, so the two arms would not
                                                        be comparable
  declares-openly   3            6          +3          declaring PAID
  never-declares    3            3          0           measured zero - both arms ran and agreed

  what a bare number would have said:
    baked-in          0 - and this is not measurable
    never-declares    0 - and this is measured, and genuinely zero
    2 units, one number, 2 kinds of answer

The structural decision

A measurement returns a value and its applicability. The repair is not a better number — no number would have worked, because the two situations were never the same quantity.

{"applicable": True,  "value": 3, "reason": None}
{"applicable": True,  "value": 0, "reason": None}      # measured zero
{"applicable": False, "value": None, "reason": "..."}  # not measurable

Three consequences, and the third is the one that generalises:

  1. A unit declares whether its declaration can be suppressed. One that will not say is refused — the harness would otherwise report a zero it never computed.
  2. SCL can only be contradicted by something that was measured. A reading that was never taken neither confirms nor contradicts the assumption, and main names it on its own line so it cannot read as agreement.
  3. The aggregator refuses. total_incentive raises rather than skipping the unmeasured unit, because a sum that quietly omits what it could not read prints a smaller number with the same confidence as a complete one.

This is the shape example 015 opened this run with — several situations arriving as one number — moved from the data to the instrument that reads the data.

The island test — and the control that makes zero a real category

Under ignore-declared, declares-openly measures zero, and it was measured: both arms of the counterfactual ran and agreed. Without a policy that produces a real zero, every zero in the report would have meant "nothing to measure" and section 3 could not come out badly.

  PASS  under ignore-declared, declares-openly measures zero
  PASS  and it WAS measured - both arms ran
  PASS  and they agree - 3
  PASS  baked-in also reads as nothing
  PASS  but it was not measured
  PASS  so a bare 0 cannot separate them, and applicability can

Section 4 proves the unmeasurable unit's stated reason by running it rather than believing the sentence: suppressing the field leaves baked-in's marker record behind, while a suppressible unit's two arms are record-identical and differ only in the declaration field.

Five mutations were run and each turns the suite red: reporting the unmeasurable unit as a plain zero (6 checks), the total skipping what it could not read (raises), the control policy starting to retry (4), baked-in no longer baking it in (4), and a non-applicable reading counted as a contradiction (1).

Two defects of mine, found by the drills in this entry

The loader crashed on a policy module with no POLICY instead of refusing it by name. An unknown shape is a case to classify, not an exception to raise.

And the first fix was not enough. I added the check, and the line that registered the module still read the attribute the check had just reported missing — so a refused module crashed the loader anyway. A guard that does not cover the code after it is not a guard.

And the second fix was not enough either — that one was found by someone else. The repaired loader still registered a module it had just reported as bad, on the reasoning that later code should be able to find it by name. Pragma found it by reading (MSSP_Board #8) and it reproduced first try. A registry that holds what the checker rejected is a registry that disagrees with its own report — and this suite was green through all three versions, because nothing here asked what the registry contained after a refusal. It asks now.

Upstream, the same day

Archaeology 019 is the most ordinary line of Python there is:

    {'a': None}     d.get(key)              None     -
    {}              d.get(key)              None     -

Same value, same type, the same object. And d.get(key, SENTINEL) — an answer that carries its own applicability, which is exactly this example's proposal — has been in the language the whole time without being the default.

What this example does not solve

The unmeasurable unit stays unmeasurable. The point is that it is named. Rebuilding baked-in so its declaration is separable is a change to the unit, not to the harness.

The unit's word about suppressibility is not verified. A unit could declare itself unsuppressible and be lying. That reads as n/a rather than as zero, which is the conservative direction — but conservative is not checked.

The counterfactual is still one unit, one policy, one run's data, exactly as in 018. Section 8 demonstrates the narrowness rather than asserting it: the same unit on the same data measures +3 under one policy and 0 under the other.

Nothing here reads intent. Outcome only.

Source

FMS

FMS/__init__.py
FMS/contract.json
{
  "name": "019-applicability-is-part-of-the-answer",
  "what_it_is": "The incentive measurement from example 018, repaired so that it reports when it does not apply instead of reporting a zero it never computed.",
  "the_structural_decision": "A measurement returns a value AND its applicability. Example 018's counterfactual handed back a number, and that number had two meanings — a unit that declared nothing measured 0, and a unit whose declaration could not be suppressed measured 0. The repair is not a better number; it is that the harness refuses to hand back a value it did not compute.",
  "why_this_one": "Example 018 named this in its own limitations. It is also the same shape example 015 opened this run with — several situations arriving as one number — moved from the data to the instrument that reads the data.",
  "status": "candidate",

  "the_three_answers": {
    "measured, non-zero": "both arms of the counterfactual ran and disagreed",
    "measured zero": "both arms ran and agreed — a real reading, and the control proves it is a category and not a synonym",
    "not applicable": "there was no second arm, so no value exists; a reason is carried instead"
  },

  "sources": {
    "declares-openly": {"holds": 6, "suppressible": true, "note": "its declaration is a separate field, so a harness can withhold it without changing anything else"},
    "never-declares":  {"holds": 6, "suppressible": true, "note": "measures a genuine zero"},
    "baked-in":        {"holds": 6, "suppressible": false, "note": "its incompleteness IS a record, so withholding the field leaves the marker behind and the two arms are not comparable — this is the unit 018 reported as 0"}
  },

  "policies": {
    "retry-declared":  "re-runs a declaring source with more budget",
    "ignore-declared": "notes the declaration and changes nothing — the control policy, under which a declaring unit has a MEASURED zero"
  },
  "why_the_control_policy_exists": "Without a policy that produces a real zero, every zero in the report would mean 'nothing to measure' and section 3 could not come out badly.",

  "the_aggregator_refuses": "total_incentive raises rather than skipping the unmeasured unit. A sum that quietly omits what it could not read prints a smaller number with the same confidence as a complete one.",

  "sets": {
    "FMS": "this file: the three answers, what each source holds and whether its declaration is separable, and the units map",
    "SCL": "which policy this deployment applies, what it assumes, and what an unmeasurable unit means here",
    "SMS": "running the sources, applying the policy, and returning each measurement with its applicability",
    "TMS": "one file per source and one per policy — each declares itself, including whether its declaration can be suppressed, and reaches no sibling",
    "DMS": "the three kinds of cell kept visibly apart, and what a bare number would have said instead"
  },

  "units": {
    "TMS/sources": ["declaration_is_baked_in.py", "declares_openly.py", "never_declares.py"],
    "TMS/policies": ["ignore_declared.py", "retry_declared.py"]
  },

  "non_goals": [
    "Measuring the unmeasurable unit. The point is that it is named, not that it is solved. Rebuilding baked-in so its declaration is separable is a change to the unit, not to the harness.",
    "Trusting the unit's own word about suppressibility. A unit could declare itself unsuppressible and be lying; that reads as `n/a` rather than as zero, which is the conservative direction but is not verification.",
    "Reading intent. The measurement is outcome only, exactly as in example 018."
  ]
}

SCL

SCL/__init__.py
SCL/policy.json
{
  "deployment": "catalogue-sync",
  "policy": "retry-declared",
  "assumes_declarations_are": "self-penalising",
  "an_unmeasurable_unit_is": "fatal",
  "why": "Example 018 measured the incentive under this deployment's own policy and found it contradicted the assumption. This deployment kept the policy and the assumption, and added the one thing 018 was missing: a unit whose incentive cannot be measured must be named, not counted as zero.",
  "not_a_general_rule": "A deployment that only ever ships suppressible units would never see this. SCL is where the position lives."
}
SCL/policy.py
"""Deployment policy: which policy runs, and what an unmeasurable unit means."""
import json
import pathlib

POLICY = json.loads((pathlib.Path(__file__).parent / "policy.json").read_text(encoding="utf-8"))


def policy_name():
    return POLICY["policy"]


def assumption():
    return POLICY["assumes_declarations_are"]


def unmeasurable_is_fatal():
    return POLICY["an_unmeasurable_unit_is"] == "fatal"


def describe():
    return (f'{POLICY["deployment"]}: apply {POLICY["policy"]}, assuming declarations are '
            f'{POLICY["assumes_declarations_are"]}')


def contradicts(measured):
    """Only a MEASURED positive incentive contradicts the assumption.

    A reading that was never taken cannot contradict anything, and must not be
    allowed to look like agreement either.
    """
    if POLICY["assumes_declarations_are"] != "self-penalising":
        return None
    if not measured["applicable"]:
        return None
    if measured["value"] > 0:
        return (f'declaring left {measured["source"]} better off by {measured["value"]} '
                f'record(s) ({measured["suppressed"]} suppressed -> {measured["declared"]} declared)')
    return None

SMS

SMS/__init__.py
SMS/measure.py
"""Run the sources, apply the policy, and measure the incentive — properly.

Example 018 computed

    incentive(unit) = contribution WITH the declaration
                    - contribution with the declaration SUPPRESSED

and returned a number. That number had two meanings and 018 said so in its own
limitations: a unit that declared nothing measured 0, and a unit whose
declaration could not be suppressed also measured 0.

The repair is not a better number. It is that **a measurement returns a value
and its applicability**, and refuses to hand back a value it did not compute.

    {"applicable": True,  "value": 3, "reason": None}
    {"applicable": True,  "value": 0, "reason": None}      <- measured zero
    {"applicable": False, "value": None, "reason": "..."}  <- not measurable
"""
import importlib

SOURCES = ["baked_in", "declares_openly", "never_declares"]
POLICIES = ["ignore_declared", "retry_declared"]

# Deliberately not a number. Anything that tries to add this to a total will
# raise instead of silently contributing nothing.
NOT_APPLICABLE = object()


def load(extra_sources=(), extra_policies=()):
    sources, policies, problems = {}, {}, []

    for name in SOURCES:
        _register(importlib.import_module(f"TMS.sources.{_module_name(name)}"),
                  sources, problems, _check_source, "NAME")
    for module in extra_sources:
        _register(module, sources, problems, _check_source, "NAME")

    for name in POLICIES:
        _register(importlib.import_module(f"TMS.policies.{name}"),
                  policies, problems, _check_policy, "POLICY")
    for module in extra_policies:
        _register(module, policies, problems, _check_policy, "POLICY")

    return sources, policies, problems


def _register(module, registry, problems, checker, key):
    """Check, then register only what is usable.

    Adding the check was not enough on its own: the line that registered the
    module still read the attribute the check had just reported missing, so a
    refused module crashed the loader instead of being refused. A guard that
    does not cover the code after it is not a guard.

    And that repair was still not enough. The first version of this function
    registered a refused module anyway, on the reasoning that later code should
    be able to find it by name — so a source this loader had just REPORTED as
    bad also appeared in the canonical registry. Pragma found it by reading
    (MSSP_Board issue #8) and it reproduced first try. A registry that holds
    what the checker rejected is a registry that disagrees with its own report.
    """
    before = len(problems)
    checker(module, problems)
    name = getattr(module, key, None)
    if name is None:
        return
    if len(problems) > before:
        return  # refused. It does not go in, under any name.
    registry[name] = module


def _module_name(name):
    return {"baked_in": "declaration_is_baked_in"}.get(name, name)


def _check_source(module, problems):
    name = getattr(module, "NAME", None)
    if not name:
        problems.append(f"a source module ({module.__name__}) does not declare NAME")
        return
    for attribute in ("CAN_FAIL_WITH", "HELD", "collect"):
        if not hasattr(module, attribute):
            problems.append(f"{name} does not declare {attribute}")
    if not getattr(module, "CAN_FAIL_WITH", None):
        problems.append(f"{name}: CAN_FAIL_WITH is empty")
    # New in this example. A unit that will not say whether its declaration can
    # be withheld cannot be measured OR reported as unmeasurable, which is the
    # worst of the three states.
    if not isinstance(getattr(module, "DECLARATION_IS_SUPPRESSIBLE", None), bool):
        problems.append(f"{name}: does not say whether its declaration can be "
                        f"suppressed - the harness would report a zero it did not compute")
    for vouch in ("COMPLETE", "IS_COMPLETE", "RETURNS_EVERYTHING"):
        if getattr(module, vouch, None) is True:
            problems.append(f"{name}: declares {vouch} - a unit may declare itself "
                            f"incomplete and may not declare itself complete")


def _check_policy(module, problems):
    # Name it before reading it. A module with no POLICY has to be refused by
    # name-of-the-file, not crash the loader — an unknown shape is a case to
    # classify, not an exception to raise.
    name = getattr(module, "POLICY", None)
    if not name:
        problems.append(f"a policy module ({module.__name__}) does not declare POLICY")
        return
    if not getattr(module, "WHAT_IT_DOES_WITH_A_DECLARATION", None):
        problems.append(f"{name}: does not say what it does with a declaration")
    if not callable(getattr(module, "apply", None)):
        problems.append(f"{name}: has no apply()")


def run_one(module, budget=1, suppress_declaration=False):
    result = module.collect(budget)
    return {
        "source": module.NAME,
        "held": module.HELD,
        "records": result["records"],
        "incomplete_because": None if suppress_declaration else result["incomplete_because"],
    }


def run_all(sources, suppress=()):
    return [run_one(sources[name], 1, suppress_declaration=name in suppress)
            for name in sorted(sources)]


def through(policy, sources, suppress=()):
    runs = run_all(sources, suppress=suppress)
    rerun = lambda name, budget: run_one(sources[name], budget)  # noqa: E731
    applied = policy.apply(runs, rerun)
    return {"rows": applied, "total": sum(len(row["kept"]) for row in applied)}


def contribution(result, name):
    for row in result["rows"]:
        if row["source"] == name:
            return len(row["kept"])
    return 0


def incentive(policy, sources, name):
    """The measurement, with its applicability attached.

    A unit whose declaration is baked into its records cannot be run without
    it, so there is no second arm and nothing to subtract. Returning 0 there
    would be reporting a value that was never computed.
    """
    module = sources[name]
    if not module.DECLARATION_IS_SUPPRESSIBLE:
        return {"source": name, "applicable": False, "value": None,
                "declared": contribution(through(policy, sources), name), "suppressed": None,
                "reason": "the declaration is not a separable field - suppressing it would "
                          "also remove a record, so the two arms would not be comparable"}

    declared = contribution(through(policy, sources), name)
    suppressed = contribution(through(policy, sources, suppress=[name]), name)
    return {"source": name, "applicable": True, "value": declared - suppressed,
            "declared": declared, "suppressed": suppressed, "reason": None}


def measure_all(policy, sources):
    return [incentive(policy, sources, name) for name in sorted(sources)]


def total_incentive(measured):
    """Deliberately refuses rather than treating a non-applicable reading as 0.

    This is the aggregator lesson: classify every input, and refuse the shapes
    you cannot classify instead of defaulting them to zero.
    """
    skipped = [m["source"] for m in measured if not m["applicable"]]
    if skipped:
        raise ValueError("cannot total an incentive across units that were not measured: "
                         + ", ".join(skipped))
    return sum(m["value"] for m in measured)

TMS

TMS/__init__.py
TMS/policies/__init__.py
TMS/policies/ignore_declared.py
"""Reads the declaration and does nothing differently.

This is the control policy. Under it, a unit that declares has an incentive of
zero and that zero is MEASURED - both arms of the counterfactual ran and agreed.
Without it, a zero would only ever mean "nothing to measure", and section 4
could not come out badly.
"""
POLICY = "ignore-declared"
WHAT_IT_DOES_WITH_A_DECLARATION = "notes it and changes nothing"


def apply(runs, rerun):
    return [{**run, "kept": run["records"]} for run in runs]
TMS/policies/retry_declared.py
"""Re-runs a source that declared itself incomplete, with a larger budget."""
POLICY = "retry-declared"
WHAT_IT_DOES_WITH_A_DECLARATION = "re-runs the source with more budget"
RETRY_BUDGET = 2


def apply(runs, rerun):
    out = []
    for run in runs:
        if run["incomplete_because"]:
            out.append({**run, "kept": rerun(run["source"], RETRY_BUDGET)["records"]})
        else:
            out.append({**run, "kept": run["records"]})
    return out
TMS/sources/__init__.py
TMS/sources/declaration_is_baked_in.py
"""It declares, and the declaration cannot be taken away.

The incompleteness is not a field beside the records — it is a record. A
harness that wants to ask "what would this unit have contributed WITHOUT its
declaration" has nothing to remove: removing the marker removes a row, which
changes the very quantity being compared.

This is the unit example 018 could not measure and reported as 0 anyway.
"""
NAME = "baked-in"
CAN_FAIL_WITH = ["unreadable-page", "cursor-expired"]
HELD = 6
DECLARATION_IS_SUPPRESSIBLE = False


def collect(budget=1):
    take = min(HELD, budget * 3)
    records = [{"from": NAME, "id": f"b-{n}"} for n in range(1, take + 1)]
    if take < HELD:
        records.append({"from": NAME, "id": "b-cursor", "marker": "more-after-cursor"})
    return {
        "records": records,
        "incomplete_because": "more-after-cursor" if take < HELD else None,
    }
TMS/sources/declares_openly.py
"""Holds six records, hands over three per unit of budget, and says so.

Its declaration is a separate field on the result, so a harness can withhold it
without changing anything else. That is what makes this unit measurable.
"""
NAME = "declares-openly"
CAN_FAIL_WITH = ["unreadable-page", "cursor-expired"]
HELD = 6
DECLARATION_IS_SUPPRESSIBLE = True


def collect(budget=1):
    take = min(HELD, budget * 3)
    return {
        "records": [{"from": NAME, "id": f"d-{n}"} for n in range(1, take + 1)],
        "incomplete_because": "more-after-cursor" if take < HELD else None,
    }
TMS/sources/never_declares.py
"""The same holdings, and it never declares anything.

Its incentive is a genuine, measured zero: the counterfactual runs, both arms
complete, and they agree.
"""
NAME = "never-declares"
CAN_FAIL_WITH = ["unreadable-page", "cursor-expired"]
HELD = 6
DECLARATION_IS_SUPPRESSIBLE = True


def collect(budget=1):
    take = min(HELD, budget * 3)
    return {
        "records": [{"from": NAME, "id": f"n-{n}"} for n in range(1, take + 1)],
        "incomplete_because": None,
    }

DMS

DMS/__init__.py
DMS/report.py
"""What a person is shown.

An unmeasured reading is never rendered in the same column shape as a measured
one. `n/a` is a different kind of cell from `0`, and the report says which.
"""


def measurements(measured):
    lines = ["  unit              suppressed   declared   incentive   reading"]
    for m in measured:
        if not m["applicable"]:
            lines.append(f'  {m["source"]:<17} {"-":<12} {m["declared"]:<10} {"n/a":<11} '
                         f'NOT MEASURED: {m["reason"]}')
            continue
        reading = ("declaring PAID" if m["value"] > 0
                   else "declaring COST it" if m["value"] < 0
                   else "measured zero - both arms ran and agreed")
        value = f'+{m["value"]}' if m["value"] > 0 else str(m["value"])
        lines.append(f'  {m["source"]:<17} {m["suppressed"]:<12} {m["declared"]:<10} '
                     f'{value:<11} {reading}')
    return "\n".join(lines)


def what_a_bare_number_would_have_said(measured):
    zeros = [m for m in measured if not m["applicable"] or m["value"] == 0]
    lines = ["  what a bare number would have said:"]
    for m in zeros:
        state = "not measurable" if not m["applicable"] else "measured, and genuinely zero"
        lines.append(f'    {m["source"]:<17} 0 - and this is {state}')
    kinds = len({m["applicable"] for m in zeros})
    lines.append(f"    {len(zeros)} units, one number, {kinds} kinds of answer")
    return "\n".join(lines)


def refusal(error):
    return "\n".join([
        f"  the total refuses: {error}",
        "  A sum that skips what it could not measure reports a smaller number with the",
        "  same confidence as a complete one.",
    ])

root

island_test.py
"""The island test.

    python src/island_test.py

Section 3 is the control: a MEASURED zero, which is what stops zero from being
a synonym for "nothing to measure". Section 4 proves the unmeasurable unit's
stated reason by running it, rather than believing the sentence.
"""
import json
import pathlib
import re
import sys

from SCL import policy
from SMS import measure
from TMS.sources import declaration_is_baked_in, declares_openly, never_declares
from TMS.policies import ignore_declared, retry_declared

HERE = pathlib.Path(__file__).parent
CONTRACT = json.loads((HERE / "FMS" / "contract.json").read_text(encoding="utf-8"))
FAILURES = []
RAN = [0]


def check(label, ok, detail=""):
    RAN[0] += 1
    print(f'  {"PASS" if ok else "FAIL"}  {label}{f" - {detail}" if detail else ""}')
    if not ok:
        FAILURES.append(label)


sources, policies, problems = measure.load()
under_retry = {m["source"]: m for m in measure.measure_all(retry_declared, sources)}
under_ignore = {m["source"]: m for m in measure.measure_all(ignore_declared, sources)}

print("\n== 1. every unit is an island, and FMS matches the tree")
check("loading raised no problems", not problems, "; ".join(problems))
for unit, declared in CONTRACT["units"].items():
    directory = HERE.joinpath(*unit.split("/"))
    on_disk = sorted(p.name for p in directory.glob("*.py") if p.name != "__init__.py")
    check(f"{unit}: FMS declares what is on disk", on_disk == sorted(declared),
          f'disk {", ".join(on_disk)} | FMS {", ".join(sorted(declared))}')
    for name in on_disk:
        body = directory.joinpath(name).read_text(encoding="utf-8")
        siblings = [n[:-3] for n in on_disk if n != name]
        check(f"{unit}/{name} reaches no sibling",
              not [s for s in siblings if re.search(rf"\bimport\b.*\b{s}\b", body)])
        check(f"{unit}/{name} reaches no other set",
              not re.search(r"\b(from|import)\s+(SMS|DMS|SCL|FMS)\b", body))

print("\n== 2. a measurement carries its applicability")
for name, m in sorted(under_retry.items()):
    check(f"{name} says whether it was measured", isinstance(m["applicable"], bool))
check("a non-applicable reading carries no value", under_retry["baked-in"]["value"] is None)
check("and carries a reason instead", bool(under_retry["baked-in"]["reason"]))
check("an applicable reading carries a value and no reason",
      under_retry["declares-openly"]["value"] == 3 and under_retry["declares-openly"]["reason"] is None)
check("NOT_APPLICABLE is not a number", not isinstance(measure.NOT_APPLICABLE, (int, float)))

print("\n== 3. the control - a MEASURED zero")
control = under_ignore["declares-openly"]
absent = under_retry["baked-in"]
check("under ignore-declared, declares-openly measures zero", control["value"] == 0)
check("and it WAS measured - both arms ran", control["applicable"] is True)
check("and they agree", control["declared"] == control["suppressed"], f'{control["declared"]}')
check("baked-in also reads as nothing", absent["value"] is None)
check("but it was not measured", absent["applicable"] is False)
check("so a bare 0 cannot separate them, and applicability can",
      control["applicable"] != absent["applicable"] and (control["value"] or 0) == 0)
check("never-declares gives a measured zero too, under both policies",
      under_retry["never-declares"]["value"] == 0 and under_ignore["never-declares"]["value"] == 0)

print("\n== 4. the unmeasurable unit's reason, proved by running it")
with_declaration = measure.run_one(declaration_is_baked_in, 1)
without_declaration = measure.run_one(declaration_is_baked_in, 1, suppress_declaration=True)
check("suppressing the field does not remove the marker record",
      any("marker" in r for r in without_declaration["records"]))
check("so the two arms hold a different number of records than a clean unit's arms do",
      len(with_declaration["records"]) == len(without_declaration["records"])
      and any("marker" in r for r in with_declaration["records"]))
clean_with = measure.run_one(declares_openly, 1)
clean_without = measure.run_one(declares_openly, 1, suppress_declaration=True)
check("a suppressible unit's two arms are record-identical",
      clean_with["records"] == clean_without["records"])
check("and differ only in the declaration field",
      clean_with["incomplete_because"] is not None and clean_without["incomplete_because"] is None)
check("baked-in's declaration survives suppression, which is why there is no second arm",
      any(r.get("marker") for r in without_declaration["records"]))
check("and the unit says so itself, up front",
      declaration_is_baked_in.DECLARATION_IS_SUPPRESSIBLE is False)

print("\n== 5. the total refuses instead of defaulting to zero")
try:
    measure.total_incentive(list(under_retry.values()))
    check("a total across an unmeasured unit is refused", False, "it returned a number")
except ValueError as refused:
    check("a total across an unmeasured unit is refused", True, str(refused))
    check("and the refusal names the unit", "baked-in" in str(refused))
measurable = [m for m in under_retry.values() if m["applicable"]]
check("a total across measured units alone is allowed",
      measure.total_incentive(measurable) == 3, f"{measure.total_incentive(measurable)}")
check("which is a different number from the one a silent skip would print",
      measure.total_incentive(measurable) == 3 and len(measurable) < len(under_retry))

print("\n== 6. SCL can only be contradicted by something that was measured")
check("a measured positive contradicts", policy.contradicts(under_retry["declares-openly"]) is not None)
check("a measured zero does not", policy.contradicts(under_retry["never-declares"]) is None)
check("and a non-applicable reading does not either",
      policy.contradicts(under_retry["baked-in"]) is None)
check("but it must not read as agreement - main names it separately",
      "NOT MEASURED" in (HERE / "main.py").read_text(encoding="utf-8"))
check("the deployment calls an unmeasurable unit fatal", policy.unmeasurable_is_fatal())

print("\n== 7. the guards from 013, 015 and 018 still hold")


def drill_source(name, **attributes):
    module = type(sys)(name)
    module.NAME = name
    module.CAN_FAIL_WITH = ["x"]
    module.HELD = 1
    module.DECLARATION_IS_SUPPRESSIBLE = True
    module.collect = lambda budget=1: {"records": [{"from": name, "id": "d-1"}],
                                       "incomplete_because": None}
    for key, value in attributes.items():
        setattr(module, key, value)
    return module


mute_sources, _, mute = measure.load(extra_sources=[drill_source("drill-mute", CAN_FAIL_WITH=[])])
check("DRILL: an empty CAN_FAIL_WITH is refused", any("CAN_FAIL_WITH is empty" in p for p in mute))
# Added 2026-08-20 after Pragma found the hole by reading (MSSP_Board #8).
# Reporting a source as bad and registering it anyway is a registry that
# disagrees with its own report, and NOTHING here noticed for a whole day.
check("and a refused source does not end up in the registry either",
      "drill-mute" not in mute_sources,
      "the loader used to report it AND register it - the suite was green through both")
_, _, vouch = measure.load(extra_sources=[drill_source("drill-vouch", COMPLETE=True)])
check("DRILL: a source declaring COMPLETE is refused", any("declares COMPLETE" in p for p in vouch))
silent = drill_source("drill-unsaid")
del silent.DECLARATION_IS_SUPPRESSIBLE
_, _, unsaid = measure.load(extra_sources=[silent])
check("DRILL: a source that will not say whether it is suppressible is refused",
      any("does not say whether its declaration can be suppressed" in p for p in unsaid))
secretive = type(sys)("drill_secretive")
secretive.POLICY = "drill-secretive"
secretive.apply = lambda runs, rerun: [{**r, "kept": r["records"]} for r in runs]
_, _, told = measure.load(extra_policies=[secretive])
check("DRILL: a policy that will not say what it does with a declaration is refused",
      any("does not say what it does" in p for p in told))
_, _, nameless = measure.load(extra_policies=[type(sys)("drill_nameless")])
check("DRILL: a policy module with no POLICY is refused by name, not by crashing",
      any("does not declare POLICY" in p for p in nameless))
_, _, honest = measure.load(extra_sources=[drill_source("drill-honest")])
check("and an honest unit raises nothing", not honest)

print("\n== 8. what this still cannot do, asserted so it stays measured")
check("nothing here reads intent",
      not re.search(r"\bintent\b|\bstrategic\b", (HERE / "SMS" / "measure.py").read_text(encoding="utf-8")))
check("the reason for non-applicability is the unit's own word, checked only by the record shape",
      declaration_is_baked_in.DECLARATION_IS_SUPPRESSIBLE is False
      and any(r.get("marker") for r in without_declaration["records"]),
      "a unit could declare itself unsuppressible and be lying; that reads as n/a, not as zero")
check("the counterfactual is still one unit, one policy, one run's data",
      under_retry["declares-openly"]["value"] != under_ignore["declares-openly"]["value"],
      f'{under_retry["declares-openly"]["value"]} under retry, '
      f'{under_ignore["declares-openly"]["value"]} under ignore - same unit, same data')

print()
if FAILURES:
    print(f'  {len(FAILURES)} FAILED: {" | ".join(FAILURES)}')
    sys.exit(1)
print(f"  {RAN[0]} checks passed - {len(sources)} sources, {len(policies)} policies, "
      f"3 kinds of answer")
main.py
"""Three sources, and a measurement that says when it does not apply.

    python src/main.py            the run under the policy SCL names
    python src/main.py --control  the same units under a policy that ignores declarations
    python src/main.py --total    ask for a total across all three
    python src/main.py --strict   exit 1 on an unmeasurable unit or a contradicted assumption
"""
import sys

from DMS import report
from SCL import policy
from SMS import measure


def main(argv):
    sources, policies, problems = measure.load()
    if problems:
        for problem in problems:
            print(f"  REFUSED: {problem}")
        return 1

    name = "ignore-declared" if "--control" in argv else policy.policy_name()
    in_force = policies[name]
    measured = measure.measure_all(in_force, sources)

    print(f"\n  {policy.describe()}")
    if name != policy.policy_name():
        print(f'  --control: running {name} instead - {in_force.WHAT_IT_DOES_WITH_A_DECLARATION}')
    print()
    print(report.measurements(measured))
    print()
    print(report.what_a_bare_number_would_have_said(measured))

    if "--total" in argv:
        print()
        try:
            print(f"  total incentive: {measure.total_incentive(measured)}")
        except ValueError as refused:
            print(report.refusal(refused))

    contradictions = [c for c in (policy.contradicts(m) for m in measured) if c]
    unmeasured = [m["source"] for m in measured if not m["applicable"]]
    if contradictions:
        print()
        for line in contradictions:
            print(f"  CONTRADICTS SCL: {line}")
    if unmeasured:
        print(f'  NOT MEASURED: {", ".join(unmeasured)} - the assumption is neither confirmed '
              f'nor contradicted there')

    if "--strict" in argv and (contradictions or (unmeasured and policy.unmeasurable_is_fatal())):
        print("\n  --strict: an unmeasurable unit or a contradicted assumption, both fatal here")
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))