Records reach work just in time: pointer lines and lessons by situation (milestone 642, steps 5–6) #231

Merged
bvandeusen merged 7 commits from dev into main 2026-11-25 09:39:15 -05:00
3 changed files with 69 additions and 11 deletions
Showing only changes of commit 5bde619511 - Show all commits
+57 -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.lesson_situation import LessonSituation
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
@@ -120,7 +121,10 @@ logger = logging.getLogger(__name__)
# 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
# v31 lesson_situations: the moments and triggers each lesson arrives at,
# with the proposals waiting and the rejections that stop a value being
# proposed again. Nothing in the lesson's text records them.
BACKUP_VERSION = 31
# 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
@@ -158,6 +162,7 @@ _BACKED_UP = [
# Lesson → rule links and their judgments, and "no rule fits" answers.
"lesson_rule_links",
"lesson_no_rule",
"lesson_situations",
# System usage telemetry, for the reason its note and rule twins travel.
"system_usage_events",
# An install's action → moment corrections, the moments each rule arrives
@@ -283,6 +288,8 @@ _COLUMN_EXCLUSIONS: dict[str, set[str]] = {
"rule_field_judgments": {"id"},
# Keyed by the lesson itself; nothing to exclude, every column travels.
"lesson_no_rule": set(),
# The (lesson, kind, value) triple is the row.
"lesson_situations": {"id"},
"note_usage_events": {"id"},
# Same as the note twin: the surrogate key is re-issued on insert.
"rule_usage_events": {"id"},
@@ -390,6 +397,7 @@ _IMPORT_COLUMN_EXCLUSIONS: dict[str, set[str]] = {
"rule_moment_judgments": {"id"},
"rule_field_judgments": {"id"},
"lesson_no_rule": set(),
"lesson_situations": {"id"},
"note_usage_events": {"id"},
"rule_usage_events": {"id"},
"system_usage_events": {"id"},
@@ -904,6 +912,20 @@ def _lesson_no_rule_rows(rows) -> list[dict]:
]
def _lesson_situation_rows(rows) -> list[dict]:
"""When each lesson applies, by SOURCE lesson id, remapped through the
note map at restore."""
return [
{
"lesson_id": r.lesson_id, "kind": r.kind, "value": r.value,
"state": r.state, "source": r.source, "note": r.note,
"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 _platform_rows(rows) -> list[dict]:
"""The global platform catalog (v25). Carried WITHOUT ids, matched on slug
at restore — the canonical_systems reasoning."""
@@ -1076,6 +1098,7 @@ async def export_full_backup() -> dict:
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()
lesson_situations = (await session.execute(select(LessonSituation).order_by(LessonSituation.id))).scalars().all()
record_systems = (await session.execute(select(RecordSystem).order_by(RecordSystem.id))).scalars().all()
supersessions = (
await session.execute(select(NoteSupersession).order_by(NoteSupersession.id))
@@ -1168,6 +1191,7 @@ async def export_full_backup() -> dict:
"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),
"lesson_situations": _lesson_situation_rows(lesson_situations),
"systems": _system_rows(
systems, {c.id: c.slug for c in canonical_systems}
),
@@ -1392,6 +1416,10 @@ async def export_user_backup(user_id: int) -> dict:
lesson_no_rule = (await session.execute(
select(LessonNoRule).where(LessonNoRule.lesson_id.in_(note_ids))
)).scalars().all() if note_ids else []
lesson_situations = (await session.execute(
select(LessonSituation).where(LessonSituation.lesson_id.in_(note_ids))
.order_by(LessonSituation.id)
)).scalars().all() if note_ids else []
# Family canon (v25). The catalog is global and taken whole, for the
# canonical_systems reason. Everything else is scoped so that BOTH
# ends of every row restore: an idea is this user's note, a ledger row
@@ -1466,6 +1494,7 @@ async def export_user_backup(user_id: int) -> dict:
"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),
"lesson_situations": _lesson_situation_rows(lesson_situations),
"systems": _system_rows(
systems, {c.id: c.slug for c in canonical_systems}
),
@@ -1853,6 +1882,25 @@ def _build_lesson_no_rule(row: dict, maps: _Maps) -> LessonNoRule | None:
)
def _build_lesson_situation(row: dict, maps: _Maps) -> LessonSituation | None:
"""Skipped when its lesson did not restore — the situation is about that
lesson and no other."""
lesson = maps.notes.get(row.get("lesson_id", 0))
if lesson is None:
return None
return LessonSituation(
lesson_id=lesson,
kind=row["kind"],
value=row.get("value") or "",
state=row.get("state") or "suggested",
source=row.get("source") or "pass",
note=row.get("note") or None,
# Absent when absent: a waiting proposal was never judged.
judged_at=_dt_or_none(row.get("judged_at")),
created_at=_dt(row.get("created_at")),
)
def _build_lesson_rule_link(row: dict, maps: _Maps) -> LessonRuleLink | None:
"""Both ends must map: a link whose lesson or rule did not restore points
at whatever took that number in the destination."""
@@ -2506,7 +2554,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
"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,
"lesson_no_rule": 0, "lesson_situations": 0, "moment_mappings": 0,
"platforms": 0, "project_platforms": 0, "family_ideas": 0,
"family_idea_platforms": 0, "family_idea_references": 0,
"family_adoptions": 0, "family_decisions": 0,
@@ -2754,6 +2802,13 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
continue
session.add(answer)
stats["lesson_no_rule"] += 1
# When each lesson applies; archives before v31 carry none.
for ls in data.get("lesson_situations", []):
situation = _build_lesson_situation(ls, maps)
if situation is None:
continue
session.add(situation)
stats["lesson_situations"] += 1
# Family canon (v25). Here because it needs projects, notes and topics
# all mapped. The platform catalog first, matched on slug and seeded
+6 -8
View File
@@ -84,11 +84,11 @@ async def test_the_prompt_menu_looks_beyond_the_bound_project_for_a_lesson():
@pytest.mark.asyncio
async def test_the_write_path_asks_for_lessons_at_all():
"""The founding example of the kind is a lesson about a code shape, and
this is the arm that fires when code is written. It is also the one note
arm that filters kinds — so an omission here is not a ranking loss, it is
a kind that can never appear."""
async def test_the_write_path_leaves_lessons_to_their_situation():
"""An edit's words resemble a lesson far more often than the edit is its
situation, so the edit door's search by meaning leaves lessons out; a
lesson reaches an edit through a situation confirmed for it
(`lesson_situations`). The kinds the door does consider stay."""
search = AsyncMock(return_value=[])
with patch.object(pc, "get_writepath_config",
AsyncMock(return_value=writepath_cfg(threshold=0.6))), \
@@ -101,9 +101,7 @@ async def test_the_write_path_asks_for_lessons_at_all():
await pc.build_write_path_hint(1, "src/ui/Badge.vue", code="x" * 400)
kw = search.await_args.kwargs
assert LESSON_NOTE_TYPE in kw["record_kinds"]
# The kinds it already carried must survive the addition — a set rewritten
# rather than extended would trade one unreachable kind for another.
assert LESSON_NOTE_TYPE not in kw["record_kinds"]
assert {"snippet", "note"} <= set(kw["record_kinds"])
assert kw["include_global_kinds"] is True
+6 -1
View File
@@ -22,7 +22,7 @@ def test_backup_version_is_current():
"""The bump is the point of the test — a payload section added without
moving the version produces backups that are structurally different and
indistinguishable by inspection."""
assert backup.BACKUP_VERSION == 30
assert backup.BACKUP_VERSION == 31
def _exportable_note(**over):
@@ -141,6 +141,7 @@ def _column_guard_targets():
)
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
from grimoire.models.lesson_situation import LessonSituation
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.rule_field_judgment import RuleFieldJudgment
from grimoire.models.design_system import DesignSystem, DesignToken
@@ -183,6 +184,7 @@ def _column_guard_targets():
"rule_relations": (RuleRelation, backup._rule_relation_rows),
"lesson_rule_links": (LessonRuleLink, backup._lesson_rule_link_rows),
"lesson_no_rule": (LessonNoRule, backup._lesson_no_rule_rows),
"lesson_situations": (LessonSituation, backup._lesson_situation_rows),
"rule_moment_judgments": (RuleMomentJudgment, backup._rule_moment_judgment_rows),
"rule_field_judgments": (RuleFieldJudgment, backup._rule_field_judgment_rows),
"note_usage_events": (NoteUsageEvent, backup._usage_event_rows),
@@ -315,6 +317,7 @@ def _import_guard_targets():
"rule_relations": backup._build_rule_relation,
"lesson_rule_links": backup._build_lesson_rule_link,
"lesson_no_rule": backup._build_lesson_no_rule,
"lesson_situations": backup._build_lesson_situation,
"rule_moment_judgments": backup._build_rule_moment_judgment,
"rule_field_judgments": backup._build_rule_field_judgment,
"note_usage_events": backup._build_usage_event,
@@ -595,6 +598,8 @@ async def test_export_full_backup_contains_every_declared_section():
"rule_triggers",
# v30: the weighed enforcement, salience and triggers.
"rule_field_judgments",
# v31: the moments and triggers each lesson arrives at.
"lesson_situations",
# v25: family canon.
"platforms", "project_platforms", "family_ideas",
"family_idea_platforms", "family_idea_references",