feat(7732): a pass weighs each rule — enforcement, salience and triggers proposed from its text and delivery history, confirmed by the operator
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Failing after 1m41s
CI & Build / integration (push) Successful in 2m9s
CI & Build / Build & push image (push) Skipped

Adds rule_field_judgments (migration 0132), the rules_to_weigh / propose_rule_weights / rule_weight_proposals / judge_rule_weights tools, the routes and the Settings › Moments panel that confirms them. A value equal to the rule's own is recorded as agreed; a different one waits; enforce is refused for a rule no act reaches; a direct edit answers a waiting suggestion. Backup v30 carries the judgments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 13:05:38 -05:00
co-authored by Claude Opus 5.5
parent 78c945e7c3
commit 619612732f
20 changed files with 1320 additions and 34 deletions
+62 -2
View File
@@ -26,6 +26,7 @@ from grimoire.models.rulebook import (
rule_triggers as rule_triggers_t,
)
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
from grimoire.models.rule_field_judgment import RuleFieldJudgment
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
from grimoire.models.project import Project
@@ -116,7 +117,10 @@ logger = logging.getLogger(__name__)
# from. A live instance rolls back only to a backup with its own id.
# v29 rule_triggers: the typed predicates on the act that deliver a rule or
# make its mount conditional. Nothing in the rule's text records them.
BACKUP_VERSION = 29
# v30 rule_field_judgments: suggested, agreed and rejected values for a rule's
# enforcement, salience and triggers. Lose them and a weighed corpus reads
# as unweighed, and every rejected value is proposed again.
BACKUP_VERSION = 30
# 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
@@ -162,6 +166,7 @@ _BACKED_UP = [
"rule_moments",
"rule_moment_judgments",
"rule_triggers",
"rule_field_judgments",
# Family canon. `platforms` is global like
# canonical_systems and rides every export for the same reason: the rows
# below name platforms by slug, and a partial catalog restores partial
@@ -269,6 +274,8 @@ _COLUMN_EXCLUSIONS: dict[str, set[str]] = {
"lesson_rule_links": {"id"},
# The same shape: the (rule, moment) pair is the row.
"rule_moment_judgments": {"id"},
# And again: the (rule, field, value) triple is the row.
"rule_field_judgments": {"id"},
# Keyed by the lesson itself; nothing to exclude, every column travels.
"lesson_no_rule": set(),
"note_usage_events": {"id"},
@@ -376,6 +383,7 @@ _IMPORT_COLUMN_EXCLUSIONS: dict[str, set[str]] = {
"rule_relations": {"id", "created_at"},
"lesson_rule_links": {"id"},
"rule_moment_judgments": {"id"},
"rule_field_judgments": {"id"},
"lesson_no_rule": set(),
"note_usage_events": {"id"},
"rule_usage_events": {"id"},
@@ -830,6 +838,21 @@ def _rule_moment_judgment_rows(rows) -> list[dict]:
]
def _rule_field_judgment_rows(rows) -> list[dict]:
"""Suggested, agreed and rejected values for a rule's enforcement,
salience and triggers (v30). The rule id is a SOURCE id, remapped at
restore."""
return [
{
"rule_id": r.rule_id, "field": r.field, "value": r.value, "state": r.state,
"source": r.source, "note": r.note, "evidence": r.evidence,
"judged_at": r.judged_at.isoformat() if r.judged_at else None,
"created_at": r.created_at.isoformat() if r.created_at else None,
}
for r 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."""
@@ -1042,6 +1065,9 @@ async def export_full_backup() -> dict:
rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).order_by(RuleMomentJudgment.id)
)).scalars().all()
rule_field_judgments = (await session.execute(
select(RuleFieldJudgment).order_by(RuleFieldJudgment.id)
)).scalars().all()
rule_relations = (await session.execute(select(RuleRelation).order_by(RuleRelation.id))).scalars().all()
lesson_rule_links = (await session.execute(select(LessonRuleLink).order_by(LessonRuleLink.id))).scalars().all()
lesson_no_rule = (await session.execute(select(LessonNoRule).order_by(LessonNoRule.lesson_id))).scalars().all()
@@ -1133,6 +1159,7 @@ async def export_full_backup() -> dict:
"rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
"rule_field_judgments": _rule_field_judgment_rows(rule_field_judgments),
"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),
@@ -1301,6 +1328,10 @@ async def export_user_backup(user_id: int) -> dict:
rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).where(RuleMomentJudgment.rule_id.in_(_rule_ids))
)).scalars().all() if _rule_ids else []
rule_field_judgments = (await session.execute(
select(RuleFieldJudgment).where(RuleFieldJudgment.rule_id.in_(_rule_ids))
.order_by(RuleFieldJudgment.id)
)).scalars().all() if _rule_ids else []
# Scoped through the RULE, not the version's user_id. That column is
# the ACTOR, so filtering on it would carry the
# versions this user wrote on someone ELSE's rule and drop the ones
@@ -1426,6 +1457,7 @@ async def export_user_backup(user_id: int) -> dict:
"rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
"rule_field_judgments": _rule_field_judgment_rows(rule_field_judgments),
"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),
@@ -1857,6 +1889,25 @@ def _build_rule_moment_judgment(row: dict, maps: _Maps) -> RuleMomentJudgment |
)
def _build_rule_field_judgment(row: dict, maps: _Maps) -> RuleFieldJudgment | None:
"""Skipped when its rule did not restore, for the reason a moment
judgment is."""
rule = maps.rules.get(row.get("rule_id", 0))
if rule is None or not row.get("field") or row.get("value") is None:
return None
return RuleFieldJudgment(
rule_id=rule,
field=row["field"],
value=row["value"],
state=row.get("state") or "suggested",
source=row.get("source") or "pass",
note=row.get("note") or None,
evidence=row.get("evidence"),
judged_at=_dt_or_none(row.get("judged_at")),
created_at=_dt(row.get("created_at")),
)
def _build_platform(row: dict, maps: _Maps) -> Platform | None:
"""Matched on SLUG, like a canonical system: this install seeded the
standard platforms from its migrations, so the common case creates nothing
@@ -2447,7 +2498,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
"code_shape_uses": 0, "canonical_systems": 0,
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
"rule_triggers": 0,
"rule_triggers": 0, "rule_field_judgments": 0,
"rule_relations": 0, "rule_versions": 0,
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
"lesson_no_rule": 0, "moment_mappings": 0,
@@ -2666,6 +2717,15 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
session.add(judgment)
stats["rule_moment_judgments"] += 1
# Weighed values for each rule (v30); archives before v30 carry none, and
# every rule restores unweighed.
for rf in data.get("rule_field_judgments", []):
weighed = _build_rule_field_judgment(rf, maps)
if weighed is None:
continue
session.add(weighed)
stats["rule_field_judgments"] += 1
for rr in data.get("rule_relations", []):
relation = _build_rule_relation(rr, maps)
if relation is None:
@@ -0,0 +1,501 @@
"""How strongly each rule arrives, and what reaches it — proposals and judgments.
A rule carries three fields that decide what happens once the work reaches it:
- `enforcement` — `inform` (a line beside the work), `hold` (the act or reply
waits for one read of the rule) or `enforce` (the act it governs is refused,
in the rule's own words, every time). A preference is always `inform`.
- `salience` — `high`, `normal` or `low`: how it ranks beside rules of the same
enforcement when a moment has more to say than fits.
- `trigger` — typed predicates on the act (tool, path, command, keyword) that
reach the rule exactly, with no resemblance involved.
Every rule written before these fields existed carries the defaults, which
say nothing about whether anyone judged them. This service records that
judgment the way moment mounts are recorded (`rule_moment_judgments`):
- THE PASS. An agent reads each rule nobody has weighed, with its delivery
history — how often it reached a session, at which places, how often it was
opened there, how often sessions said it applied or departed from it — and
proposes its enforcement and salience, and any triggers it should have
(`propose`). A value equal to what the rule already has is recorded as the
pass's agreement; a different one waits as a suggestion and changes nothing.
- THE JUDGMENT. A person confirms or rejects each suggestion (`judge`). A
confirm writes the field through the one rule write path; a reject is kept
so the value is never proposed again.
A person setting a rule's enforcement or salience directly is judging it too
(`record_edit`, called from `rulebooks.update_rule`), so a suggestion that an
edit already answered does not wait in the list.
ACL: rules are owner-scoped; every read and write goes through
`rulebooks._owned_rules_clause`.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from sqlalchemy import case, exists, func, not_, select
from grimoire.models import async_session
from grimoire.models.rule_delivery import RuleDelivery
from grimoire.models.rule_field_judgment import (
CONFIRMED, ENFORCEMENT, FIELDS, REJECTED, SALIENCE, SUGGESTED, TRIGGER,
RuleFieldJudgment,
)
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.rule_usage import RuleUsageEvent
from grimoire.models.rulebook import Rule
from grimoire.services import lesson_rules, rule_order
from grimoire.services import rule_triggers as triggers_svc
from grimoire.services.rule_moment_judgments import _int, _mounts, _owned_rules as _owned
from grimoire.services.rulebooks import ENFORCEMENTS, SALIENCES
VERDICTS = {"confirm": CONFIRMED, "reject": REJECTED}
# Rules per pass page: enough to batch the reading, few enough that each rule
# and its history is actually read.
PASS_PAGE = 25
# The delivery history a pass reads. Matches what the delivery order reads
# (`rule_deliveries.HISTORY_DAYS`), so a proposal and the ranking it changes
# look at the same window.
HISTORY_DAYS = 90
# Places listed per rule in its history, busiest first. Past this the counts
# stop changing what the proposer would say.
_PLACES = 8
_WHY_CHARS = 600
_EDIT_NOTE = "set by an edit"
def _text(v) -> str:
return v.strip() if isinstance(v, str) else ""
def trigger_value(trigger: triggers_svc.Trigger) -> str:
"""A trigger as one string, so (rule, field, value) is unique."""
return f"{trigger.kind}\t{trigger.pattern}\t{trigger.moment}"
def parse_trigger_value(value: str) -> triggers_svc.Trigger:
kind, pattern, moment = (value.split("\t", 2) + ["", ""])[:3]
return triggers_svc.Trigger(kind, pattern, moment)
def current_value(rule: Rule, field: str) -> str:
if field == ENFORCEMENT:
return rule_order.force(rule)
return rule.salience or "normal"
def _act_routed(mounts: set[str], triggers: list) -> bool:
"""Whether some act can reach the rule — what `enforce` refuses.
A trigger is matched against an act; a mount reaches an act unless it is
on the reply. A rule reached only at the reply has no act to refuse, so
enforcing it would hold the reply and claim more than it does.
"""
return bool(triggers) or any(not m.startswith("reply.") for m in mounts)
# ── reading ───────────────────────────────────────────────────────────────
async def history(session, user_id: int, rule_ids) -> dict[int, dict]:
"""What happened when each rule reached a session, over HISTORY_DAYS.
`delivered` / `opened` in total and at each place it was delivered
(`at`: a moment, or the arm that found it), busiest first; `pulled`,
`applied` and `departed` from the usage events; `misfire_days`, the days
sessions reported a mount of it arriving where it did not apply.
"""
ids = sorted({int(r) for r in rule_ids or []})
out = {rid: {"days": HISTORY_DAYS, "delivered": 0, "opened": 0, "places": [],
"pulled": 0, "applied": 0, "departed": 0, "misfire_days": 0}
for rid in ids}
if not ids:
return out
since = datetime.now(timezone.utc) - timedelta(days=HISTORY_DAYS)
rows = (await session.execute(
select(
RuleDelivery.rule_id, RuleDelivery.at, func.count(RuleDelivery.id),
func.sum(case((RuleDelivery.opened_at.is_not(None), 1), else_=0)),
)
.where(RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since,
RuleDelivery.rule_id.in_(ids))
.group_by(RuleDelivery.rule_id, RuleDelivery.at)
)).all()
for rid, at, delivered, opened in rows:
h = out[int(rid)]
h["delivered"] += int(delivered)
h["opened"] += int(opened or 0)
h["places"].append({"at": at, "delivered": int(delivered), "opened": int(opened or 0)})
for h in out.values():
h["places"] = sorted(h["places"], key=lambda p: (-p["delivered"], p["at"]))[:_PLACES]
events = (await session.execute(
select(RuleUsageEvent.rule_id, RuleUsageEvent.event, func.count())
.where(RuleUsageEvent.user_id == user_id, RuleUsageEvent.created_at >= since,
RuleUsageEvent.rule_id.in_(ids),
RuleUsageEvent.event.in_(("pulled", "applied", "departed")))
.group_by(RuleUsageEvent.rule_id, RuleUsageEvent.event)
)).all()
for rid, event, n in events:
out[int(rid)][event] = int(n)
misfires = (await session.execute(
select(RuleMomentJudgment.rule_id, RuleMomentJudgment.misfire)
.where(RuleMomentJudgment.rule_id.in_(ids), RuleMomentJudgment.misfire.isnot(None))
)).all()
for rid, mf in misfires:
out[int(rid)]["misfire_days"] += lesson_rules.evidence_summary(mf)["situations"]
return out
def _brief(rule: Rule, mounts: set[str], triggers: list[dict]) -> dict:
return {
"id": rule.id,
"title": rule.title,
"kind": rule.kind or "rule",
"statement": rule.statement,
"when_to_apply": rule.when_to_apply or "",
"home": "project" if rule.project_id else "global",
"enforcement": current_value(rule, ENFORCEMENT),
"salience": current_value(rule, SALIENCE),
"mounted": sorted(mounts),
"triggers": triggers,
}
def _unweighed_clause():
"""No enforcement or salience judgment of any kind — a rule nobody weighed."""
return not_(exists().where(
RuleFieldJudgment.rule_id == Rule.id,
RuleFieldJudgment.field.in_((ENFORCEMENT, SALIENCE)),
))
async def unweighed_rules(user_id: int, limit: int = PASS_PAGE, offset: int = 0) -> dict:
"""The caller's rules nobody has weighed, a page at a time, each with its history.
A rule leaves this list once its enforcement and salience have any answer
— a proposal, the pass's agreement, or a direct edit — so a pass run in
pieces does not read a rule twice.
"""
from grimoire.services.rulebooks import _owned_rules_clause
limit = max(1, min(int(limit or PASS_PAGE), 100))
offset = max(0, int(offset or 0))
clauses = (_owned_rules_clause(user_id), _unweighed_clause())
async with async_session() as session:
total = (await session.execute(
select(func.count()).select_from(Rule).where(*clauses)
)).scalar_one()
rules = (await session.execute(
select(Rule).where(*clauses).order_by(Rule.id).limit(limit).offset(offset)
)).scalars().all()
ids = [r.id for r in rules]
mounts = await _mounts(session, ids)
hist = await history(session, user_id, ids)
triggers = await triggers_svc.list_rule_triggers(ids)
return {
"rules": [{**_brief(r, mounts.get(r.id, set()), triggers.get(r.id, [])),
"history": hist[r.id]} for r in rules],
"total_unweighed": int(total),
"offset": offset,
}
# ── the pass ──────────────────────────────────────────────────────────────
async def _rows(session, rule_ids) -> dict[tuple[int, str, str], RuleFieldJudgment]:
if not rule_ids:
return {}
rows = (await session.execute(
select(RuleFieldJudgment).where(RuleFieldJudgment.rule_id.in_(list(rule_ids)))
)).scalars().all()
return {(r.rule_id, r.field, r.value): r for r in rows}
async def propose(user_id: int, proposals: list[dict]) -> dict:
"""Record a pass's proposals for rules' enforcement, salience and triggers.
Each item is `{rule_id, enforcement, salience, triggers?: [...], why}`.
Enforcement and salience are both required: they are the answer to "how
strongly does this rule arrive", and answering one leaves the rule half
weighed. A value equal to the rule's own is recorded as agreed and changes
nothing; a different one lands `suggested`, replacing any earlier
suggestion for that field. A trigger the rule does not have lands
`suggested`. A value already rejected is skipped and said so.
Refused alone, with why: a rule the caller does not own, an unknown value,
a preference proposed to hold or enforce, and `enforce` on a rule no act
can reach (no trigger, none proposed, and mounted only at the reply).
"""
now = datetime.now(timezone.utc)
suggested = agreed = 0
skipped: list[dict] = []
refused: list[dict] = []
items = [p for p in proposals or [] if isinstance(p, dict)]
refused += [{"item": p, "error": "each proposal is an object"}
for p in proposals or [] if not isinstance(p, dict)]
async with async_session() as session:
owned = await _owned(session, user_id, [p.get("rule_id") for p in items])
mounts = await _mounts(session, list(owned))
hist = await history(session, user_id, list(owned))
existing = await _rows(session, list(owned))
have = await triggers_svc.list_rule_triggers(list(owned))
for item in items:
rid = _int(item.get("rule_id"))
rule = owned.get(rid) if rid else None
if rule is None:
refused.append({"rule_id": item.get("rule_id"), "error": "not a rule you own"})
continue
enforcement = _text(item.get("enforcement")).lower()
salience = _text(item.get("salience")).lower()
why = _text(item.get("why"))[:_WHY_CHARS]
if enforcement not in ENFORCEMENTS or salience not in SALIENCES:
refused.append({"rule_id": rid, "error": (
f"give both enforcement (one of {', '.join(ENFORCEMENTS)}) and salience "
f"(one of {', '.join(SALIENCES)})")})
continue
if not why:
refused.append({"rule_id": rid, "error": (
"why is required: it is what the operator reads to say yes or no "
"without opening the rule")})
continue
if rule.kind == "preference" and enforcement != "inform":
refused.append({"rule_id": rid, "error": (
"a preference is always `inform`: it says how work is liked, and "
"claims no force that could stop it. Propose it as a rule's "
"enforcement only after it is made a rule")})
continue
try:
wanted = triggers_svc.require_triggers(item.get("triggers") or []) or []
except ValueError as exc:
refused.append({"rule_id": rid, "error": str(exc)})
continue
current_triggers = {trigger_value(triggers_svc.require_trigger(t))
for t in have.get(rid, [])}
new_triggers = [t for t in wanted if trigger_value(t) not in current_triggers]
if enforcement == "enforce" and not _act_routed(mounts.get(rid, set()),
have.get(rid, []) + new_triggers):
refused.append({"rule_id": rid, "error": (
"`enforce` refuses the act a rule governs, and nothing routes an act "
"to this one: it has no trigger and is mounted only at the reply, if "
"anywhere. Propose the trigger that names the act (a command, a path, "
"a tool) with it, or propose `hold`")})
continue
evidence = hist[rid]
def put(field: str, value: str, state: str) -> None:
row = existing.get((rid, field, value))
if row is None:
row = RuleFieldJudgment(rule_id=rid, field=field, value=value, source="pass")
session.add(row)
existing[(rid, field, value)] = row
row.state, row.note, row.evidence = state, why, evidence
if state != SUGGESTED:
row.judged_at = now
for field, value in ((ENFORCEMENT, enforcement), (SALIENCE, salience)):
row = existing.get((rid, field, value))
if value == current_value(rule, field):
if row is None or row.state == SUGGESTED:
put(field, value, CONFIRMED)
agreed += 1
continue
if row is not None and row.state == REJECTED:
skipped.append({"rule_id": rid, "field": field, "value": value,
"why": "already rejected" + (f": {row.note}" if row.note else "")})
continue
# One open suggestion per field: a newer reading replaces an older one.
for key, other in list(existing.items()):
if key[0] == rid and key[1] == field and key[2] != value and other.state == SUGGESTED:
await session.delete(other)
existing.pop(key)
put(field, value, SUGGESTED)
suggested += 1
for trigger in new_triggers:
value = trigger_value(trigger)
row = existing.get((rid, TRIGGER, value))
if row is not None and row.state != SUGGESTED:
skipped.append({"rule_id": rid, "field": TRIGGER, "value": trigger.to_dict(),
"why": f"already {row.state}" + (f": {row.note}" if row.note else "")})
continue
put(TRIGGER, value, SUGGESTED)
suggested += 1
await session.commit()
return {"suggested": suggested, "agreed": agreed, "skipped": skipped, "refused": refused}
# ── waiting on a person ───────────────────────────────────────────────────
def _proposal_item(row: RuleFieldJudgment) -> dict:
out = {"field": row.field, "value": row.value, "why": row.note or "",
"source": row.source, "evidence": row.evidence or {},
"created_at": row.created_at.isoformat() if row.created_at else None}
if row.field == TRIGGER:
out["trigger"] = parse_trigger_value(row.value).to_dict()
return out
async def pending(user_id: int, rule_id: int | None = None, limit: int = 200) -> dict:
"""The suggestions waiting on a judgment, grouped by rule.
Each rule carries its current enforcement, salience, mounts and triggers,
so a suggestion is read beside what it would change. A suggestion the rule
already carries — set by an edit since, or a trigger added by hand — is
left out: there is nothing left to decide.
"""
from grimoire.services.rulebooks import _owned_rules_clause
limit = max(1, min(int(limit or 200), 500))
async with async_session() as session:
stmt = (
select(RuleFieldJudgment, Rule)
.join(Rule, Rule.id == RuleFieldJudgment.rule_id)
.where(RuleFieldJudgment.state == SUGGESTED, _owned_rules_clause(user_id))
)
if rule_id:
stmt = stmt.where(Rule.id == int(rule_id))
rows = (await session.execute(
stmt.order_by(Rule.id, RuleFieldJudgment.field, RuleFieldJudgment.value).limit(limit)
)).all()
ids = sorted({r.id for _, r in rows})
mounts = await _mounts(session, ids)
triggers = await triggers_svc.list_rule_triggers(ids)
order = {f: i for i, f in enumerate(FIELDS)}
grouped: dict[int, dict] = {}
for row, rule in rows:
have = triggers.get(rule.id, [])
if row.field == TRIGGER:
if parse_trigger_value(row.value).to_dict() in have:
continue
elif row.value == current_value(rule, row.field):
continue
entry = grouped.setdefault(rule.id, {
**_brief(rule, mounts.get(rule.id, set()), have), "proposals": [],
})
entry["proposals"].append(_proposal_item(row))
for entry in grouped.values():
entry["proposals"].sort(key=lambda p: (order.get(p["field"], 9), p["value"]))
rules = sorted(grouped.values(), key=lambda r: r["id"])
return {"rules": rules, "total": sum(len(r["proposals"]) for r in rules)}
# ── judging ───────────────────────────────────────────────────────────────
def _judged_value(field: str, raw) -> str:
"""The value a judgment names, normalised the way proposals store it."""
if field == TRIGGER:
trigger = raw if isinstance(raw, dict) else None
if trigger is None and isinstance(raw, str) and "\t" in raw:
return trigger_value(parse_trigger_value(raw))
return trigger_value(triggers_svc.require_trigger(trigger))
value = _text(raw).lower()
allowed = ENFORCEMENTS if field == ENFORCEMENT else SALIENCES
if value not in allowed:
raise ValueError(f"{field} must be one of {', '.join(allowed)}")
return value
async def judge(user_id: int, judgments: list[dict]) -> dict:
"""Confirm or reject suggestions — on a person's word, since a confirm changes the rule.
Each item is `{rule_id, field, value, verdict, note?}`; for a trigger,
`value` is the trigger `{kind, pattern, moment?}`. Confirm writes the
field through `rulebooks.update_rule` (enforcement, salience) or adds the
trigger beside the rule's others; reject records that the value is wrong
here, so it is never proposed again. A bad item is refused alone.
"""
from grimoire.services.rulebooks import update_rule
done: list[dict] = []
refused: list[dict] = []
for item in judgments or []:
if not isinstance(item, dict):
refused.append({"item": item, "error": "each judgment is an object"})
continue
rid = _int(item.get("rule_id"))
field = _text(item.get("field")).lower()
state = VERDICTS.get(_text(item.get("verdict")).lower())
if rid is None or field not in FIELDS or state is None:
refused.append({"rule_id": item.get("rule_id"), "field": item.get("field"), "error": (
f"needs rule_id, a field (one of {', '.join(FIELDS)}) and a verdict "
f"(one of {', '.join(sorted(VERDICTS))})")})
continue
try:
value = _judged_value(field, item.get("value"))
except ValueError as exc:
refused.append({"rule_id": rid, "field": field, "error": str(exc)})
continue
note = _text(item.get("note"))[:_WHY_CHARS]
async with async_session() as session:
if not await _owned(session, user_id, [rid]):
refused.append({"rule_id": rid, "field": field, "error": "not a rule you own"})
continue
if state == CONFIRMED:
try:
if field == TRIGGER:
await _add_trigger(rid, parse_trigger_value(value))
elif await update_rule(rid, user_id, **{field: value}) is None:
refused.append({"rule_id": rid, "field": field, "error": "not a rule you own"})
continue
except ValueError as exc:
refused.append({"rule_id": rid, "field": field, "error": str(exc)})
continue
await _record(rid, field, value, state, note)
done.append({"rule_id": rid, "field": field, "value": value, "state": state})
return {"judged": done, "refused": refused}
async def _add_trigger(rule_id: int, trigger: triggers_svc.Trigger) -> None:
have = (await triggers_svc.list_rule_triggers([rule_id])).get(rule_id, [])
triggers = triggers_svc.require_triggers(have + [trigger.to_dict()]) or []
await triggers_svc.set_rule_triggers(rule_id, triggers)
async def _record(rule_id: int, field: str, value: str, state: str, note: str) -> None:
now = datetime.now(timezone.utc)
async with async_session() as session:
row = (await session.execute(
select(RuleFieldJudgment).where(
RuleFieldJudgment.rule_id == rule_id, RuleFieldJudgment.field == field,
RuleFieldJudgment.value == value)
)).scalar_one_or_none()
if row is None:
row = RuleFieldJudgment(rule_id=rule_id, field=field, value=value, source="edit")
session.add(row)
row.state, row.judged_at = state, now
row.note = note or row.note
await session.commit()
async def record_edit(session, rule_id: int, field: str, before: str, after: str) -> None:
"""Record a direct change of enforcement or salience, in the caller's session.
The new value is confirmed; a suggestion for any other value of that field
is rejected — the edit answered it. A rule edited this way has been
weighed, so the pass does not read it again.
"""
if field not in (ENFORCEMENT, SALIENCE) or before == after:
return
now = datetime.now(timezone.utc)
rows = (await session.execute(
select(RuleFieldJudgment).where(
RuleFieldJudgment.rule_id == rule_id, RuleFieldJudgment.field == field)
)).scalars().all()
by_value = {r.value: r for r in rows}
row = by_value.get(after)
if row is None:
row = RuleFieldJudgment(rule_id=rule_id, field=field, value=after,
source="edit", note=_EDIT_NOTE)
session.add(row)
row.state, row.judged_at = CONFIRMED, now
for value, other in by_value.items():
if value != after and other.state == SUGGESTED:
other.state, other.judged_at = REJECTED, now
other.note = f"{field} set to {after} by an edit"
+8
View File
@@ -763,6 +763,8 @@ async def update_rule(
# to survive the mutation below. A rule's history is the only record
# of what it used to say; the edit itself destroys that.
text_before = rule_versions.snapshot(rule)
weight_before = {"enforcement": rule.enforcement or "inform",
"salience": rule.salience or "normal"}
for key in clear:
if key in allowed and key in NULLABLE_RULE_TEXT:
setattr(rule, key, None)
@@ -808,6 +810,12 @@ async def update_rule(
# wording was written — which is why it is taken before the loop and
# not here.
rule_versions.record_if_changed(session, rule, user_id, text_before)
# Setting how strongly a rule arrives is a judgment of it: recorded
# beside the pass's suggestions, so one this edit answered stops waiting.
from grimoire.services import rule_field_judgments
for field, before in weight_before.items():
await rule_field_judgments.record_edit(
session, rule.id, field, before, getattr(rule, field) or before)
await session.commit()
await session.refresh(rule)
_refresh_rule_embedding(rule)