From 91fc13a3253235cb76b7fcf20a22146305348cc2 Mon Sep 17 00:00:00 2001 From: psychologister <230141834+psychologister@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:41:37 +0800 Subject: [PATCH 1/4] periodic_report: single-source the reportable trigger kinds triggers.py restated core._REPORTABLE_TRIGGER_KINDS as _REPORTABLE_KINDS while already importing eleven names from core -- the strongest form of the duplicate-knowledge case. It now borrows the owner object and the restated name is retired. The neighbouring _NON_REPORTABLE_KINDS is a different vocabulary and is left alone. The weekly preset's enabled_kinds lists the same eight kinds, but it is a per-preset configuration (the portfolio preset selects only cadence_due), so the guard declares it as an exception rather than folding it into the owner: coupling it would auto-enable future kinds, a domain decision. The declaration is pinned to one site. New guard: folded-value census, identity, retirement, behavioural parity through _normalize_policy, and poison controls. Refs #4447. Signed-off-by: psychologister <230141834+psychologister@users.noreply.github.com> --- .../capabilities/periodic_report/triggers.py | 17 +- ...t_periodic_report_reportable_kind_owner.py | 215 ++++++++++++++++++ 2 files changed, 219 insertions(+), 13 deletions(-) create mode 100644 tests/architecture/test_periodic_report_reportable_kind_owner.py diff --git a/loopx/capabilities/periodic_report/triggers.py b/loopx/capabilities/periodic_report/triggers.py index 84e7bd67df..19f4e39935 100644 --- a/loopx/capabilities/periodic_report/triggers.py +++ b/loopx/capabilities/periodic_report/triggers.py @@ -6,6 +6,7 @@ from .core import ( TRIGGER_DECISION_SCHEMA, + _REPORTABLE_TRIGGER_KINDS, _boolean, _digest, _integer, @@ -21,16 +22,6 @@ TRIGGER_REQUEST_SCHEMA = "periodic_report_trigger_request_v0" -_REPORTABLE_KINDS = { - "bounded_segment_milestone", - "cadence_due", - "manual", - "material_blocker", - "material_decision", - "material_recovery", - "primary_goal_outcome", - "vision_closed", -} _NON_REPORTABLE_KINDS = { "monitor_unchanged", "state_refreshed", @@ -84,11 +75,11 @@ def _normalize_profile(raw: object) -> dict[str, str]: def _normalize_policy(raw: object) -> dict[str, Any]: policy = _object(raw, "trigger_policy") - enabled_raw = policy.get("enabled_kinds", sorted(_REPORTABLE_KINDS)) + enabled_raw = policy.get("enabled_kinds", sorted(_REPORTABLE_TRIGGER_KINDS)) enabled: list[str] = [] for index, value in enumerate(_list(enabled_raw, "trigger_policy.enabled_kinds")): kind = _token(value, f"trigger_policy.enabled_kinds[{index}]") - if kind not in _REPORTABLE_KINDS: + if kind not in _REPORTABLE_TRIGGER_KINDS: raise ValueError(f"trigger_policy.enabled_kinds[{index}] is not reportable") if kind not in enabled: enabled.append(kind) @@ -388,7 +379,7 @@ def _normalize_candidates(raw: object, evaluated_at: str) -> list[dict[str, Any] label = f"candidates[{index}]" item = _object(value, label) kind = _token(item.get("trigger_kind"), f"{label}.trigger_kind") - if kind not in _REPORTABLE_KINDS | _NON_REPORTABLE_KINDS: + if kind not in _REPORTABLE_TRIGGER_KINDS | _NON_REPORTABLE_KINDS: raise ValueError(f"{label}.trigger_kind is invalid") observed_at = _timestamp(item.get("observed_at"), f"{label}.observed_at") observed_value = datetime.fromisoformat(observed_at.replace("Z", "+00:00")) diff --git a/tests/architecture/test_periodic_report_reportable_kind_owner.py b/tests/architecture/test_periodic_report_reportable_kind_owner.py new file mode 100644 index 0000000000..a916afec81 --- /dev/null +++ b/tests/architecture/test_periodic_report_reportable_kind_owner.py @@ -0,0 +1,215 @@ +"""Guard one owner for the periodic-report reportable trigger kinds (#4447). + +``_REPORTABLE_TRIGGER_KINDS`` in ``periodic_report/core.py`` decides which +trigger kinds may produce a periodic report. ``triggers.py`` restated the same +eight kinds as ``_REPORTABLE_KINDS`` while *already importing* eleven names from +``core`` -- the strongest form of this repository's duplicate-knowledge case: a +module restating a constant whose owner it already imports from. It now borrows +the owner object and the restated name is retired. + +The neighbouring ``_NON_REPORTABLE_KINDS`` (five different kinds) is a separate +vocabulary and is deliberately left alone. The census keys on the **folded +value**, so that neighbour is never swept: its members differ. The by-name +semantic inventory cannot see this pair either, because the two sides use +different names and both are module-private. + +Two layers: a whole-tree folded-value census (only the owner states the set), +and behavioural parity through the consumer's own ``_normalize_policy`` entry, +so a migration that changed the accepted kinds fails here. The owner's gate is +pinned by identity -- it reads the very object the consumer now borrows. +""" + +from __future__ import annotations + +import ast +import pathlib + +import pytest + +from loopx.capabilities.periodic_report import core, triggers + +REPO_ROOT = pathlib.Path(__file__).resolve().parents[2] +PACKAGE_ROOT = REPO_ROOT / "loopx" +OWNER_PATH = "loopx/capabilities/periodic_report/core.py" +CONSUMER_PATH = "loopx/capabilities/periodic_report/triggers.py" + +KINDS = frozenset( + { + "bounded_segment_milestone", + "cadence_due", + "manual", + "material_blocker", + "material_decision", + "material_recovery", + "primary_goal_outcome", + "vision_closed", + } +) +NON_REPORTABLE = frozenset( + { + "monitor_unchanged", + "state_refreshed", + "surface_only", + "todo_completed", + "vision_checkpoint", + } +) + +# A preset's ``enabled_kinds`` is a configuration choice -- which kinds *this +# preset* enables -- not the vocabulary of which kinds are reportable. The weekly +# preset enables all eight today, but the portfolio preset selects only +# ``["cadence_due"]``, proving the list is a per-preset policy. Borrowing the +# owner here would auto-enable any future reportable kind in the weekly preset, +# a domain decision rather than a deduplication. The list is sorted downstream by +# ``_normalize_policy``, so its literal order carries no meaning. Declared, and +# pinned to exactly one site below so the declaration cannot rot silently. +DECLARED_CONFIG_SITES = {"loopx/capabilities/periodic_report/presets.py": 1} + + +def _members(node: ast.expr) -> frozenset[str] | None: + """Fold a set / frozenset / list / tuple of plain string literals to members.""" + + if isinstance(node, ast.Call): + fname = getattr(node.func, "id", None) or getattr(node.func, "attr", None) + if fname in {"frozenset", "set"} and len(node.args) == 1: + return _members(node.args[0]) + return None + if isinstance(node, (ast.Set, ast.List, ast.Tuple)): + values = [ + element.value + for element in node.elts + if isinstance(element, ast.Constant) and isinstance(element.value, str) + ] + if len(values) == len(node.elts) and values: + return frozenset(values) + return None + + +def _kind_literal_sites(source: str) -> list[int]: + """Every collection literal folding to KINDS, counted once (call+set is one).""" + + tree = ast.parse(source) + wrapped = { + id(node.args[0]) + for node in ast.walk(tree) + if isinstance(node, ast.Call) + and (getattr(node.func, "id", None) or getattr(node.func, "attr", None)) + in {"frozenset", "set"} + and len(node.args) == 1 + } + return [ + node.lineno + for node in ast.walk(tree) + if id(node) not in wrapped and _members(node) == KINDS + ] + + +@pytest.fixture(scope="module") +def tree_findings() -> dict[str, str]: + findings: dict[str, str] = {} + for path in sorted(PACKAGE_ROOT.rglob("*.py")): + relative = path.relative_to(REPO_ROOT).as_posix() + if relative == OWNER_PATH: + continue + sites = _kind_literal_sites(path.read_text(encoding="utf-8")) + declared = DECLARED_CONFIG_SITES.get(relative, 0) + if len(sites) != declared: + findings[relative] = f"states the kind set at {sites}, declared {declared}" + return findings + + +def test_only_the_owner_and_the_declared_preset_state_the_kind_set(tree_findings) -> None: + assert tree_findings == {}, f"an undeclared restatement of the reportable kinds remains: {tree_findings}" + + +def test_the_owner_states_the_recorded_members_once() -> None: + assert frozenset(core._REPORTABLE_TRIGGER_KINDS) == KINDS + source = (REPO_ROOT / OWNER_PATH).read_text(encoding="utf-8") + assert len(_kind_literal_sites(source)) == 1 + + +def test_the_consumer_borrows_the_owner_object() -> None: + assert triggers._REPORTABLE_TRIGGER_KINDS is core._REPORTABLE_TRIGGER_KINDS + + +def test_the_consumer_retired_its_restated_name() -> None: + assert not hasattr(triggers, "_REPORTABLE_KINDS") + source = (REPO_ROOT / CONSUMER_PATH).read_text(encoding="utf-8") + assert _kind_literal_sites(source) == [] + assert "_REPORTABLE_TRIGGER_KINDS" in source + + +def test_the_non_reportable_neighbour_is_a_different_set() -> None: + # The five non-reportable kinds stay where they are; the value census must + # not sweep them, and they must not overlap the reportable set. + assert frozenset(triggers._NON_REPORTABLE_KINDS) == NON_REPORTABLE + assert NON_REPORTABLE.isdisjoint(KINDS) + source = (REPO_ROOT / CONSUMER_PATH).read_text(encoding="utf-8") + assert _kind_literal_sites(source) == [] + + +def test_the_preset_enabled_kinds_is_a_configuration_not_the_vocabulary() -> None: + from loopx.capabilities.periodic_report import presets + + # Two presets, two different selections: this is a per-preset policy, which + # is why the weekly list is declared rather than folded into the owner. + weekly = presets._WEEKLY_PROGRESS_PROFILE["trigger_policy"]["enabled_kinds"] + assert frozenset(weekly) == KINDS + portfolio = presets.resolve_periodic_report_profile_preset("portfolio-progress") + assert portfolio["trigger_policy"]["enabled_kinds"] == ["cadence_due"] + # The declaration is pinned to exactly one site, so it cannot rot silently. + source = (REPO_ROOT / "loopx/capabilities/periodic_report/presets.py").read_text( + encoding="utf-8" + ) + assert len(_kind_literal_sites(source)) == 1 + + +# --- behavioural parity through the consumer's own policy normalizer ---------------------- + + +@pytest.mark.parametrize("kind", sorted(KINDS)) +def test_each_reportable_kind_is_accepted(kind: str) -> None: + normalized = triggers._normalize_policy({"enabled_kinds": [kind]}) + assert normalized["enabled_kinds"] == [kind] + + +@pytest.mark.parametrize("kind", sorted(NON_REPORTABLE | {"not_a_kind"})) +def test_a_non_reportable_kind_is_rejected(kind: str) -> None: + with pytest.raises(ValueError, match="is not reportable"): + triggers._normalize_policy({"enabled_kinds": [kind]}) + + +def test_the_default_enabled_kinds_is_the_owner_set() -> None: + # With no explicit enabled_kinds the policy defaults to the full owner set, + # so the consumer's default is pinned to the borrowed object, not a copy. + normalized = triggers._normalize_policy({}) + assert normalized["enabled_kinds"] == sorted(KINDS) + + +# --- the census bites every restatement form and leaves the others ---------------------- + +_MEMBER_TEXT = ", ".join(repr(kind) for kind in sorted(KINDS)) +_NON_MEMBER_TEXT = ", ".join(repr(kind) for kind in sorted(NON_REPORTABLE)) + +POISON_CORPUS = ( + ("bare set restatement", f"X = {{{_MEMBER_TEXT}}}\n", 1), + ("frozenset call", f"X = frozenset({{{_MEMBER_TEXT}}})\n", 1), + ("set call over a list", f"X = set([{_MEMBER_TEXT}])\n", 1), + ("list literal", f"X = [{_MEMBER_TEXT}]\n", 1), + ("tuple literal", f"X = ({_MEMBER_TEXT})\n", 1), + ("renamed binding is still caught", f"_ANY = {{{_MEMBER_TEXT}}}\n", 1), + ("nested inside a function", f"def f():\n return {{{_MEMBER_TEXT}}}\n", 1), + ("importing the owner is not a restatement", "from .core import _REPORTABLE_TRIGGER_KINDS\n", 0), + ("alias rebind is not a restatement", "_REPORTABLE_KINDS = _REPORTABLE_TRIGGER_KINDS\n", 0), + ("the non-reportable neighbour is a different set", f"_NON_REPORTABLE_KINDS = {{{_NON_MEMBER_TEXT}}}\n", 0), + ("a single kind is not the whole set", 'X = {"manual"}\n', 0), +) + + +@pytest.mark.parametrize( + "label,source,expected", POISON_CORPUS, ids=[case[0] for case in POISON_CORPUS] +) +def test_the_census_names_every_form_and_leaves_the_others( + label: str, source: str, expected: int +) -> None: + assert len(_kind_literal_sites(source)) == expected, label \ No newline at end of file From 9aaaab723ab3800b29416658550755fc44a2b394 Mon Sep 17 00:00:00 2001 From: psychologister <230141834+psychologister@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:04:13 +0800 Subject: [PATCH 2/4] periodic_report: scope the reportable-kind guard to owner and validator The whole-tree folded-value census rejected a legitimate second report profile that explicitly selects the same eight kinds with its own interval (21,600s): the real decision entry accepts it and selects cadence_due, but the census flagged the config file as an illegal duplicate. Per the convergence RFC, merge candidates are advisory (an equal value set is not proof of one concept) and reuse_existing requires the same slot, compatible scope and an equivalent contract. A per-profile enabled_kinds selection is a different slot, so whole-package same-value matching belongs to the existing advisory lane (the semantic inventory's merge candidates), not a hard gate. The hard checks now pin only the owner (core) and the validation entry (triggers._normalize_policy): identity borrow, the owner states the set once, retirement of the restated name, and behavioural parity through the entry. Per-profile selections are verified through the real decision entry, adding the same-set-different-interval counterexample and the weekly/portfolio split (weekly selects an authorized manual trigger, portfolio suppresses it as disabled_by_profile). The folded-value scan and its poison controls are retained for the targeted owner/consumer checks; the preset literal-site pin and the declared-config whitelist are dropped. Refs #4447. Signed-off-by: psychologister <230141834+psychologister@users.noreply.github.com> --- ...t_periodic_report_reportable_kind_owner.py | 129 +++++++++++------- 1 file changed, 83 insertions(+), 46 deletions(-) diff --git a/tests/architecture/test_periodic_report_reportable_kind_owner.py b/tests/architecture/test_periodic_report_reportable_kind_owner.py index a916afec81..28618b15be 100644 --- a/tests/architecture/test_periodic_report_reportable_kind_owner.py +++ b/tests/architecture/test_periodic_report_reportable_kind_owner.py @@ -8,28 +8,36 @@ the owner object and the restated name is retired. The neighbouring ``_NON_REPORTABLE_KINDS`` (five different kinds) is a separate -vocabulary and is deliberately left alone. The census keys on the **folded -value**, so that neighbour is never swept: its members differ. The by-name -semantic inventory cannot see this pair either, because the two sides use -different names and both are module-private. - -Two layers: a whole-tree folded-value census (only the owner states the set), -and behavioural parity through the consumer's own ``_normalize_policy`` entry, -so a migration that changed the accepted kinds fails here. The owner's gate is -pinned by identity -- it reads the very object the consumer now borrows. +vocabulary and is deliberately left alone. The targeted literal checks key on +the **folded value**, so that neighbour is never swept: its members differ. The +by-name semantic inventory cannot see this pair either, because the two sides +use different names and both are module-private. + +Hard checks are pinned to the sites that share one semantic slot, scope and +contract: the owner (``core``) and the validation entry +(``triggers._normalize_policy``), with behavioural parity through that entry. +A profile's ``enabled_kinds`` is a different slot -- a per-profile choice of +which kinds *that profile* enables -- so two profiles may legitimately select +the same eight kinds with different intervals; those selections are verified +through the real decision entry, not by counting literals. Whole-package +same-value matching stays in the existing advisory lane (the semantic +inventory's merge candidates): the convergence RFC makes merge candidates +advisory because an equal value set is not proof of one concept, and +``reuse_existing`` requires the same slot, compatible scope and an equivalent +contract. """ from __future__ import annotations import ast import pathlib +from typing import Any import pytest from loopx.capabilities.periodic_report import core, triggers REPO_ROOT = pathlib.Path(__file__).resolve().parents[2] -PACKAGE_ROOT = REPO_ROOT / "loopx" OWNER_PATH = "loopx/capabilities/periodic_report/core.py" CONSUMER_PATH = "loopx/capabilities/periodic_report/triggers.py" @@ -55,16 +63,6 @@ } ) -# A preset's ``enabled_kinds`` is a configuration choice -- which kinds *this -# preset* enables -- not the vocabulary of which kinds are reportable. The weekly -# preset enables all eight today, but the portfolio preset selects only -# ``["cadence_due"]``, proving the list is a per-preset policy. Borrowing the -# owner here would auto-enable any future reportable kind in the weekly preset, -# a domain decision rather than a deduplication. The list is sorted downstream by -# ``_normalize_policy``, so its literal order carries no meaning. Declared, and -# pinned to exactly one site below so the declaration cannot rot silently. -DECLARED_CONFIG_SITES = {"loopx/capabilities/periodic_report/presets.py": 1} - def _members(node: ast.expr) -> frozenset[str] | None: """Fold a set / frozenset / list / tuple of plain string literals to members.""" @@ -104,24 +102,6 @@ def _kind_literal_sites(source: str) -> list[int]: ] -@pytest.fixture(scope="module") -def tree_findings() -> dict[str, str]: - findings: dict[str, str] = {} - for path in sorted(PACKAGE_ROOT.rglob("*.py")): - relative = path.relative_to(REPO_ROOT).as_posix() - if relative == OWNER_PATH: - continue - sites = _kind_literal_sites(path.read_text(encoding="utf-8")) - declared = DECLARED_CONFIG_SITES.get(relative, 0) - if len(sites) != declared: - findings[relative] = f"states the kind set at {sites}, declared {declared}" - return findings - - -def test_only_the_owner_and_the_declared_preset_state_the_kind_set(tree_findings) -> None: - assert tree_findings == {}, f"an undeclared restatement of the reportable kinds remains: {tree_findings}" - - def test_the_owner_states_the_recorded_members_once() -> None: assert frozenset(core._REPORTABLE_TRIGGER_KINDS) == KINDS source = (REPO_ROOT / OWNER_PATH).read_text(encoding="utf-8") @@ -151,17 +131,74 @@ def test_the_non_reportable_neighbour_is_a_different_set() -> None: def test_the_preset_enabled_kinds_is_a_configuration_not_the_vocabulary() -> None: from loopx.capabilities.periodic_report import presets - # Two presets, two different selections: this is a per-preset policy, which - # is why the weekly list is declared rather than folded into the owner. + # A preset's ``enabled_kinds`` is a configuration choice -- which kinds + # *this preset* enables -- not the vocabulary of which kinds are + # reportable. Borrowing the owner here would auto-enable any future + # reportable kind in the weekly preset, a domain decision rather than a + # deduplication. Two presets, two different selections, so the list is a + # per-preset policy; it is verified behaviourally below, not pinned by a + # literal-site count that a second legitimate profile would break. weekly = presets._WEEKLY_PROGRESS_PROFILE["trigger_policy"]["enabled_kinds"] assert frozenset(weekly) == KINDS portfolio = presets.resolve_periodic_report_profile_preset("portfolio-progress") assert portfolio["trigger_policy"]["enabled_kinds"] == ["cadence_due"] - # The declaration is pinned to exactly one site, so it cannot rot silently. - source = (REPO_ROOT / "loopx/capabilities/periodic_report/presets.py").read_text( - encoding="utf-8" + + +# --- profile selections are configuration, verified through the real decision entry --- + + +def _decide( + profile_id: str, policy: dict[str, Any], kind: str, facts: dict[str, Any] +) -> dict[str, Any]: + return triggers.build_periodic_report_trigger_decision( + { + "schema_version": triggers.TRIGGER_REQUEST_SCHEMA, + "evaluated_at": "2026-11-12T00:00:00Z", + "profile": {"profile_id": profile_id, "profile_version": "v1"}, + "trigger_policy": policy, + "candidates": [ + { + "trigger_kind": kind, + "observed_at": "2026-11-12T00:00:00Z", + "source_ref": f"{profile_id}-{kind}", + "evidence_digest": f"{profile_id}-{kind}-evidence", + "facts": facts, + } + ], + } ) - assert len(_kind_literal_sites(source)) == 1 + + +def test_each_profile_selection_drives_the_real_decision() -> None: + from loopx.capabilities.periodic_report import presets + + weekly = presets.resolve_periodic_report_profile_preset("weekly-progress") + portfolio = presets.resolve_periodic_report_profile_preset("portfolio-progress") + # The same authorized manual candidate: weekly enables it, portfolio does not. + selected = _decide( + "weekly_progress", weekly["trigger_policy"], "manual", {"authorized": True} + ) + assert selected["selected_trigger_kind"] == "manual" + suppressed = _decide( + "portfolio_progress", + portfolio["trigger_policy"], + "manual", + {"authorized": True}, + ) + assert suppressed["selected_trigger_kind"] is None + assert suppressed["suppressed_triggers"][0]["reason"] == "disabled_by_profile" + + +def test_a_second_profile_may_select_the_same_kinds_with_its_own_interval() -> None: + # Two profiles may legitimately select the same eight kinds with different + # intervals: the selection belongs to each profile, so the real decision + # entry must accept this one rather than treat it as a duplicate vocabulary. + policy = {"enabled_kinds": sorted(KINDS), "minimum_interval_seconds": 21_600} + decision = _decide("six_hour_digest", policy, "cadence_due", {"due": True}) + assert decision["ok"] is True + assert decision["selected_trigger_kind"] == "cadence_due" + assert decision["trigger_policy"]["enabled_kinds"] == sorted(KINDS) + assert decision["trigger_policy"]["minimum_interval_seconds"] == 21_600 # --- behavioural parity through the consumer's own policy normalizer ---------------------- @@ -186,7 +223,7 @@ def test_the_default_enabled_kinds_is_the_owner_set() -> None: assert normalized["enabled_kinds"] == sorted(KINDS) -# --- the census bites every restatement form and leaves the others ---------------------- +# --- the folded-value scan bites every restatement form and leaves the others ----------- _MEMBER_TEXT = ", ".join(repr(kind) for kind in sorted(KINDS)) _NON_MEMBER_TEXT = ", ".join(repr(kind) for kind in sorted(NON_REPORTABLE)) @@ -212,4 +249,4 @@ def test_the_default_enabled_kinds_is_the_owner_set() -> None: def test_the_census_names_every_form_and_leaves_the_others( label: str, source: str, expected: int ) -> None: - assert len(_kind_literal_sites(source)) == expected, label \ No newline at end of file + assert len(_kind_literal_sites(source)) == expected, label From 202e71c4e6427ceb9cdf3614439791f3c52f7cd6 Mon Sep 17 00:00:00 2001 From: psychologister <230141834+psychologister@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:05:39 +0800 Subject: [PATCH 3/4] periodic_report: allow same-valued report-mapping keys in the kind guard The consumer-file blanket literal bans still rejected an equivalent rewrite of the report mapping: `_REPORT_KIND` legitimately keys on the same eight reportable kinds, so rewriting it as `dict(zip(keys, values))` leaves the mapping identical but folds a keys tuple to the owner set and trips the bans. Reproduced locally: with that rewrite the decision output is unchanged yet the guard failed the retirement and neighbour tests. Per the review, AST hard assertions must stay limited to identifiable eligibility decisions and same-valued report-mapping keys must be allowed. The two consumer-wide `_kind_literal_sites(source) == []` bans are removed. The report mapping's relationship to the vocabulary is now pinned at runtime by domain parity (`set(triggers._REPORT_KIND) == KINDS`), which accepts any equivalent source shape while a drifted domain still fails. Retained: the owner states the set once, the identity borrow, retirement of the restated name, the non-reportable neighbour's disjointness, and all behavioural parity through `_normalize_policy` and the real decision entry (including the same-set-different-interval profile and the weekly/portfolio split). The folded-value scan and its poison controls now guard only the identifiable owner site; whole-package same-value matching stays in the advisory lane. Verified: the equivalent-rewrite fixture is green, mapping-domain drift, restated-name return, and a broken borrow each still fail their targeted test, and the focused periodic_report selection plus ruff are clean. Refs #4447. Signed-off-by: psychologister <230141834+psychologister@users.noreply.github.com> --- ...t_periodic_report_reportable_kind_owner.py | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/tests/architecture/test_periodic_report_reportable_kind_owner.py b/tests/architecture/test_periodic_report_reportable_kind_owner.py index 28618b15be..37b70e2084 100644 --- a/tests/architecture/test_periodic_report_reportable_kind_owner.py +++ b/tests/architecture/test_periodic_report_reportable_kind_owner.py @@ -7,17 +7,19 @@ module restating a constant whose owner it already imports from. It now borrows the owner object and the restated name is retired. +The hard checks are limited to identifiable eligibility decisions: the owner +states the vocabulary once, the consumer borrows that exact object and retires +its restated name, and the report mapping's domain equals the vocabulary. The +report mapping (``_REPORT_KIND``) legitimately keys on the same eight kinds, so +its keys are pinned by runtime domain parity, never by banning same-valued +literals -- an equivalent rewrite of that mapping must stay green. Behavioural +parity runs through the consumer's own policy normalizer and the real decision +entry. + The neighbouring ``_NON_REPORTABLE_KINDS`` (five different kinds) is a separate -vocabulary and is deliberately left alone. The targeted literal checks key on -the **folded value**, so that neighbour is never swept: its members differ. The -by-name semantic inventory cannot see this pair either, because the two sides -use different names and both are module-private. - -Hard checks are pinned to the sites that share one semantic slot, scope and -contract: the owner (``core``) and the validation entry -(``triggers._normalize_policy``), with behavioural parity through that entry. -A profile's ``enabled_kinds`` is a different slot -- a per-profile choice of -which kinds *that profile* enables -- so two profiles may legitimately select +vocabulary and is deliberately left alone; it must not overlap the reportable +set. A profile's ``enabled_kinds`` is a different slot -- a per-profile choice +of which kinds *that profile* enables -- so two profiles may legitimately select the same eight kinds with different intervals; those selections are verified through the real decision entry, not by counting literals. Whole-package same-value matching stays in the existing advisory lane (the semantic @@ -112,20 +114,25 @@ def test_the_consumer_borrows_the_owner_object() -> None: assert triggers._REPORTABLE_TRIGGER_KINDS is core._REPORTABLE_TRIGGER_KINDS +def test_the_report_mapping_domain_is_the_owner_set() -> None: + # The report mapping keys on the same eight kinds -- a legitimate + # same-valued use, not a restatement of the vocabulary. Pin the domain at + # runtime so any equivalent source shape (dict literal, dict(zip(...))) + # stays green while a drifted domain still fails. + assert set(triggers._REPORT_KIND) == KINDS + + def test_the_consumer_retired_its_restated_name() -> None: assert not hasattr(triggers, "_REPORTABLE_KINDS") source = (REPO_ROOT / CONSUMER_PATH).read_text(encoding="utf-8") - assert _kind_literal_sites(source) == [] assert "_REPORTABLE_TRIGGER_KINDS" in source def test_the_non_reportable_neighbour_is_a_different_set() -> None: - # The five non-reportable kinds stay where they are; the value census must - # not sweep them, and they must not overlap the reportable set. + # The five non-reportable kinds stay where they are; they are a separate + # vocabulary and must not overlap the reportable set. assert frozenset(triggers._NON_REPORTABLE_KINDS) == NON_REPORTABLE assert NON_REPORTABLE.isdisjoint(KINDS) - source = (REPO_ROOT / CONSUMER_PATH).read_text(encoding="utf-8") - assert _kind_literal_sites(source) == [] def test_the_preset_enabled_kinds_is_a_configuration_not_the_vocabulary() -> None: From 0ae47e92a1370cdd910a1cb48a69533ab19fed2f Mon Sep 17 00:00:00 2001 From: psychologister <230141834+psychologister@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:30:42 +0800 Subject: [PATCH 4/4] periodic_report: follow the shared kind definition at the policy entry The previous revision accepted a renamed same-value copy of the reportable kind set feeding only _normalize_policy's explicit-list check: every value check passed because the values are equal today, so the guard could not see the duplicate. Reproduced in an isolated copy -- all 34 tests passed with the copy, and with `manual` removed from the shared definition the head rejected the request with enabled_kinds[0] is not reportable while the copy accepted it and returned no_material_trigger. Exercise the consumer's actual binding instead of scanning for literals: temporarily replace the shared object in both module namespaces with the set minus `manual`, require the real policy entry and decision entry to reject the explicit list, require the default to follow the reduced set, then restore and require the same request to pass. A same-valued copy in that path is inert under the change and fails the new test, while the equivalent _REPORT_KIND rewrite and a second profile selecting the same eight kinds with its own interval stay green. Refs #4447. Signed-off-by: psychologister <230141834+psychologister@users.noreply.github.com> --- ...t_periodic_report_reportable_kind_owner.py | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tests/architecture/test_periodic_report_reportable_kind_owner.py b/tests/architecture/test_periodic_report_reportable_kind_owner.py index 37b70e2084..09f1aaa329 100644 --- a/tests/architecture/test_periodic_report_reportable_kind_owner.py +++ b/tests/architecture/test_periodic_report_reportable_kind_owner.py @@ -16,6 +16,14 @@ parity runs through the consumer's own policy normalizer and the real decision entry. +Equal values make a renamed copy indistinguishable by value, so the policy +entry is also exercised under a controlled change of the shared definition: +with ``manual`` removed from the imported object the entry rejects the explicit +list (and its default follows the reduced set), and with the definition +restored the same request passes. A same-valued copy in that path is inert +under the change and fails there, while the report mapping and per-profile +selections -- different slots -- are unaffected. + The neighbouring ``_NON_REPORTABLE_KINDS`` (five different kinds) is a separate vocabulary and is deliberately left alone; it must not overlap the reportable set. A profile's ``enabled_kinds`` is a different slot -- a per-profile choice @@ -230,6 +238,44 @@ def test_the_default_enabled_kinds_is_the_owner_set() -> None: assert normalized["enabled_kinds"] == sorted(KINDS) +def test_the_policy_entry_follows_the_shared_definition( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A renamed same-value copy feeding only the explicit-list check passes every + # value check above, because the values are equal today. Make the definition + # observably different instead -- drop ``manual`` -- and require the real + # entry to reject it, then accept it again once the definition is restored. + # A copy is inert under that change, so it fails here. + reduced = KINDS - {"manual"} + request = { + "schema_version": triggers.TRIGGER_REQUEST_SCHEMA, + "evaluated_at": "2026-11-12T00:00:00Z", + "profile": {"profile_id": "manual_probe", "profile_version": "v1"}, + "trigger_policy": {"enabled_kinds": ["manual"]}, + "candidates": [ + { + "trigger_kind": "surface_only", + "observed_at": "2026-11-12T00:00:00Z", + "source_ref": "manual-probe", + "evidence_digest": "manual-probe-evidence", + "facts": {}, + } + ], + } + with monkeypatch.context() as patched: + # Patch both legitimate lookup forms of the shared object, so an + # attribute-style ``core._REPORTABLE_TRIGGER_KINDS`` read stays green too. + patched.setattr(core, "_REPORTABLE_TRIGGER_KINDS", reduced) + patched.setattr(triggers, "_REPORTABLE_TRIGGER_KINDS", reduced) + with pytest.raises(ValueError, match=r"enabled_kinds\[0\] is not reportable"): + triggers.build_periodic_report_trigger_decision(request) + assert triggers._normalize_policy({})["enabled_kinds"] == sorted(reduced) + decision = triggers.build_periodic_report_trigger_decision(request) + assert decision["ok"] is True + assert decision["selected_trigger_kind"] is None + assert decision["reason"] == "no_material_trigger" + + # --- the folded-value scan bites every restatement form and leaves the others ----------- _MEMBER_TEXT = ", ".join(repr(kind) for kind in sorted(KINDS))