feat(moments): rules mount on moments, through every rule door (milestone 458 step 3, #4921)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / integration (push) Successful in 1m0s
CI & Build / Python tests (push) Successful in 1m51s
CI & Build / Build & push image (push) Successful in 29s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / integration (push) Successful in 1m0s
CI & Build / Python tests (push) Successful in 1m51s
CI & Build / Build & push image (push) Successful in 29s
rule_moments (migration 0117) records which moments a rule arrives at, by catalog name, cascading with the rule. rule_detail, the one seam every rule door already returns through, gains moments beside system_ids: None leaves the mounts alone, a list replaces them. get_rule and both list_rules doors read them back, batched per page. All five MCP rule/preference writes and the three REST ones take moments and validate them before their create or update. An unknown name is refused with the catalog listed and leaves no half-made rule behind; a parity test pins that ordering on every door. Backup v22 carries the mounts as a join table remapped through the rule map; a real-Postgres round trip checks they land on the restored rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -17,7 +17,9 @@ from scribe.models.system_usage import SystemUsageEvent
|
||||
from scribe.models.moment_mapping import MomentMapping
|
||||
from scribe.models.retrieval_tuning import RetrievalTuningEvent
|
||||
from scribe.models.canonical_system import CanonicalSystem
|
||||
from scribe.models.rulebook import RuleRelation, rule_systems as rule_systems_t
|
||||
from scribe.models.rulebook import (
|
||||
RuleRelation, rule_moments as rule_moments_t, rule_systems as rule_systems_t,
|
||||
)
|
||||
from scribe.models.lesson_rule_link import LessonNoRule, LessonRuleLink
|
||||
from scribe.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
|
||||
from scribe.models.project import Project
|
||||
@@ -98,8 +100,12 @@ logger = logging.getLogger(__name__)
|
||||
# actions reach which moment, and the shipped defaults it switched off. Each
|
||||
# row is a correction an operator made in-session; a restore that dropped them
|
||||
# would silently put every misfire back.
|
||||
# v22 (2026-10) added rule_moments (milestone 458): the moments each rule
|
||||
# arrives at. A mount is a judgment about when a rule applies that nothing in
|
||||
# the rule's text records, and losing it would put back exactly the misses the
|
||||
# mounts were made to fix.
|
||||
# Bump when the serialized schema changes.
|
||||
BACKUP_VERSION = 21
|
||||
BACKUP_VERSION = 22
|
||||
|
||||
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED
|
||||
# below, these two lists must together account for the entire schema — which is
|
||||
@@ -146,6 +152,8 @@ _BACKED_UP = [
|
||||
"system_usage_events",
|
||||
# v21 (2026-10): an install's action → moment corrections (milestone 458).
|
||||
"moment_mappings",
|
||||
# v22 (2026-10): the moments each rule arrives at (milestone 458).
|
||||
"rule_moments",
|
||||
]
|
||||
|
||||
# Tables intentionally NOT in the backup, surfaced in the payload so the gap is
|
||||
@@ -741,6 +749,12 @@ def _topic_rows(rows) -> list[dict]:
|
||||
]
|
||||
|
||||
|
||||
def _rule_moment_rows(rows) -> list[dict]:
|
||||
"""A rule's mounts. The moment is a catalog NAME, the same on every
|
||||
install, so only the rule id needs remapping on the way back in."""
|
||||
return [{"rule_id": rule_id, "moment": moment} for rule_id, moment in rows]
|
||||
|
||||
|
||||
def _rule_system_rows(rows) -> list[dict]:
|
||||
"""A rule's area tags, carried by canonical SLUG for the same reason the
|
||||
Systems are: the catalog is global and its ids are per-install."""
|
||||
@@ -833,6 +847,9 @@ async def export_full_backup() -> dict:
|
||||
select(rule_systems_t.c.rule_id, CanonicalSystem.slug)
|
||||
.join(CanonicalSystem, CanonicalSystem.id == rule_systems_t.c.canonical_id)
|
||||
)).all()
|
||||
rule_moment_rows = (await session.execute(
|
||||
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
|
||||
)).all()
|
||||
rule_relations = (await session.execute(select(RuleRelation))).scalars().all()
|
||||
lesson_rule_links = (await session.execute(select(LessonRuleLink))).scalars().all()
|
||||
lesson_no_rule = (await session.execute(select(LessonNoRule))).scalars().all()
|
||||
@@ -899,6 +916,7 @@ async def export_full_backup() -> dict:
|
||||
"rules": _rule_rows(rules),
|
||||
"canonical_systems": _canonical_system_rows(canonical_systems),
|
||||
"rule_systems": _rule_system_rows(rule_system_rows),
|
||||
"rule_moments": _rule_moment_rows(rule_moment_rows),
|
||||
"rule_relations": _rule_relation_rows(rule_relations),
|
||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
||||
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
|
||||
@@ -1033,6 +1051,10 @@ async def export_user_backup(user_id: int) -> dict:
|
||||
.join(CanonicalSystem, CanonicalSystem.id == rule_systems_t.c.canonical_id)
|
||||
.where(rule_systems_t.c.rule_id.in_(_rule_ids))
|
||||
)).all() if _rule_ids else []
|
||||
rule_moment_rows = (await session.execute(
|
||||
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
|
||||
.where(rule_moments_t.c.rule_id.in_(_rule_ids))
|
||||
)).all() if _rule_ids else []
|
||||
# Scoped through the RULE, not the version's user_id. That column is
|
||||
# the ACTOR (milestone 323), so filtering on it would carry the
|
||||
# versions this user wrote on someone ELSE's rule and drop the ones
|
||||
@@ -1114,6 +1136,7 @@ async def export_user_backup(user_id: int) -> dict:
|
||||
"rules": _rule_rows(rules),
|
||||
"canonical_systems": _canonical_system_rows(canonical_systems),
|
||||
"rule_systems": _rule_system_rows(rule_system_rows),
|
||||
"rule_moments": _rule_moment_rows(rule_moment_rows),
|
||||
"rule_relations": _rule_relation_rows(rule_relations),
|
||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
||||
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
|
||||
@@ -1926,7 +1949,8 @@ async def _restore_v2(data: dict) -> dict:
|
||||
"repo_bindings": 0,
|
||||
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
|
||||
"code_shape_uses": 0, "canonical_systems": 0,
|
||||
"rule_systems": 0, "rule_relations": 0, "rule_versions": 0,
|
||||
"rule_systems": 0, "rule_moments": 0,
|
||||
"rule_relations": 0, "rule_versions": 0,
|
||||
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
|
||||
"lesson_no_rule": 0, "moment_mappings": 0,
|
||||
}
|
||||
@@ -2125,6 +2149,17 @@ async def _restore_v2(data: dict) -> dict:
|
||||
))
|
||||
stats["rule_systems"] += 1
|
||||
|
||||
# The same shape for a rule's mounts (v22): a join table with no
|
||||
# model, so no builder — the rule id is the only thing to remap.
|
||||
for rm in data.get("rule_moments", []):
|
||||
mapped_rule = maps.rules.get(rm.get("rule_id", 0))
|
||||
if mapped_rule is None or not rm.get("moment"):
|
||||
continue
|
||||
await session.execute(rule_moments_t.insert().values(
|
||||
rule_id=mapped_rule, moment=rm["moment"],
|
||||
))
|
||||
stats["rule_moments"] += 1
|
||||
|
||||
for rr in data.get("rule_relations", []):
|
||||
relation = _build_rule_relation(rr, maps)
|
||||
if relation is None:
|
||||
|
||||
@@ -142,6 +142,20 @@ def require_moment(name: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def require_moments(names: list[str] | None) -> list[str] | None:
|
||||
"""A rule's moments, normalised and de-duplicated — or the first refusal.
|
||||
|
||||
None passes through as None, which every rule door reads as "leave the
|
||||
mounts alone"; a list, [] included, is the whole set after the write.
|
||||
All are checked before any is stored, so a refusal leaves nothing
|
||||
half-mounted.
|
||||
"""
|
||||
if names is None:
|
||||
return None
|
||||
if isinstance(names, str):
|
||||
names = [names]
|
||||
return list(dict.fromkeys(require_moment(n) for n in names))
|
||||
|
||||
def catalog() -> dict:
|
||||
"""The catalog as plain data, for the MCP tool and the REST door alike."""
|
||||
return {
|
||||
|
||||
@@ -433,26 +433,36 @@ async def co_surfaced_partners(user_id: int, rule_ids: list[int]) -> list[Rule]:
|
||||
return out
|
||||
|
||||
|
||||
async def rule_detail(user_id: int, rule: Rule, system_ids: list[int] | None = None) -> dict:
|
||||
"""The full record, with its areas and edges attached.
|
||||
async def rule_detail(
|
||||
user_id: int, rule: Rule, system_ids: list[int] | None = None,
|
||||
moments: list[str] | None = None,
|
||||
) -> dict:
|
||||
"""The full record, with its areas, moments and edges attached.
|
||||
|
||||
ONE seam for both doors and every write path, so create, update and get
|
||||
cannot disagree about what a rule looks like coming back — the same
|
||||
reasoning as attach_relations for notes (#2859), and the same reasoning
|
||||
rule_brief exists for one level down.
|
||||
|
||||
`system_ids=None` means "leave the tags alone"; a list (including [])
|
||||
REPLACES them.
|
||||
`system_ids=None` / `moments=None` mean "leave them alone"; a list
|
||||
(including []) REPLACES them. Doors validate `moments` with
|
||||
`moments.require_moments` BEFORE their create, so an unknown name is
|
||||
refused without leaving a rule behind.
|
||||
"""
|
||||
if system_ids is not None:
|
||||
await set_rule_systems(rule.id, user_id, system_ids)
|
||||
if moments is not None:
|
||||
await set_rule_moments(rule.id, user_id, moments)
|
||||
data = rule.to_dict()
|
||||
systems = (await list_rule_systems([rule.id])).get(rule.id, [])
|
||||
mounted = (await list_rule_moments([rule.id])).get(rule.id, [])
|
||||
relations = (await list_rule_relations([rule.id])).get(rule.id, [])
|
||||
# Attached only when present (#2483): an empty key reads as a capability
|
||||
# the record has and isn't using, which is a different claim.
|
||||
if systems:
|
||||
data["systems"] = systems
|
||||
if mounted:
|
||||
data["moments"] = mounted
|
||||
if relations:
|
||||
data["relations"] = relations
|
||||
# The concrete situations judged (or proposed) to be instances of this
|
||||
@@ -1100,6 +1110,56 @@ async def set_rule_systems(
|
||||
return sorted(wanted)
|
||||
|
||||
|
||||
async def set_rule_moments(
|
||||
rule_id: int, user_id: int, moments: list[str],
|
||||
) -> list[str] | None:
|
||||
"""Replace which MOMENTS a rule arrives at (milestone 458). None if not owned.
|
||||
|
||||
Set-semantics like set_rule_systems: the list given IS the state after.
|
||||
Every name is checked against the catalog first and the whole write is
|
||||
refused on the first unknown one — a typo stored as a mount would read
|
||||
back as attached and never fire, the silent miss moments exist to end.
|
||||
"""
|
||||
from scribe.models.rulebook import rule_moments as rule_moments_t
|
||||
from scribe.services.moments import require_moments
|
||||
|
||||
wanted = require_moments(moments) or []
|
||||
async with async_session() as session:
|
||||
rule = await _fetch_owned_rule(session, rule_id, user_id)
|
||||
if rule is None:
|
||||
return None
|
||||
await session.execute(
|
||||
sql_delete(rule_moments_t).where(rule_moments_t.c.rule_id == rule_id)
|
||||
)
|
||||
for moment in wanted:
|
||||
await session.execute(
|
||||
insert(rule_moments_t).values(rule_id=rule_id, moment=moment)
|
||||
)
|
||||
await session.commit()
|
||||
return wanted
|
||||
|
||||
|
||||
async def list_rule_moments(rule_ids: list[int]) -> dict[int, list[str]]:
|
||||
"""The moments each of a batch of rules is mounted on, in catalog order."""
|
||||
from scribe.models.rulebook import rule_moments as rule_moments_t
|
||||
from scribe.services.moments import MOMENTS
|
||||
|
||||
if not rule_ids:
|
||||
return {}
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
|
||||
.where(rule_moments_t.c.rule_id.in_(rule_ids))
|
||||
)).all()
|
||||
order = {name: i for i, name in enumerate(MOMENTS)}
|
||||
out: dict[int, list[str]] = {}
|
||||
for rule_id, moment in rows:
|
||||
out.setdefault(rule_id, []).append(moment)
|
||||
for names in out.values():
|
||||
names.sort(key=lambda n: (order.get(n, len(order)), n))
|
||||
return out
|
||||
|
||||
|
||||
async def list_rule_systems(rule_ids: list[int]) -> dict[int, list[dict]]:
|
||||
"""The canon tags for a batch of rules, keyed by rule id.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user