from datetime import datetime from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, UniqueConstraint 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", "KINDS", "MOMENT", "NONE", "REJECTED", "SITUATION_STATES", "SOURCES", "SUGGESTED", "TRIGGER", "LessonSituation", ] # The same three states as a lesson's link to a rule. CHECK # ck_lesson_situations_state (migration 0137). SITUATION_STATES = LINK_STATES # What a row names. `moment` — a catalog moment key: the lesson arrives when # the work reaches it. `trigger` — a typed predicate on the act (tool, path, # command, keyword), stored as `rule_field_judgments.trigger_value` writes it, # so it is matched exactly as a rule's trigger is. `none` — the lesson was # read and no situation fits it; it is reached by meaning alone, and the row # keeps it out of the next pass's queue. CHECK ck_lesson_situations_kind. MOMENT, TRIGGER, NONE = "moment", "trigger", "none" KINDS = (MOMENT, TRIGGER, NONE) # `pass` — an agent read the lesson and proposed; `edit` — a person set the # lesson's situations directly. CHECK ck_lesson_situations_source. SOURCES = ("pass", "edit") class LessonSituation(Base, CreatedAtMixin): """When a lesson applies, as something the work can be checked against. One row per (lesson, kind, value): - ``suggested`` — proposed by a pass. Delivers nothing until judged. - ``confirmed`` — the lesson arrives when this moment is reached or this trigger matches the act, once per session. - ``rejected`` — judged not to be when it applies, kept with the reason so the same value is never proposed again. """ __tablename__ = "lesson_situations" id: Mapped[int] = mapped_column(BigInteger, primary_key=True) lesson_id: Mapped[int] = mapped_column( BigInteger, ForeignKey("notes.id", ondelete="CASCADE"), index=True, ) kind: Mapped[str] = mapped_column(Text) value: Mapped[str] = mapped_column(Text, default="", server_default="") state: Mapped[str] = mapped_column(Text, default=SUGGESTED, server_default=SUGGESTED) source: Mapped[str] = mapped_column(Text, default="pass", server_default="pass") # For a suggestion, what the proposer read in the lesson; for a judgment, # why it was confirmed or rejected. note: Mapped[str | None] = mapped_column(Text, nullable=True) judged_at: Mapped[datetime | None] = mapped_column( DateTime(timezone=True), nullable=True, ) __table_args__ = ( UniqueConstraint("lesson_id", "kind", "value", name="uq_lesson_situations_value"), ) def to_dict(self) -> dict: return { "id": self.id, "lesson_id": self.lesson_id, "kind": self.kind, "value": self.value, "state": self.state, "source": self.source, "note": self.note or "", "judged_at": iso(self.judged_at), "created_at": iso(self.created_at), }