Files
FabledGrimoire/tests/test_moments.py
T
bvandeusenandClaude Opus 5.5 b4bdd7798c
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Python tests (push) Failing after 1m48s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Skipped
feat(7733): adherence is measured per rule and per moment, and shown
A rule is in force at a moment of a session when it was delivered there.
Each (session, rule, place) now carries at most one verdict (rule_adherence,
migration 0134): followed, departed, broken or not applicable, with where it
came from:

- an enforce rule refusing the act: followed, recorded by the moment arm, and
  never replaced;
- the session's own rule_outcome (applied, departed) and rule_misfired calls,
  which the plugin's outcome hook now also posts with the session id
  (/api/plugin/rule-verdict) onto the delivery being answered;
- a transcript review: adherence_to_judge lists what has no verdict yet, by
  session, and judge_adherence records verdicts with their evidence.

rule_adherence (MCP) and /api/retrieval/adherence give the readout: sessions
in force, opened and each verdict per rule and per place. Settings > Moments
shows it in a "Were they followed" panel, beside each moment's delivered and
opened counts, and per rule inside each moment.

Verdicts are pruned with their deliveries and left out of backups like them.
Plugin 2026.11.23.2227.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:28:23 -05:00

157 lines
5.9 KiB
Python

"""The moment catalog — the vocabulary rules mount on.
What this pins is what a mount depends on: every name is well-formed and
resolvable, an unknown name is refused rather than stored, the catalog speaks
for any kind of work rather than only software, and both doors — the MCP tool
and the REST read — hand out the same catalog.
"""
import re
import pytest
from grimoire.services import moments
from tests.helpers import FakeMCP, dev_only_hits
_NAME = re.compile(r"^[a-z]+\.[a-z]+$")
def test_the_catalog_is_not_empty():
"""The sweeps below are vacuous over an empty catalog."""
assert len(moments.MOMENTS) >= 10
def test_every_moment_is_keyed_by_its_own_well_formed_name():
for key, m in moments.MOMENTS.items():
assert key == m.name, f"{key!r} is filed under a name it does not carry"
assert _NAME.match(key), f"{key!r} is not <area>.<verb>"
def test_every_moment_says_what_it_means_and_how_it_is_reached():
for m in moments.MOMENTS.values():
assert m.means.strip() and m.reached_by.strip(), m.name
assert "\n" not in m.means, f"{m.name}: `means` is one line"
def test_the_skill_family_is_not_a_catalog_entry():
"""A family is a shape, not a moment — no rule mounts on `skill.<name>`
literally, and a catalog key starting with the prefix would shadow it."""
assert not any(k.startswith(moments.SKILL_PREFIX) for k in moments.MOMENTS)
@pytest.mark.parametrize("field", ["means", "reached_by"])
def test_the_catalog_assumes_no_particular_domain(field):
found = {
m.name: hits
for m in [*moments.MOMENTS.values(), moments.SKILL_FAMILY]
if (hits := dev_only_hits(getattr(m, field)))
}
assert not found, f"software-only vocabulary in `{field}`: {found}"
def test_the_guard_can_fail():
assert dev_only_hits("after the commit lands")
@pytest.mark.parametrize("name", list(moments.MOMENTS))
def test_every_catalog_moment_is_mountable(name):
assert moments.require_moment(name) == name
@pytest.mark.parametrize("raw,clean", [
(" Work.Finish ", "work.finish"),
("skill.verification", "skill.verification"),
("skill.grimoire:writing-plans", "skill.grimoire:writing-plans"),
("skill.grimoire-proc-release_notes", "skill.grimoire-proc-release_notes"),
])
def test_a_name_is_normalised_before_it_is_judged(raw, clean):
assert moments.require_moment(raw) == clean
@pytest.mark.parametrize("bad", [
"work.finished", "finish", "", "skill.", "skill.two words", "work.",
])
def test_an_unknown_moment_is_refused_with_the_catalog(bad):
"""A typo stored as a mount never fires — the silent failure moments end."""
with pytest.raises(ValueError) as exc:
moments.require_moment(bad)
assert "work.finish" in str(exc.value)
assert moments.SKILL_FAMILY.name in str(exc.value)
def test_the_catalog_payload_carries_every_moment_and_the_family():
data = moments.catalog()
assert [m["name"] for m in data["moments"]] == list(moments.MOMENTS)
assert data["total"] == len(moments.MOMENTS)
assert data["families"][0]["prefix"] == moments.SKILL_PREFIX
async def test_the_tool_returns_the_catalog_with_this_installs_actions():
from unittest.mock import AsyncMock, patch
from grimoire.mcp.tools import moments as tool
by_moment = {"actions": {"work.change": []}, "removed_defaults": []}
with patch.object(tool, "current_user_id", lambda: 7), \
patch.object(tool.actions_svc, "actions_by_moment",
AsyncMock(return_value=by_moment)) as read:
out = await tool.list_moments()
read.assert_awaited_once_with(7)
assert out["moments"] == moments.catalog()["moments"]
assert out["actions"] == by_moment["actions"]
assert out["removed_defaults"] == []
def test_the_tools_are_registered_and_classified():
from grimoire.mcp.server import _READ_ONLY_TOOLS, _WRITE_TOOLS
from grimoire.mcp.tools import moments as tool
mcp = FakeMCP()
tool.register(mcp)
assert mcp.names == [
"list_moments", "list_reply_shapes", "map_action", "unmap_action",
"rules_to_mount", "propose_rule_moments", "rule_moment_proposals",
"judge_rule_moments", "rule_misfired",
"rules_to_weigh", "propose_rule_weights", "rule_weight_proposals",
"judge_rule_weights",
"rule_adherence", "adherence_to_judge", "judge_adherence",
]
assert {"list_moments", "list_reply_shapes",
"rules_to_mount", "rule_moment_proposals",
"rules_to_weigh", "rule_weight_proposals",
"rule_adherence", "adherence_to_judge"} <= _READ_ONLY_TOOLS
# A confirm mounts a rule, so a read key must not reach it.
assert {"map_action", "unmap_action",
"propose_rule_moments", "judge_rule_moments", "rule_misfired",
"propose_rule_weights", "judge_rule_weights", "judge_adherence"} <= _WRITE_TOOLS
def test_both_doors_read_one_catalog():
"""Door parity: the tool and the routes call the same services, so the
session and the Settings view cannot name different moments or disagree
about what a mapping does."""
from grimoire.mcp.tools import moments as tool
from grimoire.routes import retrieval as routes
from grimoire.services import moment_actions
assert tool.moments_svc is moments
assert routes.moments_svc is moments
assert tool.actions_svc is moment_actions
assert routes.moment_actions_svc is moment_actions
def test_a_rules_moments_are_normalised_and_deduplicated():
assert moments.require_moments([" Work.Finish", "reply.report", "work.finish"]) == [
"work.finish", "reply.report",
]
assert moments.require_moments("work.finish") == ["work.finish"]
assert moments.require_moments([]) == []
def test_absent_moments_mean_leave_them_alone():
assert moments.require_moments(None) is None
def test_one_unknown_moment_refuses_the_whole_set():
with pytest.raises(ValueError, match="work.finished"):
moments.require_moments(["work.finish", "work.finished"])