Records reach work just in time: pointer lines and lessons by situation (milestone 642, steps 5–6) #231
@@ -0,0 +1,58 @@
|
||||
"""lesson_situations — when a lesson applies, as moments and triggers
|
||||
|
||||
Revision ID: 0137
|
||||
Revises: 0136
|
||||
Create Date: 2026-11-25
|
||||
|
||||
One row per (lesson, kind, value). `kind` is `moment` (a catalog moment
|
||||
key), `trigger` (a typed predicate on the act, in rule_field_judgments'
|
||||
trigger_value form) or `none` (no situation fits; value ''). `state` is
|
||||
`suggested` while a pass's proposal waits, `confirmed` or `rejected` once a
|
||||
person judges it; only confirmed rows deliver. CASCADE on the lesson: a
|
||||
situation of a record that no longer exists says nothing. No backfill: no
|
||||
lesson had a situation before this table.
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0137"
|
||||
down_revision = "0136"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# One place each, so the CHECKs and the model's tuples cannot drift (a new
|
||||
# value later means DROP + ADD CONSTRAINT in the same migration).
|
||||
_KINDS = ("moment", "trigger", "none")
|
||||
_STATES = ("suggested", "confirmed", "rejected")
|
||||
_SOURCES = ("pass", "edit")
|
||||
|
||||
|
||||
def _in(values) -> str:
|
||||
return "(" + ", ".join(f"'{v}'" for v in values) + ")"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"lesson_situations",
|
||||
sa.Column("id", sa.BigInteger(), primary_key=True),
|
||||
sa.Column("lesson_id", sa.BigInteger(), sa.ForeignKey("notes.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("kind", sa.Text(), nullable=False),
|
||||
sa.Column("value", sa.Text(), nullable=False, server_default=""),
|
||||
sa.Column("state", sa.Text(), nullable=False, server_default="suggested"),
|
||||
sa.Column("source", sa.Text(), nullable=False, server_default="pass"),
|
||||
sa.Column("note", sa.Text(), nullable=True),
|
||||
sa.Column("judged_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
|
||||
sa.UniqueConstraint("lesson_id", "kind", "value", name="uq_lesson_situations_value"),
|
||||
)
|
||||
op.create_check_constraint("ck_lesson_situations_kind", "lesson_situations", "kind IN " + _in(_KINDS))
|
||||
op.create_check_constraint("ck_lesson_situations_state", "lesson_situations", "state IN " + _in(_STATES))
|
||||
op.create_check_constraint("ck_lesson_situations_source", "lesson_situations", "source IN " + _in(_SOURCES))
|
||||
op.create_index("ix_lesson_situations_lesson_id", "lesson_situations", ["lesson_id"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_lesson_situations_lesson_id", table_name="lesson_situations")
|
||||
for name in ("source", "state", "kind"):
|
||||
op.drop_constraint(f"ck_lesson_situations_{name}", "lesson_situations", type_="check")
|
||||
op.drop_table("lesson_situations")
|
||||
@@ -114,6 +114,10 @@ endpoint at `/mcp`, not these REST routes.
|
||||
| GET | `/api/lessons/rule-candidates` | Rules a draft lesson resembles, before it is saved |
|
||||
| GET | `/api/lessons/taught-by/:record_id` | Lessons drawn from one record |
|
||||
| PUT | `/api/lessons/:id/rules/:rule_id` | Confirm or reject a lesson → rule link |
|
||||
| GET / POST | `/api/lessons/:id/situations` | A lesson's situations (moments and triggers it arrives at); add one |
|
||||
| DELETE | `/api/lessons/situations/:situation_id` | Take a situation off its lesson |
|
||||
| GET | `/api/lessons/situations/proposals` | Situations a pass proposed, waiting on a judgment, with counts |
|
||||
| POST | `/api/lessons/situations/judge` | Confirm or reject proposed situations |
|
||||
|
||||
## Design systems
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { RecordUsage } from "@/types/usage";
|
||||
|
||||
import { apiGet, apiPost, apiPut, apiPatch, apiDelete } from "@/api/client";
|
||||
import type { RuleKind } from "@/api/rulebooks";
|
||||
import type { RuleKind, RuleTrigger } from "@/api/rulebooks";
|
||||
|
||||
/** Where a lesson stands on "which rule is this an instance of?"
|
||||
* (`services/lesson_rules.py`: LINKED / NO_RULE / UNJUDGED). Three answers,
|
||||
@@ -229,3 +229,77 @@ export function lessonsTaughtBy(
|
||||
`/api/lessons/taught-by/${recordId}`,
|
||||
);
|
||||
}
|
||||
|
||||
// ── when a lesson applies (services/lesson_situations.py) ────────────────
|
||||
|
||||
/** `moment` — a catalog moment; `trigger` — a typed predicate on the act. */
|
||||
export type SituationKind = "moment" | "trigger";
|
||||
|
||||
/** One situation of a lesson: live (`confirmed`) or waiting on a person
|
||||
* (`suggested`). `describes` is how it reads in the line a session sees. */
|
||||
export interface LessonSituation {
|
||||
id: number;
|
||||
lesson_id: number;
|
||||
kind: SituationKind;
|
||||
value: string;
|
||||
state: "suggested" | "confirmed";
|
||||
source: "pass" | "edit";
|
||||
note: string;
|
||||
describes: string;
|
||||
trigger?: RuleTrigger;
|
||||
}
|
||||
|
||||
export interface LessonSituationProposals {
|
||||
lessons: {
|
||||
lesson_id: number;
|
||||
title: string;
|
||||
when_to_apply: string;
|
||||
proposals: LessonSituation[];
|
||||
}[];
|
||||
total: number;
|
||||
/** Readable lessons by where they stand: arriving at a situation, read
|
||||
* and found to have none, waiting on a judgment, or not yet read. */
|
||||
counts: { situated: number; none_fits: number; waiting: number; unsituated: number };
|
||||
}
|
||||
|
||||
export interface LessonSituationsPayload {
|
||||
situations: LessonSituation[];
|
||||
catalog: { name: string; means: string }[];
|
||||
trigger_kinds: RuleTrigger["kind"][];
|
||||
}
|
||||
|
||||
export interface SituationJudgment {
|
||||
id: number;
|
||||
verdict: "confirm" | "reject";
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export function getLessonSituationProposals(): Promise<LessonSituationProposals> {
|
||||
return apiGet("/api/lessons/situations/proposals");
|
||||
}
|
||||
|
||||
/** A confirm makes the lesson arrive at that situation, once per session; a
|
||||
* reject stops the value being proposed again. */
|
||||
export function judgeLessonSituations(
|
||||
judgments: SituationJudgment[],
|
||||
): Promise<{ judged: LessonSituation[] }> {
|
||||
return apiPost("/api/lessons/situations/judge", { judgments });
|
||||
}
|
||||
|
||||
export function getLessonSituations(lessonId: number): Promise<LessonSituationsPayload> {
|
||||
return apiGet(`/api/lessons/${lessonId}/situations`);
|
||||
}
|
||||
|
||||
/** Make one situation live: a moment, or a trigger. */
|
||||
export function addLessonSituation(
|
||||
lessonId: number,
|
||||
body: { moment: string } | { trigger: RuleTrigger },
|
||||
): Promise<LessonSituation> {
|
||||
return apiPost(`/api/lessons/${lessonId}/situations`, body);
|
||||
}
|
||||
|
||||
/** Take a situation off its lesson; kept as rejected so it is not proposed
|
||||
* again. `apiDelete` discards the body. */
|
||||
export function removeLessonSituation(situationId: number): Promise<void> {
|
||||
return apiDelete(`/api/lessons/situations/${situationId}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import {
|
||||
getLessonSituationProposals, judgeLessonSituations,
|
||||
type LessonSituation, type LessonSituationProposals,
|
||||
} from "@/api/lessons";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import ConfirmDialog from "@/components/ConfirmDialog.vue";
|
||||
|
||||
/**
|
||||
* When each lesson applies, waiting on a person. A pass read each lesson
|
||||
* beside the rules it is an instance of and proposed the moments of work, or
|
||||
* the triggers on an act (a path, a command, a tool, a word), at which it
|
||||
* should arrive. A lesson with a confirmed situation arrives there, once per
|
||||
* session, instead of whenever an edit's words resemble it. Nothing changes
|
||||
* until "Apply" is pressed; "Not this" keeps the value from being proposed
|
||||
* again. The same judgment `judge_lesson_situations` makes in a session.
|
||||
*/
|
||||
const toast = useToastStore();
|
||||
|
||||
const data = ref<LessonSituationProposals | null>(null);
|
||||
const failed = ref(false);
|
||||
const busy = ref<number | "all" | null>(null);
|
||||
const confirmingAll = ref(false);
|
||||
|
||||
const lessons = computed(() => data.value?.lessons ?? []);
|
||||
const counts = computed(() => data.value?.counts);
|
||||
const allIds = computed(() => lessons.value.flatMap((l) => l.proposals.map((p) => p.id)));
|
||||
|
||||
const allSummary = computed(() => {
|
||||
const n = allIds.value.length;
|
||||
const across = `${lessons.value.length} lesson${lessons.value.length === 1 ? "" : "s"}`;
|
||||
return `${n} situation${n === 1 ? "" : "s"} across ${across} take effect at once: each lesson `
|
||||
+ "will arrive when its situation is reached, once per session.";
|
||||
});
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
data.value = await getLessonSituationProposals();
|
||||
failed.value = false;
|
||||
} catch {
|
||||
failed.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function decide(p: LessonSituation, verdict: "confirm" | "reject") {
|
||||
busy.value = p.id;
|
||||
try {
|
||||
await judgeLessonSituations([{
|
||||
id: p.id, verdict,
|
||||
note: verdict === "confirm" ? "Applied in Settings." : "Declined in Settings.",
|
||||
}]);
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.show(apiErrorMessage(e, "Could not record that"), "error");
|
||||
} finally {
|
||||
busy.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function applyAll() {
|
||||
confirmingAll.value = false;
|
||||
busy.value = "all";
|
||||
try {
|
||||
const out = await judgeLessonSituations(allIds.value.map((id) => ({
|
||||
id, verdict: "confirm" as const, note: "Applied with Apply all in Settings.",
|
||||
})));
|
||||
toast.show(`${out.judged.length} applied.`, "success");
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.show(apiErrorMessage(e, "Could not apply the suggestions"), "error");
|
||||
} finally {
|
||||
busy.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="proposals" aria-labelledby="lesson-situations-title">
|
||||
<h3 id="lesson-situations-title" class="sub-title">When lessons arrive</h3>
|
||||
<p v-if="failed" class="error-msg">
|
||||
The lesson situations could not be loaded.
|
||||
<button type="button" class="btn-text" @click="load">Try again</button>
|
||||
</p>
|
||||
<template v-else-if="data">
|
||||
<p class="field-hint">
|
||||
A lesson with a situation arrives when the work reaches it — a moment like delivering or
|
||||
finishing, or an act on a path, command or tool — once per session. A lesson without one
|
||||
is found only when a message resembles it.
|
||||
<template v-if="counts">
|
||||
{{ counts.situated }} arrive by situation, {{ counts.none_fits }} were read and fit none,
|
||||
{{ counts.waiting }} wait on you, and {{ counts.unsituated }} have not been read.
|
||||
</template>
|
||||
</p>
|
||||
<p v-if="!lessons.length" class="field-hint empty-note">
|
||||
Nothing is waiting. A session proposes situations with <code>lessons_to_situate</code> and
|
||||
<code>propose_lesson_situations</code>; they appear here to apply or decline.
|
||||
</p>
|
||||
<template v-else>
|
||||
<div class="proposals-bar">
|
||||
<button
|
||||
type="button" class="btn-primary btn-sm"
|
||||
:disabled="busy !== null"
|
||||
@click="confirmingAll = true"
|
||||
>Apply all {{ allIds.length }}</button>
|
||||
</div>
|
||||
<ul class="proposal-list">
|
||||
<li v-for="lesson in lessons" :key="lesson.lesson_id" class="proposal-rule">
|
||||
<div class="rule-head">
|
||||
<router-link :to="`/lessons/${lesson.lesson_id}`" class="rule-title">
|
||||
#{{ lesson.lesson_id }} {{ lesson.title }}
|
||||
</router-link>
|
||||
</div>
|
||||
<p v-if="lesson.when_to_apply" class="rule-statement">
|
||||
When to apply: {{ lesson.when_to_apply }}
|
||||
</p>
|
||||
<ul class="proposal-items">
|
||||
<li v-for="p in lesson.proposals" :key="p.id" class="proposal-item">
|
||||
<code class="moment-name">{{ p.describes }}</code>
|
||||
<span class="proposal-why">{{ p.note }}</span>
|
||||
<span class="proposal-actions">
|
||||
<button
|
||||
type="button" class="btn-primary btn-sm"
|
||||
:disabled="busy !== null"
|
||||
@click="decide(p, 'confirm')"
|
||||
>Apply</button>
|
||||
<button
|
||||
type="button" class="btn-text"
|
||||
:disabled="busy !== null"
|
||||
@click="decide(p, 'reject')"
|
||||
>Not this</button>
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
</template>
|
||||
<ConfirmDialog
|
||||
v-if="confirmingAll"
|
||||
title="Apply every situation?"
|
||||
:message="allSummary"
|
||||
confirm-label="Apply all"
|
||||
:danger="false"
|
||||
@confirm="applyAll"
|
||||
@cancel="confirmingAll = false"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped src="@/assets/rule-proposals.css" />
|
||||
|
||||
<style src="@/assets/moments-shared.css" />
|
||||
|
||||
<style scoped>
|
||||
.empty-note { margin: 0; }
|
||||
</style>
|
||||
@@ -0,0 +1,230 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from "vue";
|
||||
import {
|
||||
addLessonSituation, getLessonSituations, judgeLessonSituations, removeLessonSituation,
|
||||
type LessonSituation, type LessonSituationsPayload,
|
||||
} from "@/api/lessons";
|
||||
import type { RuleTrigger } from "@/api/rulebooks";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
|
||||
/**
|
||||
* When a lesson arrives. A situation is a moment of work (delivering,
|
||||
* finishing, …) or a trigger on an act (a path, a command, a tool, a word);
|
||||
* the lesson is shown to a session when its work reaches one, once per
|
||||
* session. Proposals from a pass wait here and in Settings › Moments until
|
||||
* applied or declined. A writer can add a situation directly or take one off;
|
||||
* one taken off is not proposed again.
|
||||
*/
|
||||
const props = defineProps<{ lessonId: number; canWrite: boolean }>();
|
||||
const toast = useToastStore();
|
||||
|
||||
const data = ref<LessonSituationsPayload | null>(null);
|
||||
const failed = ref(false);
|
||||
const busy = ref(false);
|
||||
|
||||
// The add form: what kind of situation, then a moment or a pattern.
|
||||
const what = ref<"moment" | RuleTrigger["kind"]>("moment");
|
||||
const moment = ref("");
|
||||
const pattern = ref("");
|
||||
|
||||
// Placeholders are generic shapes, never anyone's own paths or commands.
|
||||
const PLACEHOLDER: Record<string, string> = {
|
||||
path: "e.g. migrations/**/*.py",
|
||||
command: "e.g. git push",
|
||||
tool: "e.g. edit",
|
||||
keyword: "e.g. release",
|
||||
};
|
||||
|
||||
const live = computed(() => (data.value?.situations ?? []).filter((s) => s.state === "confirmed"));
|
||||
const waiting = computed(() => (data.value?.situations ?? []).filter((s) => s.state === "suggested"));
|
||||
const canAdd = computed(() =>
|
||||
what.value === "moment" ? !!moment.value : pattern.value.trim().length > 0,
|
||||
);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
data.value = await getLessonSituations(props.lessonId);
|
||||
failed.value = false;
|
||||
} catch {
|
||||
failed.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function run(action: () => Promise<unknown>, done: string, failure: string) {
|
||||
busy.value = true;
|
||||
try {
|
||||
await action();
|
||||
toast.show(done, "success");
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.show(apiErrorMessage(e, failure), "error");
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function add() {
|
||||
const body = what.value === "moment"
|
||||
? { moment: moment.value }
|
||||
: { trigger: { kind: what.value, pattern: pattern.value.trim() } };
|
||||
return run(async () => {
|
||||
await addLessonSituation(props.lessonId, body);
|
||||
moment.value = "";
|
||||
pattern.value = "";
|
||||
}, "The lesson now arrives there", "Could not add that situation");
|
||||
}
|
||||
|
||||
function remove(s: LessonSituation) {
|
||||
return run(() => removeLessonSituation(s.id), "Taken off", "Could not take that off");
|
||||
}
|
||||
|
||||
function judge(s: LessonSituation, verdict: "confirm" | "reject") {
|
||||
return run(
|
||||
() => judgeLessonSituations([{
|
||||
id: s.id, verdict, note: verdict === "confirm" ? "Applied on the lesson." : "Declined on the lesson.",
|
||||
}]),
|
||||
verdict === "confirm" ? "Applied" : "Declined",
|
||||
"Could not record that",
|
||||
);
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
watch(() => props.lessonId, load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="ls-panel" aria-labelledby="ls-title">
|
||||
<h2 id="ls-title" class="ls-label">When it arrives</h2>
|
||||
<p v-if="failed" class="ls-muted">
|
||||
The situations could not be loaded.
|
||||
<button type="button" class="ls-text-btn" @click="load">Try again</button>
|
||||
</p>
|
||||
<template v-else-if="data">
|
||||
<ul v-if="live.length" class="ls-list">
|
||||
<li v-for="s in live" :key="s.id" class="ls-item">
|
||||
<code class="ls-value">{{ s.describes }}</code>
|
||||
<button
|
||||
v-if="canWrite" type="button" class="ls-text-btn"
|
||||
:disabled="busy" :aria-label="`Take off ${s.describes}`"
|
||||
@click="remove(s)"
|
||||
>Take off</button>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="ls-muted">
|
||||
No situation yet — the lesson is found only when a message resembles it.
|
||||
</p>
|
||||
|
||||
<template v-if="waiting.length">
|
||||
<h3 class="ls-sub">Proposed</h3>
|
||||
<ul class="ls-list">
|
||||
<li v-for="s in waiting" :key="s.id" class="ls-item">
|
||||
<code class="ls-value">{{ s.describes }}</code>
|
||||
<span v-if="s.note" class="ls-note">{{ s.note }}</span>
|
||||
<span v-if="canWrite" class="ls-actions">
|
||||
<button type="button" class="ls-btn" :disabled="busy" @click="judge(s, 'confirm')">Apply</button>
|
||||
<button type="button" class="ls-text-btn" :disabled="busy" @click="judge(s, 'reject')">Not this</button>
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
<form v-if="canWrite" class="ls-add" @submit.prevent="add">
|
||||
<label class="ls-field">
|
||||
<span class="ls-field-label">Arrive at</span>
|
||||
<select v-model="what" class="ls-input" :disabled="busy">
|
||||
<option value="moment">a moment of work</option>
|
||||
<option v-for="k in data.trigger_kinds" :key="k" :value="k">a {{ k }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-if="what === 'moment'" class="ls-field ls-grow">
|
||||
<span class="ls-field-label">Moment</span>
|
||||
<select v-model="moment" class="ls-input" :disabled="busy">
|
||||
<option value="" disabled>Choose a moment</option>
|
||||
<option v-for="m in data.catalog" :key="m.name" :value="m.name">
|
||||
{{ m.name }} — {{ m.means }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label v-else class="ls-field ls-grow">
|
||||
<span class="ls-field-label">Pattern</span>
|
||||
<input
|
||||
v-model="pattern" class="ls-input" type="text" maxlength="200"
|
||||
:placeholder="PLACEHOLDER[what]" :disabled="busy"
|
||||
>
|
||||
</label>
|
||||
<button type="submit" class="ls-btn" :disabled="busy || !canAdd">Add</button>
|
||||
</form>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.ls-panel {
|
||||
margin-top: 1.75rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid var(--fs-border-color);
|
||||
}
|
||||
.ls-label {
|
||||
margin: 0 0 0.5rem;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--fs-text-tertiary);
|
||||
}
|
||||
.ls-sub {
|
||||
margin: var(--fs-space-3) 0 var(--fs-space-1);
|
||||
font-size: var(--fs-size-label);
|
||||
font-weight: var(--fs-weight-medium);
|
||||
color: var(--fs-text-tertiary);
|
||||
}
|
||||
.ls-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
|
||||
.ls-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: 0.9rem; }
|
||||
.ls-value { font-size: var(--fs-size-label); color: var(--fs-text-primary); }
|
||||
.ls-note { flex: 1 1 14rem; color: var(--fs-text-secondary); font-size: var(--fs-size-label); }
|
||||
.ls-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
|
||||
.ls-muted { margin: 0; color: var(--fs-text-secondary); font-size: 0.88rem; }
|
||||
.ls-add {
|
||||
display: flex; flex-wrap: wrap; align-items: flex-end; gap: var(--fs-space-2);
|
||||
margin-top: var(--fs-space-3);
|
||||
}
|
||||
.ls-field { display: flex; flex-direction: column; gap: var(--fs-space-1); }
|
||||
.ls-grow { flex: 1 1 14rem; }
|
||||
.ls-field-label { font-size: var(--fs-size-label); color: var(--fs-text-tertiary); }
|
||||
.ls-input {
|
||||
padding: 0.4rem 0.6rem;
|
||||
border: 1px solid var(--fs-border-color);
|
||||
border-radius: var(--fs-radius-sm);
|
||||
background: var(--fs-surface-raised);
|
||||
color: var(--fs-text-primary);
|
||||
font: inherit;
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
.ls-btn {
|
||||
padding: 0.4rem 0.9rem;
|
||||
border: 1px solid var(--fs-border-color);
|
||||
border-radius: var(--fs-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--fs-text-primary);
|
||||
font: inherit;
|
||||
font-size: 0.88rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ls-text-btn {
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--fs-text-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--fs-size-label);
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ls-input:focus-visible,
|
||||
.ls-btn:focus-visible,
|
||||
.ls-text-btn:focus-visible { outline: none; box-shadow: var(--fs-focus-ring); }
|
||||
.ls-btn:disabled,
|
||||
.ls-text-btn:disabled,
|
||||
.ls-input:disabled { opacity: var(--fs-disabled-opacity); cursor: default; }
|
||||
</style>
|
||||
@@ -4,6 +4,7 @@ import { useMomentsStore } from "@/stores/moments";
|
||||
import MomentProposals from "@/components/MomentProposals.vue";
|
||||
import MomentRuleUsage from "@/components/MomentRuleUsage.vue";
|
||||
import WeightProposals from "@/components/WeightProposals.vue";
|
||||
import LessonSituationProposals from "@/components/LessonSituationProposals.vue";
|
||||
import RecordKinds from "@/components/RecordKinds.vue";
|
||||
import RecordReach from "@/components/RecordReach.vue";
|
||||
import RuleAdherence from "@/components/RuleAdherence.vue";
|
||||
@@ -171,6 +172,7 @@ onMounted(async () => {
|
||||
|
||||
<MomentProposals />
|
||||
<WeightProposals />
|
||||
<LessonSituationProposals />
|
||||
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
|
||||
<RecordReach :data="reach" :failed="reachFailed" @retry="loadReach" />
|
||||
<RecordKinds :days="days" />
|
||||
|
||||
@@ -41,6 +41,8 @@ import { useToastStore } from "@/stores/toast";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
import { recordHref } from "@/utils/recordHref";
|
||||
import { canWriteRecord } from "@/utils/permission";
|
||||
import LessonSituationsPanel from "@/components/LessonSituationsPanel.vue";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -60,6 +62,8 @@ const insightHtml = computed(() =>
|
||||
);
|
||||
|
||||
|
||||
const canWrite = computed(() => canWriteRecord(lesson.value?.permission));
|
||||
|
||||
/** The links by state — each state reads differently. Confirmed links are
|
||||
* the answer; rejected ones are kept so the reason stays readable. */
|
||||
const linksIn = (state: LessonRuleLink["state"]) =>
|
||||
@@ -199,6 +203,8 @@ onMounted(load);
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<LessonSituationsPanel :lesson-id="lesson.id" :can-write="canWrite" />
|
||||
|
||||
<section v-if="lesson.tags?.length" class="ld-tags">
|
||||
<TagPill v-for="t in lesson.tags" :key="t" :tag="t" />
|
||||
</section>
|
||||
|
||||
@@ -168,6 +168,7 @@ _READ_ONLY_TOOLS = frozenset({
|
||||
# rules are unjudged and which proposals wait. Reads of the caller's own
|
||||
# rules, as list_rules is.
|
||||
"rules_to_mount", "rule_moment_proposals",
|
||||
"lessons_to_situate", "lesson_situation_proposals",
|
||||
"rules_to_weigh", "rule_weight_proposals",
|
||||
# Adherence: the readout, and the queue a transcript review works from.
|
||||
"rule_adherence", "adherence_to_judge",
|
||||
@@ -183,6 +184,7 @@ _WRITE_TOOLS = frozenset({
|
||||
# notes, tasks, planning
|
||||
"create_note", "update_note", "delete_note",
|
||||
"create_lesson", "update_lesson", "delete_lesson", "judge_lesson_link",
|
||||
"propose_lesson_situations", "judge_lesson_situations",
|
||||
"create_task", "update_task", "delete_task", "add_task_log",
|
||||
"create_records", "start_planning",
|
||||
"create_milestone", "update_milestone", "delete_milestone",
|
||||
|
||||
@@ -14,6 +14,7 @@ from grimoire.services import access as access_svc
|
||||
from grimoire.services import dedup as dedup_svc
|
||||
from grimoire.services import knowledge as knowledge_svc
|
||||
from grimoire.services import lesson_rules as lesson_rules_svc
|
||||
from grimoire.services import lesson_situations as lesson_situations_svc
|
||||
from grimoire.services import lessons as lessons_svc
|
||||
from grimoire.services import systems as systems_svc
|
||||
from grimoire.services import trash as trash_svc
|
||||
@@ -451,7 +452,71 @@ async def delete_lesson(lesson_id: int) -> dict:
|
||||
}
|
||||
|
||||
|
||||
async def lessons_to_situate(limit: int = 25, offset: int = 0) -> dict:
|
||||
"""The lessons with no situation yet — the pass over the corpus, a page at a time.
|
||||
|
||||
A lesson with no situation arrives only when a prompt's words resemble
|
||||
it. Read each one here and decide WHEN it applies: a moment of work it
|
||||
belongs to, a trigger on the act (a `path` glob, a `command` prefix, a
|
||||
`tool`, a `keyword`), or that none fits. Record the answer with
|
||||
`propose_lesson_situations`. A lesson leaves this list once any answer is
|
||||
recorded, so the next call returns the next unread lessons.
|
||||
|
||||
Each lesson carries its title, its stated `when_to_apply`, the `rules` it
|
||||
is a confirmed instance of with their own moments and triggers (the
|
||||
strongest hint at its situation), and values already `rejected` for it.
|
||||
The page carries the moment `catalog` and the `trigger_kinds`.
|
||||
"""
|
||||
return await lesson_situations_svc.to_situate(current_user_id(), limit=limit, offset=offset)
|
||||
|
||||
|
||||
async def propose_lesson_situations(proposals: list[dict]) -> dict:
|
||||
"""Propose when lessons apply — for the operator to confirm; nothing is delivered by this call.
|
||||
|
||||
Each item is `{"lesson_id": N, "moments": ["work.deliver"], "triggers":
|
||||
[{"kind": "path", "pattern": "alembic/versions/*.py"}], "why": "…"}`.
|
||||
Empty `moments` and `triggers` say no situation fits: the lesson stays
|
||||
reachable by meaning, and leaves the pass's list.
|
||||
|
||||
Propose a moment when the lesson is about that point in the work whatever
|
||||
the work is about; a trigger when it is about a kind of file, command or
|
||||
tool. Keep it to the few points where the lesson changes what is done —
|
||||
a lesson that matches every edit is noise there. `why` is shown to the
|
||||
operator beside the proposal; write it so they can say yes or no without
|
||||
opening the lesson.
|
||||
|
||||
Returns `written`, `skipped` (already recorded, in any state) and
|
||||
`refused` (a bad item, refused alone). Then show the operator what waits
|
||||
(`lesson_situation_proposals`); they judge it in Settings › Moments or
|
||||
through `judge_lesson_situations`.
|
||||
"""
|
||||
return await lesson_situations_svc.propose(current_user_id(), proposals)
|
||||
|
||||
|
||||
async def lesson_situation_proposals(lesson_id: int = 0) -> dict:
|
||||
"""The lesson situations waiting on the operator, grouped by lesson.
|
||||
|
||||
Each proposal has its `id` (what `judge_lesson_situations` takes), its
|
||||
`kind` (`moment` or `trigger`), what it `describes`, and the proposer's
|
||||
`note`. `lesson_id` narrows to one lesson.
|
||||
"""
|
||||
return await lesson_situations_svc.pending(current_user_id(), lesson_id=lesson_id or None)
|
||||
|
||||
|
||||
async def judge_lesson_situations(judgments: list[dict]) -> dict:
|
||||
"""Confirm or reject lesson situations — on the operator's word, since a confirm changes what reaches their sessions.
|
||||
|
||||
Each item is `{"id": N, "verdict": "confirm" | "reject", "note": "why"}`,
|
||||
with the id from `lesson_situation_proposals`. A confirmed situation
|
||||
delivers its lesson when the work reaches it, once per session; a
|
||||
rejected one is never proposed again. Put the operator's reason in `note`.
|
||||
"""
|
||||
return await lesson_situations_svc.judge(current_user_id(), judgments)
|
||||
|
||||
|
||||
def register(mcp) -> None:
|
||||
for fn in (list_lessons, create_lesson, get_lesson, update_lesson,
|
||||
delete_lesson, judge_lesson_link):
|
||||
delete_lesson, judge_lesson_link, lessons_to_situate,
|
||||
propose_lesson_situations, lesson_situation_proposals,
|
||||
judge_lesson_situations):
|
||||
mcp.tool(name=fn.__name__)(fn)
|
||||
|
||||
@@ -84,6 +84,7 @@ from grimoire.models.rulebook import ( # noqa: E402, F401
|
||||
)
|
||||
# After notes and rules: it foreign-keys both.
|
||||
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401
|
||||
from grimoire.models.lesson_situation import LessonSituation # noqa: E402, F401
|
||||
# After rules: it foreign-keys them.
|
||||
from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E402, F401
|
||||
from grimoire.models.rule_field_judgment import RuleFieldJudgment # noqa: E402, F401
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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),
|
||||
}
|
||||
@@ -27,6 +27,7 @@ from grimoire.routes.utils import not_found, parse_pagination
|
||||
from grimoire.services import dedup as dedup_svc
|
||||
from grimoire.services import knowledge as knowledge_svc
|
||||
from grimoire.services import lesson_rules as lesson_rules_svc
|
||||
from grimoire.services import lesson_situations as lesson_situations_svc
|
||||
from grimoire.services import lessons as lessons_svc
|
||||
from grimoire.services import systems as systems_svc
|
||||
from grimoire.services import trash as trash_svc
|
||||
@@ -358,6 +359,78 @@ async def judge_lesson_link_route(lesson_id: int, rule_id: int):
|
||||
return jsonify(link)
|
||||
|
||||
|
||||
# ── when a lesson applies (services/lesson_situations.py) ───────────────────
|
||||
|
||||
|
||||
@lessons_bp.route("/situations/proposals", methods=["GET"])
|
||||
@login_required
|
||||
async def lesson_situation_proposals_route():
|
||||
"""The situations a pass proposed and a person has not judged, grouped
|
||||
by lesson, with how many lessons are situated, have none, or are unread
|
||||
— `lesson_situation_proposals` from the browser."""
|
||||
uid = get_current_user_id()
|
||||
out = await lesson_situations_svc.pending(uid)
|
||||
out["counts"] = await lesson_situations_svc.counts(uid)
|
||||
return jsonify(out)
|
||||
|
||||
|
||||
@lessons_bp.route("/situations/judge", methods=["POST"])
|
||||
@login_required
|
||||
async def judge_lesson_situations_route():
|
||||
"""Confirm or reject proposals: `{"judgments": [{id, verdict, note}]}`.
|
||||
A confirm changes what reaches the user's sessions."""
|
||||
data = await request.get_json(silent=True)
|
||||
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
|
||||
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
|
||||
try:
|
||||
return jsonify(await lesson_situations_svc.judge(get_current_user_id(), data["judgments"]))
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
@lessons_bp.route("/<int:lesson_id>/situations", methods=["GET"])
|
||||
@login_required
|
||||
async def lesson_situations_route(lesson_id: int):
|
||||
"""A lesson's live situations and waiting proposals, with the moment
|
||||
catalog and trigger kinds its page offers for adding one."""
|
||||
from grimoire.services import moments as moments_svc
|
||||
from grimoire.services import rule_triggers
|
||||
|
||||
return jsonify({
|
||||
"situations": await lesson_situations_svc.for_lesson(get_current_user_id(), lesson_id),
|
||||
"catalog": [{"name": m["name"], "means": m["means"]}
|
||||
for m in moments_svc.catalog()["moments"]],
|
||||
"trigger_kinds": list(rule_triggers.KINDS),
|
||||
})
|
||||
|
||||
|
||||
@lessons_bp.route("/<int:lesson_id>/situations", methods=["POST"])
|
||||
@login_required
|
||||
async def add_lesson_situation_route(lesson_id: int):
|
||||
"""Make one situation live on a lesson. Body: `{"moment": "work.deliver"}`
|
||||
or `{"trigger": {"kind", "pattern"}}`."""
|
||||
data = await request.get_json(silent=True) or {}
|
||||
trigger = data.get("trigger") if isinstance(data, dict) else None
|
||||
try:
|
||||
return jsonify(await lesson_situations_svc.add(
|
||||
get_current_user_id(), lesson_id,
|
||||
moment=str(data.get("moment") or "") if isinstance(data, dict) else "",
|
||||
trigger=trigger if isinstance(trigger, dict) else None,
|
||||
)), 201
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
@lessons_bp.route("/situations/<int:situation_id>", methods=["DELETE"])
|
||||
@login_required
|
||||
async def remove_lesson_situation_route(situation_id: int):
|
||||
"""Take a situation off its lesson; kept as rejected so it is not proposed again."""
|
||||
try:
|
||||
return jsonify(await lesson_situations_svc.remove(get_current_user_id(), situation_id))
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
@lessons_bp.route("/<int:lesson_id>", methods=["DELETE"])
|
||||
@login_required
|
||||
async def delete_lesson_route(lesson_id: int):
|
||||
|
||||
@@ -399,8 +399,16 @@ async def moment():
|
||||
shapes, forms = moment_delivery_svc.shapes_for_act(
|
||||
reached, reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
|
||||
)
|
||||
# Lessons recorded for this situation, after the rules: each once per
|
||||
# session, and booked in the record ledger only if its line is kept.
|
||||
lesson_lines, lesson_ids = await moment_delivery_svc.lessons_for_act(
|
||||
g.user.id, reached, tool, tool_input if isinstance(tool_input, dict) else {},
|
||||
)
|
||||
record_deliveries_svc.record(g.user.id, lesson_ids, "lesson_situation")
|
||||
fitted = await hook_payload_svc.fit(g.user.id, [
|
||||
*hook_payload_svc.rule_parts(result.lines, result.rule_per_line(), block="rules"),
|
||||
*(hook_payload_svc.Part(text=text, block="lessons", ids={hook_payload_svc.NOTE: (lid,)})
|
||||
for text, lid in zip(lesson_lines, lesson_ids, strict=True)),
|
||||
*(hook_payload_svc.Part(text=block, ids={hook_payload_svc.SHAPE: (key,)})
|
||||
for block, key in zip(shapes, forms, strict=False)),
|
||||
])
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
"""When a lesson applies: moments and triggers, proposed by a pass, judged by
|
||||
a person, delivered when the work reaches them.
|
||||
|
||||
WHY THIS EXISTS
|
||||
|
||||
A lesson records one situation and what was learned in it. Found by meaning,
|
||||
it arrives whenever the words of an edit or a prompt resemble it, which is
|
||||
most of the time and rarely the situation. A lesson that names WHEN it
|
||||
applies — a moment of work (`work.deliver`, `work.finish`, …) or a typed
|
||||
trigger on the act (a path, a command, a tool, a keyword) — can arrive at
|
||||
exactly that point, and at no other.
|
||||
|
||||
THE STATES (models/lesson_situation.py):
|
||||
|
||||
- THE PASS. An agent reads each lesson that has no situation yet
|
||||
(`to_situate`), beside its stated "when to apply" and the moments and
|
||||
triggers of the rules it is a confirmed instance of, and proposes its
|
||||
situation (`propose`): moments, triggers, or that none fits. A proposal
|
||||
delivers nothing.
|
||||
- THE JUDGMENT. A person confirms or rejects each proposal (`judge`), or sets
|
||||
a lesson's situation directly (`add` / `remove`), which is a judgment too.
|
||||
A rejected value is never proposed again.
|
||||
- DELIVERY. `for_act` returns the lessons whose confirmed moment this act
|
||||
reached or whose confirmed trigger it matches. The plugin's door shows each
|
||||
once per session.
|
||||
|
||||
ACL (services/access.py). Proposing, judging and editing change what a
|
||||
lesson says about itself, so they need WRITE on the lesson
|
||||
(`access.can_write_note`). Delivery reads only lessons the reader may read.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import exists, func, or_, select
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.lesson_situation import (
|
||||
CONFIRMED, MOMENT, NONE, REJECTED, SUGGESTED, TRIGGER, LessonSituation,
|
||||
)
|
||||
from grimoire.models.note import Note
|
||||
from grimoire.services import access, moments
|
||||
from grimoire.services import rule_triggers as triggers_svc
|
||||
from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line, lesson_trigger
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VERDICTS = {"confirm": CONFIRMED, "reject": REJECTED}
|
||||
|
||||
# Lessons per pass page: enough to batch the reading, few enough that each
|
||||
# lesson is actually read.
|
||||
PASS_PAGE = 25
|
||||
# A lesson's situation is a handful of points, not a net: past this it is
|
||||
# being reached by everything again.
|
||||
SITUATIONS_MAX = 8
|
||||
_NOTE_CHARS = 600
|
||||
_REMOVED_NOTE = "removed by an edit"
|
||||
|
||||
|
||||
def trigger_value(trigger: triggers_svc.Trigger) -> str:
|
||||
"""A trigger as one stored string, the form rule_field_judgments uses."""
|
||||
from grimoire.services.rule_field_judgments import trigger_value as _value
|
||||
|
||||
return _value(trigger)
|
||||
|
||||
|
||||
def parse_trigger(value: str) -> triggers_svc.Trigger:
|
||||
from grimoire.services.rule_field_judgments import parse_trigger_value
|
||||
|
||||
return parse_trigger_value(value)
|
||||
|
||||
|
||||
def describe(kind: str, value: str) -> str:
|
||||
"""How a situation reads in a line: "moment `work.deliver`"."""
|
||||
if kind == MOMENT:
|
||||
return f"moment `{value}`"
|
||||
if kind == TRIGGER:
|
||||
return parse_trigger(value).describe()
|
||||
return "no situation"
|
||||
|
||||
|
||||
def _item(row: LessonSituation) -> dict:
|
||||
out = row.to_dict()
|
||||
out["describes"] = describe(row.kind, row.value)
|
||||
if row.kind == TRIGGER:
|
||||
out["trigger"] = parse_trigger(row.value).to_dict()
|
||||
return out
|
||||
|
||||
|
||||
def _lesson_clause():
|
||||
return (Note.note_type == LESSON_NOTE_TYPE) & Note.deleted_at.is_(None)
|
||||
|
||||
|
||||
async def _require_writable(user_id: int, lesson_id: int) -> None:
|
||||
if not await access.can_write_note(user_id, int(lesson_id)):
|
||||
raise ValueError(f"lesson {lesson_id} not found or not writable")
|
||||
async with async_session() as session:
|
||||
found = (await session.execute(
|
||||
select(Note.id).where(Note.id == int(lesson_id), _lesson_clause())
|
||||
)).scalar_one_or_none()
|
||||
if found is None:
|
||||
raise ValueError(f"{lesson_id} is not a lesson")
|
||||
|
||||
|
||||
def _values(moment_names, trigger_raw) -> list[tuple[str, str]]:
|
||||
"""(kind, value) pairs, validated and de-duplicated, or the first refusal."""
|
||||
out: list[tuple[str, str]] = []
|
||||
for name in moment_names or []:
|
||||
out.append((MOMENT, moments.require_moment(name)))
|
||||
for raw in trigger_raw or []:
|
||||
out.append((TRIGGER, trigger_value(triggers_svc.require_trigger(raw))))
|
||||
out = list(dict.fromkeys(out))
|
||||
if len(out) > SITUATIONS_MAX:
|
||||
raise ValueError(f"a lesson carries at most {SITUATIONS_MAX} situations")
|
||||
return out
|
||||
|
||||
|
||||
# ── the pass ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _unsituated_clause():
|
||||
"""No proposal waiting and no live answer: every row it has, if any, was
|
||||
rejected — so a lesson whose proposals were all turned down returns to
|
||||
the queue, without them."""
|
||||
return ~exists().where(
|
||||
LessonSituation.lesson_id == Note.id,
|
||||
LessonSituation.state.in_((SUGGESTED, CONFIRMED)),
|
||||
)
|
||||
|
||||
|
||||
async def to_situate(user_id: int, limit: int = PASS_PAGE, offset: int = 0) -> dict:
|
||||
"""One page of lessons with no situation, each with what a proposer reads:
|
||||
its claim, its stated "when to apply", the rules it is a confirmed
|
||||
instance of with their moments and triggers, and the values already
|
||||
rejected for it. With the moment catalog and the trigger kinds, once."""
|
||||
from grimoire.services import lesson_rules
|
||||
|
||||
limit = max(1, min(int(limit or PASS_PAGE), 100))
|
||||
async with async_session() as session:
|
||||
base = select(Note).where(
|
||||
_lesson_clause(), access.readable_notes_clause(user_id), _unsituated_clause(),
|
||||
)
|
||||
total = (await session.execute(
|
||||
select(func.count()).select_from(base.subquery())
|
||||
)).scalar_one()
|
||||
notes = (await session.execute(
|
||||
base.order_by(Note.updated_at.desc(), Note.id.desc()).offset(max(0, int(offset or 0))).limit(limit)
|
||||
)).scalars().all()
|
||||
ids = [int(n.id) for n in notes]
|
||||
rejected: dict[int, list[dict]] = {}
|
||||
if ids:
|
||||
for row in (await session.execute(
|
||||
select(LessonSituation).where(
|
||||
LessonSituation.lesson_id.in_(ids), LessonSituation.state == REJECTED,
|
||||
)
|
||||
)).scalars().all():
|
||||
rejected.setdefault(int(row.lesson_id), []).append(
|
||||
{"describes": describe(row.kind, row.value), "why": row.note or ""}
|
||||
)
|
||||
writable = [n for n in notes if await access.can_write_note(user_id, int(n.id))]
|
||||
rules = await lesson_rules.rules_for_lessons(user_id, [int(n.id) for n in writable])
|
||||
rule_ids = {r["id"] for links in rules.values() for r in links if r["state"] == CONFIRMED}
|
||||
situations = await _rule_situations(rule_ids)
|
||||
lessons = []
|
||||
for n in writable:
|
||||
confirmed = [r for r in rules.get(int(n.id), []) if r["state"] == CONFIRMED]
|
||||
lessons.append({
|
||||
"id": int(n.id),
|
||||
"title": claim_line(n.title),
|
||||
"when_to_apply": lesson_trigger(n),
|
||||
"project_id": n.project_id,
|
||||
"rules": [{"id": r["id"], "title": r["title"], **situations.get(r["id"], {})}
|
||||
for r in confirmed],
|
||||
"rejected": rejected.get(int(n.id), []),
|
||||
})
|
||||
return {
|
||||
"lessons": lessons,
|
||||
"total": int(total),
|
||||
"offset": int(offset or 0),
|
||||
"catalog": [{"name": m["name"], "means": m["means"]} for m in moments.catalog()["moments"]],
|
||||
"trigger_kinds": list(triggers_svc.KINDS),
|
||||
}
|
||||
|
||||
|
||||
async def _rule_situations(rule_ids) -> dict[int, dict]:
|
||||
"""{rule_id: {moments, triggers}} for rules `rules_for_lessons` already
|
||||
scoped to the reader: a lesson's confirmed rule is the strongest hint at
|
||||
when the lesson applies."""
|
||||
from grimoire.services import rulebooks
|
||||
|
||||
ids = sorted(int(i) for i in rule_ids or [])
|
||||
if not ids:
|
||||
return {}
|
||||
try:
|
||||
mounts = await rulebooks.list_rule_moments(ids)
|
||||
trig = await triggers_svc.list_rule_triggers(ids)
|
||||
except Exception: # noqa: BLE001 - a hint, not the proposal
|
||||
logger.debug("rule situations unreadable", exc_info=True)
|
||||
return {}
|
||||
return {i: {"moments": list(mounts.get(i, [])), "triggers": trig.get(i, [])} for i in ids}
|
||||
|
||||
|
||||
async def propose(user_id: int, proposals: list[dict]) -> dict:
|
||||
"""Record a pass's proposals: `[{lesson_id, moments, triggers, why}]`.
|
||||
|
||||
Empty `moments` and `triggers` say no situation fits: that answer needs no
|
||||
judgment, since it delivers nothing, and is recorded confirmed so the
|
||||
lesson leaves the queue. A value already recorded for the lesson, in any
|
||||
state, is skipped: a rejection is never proposed again, and a waiting or
|
||||
live one is already there. A bad item (an unknown moment, a malformed
|
||||
trigger, a lesson the caller cannot write) is refused alone, under
|
||||
`refused`, and the rest are recorded.
|
||||
"""
|
||||
if not isinstance(proposals, list) or not proposals:
|
||||
raise ValueError("proposals is a list of {lesson_id, moments, triggers, why}")
|
||||
planned: list[tuple[int, list[tuple[str, str]], str]] = []
|
||||
refused: list[dict] = []
|
||||
for p in proposals:
|
||||
if not isinstance(p, dict):
|
||||
refused.append({"item": p, "error": "each proposal is {lesson_id, moments, triggers, why}"})
|
||||
continue
|
||||
try:
|
||||
lesson_id = int(p.get("lesson_id") or 0)
|
||||
await _require_writable(user_id, lesson_id)
|
||||
values = _values(p.get("moments"), p.get("triggers"))
|
||||
except (TypeError, ValueError) as e:
|
||||
refused.append({"lesson_id": p.get("lesson_id"), "error": str(e)})
|
||||
continue
|
||||
why = " ".join(str(p.get("why") or "").split())[:_NOTE_CHARS]
|
||||
planned.append((lesson_id, values, why))
|
||||
now = datetime.now(timezone.utc)
|
||||
written = skipped = 0
|
||||
async with async_session() as session:
|
||||
for lesson_id, values, why in planned:
|
||||
have = {(r.kind, r.value) for r in (await session.execute(
|
||||
select(LessonSituation).where(LessonSituation.lesson_id == lesson_id)
|
||||
)).scalars().all()}
|
||||
if not values:
|
||||
if (NONE, "") in have:
|
||||
skipped += 1
|
||||
continue
|
||||
session.add(LessonSituation(
|
||||
lesson_id=lesson_id, kind=NONE, value="", state=CONFIRMED,
|
||||
source="pass", note=why or None, judged_at=now,
|
||||
))
|
||||
written += 1
|
||||
continue
|
||||
for kind, value in values:
|
||||
if (kind, value) in have:
|
||||
skipped += 1
|
||||
continue
|
||||
session.add(LessonSituation(
|
||||
lesson_id=lesson_id, kind=kind, value=value, state=SUGGESTED,
|
||||
source="pass", note=why or None,
|
||||
))
|
||||
written += 1
|
||||
await session.commit()
|
||||
return {"written": written, "skipped": skipped, "refused": refused}
|
||||
|
||||
|
||||
async def pending(user_id: int, lesson_id: int | None = None, limit: int = 200) -> dict:
|
||||
"""The proposals waiting on a person, grouped by lesson, for lessons the
|
||||
caller may write — the only ones they could judge."""
|
||||
async with async_session() as session:
|
||||
q = (
|
||||
select(LessonSituation, Note)
|
||||
.join(Note, Note.id == LessonSituation.lesson_id)
|
||||
.where(LessonSituation.state == SUGGESTED, _lesson_clause(),
|
||||
access.readable_notes_clause(user_id))
|
||||
.order_by(Note.id, LessonSituation.id)
|
||||
.limit(max(1, min(int(limit or 200), 500)))
|
||||
)
|
||||
if lesson_id:
|
||||
q = q.where(LessonSituation.lesson_id == int(lesson_id))
|
||||
rows = (await session.execute(q)).all()
|
||||
grouped: dict[int, dict] = {}
|
||||
for row, note in rows:
|
||||
if int(note.id) not in grouped:
|
||||
if not await access.can_write_note(user_id, int(note.id)):
|
||||
continue
|
||||
grouped[int(note.id)] = {
|
||||
"lesson_id": int(note.id), "title": claim_line(note.title),
|
||||
"when_to_apply": lesson_trigger(note), "proposals": [],
|
||||
}
|
||||
grouped[int(note.id)]["proposals"].append(_item(row))
|
||||
lessons = list(grouped.values())
|
||||
return {"lessons": lessons, "total": sum(len(g["proposals"]) for g in lessons)}
|
||||
|
||||
|
||||
async def judge(user_id: int, judgments: list[dict]) -> dict:
|
||||
"""Confirm or reject proposals: `[{id, verdict, note?}]`, `verdict`
|
||||
"confirm" or "reject". Each must be a waiting proposal on a lesson the
|
||||
caller may write; all are checked before any is applied."""
|
||||
if not isinstance(judgments, list) or not judgments:
|
||||
raise ValueError("judgments is a list of {id, verdict, note?}")
|
||||
planned: list[tuple[int, str, str]] = []
|
||||
for j in judgments:
|
||||
if not isinstance(j, dict):
|
||||
raise ValueError("each judgment is {id, verdict, note?}")
|
||||
verdict = str(j.get("verdict") or "").strip().lower()
|
||||
if verdict not in VERDICTS:
|
||||
raise ValueError('verdict is "confirm" or "reject"')
|
||||
note = " ".join(str(j.get("note") or "").split())[:_NOTE_CHARS]
|
||||
planned.append((int(j.get("id") or 0), VERDICTS[verdict], note))
|
||||
now = datetime.now(timezone.utc)
|
||||
out = []
|
||||
async with async_session() as session:
|
||||
rows = {r.id: r for r in (await session.execute(
|
||||
select(LessonSituation).where(LessonSituation.id.in_([p[0] for p in planned]))
|
||||
)).scalars().all()}
|
||||
for sid, _state, _note in planned:
|
||||
row = rows.get(sid)
|
||||
if row is None or row.state != SUGGESTED:
|
||||
raise ValueError(f"situation {sid} is not a waiting proposal")
|
||||
await _require_writable(user_id, row.lesson_id)
|
||||
for sid, state, note in planned:
|
||||
row = rows[sid]
|
||||
row.state = state
|
||||
row.judged_at = now
|
||||
if note:
|
||||
row.note = note
|
||||
out.append(_item(row))
|
||||
await session.commit()
|
||||
return {"judged": out}
|
||||
|
||||
|
||||
# ── a person setting a lesson's situation ────────────────────────────────
|
||||
|
||||
|
||||
async def for_lesson(user_id: int, lesson_id: int) -> list[dict]:
|
||||
"""A lesson's live situations and waiting proposals, for its page."""
|
||||
if not await access.can_read_note(user_id, int(lesson_id)):
|
||||
return []
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(LessonSituation)
|
||||
.where(LessonSituation.lesson_id == int(lesson_id),
|
||||
LessonSituation.state.in_((CONFIRMED, SUGGESTED)),
|
||||
LessonSituation.kind != NONE)
|
||||
.order_by(LessonSituation.id)
|
||||
)).scalars().all()
|
||||
return [_item(r) for r in rows]
|
||||
|
||||
|
||||
async def add(user_id: int, lesson_id: int, *, moment: str = "", trigger: dict | None = None) -> dict:
|
||||
"""Make one moment or trigger live on a lesson — a person's judgment, so
|
||||
it is confirmed at once. A row already there for the value (a rejection,
|
||||
or a waiting proposal) is overturned to confirmed. A `none` answer is
|
||||
cleared: the lesson now has a situation."""
|
||||
await _require_writable(user_id, lesson_id)
|
||||
values = _values([moment] if moment else [], [trigger] if trigger else [])
|
||||
if len(values) != 1:
|
||||
raise ValueError("add one moment or one trigger")
|
||||
kind, value = values[0]
|
||||
now = datetime.now(timezone.utc)
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(LessonSituation).where(LessonSituation.lesson_id == int(lesson_id))
|
||||
)).scalars().all()
|
||||
if sum(1 for r in rows if r.state == CONFIRMED and r.kind != NONE) >= SITUATIONS_MAX:
|
||||
raise ValueError(f"a lesson carries at most {SITUATIONS_MAX} situations")
|
||||
row = next((r for r in rows if (r.kind, r.value) == (kind, value)), None)
|
||||
for r in rows:
|
||||
if r.kind == NONE:
|
||||
await session.delete(r)
|
||||
if row is None:
|
||||
row = LessonSituation(lesson_id=int(lesson_id), kind=kind, value=value)
|
||||
session.add(row)
|
||||
row.state, row.source, row.judged_at = CONFIRMED, "edit", now
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return _item(row)
|
||||
|
||||
|
||||
async def remove(user_id: int, situation_id: int) -> dict:
|
||||
"""Take a live situation off its lesson. Kept as rejected, with the
|
||||
reason, so a later pass does not propose it again."""
|
||||
async with async_session() as session:
|
||||
row = await session.get(LessonSituation, int(situation_id))
|
||||
if row is None:
|
||||
raise ValueError(f"situation {situation_id} not found")
|
||||
await _require_writable(user_id, row.lesson_id)
|
||||
row.state, row.source, row.note = REJECTED, "edit", _REMOVED_NOTE
|
||||
row.judged_at = datetime.now(timezone.utc)
|
||||
await session.commit()
|
||||
return _item(row)
|
||||
|
||||
|
||||
async def counts(user_id: int) -> dict:
|
||||
"""How many readable lessons are situated, have no situation, wait on a
|
||||
judgment, or were read and found to have none — the panel's header."""
|
||||
async with async_session() as session:
|
||||
def has(state, kind=None):
|
||||
cond = [LessonSituation.lesson_id == Note.id, LessonSituation.state == state]
|
||||
if kind == NONE:
|
||||
cond.append(LessonSituation.kind == NONE)
|
||||
elif kind:
|
||||
cond.append(LessonSituation.kind != NONE)
|
||||
return exists().where(*cond)
|
||||
|
||||
base = [_lesson_clause(), access.readable_notes_clause(user_id)]
|
||||
|
||||
async def n(*cond):
|
||||
return int((await session.execute(
|
||||
select(func.count(Note.id)).where(*base, *cond)
|
||||
)).scalar_one())
|
||||
|
||||
return {
|
||||
"situated": await n(has(CONFIRMED, "live")),
|
||||
"none_fits": await n(has(CONFIRMED, NONE)),
|
||||
"waiting": await n(has(SUGGESTED)),
|
||||
"unsituated": await n(_unsituated_clause()),
|
||||
}
|
||||
|
||||
|
||||
# ── delivery ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Arrival:
|
||||
lesson_id: int
|
||||
title: str
|
||||
because: str
|
||||
|
||||
|
||||
async def for_act(
|
||||
user_id: int, reached: list[str], *, tool: str | None = None,
|
||||
tool_input: dict | None = None, text: str = "",
|
||||
exclude: frozenset[int] = frozenset(),
|
||||
) -> list[Arrival]:
|
||||
"""The lessons whose confirmed moment is among `reached` or whose
|
||||
confirmed trigger this act (or, with no tool, this text) matches, most
|
||||
recently updated first. Readable lessons only, from any project: a lesson
|
||||
is offered wherever its situation comes up, not only where it was
|
||||
written. `exclude` are lessons this session already has. Fails open."""
|
||||
reached = [m for m in reached or [] if m]
|
||||
try:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(LessonSituation.kind, LessonSituation.value, Note.id, Note.title)
|
||||
.join(Note, Note.id == LessonSituation.lesson_id)
|
||||
.where(
|
||||
LessonSituation.state == CONFIRMED,
|
||||
or_(
|
||||
(LessonSituation.kind == MOMENT) & LessonSituation.value.in_(reached),
|
||||
LessonSituation.kind == TRIGGER,
|
||||
),
|
||||
_lesson_clause(),
|
||||
access.readable_notes_clause(user_id),
|
||||
)
|
||||
.order_by(Note.updated_at.desc(), Note.id.desc(), LessonSituation.id)
|
||||
)).all()
|
||||
except Exception: # noqa: BLE001 - a recall aid never breaks its act
|
||||
logger.warning("lesson situations unreadable", exc_info=True)
|
||||
return []
|
||||
out: dict[int, Arrival] = {}
|
||||
for kind, value, nid, title in rows:
|
||||
nid = int(nid)
|
||||
if nid in out or nid in exclude:
|
||||
continue
|
||||
if kind == TRIGGER:
|
||||
try:
|
||||
if not triggers_svc.matches(parse_trigger(value), tool, tool_input, text):
|
||||
continue
|
||||
except Exception: # noqa: BLE001 - one bad row never blocks the rest
|
||||
continue
|
||||
out[nid] = Arrival(nid, claim_line(title), describe(kind, value))
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def line(arrival: Arrival) -> str:
|
||||
"""One lesson, as the line the work sees."""
|
||||
return (
|
||||
f"> Lesson #{arrival.lesson_id} \"{arrival.title}\" — recorded for this "
|
||||
f"situation ({arrival.because}); `get_lesson({arrival.lesson_id})` has what was learned."
|
||||
)
|
||||
|
||||
|
||||
async def reachable(user_id: int) -> tuple[set[str], set[str]]:
|
||||
"""(moments, tool keys) that a confirmed lesson situation listens on, for
|
||||
the plugin's catch-all filter: a call that reaches neither never leaves
|
||||
the machine, so a lesson's trigger must name its tools here."""
|
||||
try:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(LessonSituation.kind, LessonSituation.value)
|
||||
.join(Note, Note.id == LessonSituation.lesson_id)
|
||||
.where(LessonSituation.state == CONFIRMED,
|
||||
LessonSituation.kind.in_((MOMENT, TRIGGER)),
|
||||
_lesson_clause(), access.readable_notes_clause(user_id))
|
||||
.distinct()
|
||||
)).all()
|
||||
except Exception: # noqa: BLE001 - the rules' tools are still worth listing
|
||||
logger.debug("lesson situations unreadable", exc_info=True)
|
||||
return set(), set()
|
||||
found_moments: set[str] = set()
|
||||
tools: set[str] = set()
|
||||
for kind, value in rows:
|
||||
if kind == MOMENT:
|
||||
found_moments.add(value)
|
||||
else:
|
||||
tools |= triggers_svc.tools_for(parse_trigger(value))
|
||||
return found_moments, tools
|
||||
@@ -56,8 +56,11 @@ async def reachable_tools(user_id: int) -> list[str]:
|
||||
shaped = {s.moment for s in reply_shapes.SHAPES.values() if s.key != reply_shapes.CORE_KEY}
|
||||
from grimoire.services import rule_triggers
|
||||
|
||||
from grimoire.services import lesson_situations
|
||||
|
||||
mounted = set(await rulebooks.mounted_moments(user_id))
|
||||
wanted = mounted | shaped
|
||||
lesson_moments, lesson_tools = await lesson_situations.reachable(user_id)
|
||||
wanted = mounted | shaped | lesson_moments
|
||||
mappings = await moment_actions.list_mappings(user_id)
|
||||
keys = {
|
||||
moment_actions.tool_key(action.tool)
|
||||
@@ -72,7 +75,8 @@ async def reachable_tools(user_id: int) -> list[str]:
|
||||
keys |= await rule_triggers.reachable_tools(user_id)
|
||||
except Exception: # noqa: BLE001 - the mounts' tools are still worth listing
|
||||
logger.debug("rule trigger tools unreadable", exc_info=True)
|
||||
return sorted(keys)
|
||||
# A lesson triggered by an act is reached the same way.
|
||||
return sorted(keys | lesson_tools)
|
||||
|
||||
|
||||
async def _board(user_id: int, project_id: int | None, **act):
|
||||
@@ -130,6 +134,31 @@ async def deliver_for_act(
|
||||
return reached, result
|
||||
|
||||
|
||||
async def lessons_for_act(
|
||||
user_id: int, reached: list[dict], tool: str | None, tool_input: dict | None, *,
|
||||
once_per_session: bool = True,
|
||||
) -> tuple[list[str], list[int]]:
|
||||
"""The lines and ids of the lessons recorded for this act's situation: a
|
||||
confirmed moment it reached, or a confirmed trigger it matches.
|
||||
|
||||
`once_per_session` leaves out a lesson the session's record ledger
|
||||
already holds, and is what the plugin's door asks for; a door with no
|
||||
session (an MCP reply) shows them every time its act happens, as it does
|
||||
the rules mounted there."""
|
||||
from grimoire.services import lesson_situations, record_deliveries
|
||||
|
||||
arrivals = await lesson_situations.for_act(
|
||||
user_id, [hit["moment"] for hit in reached or []],
|
||||
tool=tool, tool_input=tool_input or {},
|
||||
)
|
||||
if once_per_session and arrivals:
|
||||
had = await record_deliveries.delivered_this_session(
|
||||
user_id, [a.lesson_id for a in arrivals],
|
||||
)
|
||||
arrivals = [a for a in arrivals if a.lesson_id not in had]
|
||||
return [lesson_situations.line(a) for a in arrivals], [a.lesson_id for a in arrivals]
|
||||
|
||||
|
||||
# The file-writing tools, as tool keys: a `hold` rule never holds these.
|
||||
WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"})
|
||||
|
||||
@@ -254,6 +283,13 @@ async def attach_moment_rules(
|
||||
"rule_ids": result.shown_rule_ids,
|
||||
"open_with": "get_rule(id)",
|
||||
}
|
||||
lesson_lines, lesson_ids = await lessons_for_act(
|
||||
user_id, _reached, tool, arguments or {}, once_per_session=False,
|
||||
)
|
||||
if lesson_lines:
|
||||
data["moment_lessons"] = {
|
||||
"lines": lesson_lines, "lesson_ids": lesson_ids, "open_with": "get_lesson(id)",
|
||||
}
|
||||
# The reply shape for this moment, in full: no ledger reaches this
|
||||
# door, and an act like closing a task is rare enough that the shape
|
||||
# arriving each time costs less than one report written without it.
|
||||
|
||||
@@ -91,6 +91,30 @@ def flush(kept: set[int] | None = None) -> None:
|
||||
spawn(_insert(rows), site="record_delivery_write")
|
||||
|
||||
|
||||
async def delivered_this_session(user_id: int, note_ids) -> set[int]:
|
||||
"""Which of these records the bound session was already shown or pointed
|
||||
at, so a door that shows a record once per session can leave them out.
|
||||
Empty outside a plugin request, where there is no session to ask about."""
|
||||
sid = rule_deliveries.current_session()
|
||||
ids = {int(n) for n in note_ids or []}
|
||||
if not sid or not user_id or not ids:
|
||||
return set()
|
||||
try:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(RecordDelivery.note_id).where(
|
||||
RecordDelivery.user_id == int(user_id),
|
||||
RecordDelivery.session_id == sid,
|
||||
RecordDelivery.note_id.in_(ids),
|
||||
RecordDelivery.way.in_((PUSHED, POINTED)),
|
||||
).distinct()
|
||||
)).scalars().all()
|
||||
except Exception: # noqa: BLE001 - a repeat is better than a lost line
|
||||
logger.debug("session record ledger unreadable", exc_info=True)
|
||||
return set()
|
||||
return {int(r) for r in rows}
|
||||
|
||||
|
||||
async def _kinds(session, user_id: int, ids) -> dict[int, str]:
|
||||
"""`{note_id: kind}` for the ids this user may read; any other id is left
|
||||
out, so the ledger never records a record its reader could not open."""
|
||||
|
||||
@@ -92,9 +92,12 @@ DOORS: dict[str, Door] = {
|
||||
# What is about to be written: code to reuse, and what was already tried
|
||||
# (an issue, a dev-log, a lesson). The open to-do list resembles the code
|
||||
# and answers nothing, so work tasks are left out.
|
||||
# Not lessons: an edit's words resemble a lesson far more often than the
|
||||
# edit is its situation. A lesson reaches an edit through a situation
|
||||
# confirmed for it (`lesson_situations`), once per session.
|
||||
"work.change": Door(
|
||||
"work.change", "Altering the thing being worked on", "before every write or edit",
|
||||
frozenset({"snippet", "note", "lesson", "task:issue"}),
|
||||
frozenset({"snippet", "note", "task:issue"}),
|
||||
sources=("write_path_semantic", "write_path_place", "write_path_sync",
|
||||
"write_path_linked"),
|
||||
),
|
||||
|
||||
@@ -51,6 +51,9 @@ WRITE_TARGETS: dict[str, dict[str, str]] = {
|
||||
"update_lesson": {"lesson_id": NOTE},
|
||||
"delete_lesson": {"lesson_id": NOTE},
|
||||
"judge_lesson_link": {},
|
||||
# When a lesson applies: judgments on how the corpus is retrieved.
|
||||
"propose_lesson_situations": {},
|
||||
"judge_lesson_situations": {},
|
||||
"create_task": {"project_id": PROJECT, "milestone_id": MILESTONE, "parent_id": NOTE},
|
||||
"update_task": {"task_id": NOTE, "project_id": PROJECT, "milestone_id": MILESTONE},
|
||||
"delete_task": {"task_id": NOTE},
|
||||
|
||||
@@ -425,3 +425,22 @@ def _ungated_doors(request):
|
||||
with patch.object(plugin_context, "_gate_for", AsyncMock(return_value=None)), \
|
||||
patch.object(plugin_context, "_routed_for", AsyncMock(return_value=frozenset())):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_lesson_situations(request):
|
||||
"""Stub the lesson-situation lookups (`lesson_situations`) to find none.
|
||||
|
||||
Every moment door asks which lessons are recorded for the act, and the
|
||||
plugin's tool filter asks which tools a lesson listens on; a unit test of
|
||||
those doors has written no lessons. A test about situated lessons patches
|
||||
its own answer. The integration lane runs the real queries.
|
||||
"""
|
||||
if request.node.get_closest_marker("integration"):
|
||||
yield
|
||||
return
|
||||
from grimoire.services import lesson_situations
|
||||
|
||||
with patch.object(lesson_situations, "for_act", AsyncMock(return_value=[])), \
|
||||
patch.object(lesson_situations, "reachable", AsyncMock(return_value=(set(), set()))):
|
||||
yield
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Real-Postgres tests for `lesson_situations`: a pass proposes when a lesson
|
||||
applies, a person confirms or rejects it, and only a confirmed situation
|
||||
delivers its lesson — at the moment it names, or on an act its trigger
|
||||
matches, to a reader who may read the lesson."""
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.note import Note
|
||||
from grimoire.services import lesson_situations as svc
|
||||
from tests.helpers import ensure_user
|
||||
|
||||
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
|
||||
|
||||
|
||||
async def _world() -> dict:
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
async with async_session() as s:
|
||||
owner = await ensure_user(s, f"situations_owner_{tag}")
|
||||
stranger = await ensure_user(s, f"situations_stranger_{tag}")
|
||||
made = {
|
||||
key: Note(user_id=owner.id, note_type="lesson", title=title, body="")
|
||||
for key, title in (
|
||||
("deploy", "A green build is not a running deploy"),
|
||||
("migrate", "Migrations need their constraint in the same change"),
|
||||
("plain", "Name things for a stranger"),
|
||||
)
|
||||
}
|
||||
s.add_all(made.values())
|
||||
await s.commit()
|
||||
return {"owner": owner.id, "stranger": stranger.id,
|
||||
**{k: int(n.id) for k, n in made.items()}}
|
||||
|
||||
|
||||
async def test_a_proposal_waits_and_delivers_only_once_confirmed():
|
||||
w = await _world()
|
||||
out = await svc.propose(w["owner"], [
|
||||
{"lesson_id": w["deploy"], "moments": ["work.deliver"], "why": "about shipping"},
|
||||
{"lesson_id": w["migrate"], "triggers": [{"kind": "path", "pattern": "alembic/versions/*.py"}],
|
||||
"why": "about writing migrations"},
|
||||
{"lesson_id": w["plain"], "why": "about naming, whatever the act"},
|
||||
{"lesson_id": w["plain"], "moments": ["not.a.moment"]},
|
||||
])
|
||||
assert out["written"] == 3 and len(out["refused"]) == 1
|
||||
# Suggested rows deliver nothing.
|
||||
assert await svc.for_act(w["owner"], ["work.deliver"]) == []
|
||||
|
||||
waiting = await svc.pending(w["owner"])
|
||||
ids = {p["lesson_id"]: p["proposals"][0]["id"] for p in waiting["lessons"]}
|
||||
assert set(ids) == {w["deploy"], w["migrate"]}, "a `none` answer waits on nobody"
|
||||
await svc.judge(w["owner"], [{"id": ids[w["deploy"]], "verdict": "confirm"},
|
||||
{"id": ids[w["migrate"]], "verdict": "confirm"}])
|
||||
|
||||
at_deliver = await svc.for_act(w["owner"], ["work.deliver"])
|
||||
assert [a.lesson_id for a in at_deliver] == [w["deploy"]]
|
||||
assert "moment `work.deliver`" in svc.line(at_deliver[0])
|
||||
on_migration = await svc.for_act(
|
||||
w["owner"], ["work.change"], tool="Edit",
|
||||
tool_input={"file_path": "/repo/alembic/versions/0001_init.py"},
|
||||
)
|
||||
assert [a.lesson_id for a in on_migration] == [w["migrate"]]
|
||||
assert await svc.for_act(w["owner"], ["work.change"], tool="Edit",
|
||||
tool_input={"file_path": "/repo/src/app.py"}) == []
|
||||
# Another user's lesson never reaches them.
|
||||
assert await svc.for_act(w["stranger"], ["work.deliver"]) == []
|
||||
# The session already has it: left out.
|
||||
assert await svc.for_act(w["owner"], ["work.deliver"], exclude=frozenset({w["deploy"]})) == []
|
||||
|
||||
|
||||
async def test_a_rejected_value_is_never_proposed_again_and_the_lesson_returns_to_the_queue():
|
||||
w = await _world()
|
||||
await svc.propose(w["owner"], [{"lesson_id": w["deploy"], "moments": ["work.finish"]}])
|
||||
pid = (await svc.pending(w["owner"]))["lessons"][0]["proposals"][0]["id"]
|
||||
await svc.judge(w["owner"], [{"id": pid, "verdict": "reject", "note": "too broad"}])
|
||||
|
||||
queue = await svc.to_situate(w["owner"], limit=100)
|
||||
entry = next(item for item in queue["lessons"] if item["id"] == w["deploy"])
|
||||
assert entry["rejected"] == [{"describes": "moment `work.finish`", "why": "too broad"}]
|
||||
again = await svc.propose(w["owner"], [{"lesson_id": w["deploy"], "moments": ["work.finish"]}])
|
||||
assert again == {"written": 0, "skipped": 1, "refused": []}
|
||||
|
||||
|
||||
async def test_a_person_adds_and_takes_off_a_situation_and_the_counts_follow():
|
||||
w = await _world()
|
||||
await svc.propose(w["owner"], [{"lesson_id": w["plain"], "why": "none fits"}])
|
||||
added = await svc.add(w["owner"], w["plain"], trigger={"kind": "command", "pattern": "git push"})
|
||||
assert added["state"] == "confirmed" and added["source"] == "edit"
|
||||
live = await svc.for_lesson(w["owner"], w["plain"])
|
||||
assert [s["describes"] for s in live] == ["command `git push`"]
|
||||
|
||||
moments, tools = await svc.reachable(w["owner"])
|
||||
assert "bash" in tools
|
||||
|
||||
counts = await svc.counts(w["owner"])
|
||||
assert counts["situated"] == 1 and counts["none_fits"] == 0, "adding one clears `none`"
|
||||
assert counts["unsituated"] == 2
|
||||
|
||||
await svc.remove(w["owner"], added["id"])
|
||||
assert await svc.for_lesson(w["owner"], w["plain"]) == []
|
||||
with pytest.raises(ValueError):
|
||||
await svc.add(w["stranger"], w["plain"], moment="work.deliver")
|
||||
@@ -0,0 +1,46 @@
|
||||
"""A situated lesson reaches the work through the moment doors: the plugin's
|
||||
door shows it once per session, and an MCP reply, which has no session,
|
||||
carries it every time its act happens."""
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from grimoire.services import lesson_situations, moment_delivery
|
||||
from grimoire.services import retrieval_pipeline as rp
|
||||
|
||||
ARRIVALS = [
|
||||
lesson_situations.Arrival(41, "A green build is not a running deploy", "moment `work.deliver`"),
|
||||
lesson_situations.Arrival(42, "Read the job log first", "command `git push`"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_plugin_door_leaves_out_what_the_session_already_has():
|
||||
with patch.object(lesson_situations, "for_act", AsyncMock(return_value=ARRIVALS)), \
|
||||
patch("grimoire.services.record_deliveries.delivered_this_session",
|
||||
AsyncMock(return_value={41})):
|
||||
lines, ids = await moment_delivery.lessons_for_act(
|
||||
1, [{"moment": "work.deliver"}], "Bash", {"command": "git push"},
|
||||
)
|
||||
assert ids == [42]
|
||||
assert lines == [lesson_situations.line(ARRIVALS[1])]
|
||||
assert "`get_lesson(42)`" in lines[0] and "command `git push`" in lines[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_an_mcp_reply_carries_the_lessons_for_its_act_every_time():
|
||||
ledger = AsyncMock(return_value={41, 42})
|
||||
with patch.object(moment_delivery, "deliver_for_act",
|
||||
AsyncMock(return_value=([{"moment": "work.finish"}], rp.RuleResult()))), \
|
||||
patch.object(moment_delivery, "shapes_for_act", lambda reached: ([], {})), \
|
||||
patch.object(lesson_situations, "for_act", AsyncMock(return_value=ARRIVALS[:1])), \
|
||||
patch("grimoire.services.record_deliveries.delivered_this_session", ledger):
|
||||
data = await moment_delivery.attach_moment_rules(1, "update_task", {"status": "done"}, {})
|
||||
assert data["moment_lessons"]["lesson_ids"] == [41]
|
||||
assert data["moment_lessons"]["open_with"] == "get_lesson(id)"
|
||||
ledger.assert_not_awaited()
|
||||
|
||||
|
||||
def test_a_situation_reads_as_what_the_act_carries():
|
||||
assert lesson_situations.describe("moment", "work.finish") == "moment `work.finish`"
|
||||
assert lesson_situations.describe("trigger", "path\tmigrations/**\t") == "path `migrations/**`"
|
||||
@@ -281,7 +281,7 @@ async def test_an_arm_searches_only_the_kinds_its_door_allows():
|
||||
_r, _io_, calls = await _run(rp.AUTO_INJECT, lambda kw: [])
|
||||
assert calls[0]["record_kinds"] is None
|
||||
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [])
|
||||
assert calls[0]["record_kinds"] == ["lesson", "note", "snippet", "task:issue"]
|
||||
assert calls[0]["record_kinds"] == ["note", "snippet", "task:issue"]
|
||||
# A user's own row replaces the default.
|
||||
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [], kinds=frozenset({"snippet"}))
|
||||
assert calls[0]["record_kinds"] == ["snippet"]
|
||||
|
||||
@@ -487,7 +487,7 @@ async def test_write_path_semantic_arm_asks_for_experience_not_just_snippets():
|
||||
kw = search.await_args.kwargs
|
||||
# An open to-do resembling the code answers nothing; an ISSUE carries a root
|
||||
# cause and a NOTE carries durable knowledge. Only the todo is excluded.
|
||||
assert kw["record_kinds"] == ["lesson", "note", "snippet", "task:issue"]
|
||||
assert kw["record_kinds"] == ["note", "snippet", "task:issue"]
|
||||
# Telemetry must not claim this was a notes-only retrieval any more.
|
||||
assert rec.call_args.kwargs["is_task"] is None
|
||||
|
||||
|
||||
@@ -255,7 +255,7 @@ async def test_semantic_arm_is_snippet_only_and_browse_scoped():
|
||||
# code shape. What
|
||||
# stays out is the open to-do list, which resembles the code and answers
|
||||
# nothing.
|
||||
assert kwargs["record_kinds"] == ["lesson", "note", "snippet", "task:issue"]
|
||||
assert kwargs["record_kinds"] == ["note", "snippet", "task:issue"]
|
||||
# Nobody asked for this, so it must not reach a one-to-one direct share.
|
||||
assert kwargs["scope"] == "browse"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user