feat(7836): lessons and rules are no longer paired by arriving together
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Failing after 1m40s
CI & Build / integration (push) Successful in 2m7s
CI & Build / Build & push image (push) Skipped
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Failing after 1m40s
CI & Build / integration (push) Successful in 2m7s
CI & Build / Build & push image (push) Skipped
The co-arrival recorder counted a lesson and a rule shown in one response as evidence that the lesson is an instance of the rule, and asked the reader to judge the pair once three situations had gathered. Two records that resemble the same prompts arrive together whether or not one is an instance of the other, and the outcome bore that out (2,317 pairs suggested, 23 confirmed). It no longer runs: - neither the prompt door nor the write path records co-arrivals or carries a proposal line; - a rule read lists the lessons judged against it, confirmed first, and a lesson read the rules it was judged against: suggested rows stay in the table and no read shows them; - the lesson page and the rule editor drop the suggested section. The situation-counting helpers stay; rule moment judgments use them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -408,12 +408,12 @@ async def judge_lesson_link(
|
||||
"""Say whether a lesson is an instance of a rule: `verdict` is "confirm"
|
||||
or "reject".
|
||||
|
||||
Reach for this when Grimoire proposes a pair — a lesson and a rule that keep
|
||||
arriving together in different situations — or whenever you are reading a
|
||||
lesson and recognise the rule it falls under. Confirming makes the rule
|
||||
reachable through the situation the lesson describes; rejecting records
|
||||
that it is not, so the pair is not proposed again. `note` is the why, and
|
||||
the next reader judges the link by it.
|
||||
Reach for this when you are reading a lesson and recognise the rule it
|
||||
falls under, or when a lesson you just recorded was offered candidate
|
||||
rules. Confirming makes the rule reachable through the situation the
|
||||
lesson describes, and lists the lesson on the rule when it is opened;
|
||||
rejecting records that it is not. `note` is the why, and the next reader
|
||||
judges the link by it.
|
||||
|
||||
Returns the link: {lesson_id, rule_id, state, note, evidence, judged_at}.
|
||||
"""
|
||||
|
||||
@@ -15,7 +15,6 @@ from quart import Blueprint, g, jsonify, request
|
||||
from grimoire.auth import admin_required, get_current_user_id, login_required
|
||||
from grimoire.config import Config
|
||||
from grimoire.services import hook_payload as hook_payload_svc
|
||||
from grimoire.services import lesson_rules as lesson_rules_svc
|
||||
from grimoire.services import moment_delivery as moment_delivery_svc
|
||||
from grimoire.services import plugin_context as plugin_ctx_svc
|
||||
from grimoire.services import reply_shapes as reply_shapes_svc
|
||||
@@ -215,13 +214,6 @@ async def autoinject_retrieve():
|
||||
result = await plugin_ctx_svc.build_autoinject_hint(
|
||||
g.user.id, q, project_id=project_id, exclude_ids=exclude_ids, context=ctx,
|
||||
)
|
||||
# The one place both arms' lines meet, so the one place a lesson and a
|
||||
# rule arriving TOGETHER can be counted. Keyed on the operator's
|
||||
# prompt — the situation — and fails open to "".
|
||||
proposal = await lesson_rules_svc.co_surfaced(
|
||||
g.user.id, result.get("lesson_ids") or [], rules.get("shown_rule_ids") or [],
|
||||
arm="p", situation=q, project_id=project_id or None,
|
||||
)
|
||||
# The reply mounts go through the same rule ledger; a rule the prompt arm
|
||||
# just named is not quoted a second time by the turn's delivery.
|
||||
turn = await moment_delivery_svc.deliver_for_turn(
|
||||
@@ -232,8 +224,8 @@ async def autoinject_retrieve():
|
||||
record=False,
|
||||
)
|
||||
# One payload, in the one order: the rules, then the reply shape, then
|
||||
# what the last turn left unjudged, then the records menu, then the
|
||||
# lesson-rule proposal, fitted to the budget.
|
||||
# what the last turn left unjudged, then the records menu, fitted to the
|
||||
# budget.
|
||||
carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS]
|
||||
turn_parts = (
|
||||
[*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn
|
||||
@@ -247,7 +239,6 @@ async def autoinject_retrieve():
|
||||
*turn_parts,
|
||||
*([hook_payload_svc.Part(text=carry)] if carry else []),
|
||||
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}),
|
||||
*([hook_payload_svc.Part(text=proposal)] if proposal else []),
|
||||
])
|
||||
shapes = set(fitted.ids(hook_payload_svc.SHAPE))
|
||||
forms = {k: f for k, f in turn["shape_forms"].items() if k in shapes}
|
||||
|
||||
@@ -5,10 +5,11 @@ choice for a class of them. This service owns the link between the two — which
|
||||
rule a lesson is an instance of — and both directions of reading it.
|
||||
|
||||
THE STATES (models/lesson_rule_link.py says why each exists):
|
||||
`suggested` while evidence accumulates, `confirmed` or `rejected` once a
|
||||
judgment is made. Every write here is a JUDGMENT, so every write lands as
|
||||
confirmed or rejected; `suggested` rows come from the co-surfacing recorder,
|
||||
never from a caller naming a rule.
|
||||
`confirmed` or `rejected`, once a judgment is made. Every write here is a
|
||||
JUDGMENT, so every write lands as one of the two. `suggested` rows were
|
||||
written by a co-arrival recorder that no longer runs; they stay in the table
|
||||
and no read shows them, because a lesson and a rule that resemble the same
|
||||
prompts arrive together whether or not one is an instance of the other.
|
||||
|
||||
THE THIRD ANSWER. "Which rule is this an instance of?" has three
|
||||
answers, and only two of them are links: a rule named (confirmed), or NO RULE
|
||||
@@ -18,13 +19,12 @@ lesson that stands alone is the raw material for a rule nobody has written yet
|
||||
(see Convergence below), and that is unreadable if "nobody looked" means the
|
||||
same thing.
|
||||
|
||||
THE SOFT LINK. When one hook request puts a lesson and a rule in
|
||||
front of the reader together, `co_surfaced` records the pair as evidence on a
|
||||
SUGGESTED link, and once that evidence crosses a bar the next co-arrival asks
|
||||
the reader to judge it. The evidence counts distinct SITUATIONS, not
|
||||
arrivals: two records that resemble each other arrive together on every
|
||||
similar prompt, and counting each time would measure their similarity over
|
||||
and over rather than any relation between them.
|
||||
EVIDENCE BY SITUATION. `situation_key`, `add_evidence` and `proposal_due`
|
||||
count distinct SITUATIONS, not arrivals, for the rule↔moment signals that
|
||||
ask a reader to judge a pairing (`rule_moment_judgments`): two things that
|
||||
resemble each other arrive together on every similar prompt, and counting
|
||||
each time would measure their similarity over and over rather than any
|
||||
relation between them.
|
||||
|
||||
ACL (services/access.py). Linking changes what a lesson says about itself, so it needs
|
||||
WRITE on the lesson (`access.can_write_note`, share-aware). It names a rule, so
|
||||
@@ -42,7 +42,6 @@ import statistics
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import and_, delete, exists, func, not_, or_, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.lesson_rule_link import (
|
||||
@@ -271,8 +270,8 @@ async def rules_for_lessons(user_id: int, lesson_ids) -> dict[int, list[dict]]:
|
||||
"""{lesson_id: [{id, title, kind, state, note}]}, for rules the READER owns.
|
||||
|
||||
One query for the whole set — a lesson list would otherwise be N+1.
|
||||
Confirmed first, then suggested, then rejected: the order a reader cares
|
||||
about them in.
|
||||
Judged links only, confirmed before rejected: a rejection is kept so the
|
||||
reader sees the rule was considered and is not this one.
|
||||
"""
|
||||
from grimoire.services.rulebooks import _owned_rules_clause
|
||||
|
||||
@@ -280,24 +279,20 @@ async def rules_for_lessons(user_id: int, lesson_ids) -> dict[int, list[dict]]:
|
||||
out: dict[int, list[dict]] = {i: [] for i in ids}
|
||||
if not ids:
|
||||
return out
|
||||
order = {s: n for n, s in enumerate((CONFIRMED, SUGGESTED, REJECTED))}
|
||||
order = {CONFIRMED: 0, REJECTED: 1}
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(LessonRuleLink, Rule)
|
||||
.join(Rule, Rule.id == LessonRuleLink.rule_id)
|
||||
.where(LessonRuleLink.lesson_id.in_(ids))
|
||||
.where(LessonRuleLink.state.in_(list(order)))
|
||||
.where(_owned_rules_clause(user_id))
|
||||
)).all()
|
||||
for link, rule in sorted(rows, key=lambda r: (order.get(r[0].state, 9), r[1].id)):
|
||||
item = {
|
||||
for link, rule in sorted(rows, key=lambda r: (order[r[0].state], r[1].id)):
|
||||
out[link.lesson_id].append({
|
||||
"id": rule.id, "title": rule.title, "kind": rule.kind,
|
||||
"state": link.state, "note": link.note or "",
|
||||
}
|
||||
if link.state == SUGGESTED:
|
||||
# What the suggestion rests on, so a reader can judge it from
|
||||
# here rather than having to go and count.
|
||||
item["evidence"] = evidence_summary(link.evidence)
|
||||
out[link.lesson_id].append(item)
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
@@ -305,22 +300,25 @@ async def lessons_for_rule(user_id: int, rule_id: int) -> list[dict]:
|
||||
"""The lessons that point at one rule, readable by the caller (share-aware).
|
||||
|
||||
The reverse direction, and the one a rule's page needs: the concrete
|
||||
situations that have been judged instances of it.
|
||||
situations that have been judged instances of it. Only the confirmed
|
||||
ones travel with a rule; a rejected lesson is listed after them, so the
|
||||
rule's page shows it was considered.
|
||||
"""
|
||||
from grimoire.services.access import readable_notes_clause
|
||||
|
||||
order = {CONFIRMED: 0, REJECTED: 1}
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(LessonRuleLink, Note)
|
||||
.join(Note, Note.id == LessonRuleLink.lesson_id)
|
||||
.where(LessonRuleLink.rule_id == int(rule_id))
|
||||
.where(LessonRuleLink.state.in_(list(order)))
|
||||
.where(Note.deleted_at.is_(None))
|
||||
.where(readable_notes_clause(user_id))
|
||||
)).all()
|
||||
order = {s: n for n, s in enumerate((CONFIRMED, SUGGESTED, REJECTED))}
|
||||
return [
|
||||
{"id": note.id, "title": note.title, "state": link.state, "note": link.note or ""}
|
||||
for link, note in sorted(rows, key=lambda r: (order.get(r[0].state, 9), r[1].id))
|
||||
for link, note in sorted(rows, key=lambda r: (order[r[0].state], r[1].id))
|
||||
]
|
||||
|
||||
|
||||
@@ -582,110 +580,6 @@ def proposal_due(evidence, now: datetime) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _proposal_line(lesson_id: int, lesson_title: str, rule_id: int, rule_title: str,
|
||||
kind: str, evidence: dict) -> str:
|
||||
counts = evidence_summary(evidence)
|
||||
where = (f" across {counts['projects']} projects" if counts["projects"] > 1 else "")
|
||||
return (
|
||||
f"> Lesson #{lesson_id} \"{lesson_title}\" and {kind} #{rule_id} "
|
||||
f"\"{rule_title}\" keep arriving together — {counts['situations']} "
|
||||
f"distinct situations{where}. If the lesson is an instance of the "
|
||||
f"{kind}, `judge_lesson_link({lesson_id}, {rule_id}, \"confirm\", "
|
||||
f"note=\"why\")` links them and the {kind} becomes reachable through "
|
||||
f"the lesson's situation; if it is not, `\"reject\"` with the why "
|
||||
f"stops the pair being asked about again."
|
||||
)
|
||||
|
||||
|
||||
async def co_surfaced(
|
||||
user_id: int, lesson_ids, rule_ids, *, arm: str, situation: str,
|
||||
project_id: int | None = None,
|
||||
) -> str:
|
||||
"""Record that these lessons and rules arrived together in one request,
|
||||
and return a proposal line when a pair has earned one ("" otherwise).
|
||||
|
||||
Called by the hook doors that put both kinds in front of the reader in
|
||||
the SAME response — `/retrieve` on a prompt, `/prior-art` on a write — so
|
||||
the pairing is exact: nothing is joined across requests, and no session
|
||||
identity is needed.
|
||||
|
||||
Only pairs the reader could confirm are recorded: a lesson they may write
|
||||
and a rule they own, the two checks `judge_link` makes. A pair already
|
||||
judged (confirmed or rejected) gathers nothing more — a confirmation needs
|
||||
no evidence, and a rejection is what stops the asking.
|
||||
|
||||
One proposal per request at most, so a menu never becomes a queue of
|
||||
questions. Fails open: this rides a hook, and a recall aid must never
|
||||
break the prompt or the write it decorates.
|
||||
"""
|
||||
try:
|
||||
return await _co_surfaced(user_id, lesson_ids, rule_ids, arm, situation, project_id)
|
||||
except Exception:
|
||||
logger.warning("lesson/rule co-surfacing could not be recorded", exc_info=True)
|
||||
return ""
|
||||
|
||||
|
||||
async def _co_surfaced(user_id, lesson_ids, rule_ids, arm, situation, project_id) -> str:
|
||||
from grimoire.services.access import can_write_note
|
||||
from grimoire.services.rulebooks import _owned_rules_clause
|
||||
|
||||
lessons = _ids(lesson_ids)
|
||||
rules = _ids(rule_ids)
|
||||
key = situation_key(arm, situation)
|
||||
if not lessons or not rules or not key:
|
||||
return ""
|
||||
lessons = [lid for lid in lessons if await can_write_note(user_id, lid)]
|
||||
if not lessons:
|
||||
return ""
|
||||
now = datetime.now(timezone.utc)
|
||||
proposal = None
|
||||
async with async_session() as session:
|
||||
owned = {
|
||||
r.id: r for r in (await session.execute(
|
||||
select(Rule).where(Rule.id.in_(rules)).where(_owned_rules_clause(user_id))
|
||||
)).scalars().all()
|
||||
}
|
||||
if not owned:
|
||||
return ""
|
||||
existing = {
|
||||
(row.lesson_id, row.rule_id): row for row in (await session.execute(
|
||||
select(LessonRuleLink).where(
|
||||
LessonRuleLink.lesson_id.in_(lessons),
|
||||
LessonRuleLink.rule_id.in_(list(owned)),
|
||||
)
|
||||
)).scalars().all()
|
||||
}
|
||||
for lid in lessons:
|
||||
for rid in owned:
|
||||
row = existing.get((lid, rid))
|
||||
if row is not None and row.state != SUGGESTED:
|
||||
continue
|
||||
if row is None:
|
||||
row = LessonRuleLink(lesson_id=lid, rule_id=rid, state=SUGGESTED)
|
||||
session.add(row)
|
||||
ev = add_evidence(row.evidence, key, project_id, now)
|
||||
if proposal is None and proposal_due(ev, now):
|
||||
ev["proposed_at"] = now.isoformat()
|
||||
ev["proposed_count"] = int(ev.get("proposed_count") or 0) + 1
|
||||
proposal = (lid, rid, ev)
|
||||
row.evidence = ev
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError:
|
||||
# Two hook requests created the same pair at once; the other
|
||||
# one's row stands, and this co-arrival is simply not counted.
|
||||
await session.rollback()
|
||||
return ""
|
||||
if proposal is None:
|
||||
return ""
|
||||
lid, rid, ev = proposal
|
||||
lesson_title = (await session.execute(
|
||||
select(Note.title).where(Note.id == lid)
|
||||
)).scalar_one_or_none() or ""
|
||||
rule = owned[rid]
|
||||
return _proposal_line(lid, lesson_title, rid, rule.title, rule.kind or "rule", ev)
|
||||
|
||||
|
||||
# ── Reaching a rule through its lessons ──────────────────────────────────────
|
||||
|
||||
|
||||
@@ -693,10 +587,9 @@ async def confirmed_lessons(user_id: int) -> set[int]:
|
||||
"""The lessons, readable by the caller, that carry a CONFIRMED link to a
|
||||
rule the caller owns — the only lessons that can bring a rule along.
|
||||
|
||||
CONFIRMED ONLY, and the reason is the soft link's: a suggested link that
|
||||
carried its rule would put the two side by side on every prompt that
|
||||
found the lesson, which is exactly the co-arrival the soft link counts
|
||||
as evidence — the suggestion would manufacture its own proof.
|
||||
CONFIRMED ONLY: nobody judged a suggested link, and a lesson that brought
|
||||
an unjudged rule along would put a rule in front of the reader on the
|
||||
strength of a resemblance alone.
|
||||
|
||||
Asked first and cheaply, so an arm on an install with no confirmed links
|
||||
— every install, until someone judges one — never pays for a search.
|
||||
|
||||
@@ -862,18 +862,9 @@ async def build_autoinject_hint(
|
||||
project_id=project_id,
|
||||
)
|
||||
|
||||
# The lessons this menu put in front of the reader, repeats included — for
|
||||
# the soft-link recorder, which pairs them with the rule arm's
|
||||
# lines in the same response. Relevance, not the session ledger, is what
|
||||
# makes a co-arrival, so a `seen` lesson counts — and so does one the
|
||||
# operator named, which is relevance by their own say-so.
|
||||
lesson_ids = [
|
||||
int(n.id) for n in [*named, *(n for _s, n in kept)]
|
||||
if _record_kind(n) == LESSON_NOTE_TYPE
|
||||
]
|
||||
return {
|
||||
"context": "\n".join(lines), "note_ids": note_ids, "config": cfg,
|
||||
"lesson_ids": lesson_ids, "parts": parts,
|
||||
"parts": parts,
|
||||
}
|
||||
|
||||
|
||||
@@ -936,7 +927,7 @@ async def _rule_moment(
|
||||
query the arm searched with, and skips what the arm named plus what the
|
||||
session's ledger holds — suppression is by RULE, whichever lesson reached
|
||||
it. Its lines and fresh ids join the arm's; `shown_rule_ids` stays the
|
||||
direct arm's band, which is what the soft-link recorder pairs.
|
||||
direct arm's band.
|
||||
"""
|
||||
result = await rp.run_rule_arm(
|
||||
arm, moment, floor=floor, budget=budget, io=_rule_io(),
|
||||
@@ -1026,7 +1017,7 @@ async def build_prompt_rule_hint(
|
||||
result.lines, result.rule_per_line(), block="rules",
|
||||
)
|
||||
# Every rule LINE the direct arm showed, repeats and the reserved
|
||||
# slot included — for the soft-link recorder. Distinct
|
||||
# slot included — what the payload fitter keeps or drops. Distinct
|
||||
# from `rule_ids`, which is telemetry's fresh-only cut.
|
||||
out["shown_rule_ids"] = result.shown_rule_ids
|
||||
except Exception:
|
||||
@@ -1697,7 +1688,6 @@ async def build_write_path_hint(
|
||||
rule_lines: list[str] = []
|
||||
rule_line_ids: list[int] = []
|
||||
rule_ids: list[int] = []
|
||||
shown_rule_ids: list[int] = []
|
||||
checkpoint: dict = {}
|
||||
try:
|
||||
result = await _rule_moment(
|
||||
@@ -1714,9 +1704,6 @@ async def build_write_path_hint(
|
||||
rule_lines = result.lines
|
||||
rule_line_ids = result.rule_per_line()
|
||||
rule_ids.extend(result.rule_ids)
|
||||
# Every rule line the band showed, repeats included — what the
|
||||
# soft-link recorder pairs with this response's lessons.
|
||||
shown_rule_ids = result.shown_rule_ids
|
||||
checkpoint = result.checkpoint
|
||||
except Exception:
|
||||
logger.debug("write-path rule arm failed", exc_info=True)
|
||||
@@ -1917,20 +1904,6 @@ async def build_write_path_hint(
|
||||
|
||||
lines.extend(rule_lines)
|
||||
|
||||
# A lesson and a rule on this one response: the soft-link
|
||||
# recorder counts the pair, keyed on the FILE — every edit to one file is
|
||||
# one situation — and asks about it once the evidence holds. Fails open.
|
||||
shown_lessons = [
|
||||
int(item["id"]) for _m, item in menu if item.get("kind") == LESSON_NOTE_TYPE
|
||||
]
|
||||
proposal = await lesson_rules_svc.co_surfaced(
|
||||
user_id, shown_lessons, shown_rule_ids, arm="w", situation=path,
|
||||
project_id=project_id or None,
|
||||
)
|
||||
if proposal:
|
||||
lines.append(proposal)
|
||||
parts.append(hook_payload.Part(text=proposal))
|
||||
|
||||
return {
|
||||
"context": "\n".join(lines),
|
||||
"parts": parts,
|
||||
|
||||
@@ -11,7 +11,7 @@ sources that both stop at a proposal:
|
||||
nothing; a person confirms it (`judge`).
|
||||
- THE SIGNAL. A rule a session OPENS shortly after a moment fired is evidence
|
||||
it belongs on that moment. Recorded per distinct session with the evidence
|
||||
model lesson↔rule soft links use (lesson_rules: three situations, a
|
||||
model in lesson_rules (`add_evidence`, `proposal_due`: three situations, a
|
||||
cooldown), and once it crosses the bar the next open asks the reader to
|
||||
offer the mount (`co_occurred`).
|
||||
|
||||
|
||||
Reference in New Issue
Block a user