feat(rules): move a rule between global and project scope, keeping its id, history, areas and edges (#4063)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 54s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m41s
CI & Build / Build & push image (push) Successful in 33s

A rule's home is its reach: a rulebook topic makes it global, a project makes it
that project's. There was no way to change one, so a project rule decided to be
global could only be recreated and the original trashed — losing the id every
record cites, its edit history, its area tags and its relations.

- services.rulebooks.move_rule(rule_id, user_id, topic_id= | project_id=):
  exactly one destination (the model's CHECK), owned by the caller, not the
  rule's current home. A topic already holding a live rule with the same title
  is refused with a message naming that rule, instead of uq_rule_per_topic
  failing the commit. Someone else's rule reads as not found.
- Deliberately NOT done, and said in the docstring: no version (a version is
  what a rule said, milestone 323 decision 4), no duplicate gate (nothing new
  enters the corpus), no re-embed (retrieval reads the home at query time).
- Both doors: MCP move_rule, REST POST /api/rules/<id>/move (rule 33).
- UI: RuleHomePicker, one component in the rule editor (a global rule) and a
  project's rules tab (a project rule), so the two cannot drift on what a
  destination is.
- using-scribe names move_rule under "Where a new rule goes". Plugin
  2026.09.15.1626.

Milestone 414 step 3.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01821k5B3Ysecp9fNYs92Kuy
This commit is contained in:
2026-09-15 12:26:39 -04:00
co-authored by Claude Opus 5
parent b6751e4214
commit 4e4020c040
14 changed files with 471 additions and 6 deletions
+138
View File
@@ -0,0 +1,138 @@
"""Real-Postgres tests for moving a rule between homes (milestone 414, step 3).
A rule's home is its reach: a rulebook topic makes it global, a project makes
it that project's. The alternative to a move — recreate the rule in the other
home and trash the original — loses the id every record cites, the edit
history, the area tags and the typed edges. These pin that a move keeps all
four, and that the refusals happen before anything is written: the topic/
project CHECK (migration 0059) and the per-topic title index would otherwise
fail the commit with a raw database error.
"""
import uuid
from unittest.mock import MagicMock, patch
import pytest
import pytest_asyncio
from scribe.models import async_session
from scribe.models.project import Project
from scribe.models.rulebook import Rule
from scribe.services import canonical_systems as canonical_svc
from scribe.services import rule_versions as rv_svc
from scribe.services import rulebooks as rulebooks_svc
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
@pytest.fixture(autouse=True)
def _no_reindex():
"""Rule writes detach an embedding refresh that outlives the test's loop
and races the next fixture; nothing here is about recall."""
with patch("scribe.services.rulebooks._refresh_rule_embedding", MagicMock()):
yield
@pytest_asyncio.fixture
async def homes():
"""A project rule with a version, an area tag and an incoming edge, plus a
topic to move it into and a second project."""
tag = uuid.uuid4().hex[:8]
async with async_session() as s:
owner = await ensure_user(s, f"rule_move_owner_{tag}")
stranger = await ensure_user(s, f"rule_move_stranger_{tag}")
home = Project(user_id=owner.id, title="Where it started")
other = Project(user_id=owner.id, title="Somewhere else")
theirs = Project(user_id=stranger.id, title="Not yours")
s.add_all([home, other, theirs])
await s.flush()
ids = {"owner": owner.id, "stranger": stranger.id, "home": home.id,
"other": other.id, "theirs": theirs.id}
await s.commit()
owner = ids["owner"]
book = await rulebooks_svc.create_rulebook(owner, "House style")
topic = await rulebooks_svc.create_topic(book.id, owner, "transport")
rule = await rulebooks_svc.create_project_rule(
ids["home"], owner, "Plain HTTP only", "No app-level TLS.",
when_to_apply="setting a cookie flag or a URL scheme",
)
await rulebooks_svc.update_rule(rule.id, owner, statement="No app-level TLS, ever.")
area = await canonical_svc.find_by_name("CI & Release")
await rulebooks_svc.set_rule_systems(rule.id, owner, [area.id])
downstream = await rulebooks_svc.create_project_rule(
ids["home"], owner, "No Secure-Context APIs", "Browsers withhold them.",
when_to_apply="reaching for the clipboard API",
)
await rulebooks_svc.add_rule_relation(owner, downstream.id, rule.id, "elaborates")
ids.update(topic=topic.id, rule=rule.id, area=area.id)
return ids
async def _row(rule_id: int) -> Rule:
async with async_session() as s:
return await s.get(Rule, rule_id)
async def test_a_project_rule_becomes_global_and_keeps_everything(homes):
owner, rule_id = homes["owner"], homes["rule"]
moved = await rulebooks_svc.move_rule(rule_id, owner, topic_id=homes["topic"])
assert moved.id == rule_id
row = await _row(rule_id)
assert (row.topic_id, row.project_id) == (homes["topic"], None)
assert len(await rv_svc.list_versions(rule_id)) == 1, "the move must not drop history"
areas = await rulebooks_svc.list_rule_systems([rule_id])
assert [a["id"] for a in areas[rule_id]] == [homes["area"]]
edges = await rulebooks_svc.list_rule_relations([rule_id])
assert [e["kind"] for e in edges[rule_id]] == ["elaborates"]
async def test_a_move_writes_no_version(homes):
"""A version records what a rule SAID (milestone 323, decision 4). A move
changes where it binds, not a word of it."""
before = len(await rv_svc.list_versions(homes["rule"]))
await rulebooks_svc.move_rule(homes["rule"], homes["owner"], topic_id=homes["topic"])
assert len(await rv_svc.list_versions(homes["rule"])) == before
async def test_a_global_rule_can_move_onto_a_project(homes):
owner, rule_id = homes["owner"], homes["rule"]
await rulebooks_svc.move_rule(rule_id, owner, topic_id=homes["topic"])
await rulebooks_svc.move_rule(rule_id, owner, project_id=homes["other"])
row = await _row(rule_id)
assert (row.topic_id, row.project_id) == (None, homes["other"])
async def test_refusals_happen_before_anything_is_written(homes):
owner, rule_id = homes["owner"], homes["rule"]
with pytest.raises(ValueError, match="exactly one"):
await rulebooks_svc.move_rule(rule_id, owner)
with pytest.raises(ValueError, match="exactly one"):
await rulebooks_svc.move_rule(rule_id, owner, topic_id=homes["topic"],
project_id=homes["other"])
with pytest.raises(ValueError, match="already on project"):
await rulebooks_svc.move_rule(rule_id, owner, project_id=homes["home"])
with pytest.raises(ValueError, match="not found"):
await rulebooks_svc.move_rule(rule_id, owner, project_id=homes["theirs"])
# A topic already holding a live rule with this title: named, not a raw
# IntegrityError from uq_rule_per_topic at commit.
clash = await rulebooks_svc.create_rule(
homes["topic"], owner, "Plain HTTP only", "Already here.",
when_to_apply="setting a cookie flag",
)
with pytest.raises(ValueError, match=f"rule {clash.id}"):
await rulebooks_svc.move_rule(rule_id, owner, topic_id=homes["topic"])
row = await _row(rule_id)
assert (row.topic_id, row.project_id) == (None, homes["home"])
async def test_someone_elses_rule_is_not_found(homes):
"""None, like every other rule read the caller cannot see — not an error
that confirms the rule exists."""
assert await rulebooks_svc.move_rule(
homes["rule"], homes["stranger"], project_id=homes["theirs"],
) is None
+28 -2
View File
@@ -204,8 +204,9 @@ def test_register_attaches_every_tool():
# 28 since milestone 394 took list_always_on_rules and the two
# always-on exclusion tools with the tier they served.
# 22 since milestone 414 retired subscriptions and suppressions: the two
# subscribe tools and the four suppress/unsuppress tools.
assert len(mcp.names) == 22
# subscribe tools and the four suppress/unsuppress tools. 23 with move_rule
# (milestone 414 step 3), the way a rule changes home.
assert len(mcp.names) == 23
# spot-check a few names
assert "list_rulebooks" in mcp.names
assert "create_rule" in mcp.names
@@ -216,6 +217,7 @@ def test_register_attaches_every_tool():
assert "create_preference" in mcp.names
assert "update_preference" in mcp.names
assert "create_project_rule" in mcp.names
assert "move_rule" in mcp.names
# milestone 312: the sweep, and the stamp that answers it
assert "rules_due_for_verification" in mcp.names
assert "mark_rule_verified" in mcp.names
@@ -448,3 +450,27 @@ def test_rule_history_docstring_says_what_a_version_HOLDS():
"and, not finding it, is likely to hand-copy the old text back with "
"no record of why."
)
@pytest.mark.asyncio
async def test_move_rule_passes_one_destination_and_returns_the_detail():
"""The tool is a thin door: the service decides what a valid move is, and
the reply is the same rule_detail every other write returns."""
moved = fake_rule(id=94, topic_id=12, project_id=None)
move = AsyncMock(return_value=moved)
detail = AsyncMock(return_value={"id": 94, "topic_id": 12, "project_id": None})
with patch("scribe.mcp.tools.rulebooks.rulebooks_svc.move_rule", move), \
patch("scribe.mcp.tools.rulebooks.rulebooks_svc.rule_detail", detail):
from scribe.mcp.tools.rulebooks import move_rule
out = await move_rule(rule_id=94, topic_id=12)
assert move.await_args.args[0] == 94
assert move.await_args.kwargs == {"topic_id": 12, "project_id": 0}
assert out["topic_id"] == 12
@pytest.mark.asyncio
async def test_move_rule_on_someone_elses_rule_is_not_found():
with patch("scribe.mcp.tools.rulebooks.rulebooks_svc.move_rule", AsyncMock(return_value=None)):
from scribe.mcp.tools.rulebooks import move_rule
with pytest.raises(ValueError, match="not found"):
await move_rule(rule_id=94, project_id=3)
+1 -1
View File
@@ -93,7 +93,7 @@ def test_rule_handlers_callable():
from scribe.routes import rulebooks as rb_routes
for name in (
"list_rules", "create_rule", "get_rule", "update_rule", "delete_rule",
"get_project_rules",
"get_project_rules", "move_rule",
# The typed edges — both doors carry them (rule 33).
"relate_rules", "unrelate_rules",
):