Files
FabledScribe/tests/test_moment_actions.py
T
bvandeusenandClaude Opus 5.5 cf3de5bae1
CI & Build / Plugin hooks (push) Successful in 18s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m23s
CI & Build / Python tests (push) Successful in 2m0s
CI & Build / Build & push image (push) Successful in 36s
feat(moments): actions map onto moments, with in-session corrections (milestone 458 step 2, #4920)
moment_actions.resolve(tool, input) names every moment a call reaches and
the action that reached it. One call can reach several: kubectl apply is
a run, a deliver and a reach outside the workspace. Command tools match by
how each segment of the line starts, with a word boundary; other tools by
field=value arguments. The MCP server prefix and case are ignored.

56 shipped defaults cover the harness tools, Scribe tools and common
command shapes. moment_mappings (migration 0116) holds what an install
adds and the defaults it switches off. A removal is a stored row, so an
upgrade does not switch the default back on.

Per the operator ruling, corrections happen in the session: map_action
and unmap_action (write tools) return now_reaches so the fix can be
confirmed in the same reply. list_moments now shows each moment's
actions on this install. REST mirrors both doors, recorded as human.
Backup v21 carries the mappings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 10:58:00 -04:00

182 lines
7.2 KiB
Python

"""Which actions reach which moment (milestone 458 step 2) — the pure half.
Matching and resolution take no database: the defaults are code and an
install's mappings arrive as rows, so every case below hands `resolve` the
rows it needs. The writes that store those rows are exercised against real
Postgres in `test_integration_moment_mappings.py`.
"""
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
from scribe.services import moment_actions as ma
from scribe.services import moments
def _row(tool, match, moment, effect=ma.ADD):
return SimpleNamespace(tool=tool, match=match, moment=moment, effect=effect)
def _reached(tool, tool_input=None, mappings=()):
return [h["moment"] for h in ma.resolve(tool, tool_input, mappings)]
# ── the defaults ─────────────────────────────────────────────────────────
def test_every_default_reaches_a_real_moment():
"""A default naming a moment that is not in the catalog would never be
mounted on — the typo require_moment refuses at the door."""
bad = [a for a in ma.DEFAULT_ACTIONS if not moments.is_moment(a.moment)]
assert not bad, bad
def test_no_default_is_listed_twice():
keys = [(ma.tool_key(a.tool), a.match, a.moment) for a in ma.DEFAULT_ACTIONS]
assert len(keys) == len(set(keys))
def test_every_default_is_a_mapping_the_door_would_accept():
"""The defaults pass the same validation an install's mapping does, so a
default and an install's copy of it can never disagree about its shape."""
for a in ma.DEFAULT_ACTIONS:
assert ma._clean(a.tool, a.match, a.moment) == (a.tool, a.match, a.moment)
# ── matching ─────────────────────────────────────────────────────────────
@pytest.mark.parametrize("command", [
"git push origin dev",
"git push",
"cd app && git push",
"make lint; git push --tags",
"GIT_TRACE=1 git push",
" git push ",
])
def test_a_command_prefix_matches_any_segment_of_the_line(command):
assert "work.deliver" in _reached("Bash", {"command": command})
@pytest.mark.parametrize("command", ["git pushd", "echo git push", "git status"])
def test_a_command_prefix_needs_a_word_boundary_and_the_head_of_a_segment(command):
assert "work.deliver" not in _reached("Bash", {"command": command})
def test_one_action_reaches_every_moment_it_is():
"""`kubectl apply` is a run, a deliver and a reach outside the workspace."""
assert _reached("Bash", {"command": "kubectl apply -f deploy.yaml"}) == [
"work.run", "work.deliver", "env.reach",
]
def test_the_most_specific_action_is_the_one_named():
hits = ma.resolve("Bash", {"command": "git push"})
deliver = next(h for h in hits if h["moment"] == "work.deliver")
assert deliver["match"] == "git push"
run = next(h for h in hits if h["moment"] == "work.run")
assert run["match"] == ""
def test_an_ordinary_command_is_only_a_run():
assert _reached("Bash", {"command": "ls -la"}) == ["work.run"]
def test_an_unknown_tool_reaches_nothing():
assert _reached("SomeOtherTool", {"x": 1}) == []
@pytest.mark.parametrize("name", [
"mcp__plugin_scribe_scribe__update_task", "mcp__scribe__update_task",
"update_task", "Update_Task",
])
def test_the_server_prefix_and_case_do_not_matter(name):
assert _reached(name, {"task_id": 1, "status": "done"}) == ["work.finish"]
@pytest.mark.parametrize("status,expected", [
("done", ["work.finish"]),
("cancelled", ["work.finish"]),
("in_progress", ["work.start"]),
("todo", []),
("", []),
])
def test_arguments_select_the_moment(status, expected):
assert _reached("update_task", {"task_id": 1, "status": status}) == expected
def test_a_whole_tool_mapping_ignores_its_arguments():
assert _reached("Edit", {"file_path": "x", "old_string": "a"}) == ["work.change"]
def test_loading_a_procedure_reaches_its_own_moment():
assert _reached("Skill", {"skill": "scribe:writing-plans"}) == [
"skill.scribe:writing-plans",
]
def test_a_procedure_name_that_is_not_a_moment_reaches_nothing():
assert _reached("Skill", {"skill": "two words"}) == []
assert _reached("Skill", {}) == []
# ── an install's own ─────────────────────────────────────────────────────
def test_an_install_mapping_adds_a_moment():
rows = [_row("Bash", "make ship", "work.deliver")]
assert "work.deliver" in _reached("Bash", {"command": "make ship"}, rows)
assert "work.deliver" not in _reached("Bash", {"command": "make ship"})
def test_removing_a_default_removes_only_that_default():
"""`curl` stops reaching env.reach here; it is still a run, and `ssh`
still reaches out — a removal overrides nothing it did not name."""
rows = [_row("Bash", "curl", "env.reach", ma.REMOVE)]
assert _reached("Bash", {"command": "curl localhost:8000"}, rows) == ["work.run"]
assert "env.reach" in _reached("Bash", {"command": "ssh box"}, rows)
def test_a_removal_matches_the_default_whatever_the_tool_is_called():
rows = [_row("mcp__x__update_task", "status=done", "work.finish", ma.REMOVE)]
assert _reached("update_task", {"status": "done"}, rows) == []
def test_an_install_mapping_is_named_as_the_installs():
rows = [_row("Bash", "make ship", "work.deliver")]
hit = next(h for h in ma.resolve("Bash", {"command": "make ship"}, rows)
if h["moment"] == "work.deliver")
assert (hit["via"], hit["match"]) == (ma.INSTALL, "make ship")
# ── validation ───────────────────────────────────────────────────────────
def test_a_prefix_on_a_tool_that_runs_no_command_is_refused():
"""It would be stored and never match — a mapping that looks made and is
not, which is the misfire this table exists to fix."""
with pytest.raises(ValueError, match="field=value"):
ma._clean("update_task", "done", "work.finish")
def test_an_unknown_moment_is_refused():
with pytest.raises(ValueError, match="unknown moment"):
ma._clean("Bash", "make ship", "work.ship")
def test_a_mapping_is_normalised_before_it_is_stored():
assert ma._clean("mcp__x__update_task", " status=done ", " Work.Finish") == (
"update_task", "status=done", "work.finish",
)
assert ma._clean("Bash", "make ship", "work.deliver")[1] == "make ship"
def test_a_tool_is_required():
with pytest.raises(ValueError, match="tool is required"):
ma._clean(" ", "", "work.run")
# ── failing open ─────────────────────────────────────────────────────────
async def test_an_unreadable_mapping_table_costs_the_corrections_not_the_moments():
with patch.object(ma, "list_mappings", AsyncMock(side_effect=RuntimeError("db down"))):
hits = await ma.moments_for(7, "Bash", {"command": "git push"})
assert [h["moment"] for h in hits] == ["work.run", "work.deliver"]