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

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:
2026-11-25 06:02:10 -05:00
co-authored by Claude Opus 5.5
parent 2f93a4f7b5
commit 1a8c02bfe5
13 changed files with 69 additions and 358 deletions
+5 -8
View File
@@ -11,8 +11,8 @@ import type { RuleKind } from "@/api/rulebooks";
* another one fits. */ * another one fits. */
export type RuleJudgment = "linked" | "no_rule" | "unjudged"; export type RuleJudgment = "linked" | "no_rule" | "unjudged";
/** A link's state (`models/lesson_rule_link.py` LINK_STATES). */ /** A judged link's state; the reads list only these two. */
export type LinkState = "suggested" | "confirmed" | "rejected"; export type LinkState = "confirmed" | "rejected";
/** One link from a lesson to a rule, in the reader's view: only rules the /** One link from a lesson to a rule, in the reader's view: only rules the
* reader owns are listed (`rules_for_lessons`). */ * reader owns are listed (`rules_for_lessons`). */
@@ -20,14 +20,11 @@ export interface LessonRuleLink {
id: number; id: number;
title: string; title: string;
kind: RuleKind; kind: RuleKind;
/** `suggested` carries nothing in retrieval until it is judged; only /** `confirmed` changes what surfaces; `rejected` is kept so the reason
* `confirmed` changes what surfaces; `rejected` is kept so the pair is * stays readable. */
* never proposed again. */
state: LinkState; state: LinkState;
/** Why it was confirmed or rejected. */ /** Why it was confirmed or rejected. */
note: string; note: string;
/** What a suggestion rests on — sent on suggested links only. */
evidence?: { situations: number; projects: number; co_surfaced: number };
} }
/** A lesson: a transferable insight, retrievable by the SITUATION it applies /** A lesson: a transferable insight, retrievable by the SITUATION it applies
@@ -79,7 +76,7 @@ export interface Lesson {
updated_at: string | null; updated_at: string | null;
systems?: { id: number; name: string }[]; systems?: { id: number; name: string }[];
usage?: RecordUsage; usage?: RecordUsage;
/** The rules this lesson points at, confirmed first, then suggested, then /** The rules this lesson was judged against, confirmed first, then
* rejected. Absent (with `rule_judgment`) when the links could not be read * rejected. Absent (with `rule_judgment`) when the links could not be read
* — which is "not attached", never "no rule". */ * — which is "not attached", never "no rule". */
rules?: LessonRuleLink[]; rules?: LessonRuleLink[];
+3 -3
View File
@@ -120,9 +120,9 @@ export interface Rule {
/** Present only when the rule has triggers. */ /** Present only when the rule has triggers. */
triggers?: RuleTrigger[]; triggers?: RuleTrigger[];
relations?: RuleRelation[]; relations?: RuleRelation[];
/** The lessons that point at this rule — the concrete /** The lessons judged against this rule — confirmed instances of it
* situations judged instances of it, plus any suggested and awaiting a * first, then those judged not to be. Readable lessons only; omitted when
* judgment. Readable lessons only; omitted when there are none. */ * there are none. */
lessons?: { id: number; title: string; state: LinkState; note: string }[]; lessons?: { id: number; title: string; state: LinkState; note: string }[];
} }
@@ -570,13 +570,13 @@ watch(() => props.ruleId, load);
<ul> <ul>
<li v-for="l in lessons" :key="l.id" class="relation"> <li v-for="l in lessons" :key="l.id" class="relation">
<router-link :to="`/lessons/${l.id}`" class="relation-target">{{ l.title }}</router-link> <router-link :to="`/lessons/${l.id}`" class="relation-target">{{ l.title }}</router-link>
<span v-if="l.state === 'suggested'" class="rule-chip">suggested</span> <span v-if="l.state === 'rejected'" class="rule-chip">not an instance</span>
<span v-if="l.note" class="relation-note">{{ l.note }}</span> <span v-if="l.note" class="relation-note">{{ l.note }}</span>
</li> </li>
</ul> </ul>
<p class="field-note"> <p class="field-note">
The situations that keep proving this rule. A confirmed lesson brings the rule along The situations that keep proving this rule. A confirmed lesson brings the rule along
when it surfaces; a suggested one waits for a judgment on the lesson's page. when it surfaces, and arrives with the rule when you open it.
</p> </p>
</section> </section>
@@ -603,7 +603,7 @@ watch(() => props.ruleId, load);
</div> </div>
</template> </template>
<!-- `.rule-chip` for the "suggested" marker on a lesson — the chip the rule <!-- `.rule-chip` for the "not an instance" marker on a lesson — the chip the rule
panes already use, loaded here because the slide-over can open with no panes already use, loaded here because the slide-over can open with no
pane that loads it (a link straight to ?rule=N). pane that loads it (a link straight to ?rule=N).
Block 0, as in every pane that loads it: a shared src must sit at Block 0, as in every pane that loads it: a shared src must sit at
+1 -73
View File
@@ -30,7 +30,6 @@ import { apiErrorMessage } from "@/api/client";
import { import {
deleteLesson, deleteLesson,
getLesson, getLesson,
judgeLessonLink,
type Lesson, type Lesson,
type LessonRuleLink, type LessonRuleLink,
} from "@/api/lessons"; } from "@/api/lessons";
@@ -41,7 +40,6 @@ import { DEAD_WEIGHT_ADVICE } from "@/utils/deadWeight";
import { useToastStore } from "@/stores/toast"; import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown"; import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs"; import { vRecordRefs } from "@/directives/recordRefs";
import { canWriteRecord } from "@/utils/permission";
import { recordHref } from "@/utils/recordHref"; import { recordHref } from "@/utils/recordHref";
const route = useRoute(); const route = useRoute();
@@ -62,16 +60,11 @@ const insightHtml = computed(() =>
); );
const canWrite = computed(() => canWriteRecord(lesson.value?.permission));
/** The links by state — each state reads differently. Confirmed links are /** The links by state — each state reads differently. Confirmed links are
* the answer; suggested ones are evidence waiting on a judgment; rejected * the answer; rejected ones are kept so the reason stays readable. */
* ones are kept so the pair is never proposed again, and shown so the reason
* stays readable. */
const linksIn = (state: LessonRuleLink["state"]) => const linksIn = (state: LessonRuleLink["state"]) =>
computed(() => (lesson.value?.rules ?? []).filter((r) => r.state === state)); computed(() => (lesson.value?.rules ?? []).filter((r) => r.state === state));
const confirmedRules = linksIn("confirmed"); const confirmedRules = linksIn("confirmed");
const suggestedRules = linksIn("suggested");
const rejectedRules = linksIn("rejected"); const rejectedRules = linksIn("rejected");
/** A rule opens in the rules view's editor, which takes the rule alone. */ /** A rule opens in the rules view's editor, which takes the rule alone. */
@@ -79,36 +72,6 @@ function ruleHref(ruleId: number) {
return { path: "/rules", query: { rule: String(ruleId) } }; return { path: "/rules", query: { rule: String(ruleId) } };
} }
/** What a suggestion rests on, in the units it was proposed by: distinct
* situations, not raw arrivals — one situation repeated proves nothing. */
function evidenceLine(ev: NonNullable<LessonRuleLink["evidence"]>): string {
const situations = `${ev.situations} distinct situation${ev.situations === 1 ? "" : "s"}`;
const projects = ev.projects > 1 ? `, across ${ev.projects} projects` : "";
return `Arrived together in ${situations}${projects}.`;
}
const judging = ref<number | null>(null);
/** Judge a suggested link from here. Re-reads the lesson rather than editing
* the list in place: confirming also clears a "no rule fits" answer, and the
* judgment line has to come back from the server to be right. */
async function judge(rule: LessonRuleLink, verdict: "confirm" | "reject") {
judging.value = rule.id;
try {
await judgeLessonLink(lessonId.value, rule.id, verdict);
lesson.value = await getLesson(lessonId.value);
toast.show(
verdict === "confirm"
? "Linked — the rule can now surface through this lesson"
: "Not an instance — this pair will not be suggested again",
);
} catch (e) {
toast.show(apiErrorMessage(e, "Failed to record the judgment"), "error");
} finally {
judging.value = null;
}
}
async function load() { async function load() {
loading.value = true; loading.value = true;
error.value = null; error.value = null;
@@ -223,39 +186,6 @@ onMounted(load);
nobody has said none fits. nobody has said none fits.
</p> </p>
<template v-if="suggestedRules.length">
<h3 class="ld-sub-label">Suggested</h3>
<ul class="ld-sources">
<li v-for="r in suggestedRules" :key="r.id">
<router-link :to="ruleHref(r.id)" class="ld-link">
{{ r.title }}
</router-link>
<span v-if="r.kind === 'preference'" class="rule-chip rule-chip-preference">
preference
</span>
<p v-if="r.evidence" class="ld-link-note">{{ evidenceLine(r.evidence) }}</p>
<div v-if="canWrite" class="ld-judge">
<button
type="button"
class="ld-ghost ld-small"
:disabled="judging === r.id"
@click="judge(r, 'confirm')"
>
Confirm
</button>
<button
type="button"
class="ld-ghost ld-small"
:disabled="judging === r.id"
@click="judge(r, 'reject')"
>
Not an instance
</button>
</div>
</li>
</ul>
</template>
<template v-if="rejectedRules.length"> <template v-if="rejectedRules.length">
<h3 class="ld-sub-label">Judged not an instance</h3> <h3 class="ld-sub-label">Judged not an instance</h3>
<ul class="ld-sources ld-rejected"> <ul class="ld-sources ld-rejected">
@@ -410,8 +340,6 @@ onMounted(load);
color: var(--fs-text-tertiary); color: var(--fs-text-tertiary);
} }
.ld-rejected .ld-link { color: var(--fs-text-secondary); } .ld-rejected .ld-link { color: var(--fs-text-secondary); }
.ld-judge { display: flex; gap: var(--fs-space-2); margin-top: var(--fs-space-1); }
.ld-small { padding: 0.15rem 0.6rem; font-size: var(--fs-size-label); }
.ld-ghost:disabled { opacity: var(--fs-disabled-opacity); cursor: default; } .ld-ghost:disabled { opacity: var(--fs-disabled-opacity); cursor: default; }
.ld-tags { display: flex; flex-wrap: wrap; gap: 0.35rem; margin-top: 1.25rem; } .ld-tags { display: flex; flex-wrap: wrap; gap: 0.35rem; margin-top: 1.25rem; }
+6 -6
View File
@@ -408,12 +408,12 @@ async def judge_lesson_link(
"""Say whether a lesson is an instance of a rule: `verdict` is "confirm" """Say whether a lesson is an instance of a rule: `verdict` is "confirm"
or "reject". or "reject".
Reach for this when Grimoire proposes a pair — a lesson and a rule that keep Reach for this when you are reading a lesson and recognise the rule it
arriving together in different situations — or whenever you are reading a falls under, or when a lesson you just recorded was offered candidate
lesson and recognise the rule it falls under. Confirming makes the rule rules. Confirming makes the rule reachable through the situation the
reachable through the situation the lesson describes; rejecting records lesson describes, and lists the lesson on the rule when it is opened;
that it is not, so the pair is not proposed again. `note` is the why, and rejecting records that it is not. `note` is the why, and the next reader
the next reader judges the link by it. judges the link by it.
Returns the link: {lesson_id, rule_id, state, note, evidence, judged_at}. Returns the link: {lesson_id, rule_id, state, note, evidence, judged_at}.
""" """
+2 -11
View File
@@ -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.auth import admin_required, get_current_user_id, login_required
from grimoire.config import Config from grimoire.config import Config
from grimoire.services import hook_payload as hook_payload_svc 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 moment_delivery as moment_delivery_svc
from grimoire.services import plugin_context as plugin_ctx_svc from grimoire.services import plugin_context as plugin_ctx_svc
from grimoire.services import reply_shapes as reply_shapes_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( result = await plugin_ctx_svc.build_autoinject_hint(
g.user.id, q, project_id=project_id, exclude_ids=exclude_ids, context=ctx, 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 # 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. # just named is not quoted a second time by the turn's delivery.
turn = await moment_delivery_svc.deliver_for_turn( turn = await moment_delivery_svc.deliver_for_turn(
@@ -232,8 +224,8 @@ async def autoinject_retrieve():
record=False, record=False,
) )
# One payload, in the one order: the rules, then the reply shape, then # 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 # what the last turn left unjudged, then the records menu, fitted to the
# lesson-rule proposal, fitted to the budget. # budget.
carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS] carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS]
turn_parts = ( turn_parts = (
[*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn [*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn
@@ -247,7 +239,6 @@ async def autoinject_retrieve():
*turn_parts, *turn_parts,
*([hook_payload_svc.Part(text=carry)] if carry else []), *([hook_payload_svc.Part(text=carry)] if carry else []),
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}), *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)) shapes = set(fitted.ids(hook_payload_svc.SHAPE))
forms = {k: f for k, f in turn["shape_forms"].items() if k in shapes} forms = {k: f for k, f in turn["shape_forms"].items() if k in shapes}
+27 -134
View File
@@ -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. rule a lesson is an instance of — and both directions of reading it.
THE STATES (models/lesson_rule_link.py says why each exists): THE STATES (models/lesson_rule_link.py says why each exists):
`suggested` while evidence accumulates, `confirmed` or `rejected` once a `confirmed` or `rejected`, once a judgment is made. Every write here is a
judgment is made. Every write here is a JUDGMENT, so every write lands as JUDGMENT, so every write lands as one of the two. `suggested` rows were
confirmed or rejected; `suggested` rows come from the co-surfacing recorder, written by a co-arrival recorder that no longer runs; they stay in the table
never from a caller naming a rule. 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 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 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 (see Convergence below), and that is unreadable if "nobody looked" means the
same thing. same thing.
THE SOFT LINK. When one hook request puts a lesson and a rule in EVIDENCE BY SITUATION. `situation_key`, `add_evidence` and `proposal_due`
front of the reader together, `co_surfaced` records the pair as evidence on a count distinct SITUATIONS, not arrivals, for the rule↔moment signals that
SUGGESTED link, and once that evidence crosses a bar the next co-arrival asks ask a reader to judge a pairing (`rule_moment_judgments`): two things that
the reader to judge it. The evidence counts distinct SITUATIONS, not resemble each other arrive together on every similar prompt, and counting
arrivals: two records that resemble each other arrive together on every each time would measure their similarity over and over rather than any
similar prompt, and counting each time would measure their similarity over relation between them.
and over rather than any relation between them.
ACL (services/access.py). Linking changes what a lesson says about itself, so it needs 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 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 datetime import datetime, timedelta, timezone
from sqlalchemy import and_, delete, exists, func, not_, or_, select from sqlalchemy import and_, delete, exists, func, not_, or_, select
from sqlalchemy.exc import IntegrityError
from grimoire.models import async_session from grimoire.models import async_session
from grimoire.models.lesson_rule_link import ( 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. """{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. 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 Judged links only, confirmed before rejected: a rejection is kept so the
about them in. reader sees the rule was considered and is not this one.
""" """
from grimoire.services.rulebooks import _owned_rules_clause 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} out: dict[int, list[dict]] = {i: [] for i in ids}
if not ids: if not ids:
return out return out
order = {s: n for n, s in enumerate((CONFIRMED, SUGGESTED, REJECTED))} order = {CONFIRMED: 0, REJECTED: 1}
async with async_session() as session: async with async_session() as session:
rows = (await session.execute( rows = (await session.execute(
select(LessonRuleLink, Rule) select(LessonRuleLink, Rule)
.join(Rule, Rule.id == LessonRuleLink.rule_id) .join(Rule, Rule.id == LessonRuleLink.rule_id)
.where(LessonRuleLink.lesson_id.in_(ids)) .where(LessonRuleLink.lesson_id.in_(ids))
.where(LessonRuleLink.state.in_(list(order)))
.where(_owned_rules_clause(user_id)) .where(_owned_rules_clause(user_id))
)).all() )).all()
for link, rule in sorted(rows, key=lambda r: (order.get(r[0].state, 9), r[1].id)): for link, rule in sorted(rows, key=lambda r: (order[r[0].state], r[1].id)):
item = { out[link.lesson_id].append({
"id": rule.id, "title": rule.title, "kind": rule.kind, "id": rule.id, "title": rule.title, "kind": rule.kind,
"state": link.state, "note": link.note or "", "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 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 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 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 from grimoire.services.access import readable_notes_clause
order = {CONFIRMED: 0, REJECTED: 1}
async with async_session() as session: async with async_session() as session:
rows = (await session.execute( rows = (await session.execute(
select(LessonRuleLink, Note) select(LessonRuleLink, Note)
.join(Note, Note.id == LessonRuleLink.lesson_id) .join(Note, Note.id == LessonRuleLink.lesson_id)
.where(LessonRuleLink.rule_id == int(rule_id)) .where(LessonRuleLink.rule_id == int(rule_id))
.where(LessonRuleLink.state.in_(list(order)))
.where(Note.deleted_at.is_(None)) .where(Note.deleted_at.is_(None))
.where(readable_notes_clause(user_id)) .where(readable_notes_clause(user_id))
)).all() )).all()
order = {s: n for n, s in enumerate((CONFIRMED, SUGGESTED, REJECTED))}
return [ return [
{"id": note.id, "title": note.title, "state": link.state, "note": link.note or ""} {"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 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 ────────────────────────────────────── # ── 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 """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. 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 CONFIRMED ONLY: nobody judged a suggested link, and a lesson that brought
carried its rule would put the two side by side on every prompt that an unjudged rule along would put a rule in front of the reader on the
found the lesson, which is exactly the co-arrival the soft link counts strength of a resemblance alone.
as evidence — the suggestion would manufacture its own proof.
Asked first and cheaply, so an arm on an install with no confirmed links 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. — every install, until someone judges one — never pays for a search.
+3 -30
View File
@@ -862,18 +862,9 @@ async def build_autoinject_hint(
project_id=project_id, 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 { return {
"context": "\n".join(lines), "note_ids": note_ids, "config": cfg, "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 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 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 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( result = await rp.run_rule_arm(
arm, moment, floor=floor, budget=budget, io=_rule_io(), 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", result.lines, result.rule_per_line(), block="rules",
) )
# Every rule LINE the direct arm showed, repeats and the reserved # 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. # from `rule_ids`, which is telemetry's fresh-only cut.
out["shown_rule_ids"] = result.shown_rule_ids out["shown_rule_ids"] = result.shown_rule_ids
except Exception: except Exception:
@@ -1697,7 +1688,6 @@ async def build_write_path_hint(
rule_lines: list[str] = [] rule_lines: list[str] = []
rule_line_ids: list[int] = [] rule_line_ids: list[int] = []
rule_ids: list[int] = [] rule_ids: list[int] = []
shown_rule_ids: list[int] = []
checkpoint: dict = {} checkpoint: dict = {}
try: try:
result = await _rule_moment( result = await _rule_moment(
@@ -1714,9 +1704,6 @@ async def build_write_path_hint(
rule_lines = result.lines rule_lines = result.lines
rule_line_ids = result.rule_per_line() rule_line_ids = result.rule_per_line()
rule_ids.extend(result.rule_ids) 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 checkpoint = result.checkpoint
except Exception: except Exception:
logger.debug("write-path rule arm failed", exc_info=True) logger.debug("write-path rule arm failed", exc_info=True)
@@ -1917,20 +1904,6 @@ async def build_write_path_hint(
lines.extend(rule_lines) 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 { return {
"context": "\n".join(lines), "context": "\n".join(lines),
"parts": parts, "parts": parts,
@@ -11,7 +11,7 @@ sources that both stop at a proposal:
nothing; a person confirms it (`judge`). nothing; a person confirms it (`judge`).
- THE SIGNAL. A rule a session OPENS shortly after a moment fired is evidence - 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 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 cooldown), and once it crosses the bar the next open asks the reader to
offer the mount (`co_occurred`). offer the mount (`co_occurred`).
-1
View File
@@ -221,7 +221,6 @@ def _no_lesson_rule_links(request):
with patch("grimoire.services.lesson_rules.attach_lesson_rules", AsyncMock()), \ with patch("grimoire.services.lesson_rules.attach_lesson_rules", AsyncMock()), \
patch("grimoire.services.lesson_rules.attach_rule_lessons", AsyncMock()), \ patch("grimoire.services.lesson_rules.attach_rule_lessons", AsyncMock()), \
patch("grimoire.services.lesson_rules.rule_candidates", AsyncMock(return_value=[])), \ patch("grimoire.services.lesson_rules.rule_candidates", AsyncMock(return_value=[])), \
patch("grimoire.services.lesson_rules.co_surfaced", AsyncMock(return_value="")), \
patch("grimoire.services.plugin_context._rules_via_lessons", patch("grimoire.services.plugin_context._rules_via_lessons",
AsyncMock(return_value=([], []))), \ AsyncMock(return_value=([], []))), \
patch("grimoire.services.lesson_rules.convergence_for", AsyncMock(return_value=None)): patch("grimoire.services.lesson_rules.convergence_for", AsyncMock(return_value=None)):
+18 -63
View File
@@ -259,87 +259,42 @@ async def test_deleting_the_lesson_takes_its_answer_with_it(world):
assert left == [] assert left == []
# ── soft links from co-surfacing ──────────────────────────────────────────── # ── suggested links: inert, and absent from every read ──────────────────────
async def _link(lesson_id: int, rule_id: int): async def _suggest(lesson_id: int, rule_id: int) -> None:
"""A suggested row, as the retired co-arrival recorder left them."""
async with async_session() as s: async with async_session() as s:
return (await s.execute( s.add(LessonRuleLink(lesson_id=lesson_id, rule_id=rule_id, state="suggested",
select(LessonRuleLink).where( evidence={"situations": ["p:1", "p:2", "p:3"]}))
LessonRuleLink.lesson_id == lesson_id, LessonRuleLink.rule_id == rule_id, await s.commit()
)
)).scalar_one_or_none()
async def _arrive(world, prompt: str, project: int | None = None, rules=None) -> str: async def test_a_suggested_link_is_in_no_read_and_leaves_the_lesson_unjudged(world):
return await links_svc.co_surfaced( await _suggest(world["lesson"], world["r1"])
world["owner"], [world["lesson"]], rules or [world["r1"]], await links_svc.judge_link(world["owner"], world["lesson"], world["r2"], "reject", "not this")
arm="p", situation=prompt, project_id=project,
)
async def test_distinct_situations_reach_the_bar_and_the_proposal_fires_once(world):
assert await _arrive(world, "the CI run is still going after twenty minutes") == ""
assert await _arrive(world, "deploy job hanging on the image build step") == ""
line = await _arrive(world, "integration lane overran its usual duration", world["mine"])
assert f"judge_lesson_link({world['lesson']}, {world['r1']}" in line
link = await _link(world["lesson"], world["r1"])
assert link.state == "suggested"
assert links_svc.evidence_summary(link.evidence)["situations"] == 3
# Within the cooldown a fourth situation is counted but not asked again.
assert await _arrive(world, "pipeline stuck waiting on a runner for ages") == ""
link = await _link(world["lesson"], world["r1"])
assert links_svc.evidence_summary(link.evidence)["situations"] == 4
async def test_the_same_prompt_repeated_never_reaches_the_bar(world):
for _ in range(5):
assert await _arrive(world, "is the CI run still going") == ""
ev = links_svc.evidence_summary((await _link(world["lesson"], world["r1"])).evidence)
assert ev == {"situations": 1, "projects": 0, "co_surfaced": 5}
async def test_a_judged_pair_gathers_nothing_and_is_never_proposed(world):
owner = world["owner"]
await links_svc.judge_link(owner, world["lesson"], world["r1"], "reject", "different failure")
await links_svc.judge_link(owner, world["lesson"], world["r2"], "confirm")
for prompt in ("first situation here", "second situation there", "third situation elsewhere"):
assert await _arrive(world, prompt, rules=[world["r1"], world["r2"]]) == ""
assert (await _link(world["lesson"], world["r1"])).evidence is None
assert (await _link(world["lesson"], world["r2"])).evidence is None
async def test_a_rule_the_reader_does_not_own_is_not_paired(world):
for prompt in ("first situation here", "second situation there", "third situation elsewhere"):
assert await _arrive(world, prompt, rules=[world["foreign"]]) == ""
assert await _link(world["lesson"], world["foreign"]) is None
async def test_a_suggestion_shows_its_evidence_and_leaves_the_lesson_unjudged(world):
await _arrive(world, "the CI run is still going after twenty minutes", world["mine"])
rules = (await links_svc.rules_for_lessons(world["owner"], [world["lesson"]]))[world["lesson"]] rules = (await links_svc.rules_for_lessons(world["owner"], [world["lesson"]]))[world["lesson"]]
assert rules[0]["state"] == "suggested" assert [(r["id"], r["state"]) for r in rules] == [(world["r2"], "rejected")]
assert rules[0]["evidence"] == {"situations": 1, "projects": 1, "co_surfaced": 1} assert [x["id"] for x in await links_svc.lessons_for_rule(world["owner"], world["r1"])] == []
assert (await _judgment(world["lesson"]))["rule_judgment"] == "unjudged" assert (await _judgment(world["lesson"]))["rule_judgment"] == "unjudged"
async def test_confirming_a_suggestion_keeps_what_it_rested_on(world): async def test_confirming_a_suggested_pair_puts_it_in_the_rules_read(world):
for prompt in ("first situation here", "second situation there", "third situation elsewhere"): await _suggest(world["lesson"], world["r1"])
await _arrive(world, prompt)
out = await links_svc.judge_link(world["owner"], world["lesson"], world["r1"], "confirm", "same failure class") out = await links_svc.judge_link(world["owner"], world["lesson"], world["r1"], "confirm", "same failure class")
assert out["state"] == "confirmed" assert out["state"] == "confirmed"
assert len(out["evidence"]["situations"]) == 3 lessons = await links_svc.lessons_for_rule(world["owner"], world["r1"])
assert [(x["id"], x["state"]) for x in lessons] == [(world["lesson"], "confirmed")]
# ── which links can carry a rule ──────────────────────────────────────────── # ── which links can carry a rule ────────────────────────────────────────────
async def test_only_a_confirmed_link_can_carry_its_rule(world): async def test_only_a_confirmed_link_can_carry_its_rule(world):
"""A suggested link never expands: it would manufacture the co-arrival """A suggested link never carries its rule: nothing judged it. A rejected
that co-surfacing counts, and prove itself. A rejected one obviously not.""" one obviously not."""
owner, lesson = world["owner"], world["lesson"] owner, lesson = world["owner"], world["lesson"]
await links_svc.co_surfaced(owner, [lesson], [world["r1"]], arm="p", situation="one ask here") await _suggest(lesson, world["r1"])
await links_svc.judge_link(owner, lesson, world["r2"], "reject", "not this") await links_svc.judge_link(owner, lesson, world["r2"], "reject", "not this")
assert await links_svc.confirmed_lessons(owner) == set() assert await links_svc.confirmed_lessons(owner) == set()
assert await links_svc.confirmed_rules_in_scope(owner, [lesson], world["mine"]) == {} assert await links_svc.confirmed_rules_in_scope(owner, [lesson], world["mine"]) == {}
-24
View File
@@ -9,7 +9,6 @@ is tested against Postgres in tests/test_integration_lesson_rule_links.py.
""" """
from __future__ import annotations from __future__ import annotations
import inspect
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from grimoire.services import lesson_rules as links_svc from grimoire.services import lesson_rules as links_svc
@@ -76,28 +75,5 @@ def test_a_passed_over_proposal_waits_out_the_cooldown():
assert links_svc.proposal_due(ev, NOW + links_svc.PROPOSE_COOLDOWN) assert links_svc.proposal_due(ev, NOW + links_svc.PROPOSE_COOLDOWN)
def test_the_proposal_names_the_call_that_answers_it():
line = links_svc._proposal_line(
41, "An overrun run usually failed early", 7, "Read the job log first",
"rule", {"situations": ["p:1", "p:2", "p:3"], "projects": [2, 5]},
)
assert 'judge_lesson_link(41, 7, "confirm"' in line
assert '"reject"' in line
assert "3 distinct situations across 2 projects" in line
def test_evidence_summary_reads_nothing_as_zero_not_an_error(): def test_evidence_summary_reads_nothing_as_zero_not_an_error():
assert links_svc.evidence_summary(None) == {"situations": 0, "projects": 0, "co_surfaced": 0} assert links_svc.evidence_summary(None) == {"situations": 0, "projects": 0, "co_surfaced": 0}
def test_both_hook_doors_count_the_pair_on_their_own_arm():
"""The two responses that carry lessons and rules together. A door that
renders both and does not record the pair is the miss this step exists
to close, and it would produce no error anywhere — only an empty table."""
from grimoire.routes import plugin as plugin_routes
from grimoire.services import plugin_context
prompt_door = inspect.getsource(plugin_routes.autoinject_retrieve)
assert "co_surfaced(" in prompt_door and 'arm="p"' in prompt_door
write_door = inspect.getsource(plugin_context.build_write_path_hint)
assert "co_surfaced(" in write_door and 'arm="w"' in write_door
-1
View File
@@ -43,7 +43,6 @@ async def _retrieve(query_string, turn_context="CORE SHAPE"):
"shown_rule_ids": [11]})), \ "shown_rule_ids": [11]})), \
patch.object(routes.plugin_ctx_svc, "build_autoinject_hint", patch.object(routes.plugin_ctx_svc, "build_autoinject_hint",
AsyncMock(return_value={"context": "NOTES MENU", "note_ids": []})), \ AsyncMock(return_value={"context": "NOTES MENU", "note_ids": []})), \
patch.object(routes.lesson_rules_svc, "co_surfaced", AsyncMock(return_value="")), \
patch.object(routes.moment_delivery_svc, "deliver_for_turn", turn): patch.object(routes.moment_delivery_svc, "deliver_for_turn", turn):
resp = await inspect.unwrap(routes.autoinject_retrieve)() resp = await inspect.unwrap(routes.autoinject_retrieve)()
return await resp.get_json(), turn return await resp.get_json(), turn