from datetime import datetime from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, UniqueConstraint from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm import Mapped, mapped_column from grimoire.models import Base from grimoire.models.base import CreatedAtMixin, iso from grimoire.models.lesson_rule_link import CONFIRMED, LINK_STATES, REJECTED, SUGGESTED __all__ = [ "CONFIRMED", "ENFORCEMENT", "FIELDS", "REJECTED", "SALIENCE", "SUGGESTED", "TRIGGER", "RuleFieldJudgment", ] # The fields of a rule that decide how it arrives once it is reached: what it # does (`enforcement`), how it ranks beside rules of the same force # (`salience`), and the typed predicates that reach it (`trigger`). ENFORCEMENT, SALIENCE, TRIGGER = "enforcement", "salience", "trigger" FIELDS = (ENFORCEMENT, SALIENCE, TRIGGER) class RuleFieldJudgment(Base, CreatedAtMixin): """A proposed or judged value for one of a rule's delivery fields. The rule row holds the current value; this holds the reasoning behind it and the values that were turned down. One row per (rule, field, value): - ``suggested`` — a pass read the rule and its delivery history and proposed this value. Changes nothing until a person confirms it. - ``confirmed`` — the value was judged right. For a proposal equal to what the rule already carries, the pass's agreement is recorded this way, so a rule that was looked at and left alone does not read as one nobody looked at. - ``rejected`` — judged wrong, kept with its reason so it is never proposed again. `value` is the enforcement or salience name, or for a trigger `kindpatternmoment` — one string, so the pair is unique. `evidence` is the delivery history the proposer read, as it stood then. """ __tablename__ = "rule_field_judgments" id: Mapped[int] = mapped_column(BigInteger, primary_key=True) rule_id: Mapped[int] = mapped_column( BigInteger, ForeignKey("rules.id", ondelete="CASCADE"), index=True, ) field: Mapped[str] = mapped_column(Text) value: Mapped[str] = mapped_column(Text) state: Mapped[str] = mapped_column(Text, default=SUGGESTED, server_default=SUGGESTED) # `pass` — an agent proposed it; `edit` — a person set the field directly. source: Mapped[str] = mapped_column(Text, default="pass", server_default="pass") note: Mapped[str | None] = mapped_column(Text, nullable=True) evidence: Mapped[dict | None] = mapped_column(JSONB, nullable=True) judged_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) __table_args__ = ( UniqueConstraint("rule_id", "field", "value", name="uq_rule_field_judgments_value"), ) def to_dict(self) -> dict: return { "rule_id": self.rule_id, "field": self.field, "value": self.value, "state": self.state, "source": self.source, "note": self.note or "", "evidence": self.evidence or {}, "judged_at": iso(self.judged_at), "created_at": iso(self.created_at), }