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,
|
||||
@@ -11,8 +11,8 @@ import type { RuleKind } from "@/api/rulebooks";
|
||||
* another one fits. */
|
||||
export type RuleJudgment = "linked" | "no_rule" | "unjudged";
|
||||
|
||||
/** A link's state (`models/lesson_rule_link.py` LINK_STATES). */
|
||||
export type LinkState = "suggested" | "confirmed" | "rejected";
|
||||
/** A judged link's state; the reads list only these two. */
|
||||
export type LinkState = "confirmed" | "rejected";
|
||||
|
||||
/** One link from a lesson to a rule, in the reader's view: only rules the
|
||||
* reader owns are listed (`rules_for_lessons`). */
|
||||
@@ -20,14 +20,11 @@ export interface LessonRuleLink {
|
||||
id: number;
|
||||
title: string;
|
||||
kind: RuleKind;
|
||||
/** `suggested` carries nothing in retrieval until it is judged; only
|
||||
* `confirmed` changes what surfaces; `rejected` is kept so the pair is
|
||||
* never proposed again. */
|
||||
/** `confirmed` changes what surfaces; `rejected` is kept so the reason
|
||||
* stays readable. */
|
||||
state: LinkState;
|
||||
/** Why it was confirmed or rejected. */
|
||||
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
|
||||
@@ -79,7 +76,7 @@ export interface Lesson {
|
||||
updated_at: string | null;
|
||||
systems?: { id: number; name: string }[];
|
||||
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
|
||||
* — which is "not attached", never "no rule". */
|
||||
rules?: LessonRuleLink[];
|
||||
@@ -232,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}`);
|
||||
}
|
||||
|
||||
@@ -290,6 +290,9 @@ export interface RecordKindsDoor {
|
||||
default: string[];
|
||||
/** The user changed this door; otherwise it follows the shipped default. */
|
||||
changed: boolean;
|
||||
/** Its lines are recorded per session; a door that answers in a tool
|
||||
* reply is not, so it has no counts. */
|
||||
measured: boolean;
|
||||
/** Lines this door pushed of each kind, and how many were opened. */
|
||||
evidence: Record<string, WayCounts>;
|
||||
}
|
||||
@@ -311,7 +314,7 @@ export function setRecordKinds(door: string, kinds: string[] | null): Promise<Re
|
||||
}
|
||||
|
||||
/** How a record arrived in front of a session. */
|
||||
export type RecordWay = "pushed" | "asked" | "direct";
|
||||
export type RecordWay = "pushed" | "pointed" | "asked" | "direct";
|
||||
|
||||
export interface WayCounts {
|
||||
delivered: number;
|
||||
|
||||
@@ -120,9 +120,9 @@ export interface Rule {
|
||||
/** Present only when the rule has triggers. */
|
||||
triggers?: RuleTrigger[];
|
||||
relations?: RuleRelation[];
|
||||
/** The lessons that point at this rule — the concrete
|
||||
* situations judged instances of it, plus any suggested and awaiting a
|
||||
* judgment. Readable lessons only; omitted when there are none. */
|
||||
/** The lessons judged against this rule — confirmed instances of it
|
||||
* first, then those judged not to be. Readable lessons only; omitted when
|
||||
* there are none. */
|
||||
lessons?: { id: number; title: string; state: LinkState; note: string }[];
|
||||
}
|
||||
|
||||
|
||||
@@ -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" />
|
||||
|
||||
@@ -80,6 +80,9 @@ onMounted(load);
|
||||
<span class="door-fires">{{ row.fires }}</span>
|
||||
<span v-if="!row.changed" class="door-default">shipped default</span>
|
||||
</legend>
|
||||
<p v-if="!row.measured" class="door-default">
|
||||
Named by id in the reply that sets a task in progress, so there are no counts for it.
|
||||
</p>
|
||||
<ul class="kind-list">
|
||||
<li v-for="k in table.kinds" :key="k.kind" class="kind-cell">
|
||||
<label class="kind-label">
|
||||
@@ -89,7 +92,7 @@ onMounted(load);
|
||||
/>
|
||||
{{ k.label }}
|
||||
</label>
|
||||
<span v-if="!table.evidence_failed" class="kind-evidence">{{ evidenceText(row, k.kind) }}</span>
|
||||
<span v-if="!table.evidence_failed && row.measured" class="kind-evidence">{{ evidenceText(row, k.kind) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<button v-if="row.changed" type="button" class="btn-text door-reset" @click="save(row.door, null)">
|
||||
|
||||
@@ -35,6 +35,7 @@ function kindLabel(kind: string): string {
|
||||
// shows one number; the others show how many of those delivered were opened.
|
||||
const WAYS: [RecordWay, string][] = [
|
||||
["pushed", "shown by a hook"],
|
||||
["pointed", "named in a pointer"],
|
||||
["asked", "from its own search"],
|
||||
["direct", "opened unshown"],
|
||||
];
|
||||
@@ -58,8 +59,8 @@ function wayText(way: RecordWay, c: WayCounts): string {
|
||||
<template v-else>
|
||||
<p class="field-hint">
|
||||
Records opened, out of those delivered, over the last {{ data.days }} days across
|
||||
{{ data.sessions }} sessions: shown by a hook, returned by a search the session ran,
|
||||
or opened with nothing showing them first.
|
||||
{{ data.sessions }} sessions: shown by a hook, named by id in a pointer line,
|
||||
returned by a search the session ran, or opened with nothing showing them first.
|
||||
</p>
|
||||
<div class="reach-totals">
|
||||
<span v-for="[way, label] in WAYS" :key="way">
|
||||
|
||||
@@ -570,13 +570,13 @@ watch(() => props.ruleId, load);
|
||||
<ul>
|
||||
<li v-for="l in lessons" :key="l.id" class="relation">
|
||||
<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>
|
||||
</li>
|
||||
</ul>
|
||||
<p class="field-note">
|
||||
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>
|
||||
</section>
|
||||
|
||||
@@ -603,7 +603,7 @@ watch(() => props.ruleId, load);
|
||||
</div>
|
||||
</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
|
||||
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
|
||||
|
||||
@@ -30,7 +30,6 @@ import { apiErrorMessage } from "@/api/client";
|
||||
import {
|
||||
deleteLesson,
|
||||
getLesson,
|
||||
judgeLessonLink,
|
||||
type Lesson,
|
||||
type LessonRuleLink,
|
||||
} from "@/api/lessons";
|
||||
@@ -41,8 +40,9 @@ import { DEAD_WEIGHT_ADVICE } from "@/utils/deadWeight";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
import { canWriteRecord } from "@/utils/permission";
|
||||
import { recordHref } from "@/utils/recordHref";
|
||||
import { canWriteRecord } from "@/utils/permission";
|
||||
import LessonSituationsPanel from "@/components/LessonSituationsPanel.vue";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -65,13 +65,10 @@ const insightHtml = computed(() =>
|
||||
const canWrite = computed(() => canWriteRecord(lesson.value?.permission));
|
||||
|
||||
/** The links by state — each state reads differently. Confirmed links are
|
||||
* the answer; suggested ones are evidence waiting on a judgment; rejected
|
||||
* ones are kept so the pair is never proposed again, and shown so the reason
|
||||
* stays readable. */
|
||||
* the answer; rejected ones are kept so the reason stays readable. */
|
||||
const linksIn = (state: LessonRuleLink["state"]) =>
|
||||
computed(() => (lesson.value?.rules ?? []).filter((r) => r.state === state));
|
||||
const confirmedRules = linksIn("confirmed");
|
||||
const suggestedRules = linksIn("suggested");
|
||||
const rejectedRules = linksIn("rejected");
|
||||
|
||||
/** A rule opens in the rules view's editor, which takes the rule alone. */
|
||||
@@ -79,36 +76,6 @@ function ruleHref(ruleId: number) {
|
||||
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() {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
@@ -223,39 +190,6 @@ onMounted(load);
|
||||
nobody has said none fits.
|
||||
</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">
|
||||
<h3 class="ld-sub-label">Judged not an instance</h3>
|
||||
<ul class="ld-sources ld-rejected">
|
||||
@@ -269,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>
|
||||
@@ -410,8 +346,6 @@ onMounted(load);
|
||||
color: var(--fs-text-tertiary);
|
||||
}
|
||||
.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-tags { display: flex; flex-wrap: wrap; gap: 0.35rem; margin-top: 1.25rem; }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "grimoire",
|
||||
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
|
||||
"version": "2026.11.24.1827",
|
||||
"version": "2026.11.25.0016",
|
||||
"author": {
|
||||
"name": "Bryan Van Deusen"
|
||||
},
|
||||
|
||||
@@ -19,7 +19,9 @@ What only Claude Code needs said:
|
||||
notes and prior art that resemble what you are doing — and, when a tool call
|
||||
or the reply ending a turn reaches a moment of work, the rules mounted on
|
||||
it. Open the ones that apply; using-grimoire says what a quiet turn means and
|
||||
how to correct a moment that fired wrongly.
|
||||
how to correct a moment that fired wrongly. A line beginning "Also
|
||||
resembling this, not shown" names records by id only, because they matched
|
||||
less clearly than the lines above it: open one when it may bear on the work.
|
||||
- **A rule can hold or refuse a tool call.** A held call names its rule and
|
||||
goes ahead once the rule has been read: read it, then make the call again.
|
||||
A refused call is a boundary the operator drew; it moves when they change
|
||||
|
||||
@@ -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
|
||||
@@ -408,12 +409,12 @@ async def judge_lesson_link(
|
||||
"""Say whether a lesson is an instance of a rule: `verdict` is "confirm"
|
||||
or "reject".
|
||||
|
||||
Reach for this when Grimoire proposes a pair — a lesson and a rule that keep
|
||||
arriving together in different situations — or whenever you are reading a
|
||||
lesson and recognise the rule it falls under. Confirming makes the rule
|
||||
reachable through the situation the lesson describes; rejecting records
|
||||
that it is not, so the pair is not proposed again. `note` is the why, and
|
||||
the next reader judges the link by it.
|
||||
Reach for this when you are reading a lesson and recognise the rule it
|
||||
falls under, or when a lesson you just recorded was offered candidate
|
||||
rules. Confirming makes the rule reachable through the situation the
|
||||
lesson describes, and lists the lesson on the rule when it is opened;
|
||||
rejecting records that it is not. `note` is the why, and the next reader
|
||||
judges the link by it.
|
||||
|
||||
Returns the link: {lesson_id, rule_id, state, note, evidence, judged_at}.
|
||||
"""
|
||||
@@ -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)
|
||||
|
||||
@@ -18,6 +18,8 @@ Sentinels (preserved from existing fable-mcp):
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from grimoire.mcp._context import current_user_id
|
||||
from grimoire.mcp.tools import systems as systems_tools
|
||||
from grimoire.services import access as access_svc
|
||||
@@ -34,6 +36,7 @@ from grimoire.services.notes import minted_kind
|
||||
from grimoire.services import placement as placement_svc
|
||||
from grimoire.services import planning as planning_svc
|
||||
from grimoire.services import record_batch as batch_svc
|
||||
from grimoire.services import record_kinds, record_links
|
||||
from grimoire.services import rulebooks as rulebooks_svc
|
||||
from grimoire.services import systems as systems_svc
|
||||
from grimoire.services import task_logs as task_logs_svc
|
||||
@@ -43,6 +46,8 @@ from grimoire.services.record_refs import refuse_guessed_ids
|
||||
from grimoire.services.text import elide
|
||||
from grimoire.services import moment_delivery
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# A work log entry is prose, often long — the discipline asks for what was
|
||||
# decided and why, not a line of status. Two caps, not one, because the entries
|
||||
@@ -410,6 +415,11 @@ async def update_task(
|
||||
reconstructing them, because a remembered milestone title or "next step"
|
||||
reads exactly like a real one when it is wrong.
|
||||
|
||||
Setting a task `in_progress` also returns `records_in_area` when the
|
||||
task's areas hold notes or open issues: one line naming them by id with
|
||||
the call that opens each. Read the ones that bear on the work before
|
||||
starting it.
|
||||
|
||||
Closing a task (done or cancelled) also returns `reply_shape`, the
|
||||
default shape of the completion report you are about to write, and
|
||||
`report_back`: a one-line reminder of what that reply should cover. The
|
||||
@@ -465,11 +475,29 @@ async def update_task(
|
||||
# Owed family adoptions filed while the task was open — work now
|
||||
# waiting in some project, which the report names.
|
||||
await family_adoption_svc.attach_owed_adoptions(uid, data, note)
|
||||
if status == "in_progress":
|
||||
await _attach_area_records(uid, task_id, data)
|
||||
return await moment_delivery.attach_moment_rules(
|
||||
uid, "update_task", {"status": status, "project_id": project_id}, data,
|
||||
)
|
||||
|
||||
|
||||
async def _attach_area_records(uid: int, task_id: int, data: dict) -> None:
|
||||
"""Name, by id, what is recorded in the areas of a task being taken up:
|
||||
the `work.start` row of the kind×moment table says which kinds. Absent
|
||||
when the task has no area or nothing is recorded there."""
|
||||
try:
|
||||
kinds = await record_kinds.kinds_for(uid, "work.start")
|
||||
found = await record_links.area_records(uid, task_id, kinds)
|
||||
line = record_kinds.pointer_line(
|
||||
found, "Recorded in this task's areas", capped_at=record_links.AREA_DEPTH,
|
||||
)
|
||||
if line:
|
||||
data["records_in_area"] = line[0].removeprefix("> ")
|
||||
except Exception: # noqa: BLE001 - a decoration never breaks the payload
|
||||
logger.debug("area records for task %s could not be attached", task_id, exc_info=True)
|
||||
|
||||
|
||||
async def add_task_log(task_id: int, content: str) -> dict:
|
||||
"""Append a timestamped progress log entry to a Grimoire task.
|
||||
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
@@ -10,7 +10,8 @@ from grimoire.models.base import iso
|
||||
PUSHED = "pushed" # a hook put it there unasked (auto-inject, the write path, a slot)
|
||||
ASKED = "asked" # it was a result of a search the session ran itself
|
||||
DIRECT = "direct" # it was opened with nothing delivering it first in the session
|
||||
WAYS = (PUSHED, ASKED, DIRECT)
|
||||
POINTED = "pointed" # named by id in a pointer line, without its title or passage
|
||||
WAYS = (PUSHED, POINTED, ASKED, DIRECT)
|
||||
|
||||
|
||||
class RecordDelivery(Base):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -15,7 +15,6 @@ from quart import Blueprint, g, jsonify, request
|
||||
from grimoire.auth import admin_required, get_current_user_id, login_required
|
||||
from grimoire.config import Config
|
||||
from grimoire.services import hook_payload as hook_payload_svc
|
||||
from grimoire.services import lesson_rules as lesson_rules_svc
|
||||
from grimoire.services import moment_delivery as moment_delivery_svc
|
||||
from grimoire.services import plugin_context as plugin_ctx_svc
|
||||
from grimoire.services import reply_shapes as reply_shapes_svc
|
||||
@@ -215,13 +214,6 @@ async def autoinject_retrieve():
|
||||
result = await plugin_ctx_svc.build_autoinject_hint(
|
||||
g.user.id, q, project_id=project_id, exclude_ids=exclude_ids, context=ctx,
|
||||
)
|
||||
# The one place both arms' lines meet, so the one place a lesson and a
|
||||
# rule arriving TOGETHER can be counted. Keyed on the operator's
|
||||
# prompt — the situation — and fails open to "".
|
||||
proposal = await lesson_rules_svc.co_surfaced(
|
||||
g.user.id, result.get("lesson_ids") or [], rules.get("shown_rule_ids") or [],
|
||||
arm="p", situation=q, project_id=project_id or None,
|
||||
)
|
||||
# The reply mounts go through the same rule ledger; a rule the prompt arm
|
||||
# just named is not quoted a second time by the turn's delivery.
|
||||
turn = await moment_delivery_svc.deliver_for_turn(
|
||||
@@ -232,8 +224,8 @@ async def autoinject_retrieve():
|
||||
record=False,
|
||||
)
|
||||
# One payload, in the one order: the rules, then the reply shape, then
|
||||
# what the last turn left unjudged, then the records menu, then the
|
||||
# lesson-rule proposal, fitted to the budget.
|
||||
# what the last turn left unjudged, then the records menu, fitted to the
|
||||
# budget.
|
||||
carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS]
|
||||
turn_parts = (
|
||||
[*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn
|
||||
@@ -247,7 +239,6 @@ async def autoinject_retrieve():
|
||||
*turn_parts,
|
||||
*([hook_payload_svc.Part(text=carry)] if carry else []),
|
||||
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}),
|
||||
*([hook_payload_svc.Part(text=proposal)] if proposal else []),
|
||||
])
|
||||
shapes = set(fitted.ids(hook_payload_svc.SHAPE))
|
||||
forms = {k: f for k, f in turn["shape_forms"].items() if k in shapes}
|
||||
@@ -408,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)),
|
||||
])
|
||||
|
||||
@@ -26,6 +26,7 @@ from grimoire.models.rulebook import (
|
||||
rule_triggers as rule_triggers_t,
|
||||
)
|
||||
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
|
||||
from grimoire.models.lesson_situation import LessonSituation
|
||||
from grimoire.models.rule_field_judgment import RuleFieldJudgment
|
||||
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
|
||||
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
|
||||
@@ -120,7 +121,10 @@ logger = logging.getLogger(__name__)
|
||||
# v30 rule_field_judgments: suggested, agreed and rejected values for a rule's
|
||||
# enforcement, salience and triggers. Lose them and a weighed corpus reads
|
||||
# as unweighed, and every rejected value is proposed again.
|
||||
BACKUP_VERSION = 30
|
||||
# v31 lesson_situations: the moments and triggers each lesson arrives at,
|
||||
# with the proposals waiting and the rejections that stop a value being
|
||||
# proposed again. Nothing in the lesson's text records them.
|
||||
BACKUP_VERSION = 31
|
||||
|
||||
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED
|
||||
# below, these two lists must together account for the entire schema — which is
|
||||
@@ -158,6 +162,7 @@ _BACKED_UP = [
|
||||
# Lesson → rule links and their judgments, and "no rule fits" answers.
|
||||
"lesson_rule_links",
|
||||
"lesson_no_rule",
|
||||
"lesson_situations",
|
||||
# System usage telemetry, for the reason its note and rule twins travel.
|
||||
"system_usage_events",
|
||||
# An install's action → moment corrections, the moments each rule arrives
|
||||
@@ -283,6 +288,8 @@ _COLUMN_EXCLUSIONS: dict[str, set[str]] = {
|
||||
"rule_field_judgments": {"id"},
|
||||
# Keyed by the lesson itself; nothing to exclude, every column travels.
|
||||
"lesson_no_rule": set(),
|
||||
# The (lesson, kind, value) triple is the row.
|
||||
"lesson_situations": {"id"},
|
||||
"note_usage_events": {"id"},
|
||||
# Same as the note twin: the surrogate key is re-issued on insert.
|
||||
"rule_usage_events": {"id"},
|
||||
@@ -390,6 +397,7 @@ _IMPORT_COLUMN_EXCLUSIONS: dict[str, set[str]] = {
|
||||
"rule_moment_judgments": {"id"},
|
||||
"rule_field_judgments": {"id"},
|
||||
"lesson_no_rule": set(),
|
||||
"lesson_situations": {"id"},
|
||||
"note_usage_events": {"id"},
|
||||
"rule_usage_events": {"id"},
|
||||
"system_usage_events": {"id"},
|
||||
@@ -904,6 +912,20 @@ def _lesson_no_rule_rows(rows) -> list[dict]:
|
||||
]
|
||||
|
||||
|
||||
def _lesson_situation_rows(rows) -> list[dict]:
|
||||
"""When each lesson applies, by SOURCE lesson id, remapped through the
|
||||
note map at restore."""
|
||||
return [
|
||||
{
|
||||
"lesson_id": r.lesson_id, "kind": r.kind, "value": r.value,
|
||||
"state": r.state, "source": r.source, "note": r.note,
|
||||
"judged_at": r.judged_at.isoformat() if r.judged_at else None,
|
||||
"created_at": r.created_at.isoformat() if r.created_at else None,
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def _platform_rows(rows) -> list[dict]:
|
||||
"""The global platform catalog (v25). Carried WITHOUT ids, matched on slug
|
||||
at restore — the canonical_systems reasoning."""
|
||||
@@ -1076,6 +1098,7 @@ async def export_full_backup() -> dict:
|
||||
rule_relations = (await session.execute(select(RuleRelation).order_by(RuleRelation.id))).scalars().all()
|
||||
lesson_rule_links = (await session.execute(select(LessonRuleLink).order_by(LessonRuleLink.id))).scalars().all()
|
||||
lesson_no_rule = (await session.execute(select(LessonNoRule).order_by(LessonNoRule.lesson_id))).scalars().all()
|
||||
lesson_situations = (await session.execute(select(LessonSituation).order_by(LessonSituation.id))).scalars().all()
|
||||
record_systems = (await session.execute(select(RecordSystem).order_by(RecordSystem.id))).scalars().all()
|
||||
supersessions = (
|
||||
await session.execute(select(NoteSupersession).order_by(NoteSupersession.id))
|
||||
@@ -1168,6 +1191,7 @@ async def export_full_backup() -> dict:
|
||||
"rule_relations": _rule_relation_rows(rule_relations),
|
||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
||||
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
|
||||
"lesson_situations": _lesson_situation_rows(lesson_situations),
|
||||
"systems": _system_rows(
|
||||
systems, {c.id: c.slug for c in canonical_systems}
|
||||
),
|
||||
@@ -1392,6 +1416,10 @@ async def export_user_backup(user_id: int) -> dict:
|
||||
lesson_no_rule = (await session.execute(
|
||||
select(LessonNoRule).where(LessonNoRule.lesson_id.in_(note_ids))
|
||||
)).scalars().all() if note_ids else []
|
||||
lesson_situations = (await session.execute(
|
||||
select(LessonSituation).where(LessonSituation.lesson_id.in_(note_ids))
|
||||
.order_by(LessonSituation.id)
|
||||
)).scalars().all() if note_ids else []
|
||||
# Family canon (v25). The catalog is global and taken whole, for the
|
||||
# canonical_systems reason. Everything else is scoped so that BOTH
|
||||
# ends of every row restore: an idea is this user's note, a ledger row
|
||||
@@ -1466,6 +1494,7 @@ async def export_user_backup(user_id: int) -> dict:
|
||||
"rule_relations": _rule_relation_rows(rule_relations),
|
||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
||||
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
|
||||
"lesson_situations": _lesson_situation_rows(lesson_situations),
|
||||
"systems": _system_rows(
|
||||
systems, {c.id: c.slug for c in canonical_systems}
|
||||
),
|
||||
@@ -1853,6 +1882,25 @@ def _build_lesson_no_rule(row: dict, maps: _Maps) -> LessonNoRule | None:
|
||||
)
|
||||
|
||||
|
||||
def _build_lesson_situation(row: dict, maps: _Maps) -> LessonSituation | None:
|
||||
"""Skipped when its lesson did not restore — the situation is about that
|
||||
lesson and no other."""
|
||||
lesson = maps.notes.get(row.get("lesson_id", 0))
|
||||
if lesson is None:
|
||||
return None
|
||||
return LessonSituation(
|
||||
lesson_id=lesson,
|
||||
kind=row["kind"],
|
||||
value=row.get("value") or "",
|
||||
state=row.get("state") or "suggested",
|
||||
source=row.get("source") or "pass",
|
||||
note=row.get("note") or None,
|
||||
# Absent when absent: a waiting proposal was never judged.
|
||||
judged_at=_dt_or_none(row.get("judged_at")),
|
||||
created_at=_dt(row.get("created_at")),
|
||||
)
|
||||
|
||||
|
||||
def _build_lesson_rule_link(row: dict, maps: _Maps) -> LessonRuleLink | None:
|
||||
"""Both ends must map: a link whose lesson or rule did not restore points
|
||||
at whatever took that number in the destination."""
|
||||
@@ -2506,7 +2554,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
|
||||
"rule_triggers": 0, "rule_field_judgments": 0,
|
||||
"rule_relations": 0, "rule_versions": 0,
|
||||
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
|
||||
"lesson_no_rule": 0, "moment_mappings": 0,
|
||||
"lesson_no_rule": 0, "lesson_situations": 0, "moment_mappings": 0,
|
||||
"platforms": 0, "project_platforms": 0, "family_ideas": 0,
|
||||
"family_idea_platforms": 0, "family_idea_references": 0,
|
||||
"family_adoptions": 0, "family_decisions": 0,
|
||||
@@ -2754,6 +2802,13 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
|
||||
continue
|
||||
session.add(answer)
|
||||
stats["lesson_no_rule"] += 1
|
||||
# When each lesson applies; archives before v31 carry none.
|
||||
for ls in data.get("lesson_situations", []):
|
||||
situation = _build_lesson_situation(ls, maps)
|
||||
if situation is None:
|
||||
continue
|
||||
session.add(situation)
|
||||
stats["lesson_situations"] += 1
|
||||
|
||||
# Family canon (v25). Here because it needs projects, notes and topics
|
||||
# all mapped. The platform catalog first, matched on slug and seeded
|
||||
|
||||
@@ -5,10 +5,11 @@ choice for a class of them. This service owns the link between the two — which
|
||||
rule a lesson is an instance of — and both directions of reading it.
|
||||
|
||||
THE STATES (models/lesson_rule_link.py says why each exists):
|
||||
`suggested` while evidence accumulates, `confirmed` or `rejected` once a
|
||||
judgment is made. Every write here is a JUDGMENT, so every write lands as
|
||||
confirmed or rejected; `suggested` rows come from the co-surfacing recorder,
|
||||
never from a caller naming a rule.
|
||||
`confirmed` or `rejected`, once a judgment is made. Every write here is a
|
||||
JUDGMENT, so every write lands as one of the two. `suggested` rows were
|
||||
written by a co-arrival recorder that no longer runs; they stay in the table
|
||||
and no read shows them, because a lesson and a rule that resemble the same
|
||||
prompts arrive together whether or not one is an instance of the other.
|
||||
|
||||
THE THIRD ANSWER. "Which rule is this an instance of?" has three
|
||||
answers, and only two of them are links: a rule named (confirmed), or NO RULE
|
||||
@@ -18,13 +19,12 @@ lesson that stands alone is the raw material for a rule nobody has written yet
|
||||
(see Convergence below), and that is unreadable if "nobody looked" means the
|
||||
same thing.
|
||||
|
||||
THE SOFT LINK. When one hook request puts a lesson and a rule in
|
||||
front of the reader together, `co_surfaced` records the pair as evidence on a
|
||||
SUGGESTED link, and once that evidence crosses a bar the next co-arrival asks
|
||||
the reader to judge it. The evidence counts distinct SITUATIONS, not
|
||||
arrivals: two records that resemble each other arrive together on every
|
||||
similar prompt, and counting each time would measure their similarity over
|
||||
and over rather than any relation between them.
|
||||
EVIDENCE BY SITUATION. `situation_key`, `add_evidence` and `proposal_due`
|
||||
count distinct SITUATIONS, not arrivals, for the rule↔moment signals that
|
||||
ask a reader to judge a pairing (`rule_moment_judgments`): two things that
|
||||
resemble each other arrive together on every similar prompt, and counting
|
||||
each time would measure their similarity over and over rather than any
|
||||
relation between them.
|
||||
|
||||
ACL (services/access.py). Linking changes what a lesson says about itself, so it needs
|
||||
WRITE on the lesson (`access.can_write_note`, share-aware). It names a rule, so
|
||||
@@ -42,7 +42,6 @@ import statistics
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import and_, delete, exists, func, not_, or_, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.lesson_rule_link import (
|
||||
@@ -65,6 +64,10 @@ _REMOVED_NOTE = "removed from the lesson's rules by an update"
|
||||
# of that answer's reason.
|
||||
_NO_RULE_NOTE = "no rule fits: "
|
||||
|
||||
# The link states a read returns, in the order it lists them: a judgment,
|
||||
# never a suggestion.
|
||||
READ_STATES = (CONFIRMED, REJECTED)
|
||||
|
||||
# What `rule_judgment` reads on a lesson payload — the three answers.
|
||||
LINKED, NO_RULE, UNJUDGED = "linked", "no_rule", "unjudged"
|
||||
|
||||
@@ -271,8 +274,8 @@ async def rules_for_lessons(user_id: int, lesson_ids) -> dict[int, list[dict]]:
|
||||
"""{lesson_id: [{id, title, kind, state, note}]}, for rules the READER owns.
|
||||
|
||||
One query for the whole set — a lesson list would otherwise be N+1.
|
||||
Confirmed first, then suggested, then rejected: the order a reader cares
|
||||
about them in.
|
||||
Judged links only, confirmed before rejected: a rejection is kept so the
|
||||
reader sees the rule was considered and is not this one.
|
||||
"""
|
||||
from grimoire.services.rulebooks import _owned_rules_clause
|
||||
|
||||
@@ -280,24 +283,20 @@ async def rules_for_lessons(user_id: int, lesson_ids) -> dict[int, list[dict]]:
|
||||
out: dict[int, list[dict]] = {i: [] for i in ids}
|
||||
if not ids:
|
||||
return out
|
||||
order = {s: n for n, s in enumerate((CONFIRMED, SUGGESTED, REJECTED))}
|
||||
order = {s: n for n, s in enumerate(READ_STATES)}
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(LessonRuleLink, Rule)
|
||||
.join(Rule, Rule.id == LessonRuleLink.rule_id)
|
||||
.where(LessonRuleLink.lesson_id.in_(ids))
|
||||
.where(LessonRuleLink.state.in_(list(order)))
|
||||
.where(_owned_rules_clause(user_id))
|
||||
)).all()
|
||||
for link, rule in sorted(rows, key=lambda r: (order.get(r[0].state, 9), r[1].id)):
|
||||
item = {
|
||||
for link, rule in sorted(rows, key=lambda r: (order[r[0].state], r[1].id)):
|
||||
out[link.lesson_id].append({
|
||||
"id": rule.id, "title": rule.title, "kind": rule.kind,
|
||||
"state": link.state, "note": link.note or "",
|
||||
}
|
||||
if link.state == SUGGESTED:
|
||||
# What the suggestion rests on, so a reader can judge it from
|
||||
# here rather than having to go and count.
|
||||
item["evidence"] = evidence_summary(link.evidence)
|
||||
out[link.lesson_id].append(item)
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
@@ -305,22 +304,25 @@ async def lessons_for_rule(user_id: int, rule_id: int) -> list[dict]:
|
||||
"""The lessons that point at one rule, readable by the caller (share-aware).
|
||||
|
||||
The reverse direction, and the one a rule's page needs: the concrete
|
||||
situations that have been judged instances of it.
|
||||
situations that have been judged instances of it. Only the confirmed
|
||||
ones travel with a rule; a rejected lesson is listed after them, so the
|
||||
rule's page shows it was considered.
|
||||
"""
|
||||
from grimoire.services.access import readable_notes_clause
|
||||
|
||||
order = {s: n for n, s in enumerate(READ_STATES)}
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(LessonRuleLink, Note)
|
||||
.join(Note, Note.id == LessonRuleLink.lesson_id)
|
||||
.where(LessonRuleLink.rule_id == int(rule_id))
|
||||
.where(LessonRuleLink.state.in_(list(order)))
|
||||
.where(Note.deleted_at.is_(None))
|
||||
.where(readable_notes_clause(user_id))
|
||||
)).all()
|
||||
order = {s: n for n, s in enumerate((CONFIRMED, SUGGESTED, REJECTED))}
|
||||
return [
|
||||
{"id": note.id, "title": note.title, "state": link.state, "note": link.note or ""}
|
||||
for link, note in sorted(rows, key=lambda r: (order.get(r[0].state, 9), r[1].id))
|
||||
for link, note in sorted(rows, key=lambda r: (order[r[0].state], r[1].id))
|
||||
]
|
||||
|
||||
|
||||
@@ -582,110 +584,6 @@ def proposal_due(evidence, now: datetime) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _proposal_line(lesson_id: int, lesson_title: str, rule_id: int, rule_title: str,
|
||||
kind: str, evidence: dict) -> str:
|
||||
counts = evidence_summary(evidence)
|
||||
where = (f" across {counts['projects']} projects" if counts["projects"] > 1 else "")
|
||||
return (
|
||||
f"> Lesson #{lesson_id} \"{lesson_title}\" and {kind} #{rule_id} "
|
||||
f"\"{rule_title}\" keep arriving together — {counts['situations']} "
|
||||
f"distinct situations{where}. If the lesson is an instance of the "
|
||||
f"{kind}, `judge_lesson_link({lesson_id}, {rule_id}, \"confirm\", "
|
||||
f"note=\"why\")` links them and the {kind} becomes reachable through "
|
||||
f"the lesson's situation; if it is not, `\"reject\"` with the why "
|
||||
f"stops the pair being asked about again."
|
||||
)
|
||||
|
||||
|
||||
async def co_surfaced(
|
||||
user_id: int, lesson_ids, rule_ids, *, arm: str, situation: str,
|
||||
project_id: int | None = None,
|
||||
) -> str:
|
||||
"""Record that these lessons and rules arrived together in one request,
|
||||
and return a proposal line when a pair has earned one ("" otherwise).
|
||||
|
||||
Called by the hook doors that put both kinds in front of the reader in
|
||||
the SAME response — `/retrieve` on a prompt, `/prior-art` on a write — so
|
||||
the pairing is exact: nothing is joined across requests, and no session
|
||||
identity is needed.
|
||||
|
||||
Only pairs the reader could confirm are recorded: a lesson they may write
|
||||
and a rule they own, the two checks `judge_link` makes. A pair already
|
||||
judged (confirmed or rejected) gathers nothing more — a confirmation needs
|
||||
no evidence, and a rejection is what stops the asking.
|
||||
|
||||
One proposal per request at most, so a menu never becomes a queue of
|
||||
questions. Fails open: this rides a hook, and a recall aid must never
|
||||
break the prompt or the write it decorates.
|
||||
"""
|
||||
try:
|
||||
return await _co_surfaced(user_id, lesson_ids, rule_ids, arm, situation, project_id)
|
||||
except Exception:
|
||||
logger.warning("lesson/rule co-surfacing could not be recorded", exc_info=True)
|
||||
return ""
|
||||
|
||||
|
||||
async def _co_surfaced(user_id, lesson_ids, rule_ids, arm, situation, project_id) -> str:
|
||||
from grimoire.services.access import can_write_note
|
||||
from grimoire.services.rulebooks import _owned_rules_clause
|
||||
|
||||
lessons = _ids(lesson_ids)
|
||||
rules = _ids(rule_ids)
|
||||
key = situation_key(arm, situation)
|
||||
if not lessons or not rules or not key:
|
||||
return ""
|
||||
lessons = [lid for lid in lessons if await can_write_note(user_id, lid)]
|
||||
if not lessons:
|
||||
return ""
|
||||
now = datetime.now(timezone.utc)
|
||||
proposal = None
|
||||
async with async_session() as session:
|
||||
owned = {
|
||||
r.id: r for r in (await session.execute(
|
||||
select(Rule).where(Rule.id.in_(rules)).where(_owned_rules_clause(user_id))
|
||||
)).scalars().all()
|
||||
}
|
||||
if not owned:
|
||||
return ""
|
||||
existing = {
|
||||
(row.lesson_id, row.rule_id): row for row in (await session.execute(
|
||||
select(LessonRuleLink).where(
|
||||
LessonRuleLink.lesson_id.in_(lessons),
|
||||
LessonRuleLink.rule_id.in_(list(owned)),
|
||||
)
|
||||
)).scalars().all()
|
||||
}
|
||||
for lid in lessons:
|
||||
for rid in owned:
|
||||
row = existing.get((lid, rid))
|
||||
if row is not None and row.state != SUGGESTED:
|
||||
continue
|
||||
if row is None:
|
||||
row = LessonRuleLink(lesson_id=lid, rule_id=rid, state=SUGGESTED)
|
||||
session.add(row)
|
||||
ev = add_evidence(row.evidence, key, project_id, now)
|
||||
if proposal is None and proposal_due(ev, now):
|
||||
ev["proposed_at"] = now.isoformat()
|
||||
ev["proposed_count"] = int(ev.get("proposed_count") or 0) + 1
|
||||
proposal = (lid, rid, ev)
|
||||
row.evidence = ev
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError:
|
||||
# Two hook requests created the same pair at once; the other
|
||||
# one's row stands, and this co-arrival is simply not counted.
|
||||
await session.rollback()
|
||||
return ""
|
||||
if proposal is None:
|
||||
return ""
|
||||
lid, rid, ev = proposal
|
||||
lesson_title = (await session.execute(
|
||||
select(Note.title).where(Note.id == lid)
|
||||
)).scalar_one_or_none() or ""
|
||||
rule = owned[rid]
|
||||
return _proposal_line(lid, lesson_title, rid, rule.title, rule.kind or "rule", ev)
|
||||
|
||||
|
||||
# ── Reaching a rule through its lessons ──────────────────────────────────────
|
||||
|
||||
|
||||
@@ -693,10 +591,9 @@ async def confirmed_lessons(user_id: int) -> set[int]:
|
||||
"""The lessons, readable by the caller, that carry a CONFIRMED link to a
|
||||
rule the caller owns — the only lessons that can bring a rule along.
|
||||
|
||||
CONFIRMED ONLY, and the reason is the soft link's: a suggested link that
|
||||
carried its rule would put the two side by side on every prompt that
|
||||
found the lesson, which is exactly the co-arrival the soft link counts
|
||||
as evidence — the suggestion would manufacture its own proof.
|
||||
CONFIRMED ONLY: nobody judged a suggested link, and a lesson that brought
|
||||
an unjudged rule along would put a rule in front of the reader on the
|
||||
strength of a resemblance alone.
|
||||
|
||||
Asked first and cheaply, so an arm on an install with no confirmed links
|
||||
— every install, until someone judges one — never pays for a search.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -25,7 +25,10 @@ from grimoire.services import knowledge as knowledge_svc
|
||||
from grimoire.services import notes as notes_svc
|
||||
from grimoire.services import projects as projects_svc
|
||||
from grimoire.services import record_refs as record_refs_svc
|
||||
from grimoire.models.record_delivery import POINTED
|
||||
from grimoire.services import record_deliveries as record_deliveries_svc
|
||||
from grimoire.services import record_kinds
|
||||
from grimoire.services import record_links as record_links_svc
|
||||
from grimoire.services import shape_ledger as shape_ledger_svc
|
||||
from grimoire.services import snippets as snippets_svc
|
||||
from grimoire.services import task_claims as task_claims_svc
|
||||
@@ -340,6 +343,11 @@ _TOOL_QUERY_CHARS = 400
|
||||
# pointless embedding round-trip on trivial edits.
|
||||
WRITEPATH_MIN_CODE_CHARS = 48
|
||||
|
||||
# At most this many issues linked by structure on one write: a file worked on
|
||||
# for months is named by dozens, and the newest two carry what was last tried
|
||||
# there; the rest are one search away.
|
||||
LINKED_ISSUES_MAX = 2
|
||||
|
||||
# --- concept extraction for the semantic arm's query -------------------------
|
||||
# A snippet's embedded text is f"{title}\n{body}", and for a snippet that body is
|
||||
# composed markdown: **When to use:**, **Signature:**, **Location:**, then the
|
||||
@@ -689,7 +697,7 @@ async def build_autoinject_hint(
|
||||
if not _has_subject(q):
|
||||
# Nothing to search for: the menu would answer the previous reply,
|
||||
# not the operator. Records named by number are still shown.
|
||||
kept, chunks = [], {}
|
||||
kept, chunks, pointers = [], {}, {}
|
||||
else:
|
||||
# Everything below searches, logs and fills its slots on the ENRICHED
|
||||
# query, so the telemetry row records what was actually asked.
|
||||
@@ -703,8 +711,8 @@ async def build_autoinject_hint(
|
||||
),
|
||||
floor=cfg["threshold"], budget=cfg["top_k"], io=_note_io(),
|
||||
)
|
||||
kept, chunks = result.menu, result.chunks
|
||||
if not kept and not named:
|
||||
kept, chunks, pointers = result.menu, result.chunks, result.pointers
|
||||
if not kept and not named and not pointers:
|
||||
return empty
|
||||
|
||||
# A collaborator's note can reach this menu via a shared project, and the
|
||||
@@ -832,6 +840,17 @@ async def build_autoinject_hint(
|
||||
ids={hook_payload.NOTE: (nid,)},
|
||||
))
|
||||
|
||||
# What else cleared the floor, named by id only. Recorded as `pointed`
|
||||
# rather than surfaced: no line was spent on these, so an open that
|
||||
# follows says whether a pointer is enough.
|
||||
pointer = record_kinds.pointer_line(pointers, POINTER_LEAD)
|
||||
if pointer:
|
||||
lines.append(pointer[0])
|
||||
parts.append(hook_payload.Part(
|
||||
text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])},
|
||||
))
|
||||
record_deliveries_svc.record(user_id, pointer[1], "auto_inject_pointer", way=POINTED)
|
||||
|
||||
# A lookup, not a ranking, so it writes no retrieval_logs row — there is no
|
||||
# score or bar to tune — and its surfacings are its own source, which is
|
||||
# what lets pull-through say whether a named record gets opened. The
|
||||
@@ -843,18 +862,9 @@ async def build_autoinject_hint(
|
||||
project_id=project_id,
|
||||
)
|
||||
|
||||
# The lessons this menu put in front of the reader, repeats included — for
|
||||
# the soft-link recorder, which pairs them with the rule arm's
|
||||
# lines in the same response. Relevance, not the session ledger, is what
|
||||
# makes a co-arrival, so a `seen` lesson counts — and so does one the
|
||||
# operator named, which is relevance by their own say-so.
|
||||
lesson_ids = [
|
||||
int(n.id) for n in [*named, *(n for _s, n in kept)]
|
||||
if _record_kind(n) == LESSON_NOTE_TYPE
|
||||
]
|
||||
return {
|
||||
"context": "\n".join(lines), "note_ids": note_ids, "config": cfg,
|
||||
"lesson_ids": lesson_ids, "parts": parts,
|
||||
"parts": parts,
|
||||
}
|
||||
|
||||
|
||||
@@ -917,7 +927,7 @@ async def _rule_moment(
|
||||
query the arm searched with, and skips what the arm named plus what the
|
||||
session's ledger holds — suppression is by RULE, whichever lesson reached
|
||||
it. Its lines and fresh ids join the arm's; `shown_rule_ids` stays the
|
||||
direct arm's band, which is what the soft-link recorder pairs.
|
||||
direct arm's band.
|
||||
"""
|
||||
result = await rp.run_rule_arm(
|
||||
arm, moment, floor=floor, budget=budget, io=_rule_io(),
|
||||
@@ -1007,7 +1017,7 @@ async def build_prompt_rule_hint(
|
||||
result.lines, result.rule_per_line(), block="rules",
|
||||
)
|
||||
# Every rule LINE the direct arm showed, repeats and the reserved
|
||||
# slot included — for the soft-link recorder. Distinct
|
||||
# slot included — what the payload fitter keeps or drops. Distinct
|
||||
# from `rule_ids`, which is telemetry's fresh-only cut.
|
||||
out["shown_rule_ids"] = result.shown_rule_ids
|
||||
except Exception:
|
||||
@@ -1064,6 +1074,11 @@ def _rule_io() -> rp.RuleIO:
|
||||
# this exact file" is a stronger claim than "this resembles something".
|
||||
|
||||
|
||||
# How a door's pointer line opens: records that cleared the floor and were
|
||||
# not shown. The static context teaches what a line opening this way means.
|
||||
POINTER_LEAD = "Also resembling this, not shown"
|
||||
|
||||
|
||||
def _prior_art_line(item: dict, marker: str, owner: str | None, foreign_lang: str = "") -> str:
|
||||
"""One menu line: `- #12 [here] "title"`, attributed when it isn't yours.
|
||||
|
||||
@@ -1384,6 +1399,10 @@ async def build_write_path_hint(
|
||||
# a FILE path — so the file query returns precisely the snippets recorded
|
||||
# AT this path: the sync class. The directory query is the reuse-shaped
|
||||
# "nearby" arm, unchanged.
|
||||
# The kinds this user's write path considers (the kind×moment table).
|
||||
# The structural lookups below read it as the search by meaning does: a
|
||||
# kind turned off at this door is not offered here by any arm.
|
||||
kinds = await record_kinds.kinds_for(user_id, rp.WRITE_PATH.door)
|
||||
here: list[dict] = []
|
||||
nearby: list[dict] = []
|
||||
try:
|
||||
@@ -1391,7 +1410,7 @@ async def build_write_path_hint(
|
||||
user_id, path=path, limit=top_k, project_id=scope_project,
|
||||
)
|
||||
directory = path.rsplit("/", 1)[0] if "/" in path else ""
|
||||
if directory and len(here) < top_k:
|
||||
if directory and len(here) < top_k and "snippet" in kinds:
|
||||
nearby, _ = await snippets_svc.list_snippets(
|
||||
user_id, path=directory, limit=top_k, project_id=scope_project,
|
||||
)
|
||||
@@ -1429,6 +1448,26 @@ async def build_write_path_hint(
|
||||
item["seen"] = nid in excluded
|
||||
placed.append(("nearby · seen" if nid in excluded else "nearby", item))
|
||||
|
||||
# --- arm 1b: issues linked by structure ---
|
||||
# An issue that names this file, or is open in its area, needs no
|
||||
# resemblance to belong here, so it takes the issue's place before the
|
||||
# search by meaning runs, and that search does not list it again.
|
||||
linked: list[tuple[str, dict]] = []
|
||||
if "task:issue" in kinds and project_id:
|
||||
room = min(LINKED_ISSUES_MAX, top_k - len(synced) - len(placed))
|
||||
for link, note in await record_links_svc.issues_for_path(
|
||||
user_id, project_id, path, limit=room, exclude=frozenset(seen),
|
||||
):
|
||||
nid = int(note.id)
|
||||
seen.add(nid)
|
||||
kind = _record_kind(note)
|
||||
marker = f"{link} · {kind}" + (" · seen" if nid in excluded else "")
|
||||
linked.append((marker, {
|
||||
"id": nid, "title": note.title, "user_id": note.user_id,
|
||||
"name": _menu_name(note.title, note.note_type, note.data, note.body),
|
||||
"seen": nid in excluded, "kind": kind, "linked": True,
|
||||
}))
|
||||
|
||||
# The stamping feed's "actually pulled it" half. Read once, before
|
||||
# the semantic arm, because the arm's query doubles as the resemblance
|
||||
# test: a pulled snippet this session already saw (so it sits in `seen`)
|
||||
@@ -1440,7 +1479,7 @@ async def build_write_path_hint(
|
||||
|
||||
# --- arm 2: by meaning ---
|
||||
scored: list[tuple[str, dict]] = []
|
||||
remaining = top_k - len(synced) - len(placed)
|
||||
remaining = top_k - len(synced) - len(placed) - len(linked)
|
||||
query = (code or "").strip()
|
||||
# Drop payloads too small to carry meaning before spending an embedding on
|
||||
# them — a one-line Edit is not a helper being rewritten, and its embedding
|
||||
@@ -1462,6 +1501,7 @@ async def build_write_path_hint(
|
||||
# loop is not conditional, so it needs something to read either way, and an
|
||||
# empty mapping means every line falls back to its title alone.
|
||||
wp_chunks: dict[int, dict] = {}
|
||||
pointers: dict[str, list[int]] = {}
|
||||
if remaining > 0 and query:
|
||||
# The ranked half is `retrieval_pipeline.run_note_arm` with the
|
||||
# WRITE_PATH spec: which kinds it asks for and why, the withheld-menu
|
||||
@@ -1476,11 +1516,12 @@ async def build_write_path_hint(
|
||||
user_id=user_id, query=query, project_id=project_id,
|
||||
seen=frozenset(excluded), in_menu=frozenset(seen),
|
||||
still_scored=frozenset(pulled),
|
||||
kinds=await record_kinds.kinds_for(user_id, rp.WRITE_PATH.door),
|
||||
kinds=kinds,
|
||||
),
|
||||
floor=cfg["threshold"], budget=remaining, io=_note_io(),
|
||||
)
|
||||
wp_chunks = result.chunks
|
||||
pointers = result.pointers
|
||||
resembles = {
|
||||
int(note.id): float(score) for score, note in result.answered
|
||||
if int(note.id) in pulled
|
||||
@@ -1535,7 +1576,9 @@ async def build_write_path_hint(
|
||||
},
|
||||
))
|
||||
|
||||
menu = (placed + scored)[:max(0, top_k - len(synced))]
|
||||
# Structure first: what is linked to the file, then what sits beside it,
|
||||
# then what was found by meaning.
|
||||
menu = (linked + placed + scored)[:max(0, top_k - len(synced))]
|
||||
|
||||
# The suggestion runs whether or not anything is rendered — after dedup,
|
||||
# the common case is a silent hint and a pulled canon being instantiated.
|
||||
@@ -1645,7 +1688,6 @@ async def build_write_path_hint(
|
||||
rule_lines: list[str] = []
|
||||
rule_line_ids: list[int] = []
|
||||
rule_ids: list[int] = []
|
||||
shown_rule_ids: list[int] = []
|
||||
checkpoint: dict = {}
|
||||
try:
|
||||
result = await _rule_moment(
|
||||
@@ -1662,9 +1704,6 @@ async def build_write_path_hint(
|
||||
rule_lines = result.lines
|
||||
rule_line_ids = result.rule_per_line()
|
||||
rule_ids.extend(result.rule_ids)
|
||||
# Every rule line the band showed, repeats included — what the
|
||||
# soft-link recorder pairs with this response's lessons.
|
||||
shown_rule_ids = result.shown_rule_ids
|
||||
checkpoint = result.checkpoint
|
||||
except Exception:
|
||||
logger.debug("write-path rule arm failed", exc_info=True)
|
||||
@@ -1689,7 +1728,7 @@ async def build_write_path_hint(
|
||||
]
|
||||
|
||||
if (not staleness and not synced and not menu and not suggested
|
||||
and not divergence and not derive and not rule_lines):
|
||||
and not divergence and not derive and not rule_lines and not pointers):
|
||||
if design_text or rulings["lines"]:
|
||||
return {
|
||||
**empty,
|
||||
@@ -1814,6 +1853,14 @@ async def build_write_path_hint(
|
||||
entry.append(f"> ↳ {passage}")
|
||||
parts[-1] = replace(parts[-1], text="\n".join(entry))
|
||||
|
||||
pointer = record_kinds.pointer_line(pointers, POINTER_LEAD)
|
||||
if pointer:
|
||||
lines.append(pointer[0])
|
||||
parts.append(hook_payload.Part(
|
||||
text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])},
|
||||
))
|
||||
record_deliveries_svc.record(user_id, pointer[1], "write_path_pointer", way=POINTED)
|
||||
|
||||
if suggested:
|
||||
lines.append(_suggest_line(path, suggested))
|
||||
parts.append(hook_payload.Part(text=lines[-1]))
|
||||
@@ -1844,9 +1891,12 @@ async def build_write_path_hint(
|
||||
# same call. The semantic arm's rows (`write_path_semantic`)
|
||||
# were written by the pipeline beside its call row, so only the
|
||||
# lookups are booked here.
|
||||
if int(item["id"]) in excluded or not marker.startswith("nearby"):
|
||||
if int(item["id"]) in excluded:
|
||||
continue
|
||||
by_arm.setdefault("write_path_place", []).append(int(item["id"]))
|
||||
if item.get("linked"):
|
||||
by_arm.setdefault("write_path_linked", []).append(int(item["id"]))
|
||||
elif marker.startswith("nearby"):
|
||||
by_arm.setdefault("write_path_place", []).append(int(item["id"]))
|
||||
for arm, ids in by_arm.items():
|
||||
record_surfaced(
|
||||
user_id=user_id, note_ids=ids, source=arm, project_id=project_id,
|
||||
@@ -1854,20 +1904,6 @@ async def build_write_path_hint(
|
||||
|
||||
lines.extend(rule_lines)
|
||||
|
||||
# A lesson and a rule on this one response: the soft-link
|
||||
# recorder counts the pair, keyed on the FILE — every edit to one file is
|
||||
# one situation — and asks about it once the evidence holds. Fails open.
|
||||
shown_lessons = [
|
||||
int(item["id"]) for _m, item in menu if item.get("kind") == LESSON_NOTE_TYPE
|
||||
]
|
||||
proposal = await lesson_rules_svc.co_surfaced(
|
||||
user_id, shown_lessons, shown_rule_ids, arm="w", situation=path,
|
||||
project_id=project_id or None,
|
||||
)
|
||||
if proposal:
|
||||
lines.append(proposal)
|
||||
parts.append(hook_payload.Part(text=proposal))
|
||||
|
||||
return {
|
||||
"context": "\n".join(lines),
|
||||
"parts": parts,
|
||||
|
||||
@@ -14,7 +14,8 @@ four calls:
|
||||
of it in the session gets the stamp. With nothing delivering it first, a
|
||||
`direct` row is written, delivered and opened at once: the record was
|
||||
reached without being shown.
|
||||
- `summary` — per kind, how records arrived (`pushed`, `asked`, `direct`),
|
||||
- `summary` — per kind, how records arrived (`pushed`, `pointed`, `asked`,
|
||||
`direct`),
|
||||
by door, and how many were opened.
|
||||
|
||||
Only rows from a plugin that reports its version count in the readout: an
|
||||
@@ -30,7 +31,7 @@ from sqlalchemy import case, delete, func, select, tuple_, update
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.note import Note
|
||||
from grimoire.models.record_delivery import ASKED, DIRECT, PUSHED, RecordDelivery
|
||||
from grimoire.models.record_delivery import ASKED, DIRECT, POINTED, PUSHED, RecordDelivery
|
||||
from grimoire.models.retrieval_log import RetrievalLog
|
||||
from grimoire.services import rule_deliveries
|
||||
from grimoire.services.access import readable_notes_clause
|
||||
@@ -55,15 +56,16 @@ def reset() -> None:
|
||||
_pending.set([])
|
||||
|
||||
|
||||
def record(user_id: int | None, note_ids, source: str) -> None:
|
||||
"""Record records a hook pushed to the bound session. A no-op outside a
|
||||
plugin request, since an open could never be tied back to it."""
|
||||
def record(user_id: int | None, note_ids, source: str, way: str = PUSHED) -> None:
|
||||
"""Record records a hook put in front of the bound session: `pushed` as a
|
||||
line, or `pointed` when only named by id in a pointer line. A no-op
|
||||
outside a plugin request, since an open could never be tied back to it."""
|
||||
sid = rule_deliveries.current_session()
|
||||
if not sid or not user_id:
|
||||
return
|
||||
try:
|
||||
rows = [{"user_id": int(user_id), "session_id": sid, "note_id": int(n),
|
||||
"way": PUSHED, "source": source, "plugin": rule_deliveries.current_plugin()}
|
||||
"way": way, "source": source, "plugin": rule_deliveries.current_plugin()}
|
||||
for n in dict.fromkeys(note_ids or [])]
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
logger.debug("record delivery payload build failed", exc_info=True)
|
||||
@@ -89,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."""
|
||||
@@ -239,7 +265,7 @@ async def summary(user_id: int, days: int = 30) -> dict:
|
||||
)).scalar_one()
|
||||
|
||||
def zero() -> dict:
|
||||
return {w: {"delivered": 0, "opened": 0} for w in (PUSHED, ASKED, DIRECT)}
|
||||
return {w: {"delivered": 0, "opened": 0} for w in (PUSHED, POINTED, ASKED, DIRECT)}
|
||||
|
||||
kinds: dict[str, dict] = {}
|
||||
totals = zero()
|
||||
|
||||
@@ -31,10 +31,10 @@ back to its default removes the stored change.
|
||||
|
||||
THE DOORS
|
||||
|
||||
A door is a point where a record search fires: a catalog moment
|
||||
(`work.change`), or the operator's message, which is when a session first
|
||||
hears what the work is and is not a moment rules mount on, so it has its
|
||||
own key (`message`).
|
||||
A door is a point where records are offered: a catalog moment
|
||||
(`work.change` before a write, `work.start` when a task is taken up), or the
|
||||
operator's message, which is when a session first hears what the work is and
|
||||
is not a moment rules mount on, so it has its own key (`message`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -92,10 +92,21 @@ 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"}),
|
||||
sources=("write_path_semantic",),
|
||||
frozenset({"snippet", "note", "task:issue"}),
|
||||
sources=("write_path_semantic", "write_path_place", "write_path_sync",
|
||||
"write_path_linked"),
|
||||
),
|
||||
# Taking up a task: what is recorded in the task's own areas, named by id
|
||||
# in the reply that set it in progress. Notes for what is known there,
|
||||
# open issues for what is still wrong there.
|
||||
"work.start": Door(
|
||||
"work.start", "Taking up a piece of work", "when a task is set in progress",
|
||||
frozenset({"note", "task:issue"}),
|
||||
),
|
||||
}
|
||||
|
||||
@@ -138,6 +149,59 @@ def kinds_clause(kinds: Iterable[str]):
|
||||
return or_(*parts) if parts else false()
|
||||
|
||||
|
||||
# A pointer line names at most this many records of a kind; the count says
|
||||
# how many there were.
|
||||
POINTER_IDS = 3
|
||||
_PLURALS = {
|
||||
"snippet": "snippets", "note": "notes", "lesson": "lessons", "process": "processes",
|
||||
"task:issue": "issues", "task:work": "tasks", "task:spike": "spikes",
|
||||
"task:plan": "plans",
|
||||
}
|
||||
|
||||
|
||||
def opener(kind: str) -> str:
|
||||
"""The MCP call that opens a record of this kind."""
|
||||
if kind.startswith(TASK_PREFIX):
|
||||
return "get_task"
|
||||
return {"snippet": "get_snippet", "lesson": "get_lesson",
|
||||
"process": "get_process"}.get(kind, "get_note")
|
||||
|
||||
|
||||
def pointer_line(
|
||||
pointers: dict[str, list[int]], lead: str, *, capped_at: int | None = None,
|
||||
) -> tuple[str, list[int]] | None:
|
||||
"""One line naming records by id, per kind, with the call that opens each
|
||||
kind; and the ids it named. None when there is nothing to point at.
|
||||
|
||||
A line and a passage per record is what a payload cannot afford for
|
||||
everything that may bear on the work; an id costs a few characters, and
|
||||
the session is the one placed to judge whether to open it. A kind with
|
||||
more records than it names says how many; `capped_at` is the depth the
|
||||
lookup stopped at, so a count that reached it reads as "at least".
|
||||
"""
|
||||
named: list[int] = []
|
||||
phrases: list[str] = []
|
||||
for kind in KINDS:
|
||||
ids = pointers.get(kind) or []
|
||||
if not ids:
|
||||
continue
|
||||
shown = ids[:POINTER_IDS]
|
||||
named.extend(shown)
|
||||
count = ""
|
||||
if len(ids) > len(shown):
|
||||
count = f"{len(ids)}+ " if capped_at and len(ids) >= capped_at else f"{len(ids)} "
|
||||
phrases.append(
|
||||
f"{count}{_PLURALS[kind]} " + ", ".join(f"#{i}" for i in shown)
|
||||
+ f" (`{opener(kind)}(id)`)"
|
||||
)
|
||||
if not phrases:
|
||||
return None
|
||||
return (
|
||||
f"> {lead}: " + "; ".join(phrases) + ". Open one if it may bear on the work.",
|
||||
named,
|
||||
)
|
||||
|
||||
|
||||
async def _stored(user_id: int) -> dict[str, frozenset[str]]:
|
||||
from grimoire.services.settings import get_setting
|
||||
|
||||
@@ -194,6 +258,9 @@ async def table(user_id: int, days: int = 30) -> dict:
|
||||
"kinds": sorted(stored.get(d.key, d.default), key=KINDS.index),
|
||||
"default": sorted(d.default, key=KINDS.index),
|
||||
"changed": d.key in stored,
|
||||
# A door whose lines reach the session in a tool reply rather
|
||||
# than a plugin hook has no session to record them against.
|
||||
"measured": bool(d.sources),
|
||||
"evidence": (evidence or {}).get(d.key, {}),
|
||||
}
|
||||
for d in DOORS.values()
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Records linked to the work by structure: no score, no bar.
|
||||
|
||||
WHY THIS EXISTS
|
||||
|
||||
A search by meaning asks "what resembles the words of this edit", and the
|
||||
answer is often a record about something else that happens to read the same.
|
||||
A record that NAMES the file being edited, or is open in the area the file
|
||||
belongs to, needs no resemblance to be relevant: the link is the reason. So
|
||||
these lookups run first, their lines take the kind's place in the payload,
|
||||
and the search by meaning only fills what they left.
|
||||
|
||||
THE TWO LINKS, strongest first
|
||||
|
||||
- **Names this file** — an issue whose body, or one of whose logs, carries the
|
||||
file's repo-relative path. That is how a session records what it touched,
|
||||
so an issue that fixed something in this file says so in its own words.
|
||||
Any status: a closed issue is the record of what was already tried here.
|
||||
- **Open in this area** — an issue still open, tagged to an area (System)
|
||||
whose path patterns cover the file. A finished issue in the area is
|
||||
history the file may not share; an open one is live work on it.
|
||||
|
||||
Both are scoped to the project and to what the reader may read.
|
||||
|
||||
`area_records` answers the same question for a task being taken up: the
|
||||
records tagged to the task's own areas, which its reply names by id.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from sqlalchemy import exists, or_, select
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.note import Note
|
||||
from grimoire.models.system import RecordSystem
|
||||
from grimoire.models.task_log import TaskLog
|
||||
from grimoire.services.access import readable_notes_clause
|
||||
from grimoire.services.record_kinds import kind_of, kinds_clause
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
NAMES_FILE = "names this file"
|
||||
OPEN_IN_AREA = "open in this area"
|
||||
_CLOSED = ("done", "cancelled")
|
||||
|
||||
|
||||
def _issue(user_id: int, project_id: int):
|
||||
return (
|
||||
select(Note)
|
||||
.where(
|
||||
Note.project_id == project_id,
|
||||
Note.status.isnot(None),
|
||||
Note.task_kind == "issue",
|
||||
Note.deleted_at.is_(None),
|
||||
readable_notes_clause(user_id),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def issues_for_path(
|
||||
user_id: int, project_id: int, path: str, *, limit: int,
|
||||
exclude: set[int] | frozenset[int] = frozenset(),
|
||||
) -> list[tuple[str, Note]]:
|
||||
"""Issues linked to the file at `path`, each with the link that found it:
|
||||
those naming the file first, then those open in its area, most recently
|
||||
touched first within each, at most `limit` in all."""
|
||||
path = (path or "").strip()
|
||||
if not project_id or not path or limit <= 0:
|
||||
return []
|
||||
from grimoire.services.systems import systems_for_paths
|
||||
|
||||
out: list[tuple[str, Note]] = []
|
||||
taken = set(exclude)
|
||||
try:
|
||||
async with async_session() as session:
|
||||
# A literal path, not a pattern: `_` and `%` are common in file
|
||||
# names and would otherwise match any character.
|
||||
named = (await session.execute(
|
||||
_issue(user_id, project_id)
|
||||
.where(or_(
|
||||
Note.body.contains(path, autoescape=True),
|
||||
exists().where(
|
||||
TaskLog.task_id == Note.id,
|
||||
TaskLog.content.contains(path, autoescape=True),
|
||||
),
|
||||
))
|
||||
.order_by(Note.updated_at.desc(), Note.id.desc())
|
||||
.limit(limit + len(taken))
|
||||
)).scalars().all()
|
||||
for note in named:
|
||||
if int(note.id) not in taken and len(out) < limit:
|
||||
out.append((NAMES_FILE, note))
|
||||
taken.add(int(note.id))
|
||||
if len(out) >= limit:
|
||||
return out
|
||||
areas = [s.id for s, _hit in await systems_for_paths(user_id, project_id, [path])]
|
||||
if not areas:
|
||||
return out
|
||||
open_here = (await session.execute(
|
||||
_issue(user_id, project_id)
|
||||
.where(
|
||||
Note.status.not_in(_CLOSED),
|
||||
exists().where(
|
||||
RecordSystem.note_id == Note.id,
|
||||
RecordSystem.system_id.in_(areas),
|
||||
),
|
||||
)
|
||||
.order_by(Note.updated_at.desc(), Note.id.desc())
|
||||
.limit(limit + len(taken))
|
||||
)).scalars().all()
|
||||
for note in open_here:
|
||||
if int(note.id) not in taken and len(out) < limit:
|
||||
out.append((OPEN_IN_AREA, note))
|
||||
taken.add(int(note.id))
|
||||
except Exception: # noqa: BLE001 - a recall aid never breaks its act
|
||||
logger.warning("linked-issue lookup failed", exc_info=True)
|
||||
return out
|
||||
|
||||
|
||||
# How many records of a task's areas are counted for its pointer line; past
|
||||
# this the count reads "at least".
|
||||
AREA_DEPTH = 20
|
||||
|
||||
|
||||
async def area_records(
|
||||
user_id: int, record_id: int, kinds, *, depth: int = AREA_DEPTH,
|
||||
) -> dict[str, list[int]]:
|
||||
"""`{kind: [id, …]}` of the records sharing an area with `record_id`,
|
||||
newest first: of the given kinds, readable by this user, and, for tasks,
|
||||
still open. The record itself is left out."""
|
||||
kinds = list(kinds or ())
|
||||
if not record_id or not kinds:
|
||||
return {}
|
||||
try:
|
||||
async with async_session() as session:
|
||||
areas = select(RecordSystem.system_id).where(RecordSystem.note_id == record_id)
|
||||
rows = (await session.execute(
|
||||
select(Note.id, Note.note_type, Note.status, Note.task_kind)
|
||||
.where(
|
||||
Note.id != record_id,
|
||||
Note.deleted_at.is_(None),
|
||||
readable_notes_clause(user_id),
|
||||
kinds_clause(kinds),
|
||||
or_(Note.status.is_(None), Note.status.not_in(_CLOSED)),
|
||||
exists().where(
|
||||
RecordSystem.note_id == Note.id,
|
||||
RecordSystem.system_id.in_(areas),
|
||||
),
|
||||
)
|
||||
.order_by(Note.updated_at.desc(), Note.id.desc())
|
||||
.limit(depth)
|
||||
)).all()
|
||||
except Exception: # noqa: BLE001 - a decoration never breaks the payload
|
||||
logger.warning("area records lookup failed", exc_info=True)
|
||||
return {}
|
||||
out: dict[str, list[int]] = {}
|
||||
for nid, note_type, status, task_kind in rows:
|
||||
out.setdefault(kind_of(note_type, status, task_kind), []).append(int(nid))
|
||||
return out
|
||||
@@ -1274,6 +1274,12 @@ class NoteResult:
|
||||
slot_ids: dict = field(default_factory=dict)
|
||||
"""{slot source: the id it spent}."""
|
||||
|
||||
pointers: dict = field(default_factory=dict)
|
||||
"""{kind: [id, …]} — records the search found past the floor that the
|
||||
payload does not show (the gate held them back, or the budget had no
|
||||
room), best first. A door names them by id in one pointer line instead
|
||||
of spending a line and a passage on each."""
|
||||
|
||||
gate: Any = None
|
||||
"""The `cue_gate.Gate` this call's lines were held to, or None."""
|
||||
|
||||
@@ -1390,6 +1396,27 @@ async def _reserve_note_slot(
|
||||
return (menu + placed)[:budget], slot_id
|
||||
|
||||
|
||||
# How many results past the menu's own a notes arm fetches for its pointer
|
||||
# line. The line names at most a few per kind, so a deeper fetch would only
|
||||
# count records nobody is told the ids of.
|
||||
POINTER_DEPTH = 6
|
||||
|
||||
|
||||
def _pointers(answered: list, exclude) -> dict[str, list[int]]:
|
||||
"""{kind: ids} of the answered records not excluded, in rank order."""
|
||||
out: dict[str, list[int]] = {}
|
||||
for _s, note in answered:
|
||||
nid = int(note.id)
|
||||
if nid in exclude:
|
||||
continue
|
||||
kind = record_kinds.kind_of(
|
||||
getattr(note, "note_type", None), getattr(note, "status", None),
|
||||
getattr(note, "task_kind", None),
|
||||
)
|
||||
out.setdefault(kind, []).append(nid)
|
||||
return out
|
||||
|
||||
|
||||
async def run_note_arm(
|
||||
arm: NoteArm, moment: NoteMoment, *, floor: float, budget: int, io: NoteIO,
|
||||
) -> NoteResult:
|
||||
@@ -1417,8 +1444,9 @@ async def run_note_arm(
|
||||
scored = moment.in_menu & moment.still_scored
|
||||
kwargs: dict = {
|
||||
# The still-scored ids come back and are dropped below, so the
|
||||
# limit has to cover them.
|
||||
"limit": budget + len(scored), "threshold": floor,
|
||||
# limit has to cover them; POINTER_DEPTH more are fetched for the
|
||||
# pointer line, and never reach the menu or the call row.
|
||||
"limit": budget + len(scored) + POINTER_DEPTH, "threshold": floor,
|
||||
"project_id": moment.project_id or None,
|
||||
**note_search_filters(arm), "report": report,
|
||||
"record_kinds": record_kinds.search_kinds(allowed),
|
||||
@@ -1474,6 +1502,7 @@ async def run_note_arm(
|
||||
_telemetry_failed(source)
|
||||
result = NoteResult(
|
||||
answered=answered, chunks=report.get("best_chunk") or {}, gate=gate,
|
||||
pointers=_pointers(answered, moment.in_menu | moment.seen | moment.named),
|
||||
)
|
||||
if not hits:
|
||||
return result
|
||||
@@ -1507,6 +1536,12 @@ async def run_note_arm(
|
||||
# A named record is shown once, in its own block, never again as a match.
|
||||
menu = [(s, n) for s, n in menu if int(n.id) not in moment.named]
|
||||
result.menu = menu
|
||||
shown_here = {int(n.id) for _s, n in menu} | set(result.slot_ids.values())
|
||||
result.pointers = {
|
||||
k: [i for i in ids if i not in shown_here]
|
||||
for k, ids in result.pointers.items()
|
||||
}
|
||||
result.pointers = {k: ids for k, ids in result.pointers.items() if ids}
|
||||
|
||||
# What SURVIVED the band — the menu the reader saw — where the call
|
||||
# row holds the candidate set a floor is tuned against. FRESH ONLY,
|
||||
|
||||
@@ -181,6 +181,8 @@ POINTS: dict[str, Point] = dict([
|
||||
# the strongest possible claim, "there is already a canonical helper in
|
||||
# this exact file", be measured.
|
||||
_p("write_path_place", AMBIENT, "a snippet already placed in this very file"),
|
||||
_p("write_path_linked", AMBIENT,
|
||||
"an issue that names the file being written, or is open in its area"),
|
||||
_p("write_path_semantic", AMBIENT, "prior art matched by meaning"),
|
||||
_p("write_path_sync", AMBIENT,
|
||||
"records that should be updated alongside this edit"),
|
||||
@@ -230,7 +232,7 @@ FAN_OUT_SITES: dict[str, tuple[str, ...]] = {
|
||||
# The write path's two LOOKUPS. Its ranked arm (`write_path_semantic`)
|
||||
# records through the pipeline's site below.
|
||||
"grimoire/services/plugin_context.py::record_surfaced(source=arm)": (
|
||||
"write_path_place", "write_path_sync",
|
||||
"write_path_place", "write_path_sync", "write_path_linked",
|
||||
),
|
||||
"grimoire/services/system_rulings.py::record_system_surfaced(source=source)": (
|
||||
"rulings_pre_tool", "rulings_write_path",
|
||||
|
||||
@@ -11,7 +11,7 @@ sources that both stop at a proposal:
|
||||
nothing; a person confirms it (`judge`).
|
||||
- THE SIGNAL. A rule a session OPENS shortly after a moment fired is evidence
|
||||
it belongs on that moment. Recorded per distinct session with the evidence
|
||||
model lesson↔rule soft links use (lesson_rules: three situations, a
|
||||
model in lesson_rules (`add_evidence`, `proposal_due`: three situations, a
|
||||
cooldown), and once it crosses the bar the next open asks the reader to
|
||||
offer the mount (`co_occurred`).
|
||||
|
||||
|
||||
@@ -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},
|
||||
|
||||
+38
-1
@@ -221,7 +221,6 @@ def _no_lesson_rule_links(request):
|
||||
with patch("grimoire.services.lesson_rules.attach_lesson_rules", 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.co_surfaced", AsyncMock(return_value="")), \
|
||||
patch("grimoire.services.plugin_context._rules_via_lessons",
|
||||
AsyncMock(return_value=([], []))), \
|
||||
patch("grimoire.services.lesson_rules.convergence_for", AsyncMock(return_value=None)):
|
||||
@@ -388,6 +387,25 @@ def _default_record_kinds(request):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_linked_issues(request):
|
||||
"""Stub the structural lookups (`record_links`) to find nothing.
|
||||
|
||||
They read notes, task logs and areas, which a unit test of the write path
|
||||
or of `update_task` has not written; a test about them patches its own
|
||||
answer.
|
||||
The integration lane runs the real query.
|
||||
"""
|
||||
if request.node.get_closest_marker("integration"):
|
||||
yield
|
||||
return
|
||||
from grimoire.services import record_links
|
||||
|
||||
with patch.object(record_links, "issues_for_path", AsyncMock(return_value=[])), \
|
||||
patch.object(record_links, "area_records", AsyncMock(return_value={})):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _ungated_doors(request):
|
||||
"""Leave the plugin doors' cue-swap gate off unless a test asks for it.
|
||||
@@ -407,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
|
||||
|
||||
@@ -259,87 +259,42 @@ async def test_deleting_the_lesson_takes_its_answer_with_it(world):
|
||||
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:
|
||||
return (await s.execute(
|
||||
select(LessonRuleLink).where(
|
||||
LessonRuleLink.lesson_id == lesson_id, LessonRuleLink.rule_id == rule_id,
|
||||
)
|
||||
)).scalar_one_or_none()
|
||||
s.add(LessonRuleLink(lesson_id=lesson_id, rule_id=rule_id, state="suggested",
|
||||
evidence={"situations": ["p:1", "p:2", "p:3"]}))
|
||||
await s.commit()
|
||||
|
||||
|
||||
async def _arrive(world, prompt: str, project: int | None = None, rules=None) -> str:
|
||||
return await links_svc.co_surfaced(
|
||||
world["owner"], [world["lesson"]], rules or [world["r1"]],
|
||||
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"])
|
||||
async def test_a_suggested_link_is_in_no_read_and_leaves_the_lesson_unjudged(world):
|
||||
await _suggest(world["lesson"], world["r1"])
|
||||
await links_svc.judge_link(world["owner"], world["lesson"], world["r2"], "reject", "not this")
|
||||
rules = (await links_svc.rules_for_lessons(world["owner"], [world["lesson"]]))[world["lesson"]]
|
||||
assert rules[0]["state"] == "suggested"
|
||||
assert rules[0]["evidence"] == {"situations": 1, "projects": 1, "co_surfaced": 1}
|
||||
assert [(r["id"], r["state"]) for r in rules] == [(world["r2"], "rejected")]
|
||||
assert [x["id"] for x in await links_svc.lessons_for_rule(world["owner"], world["r1"])] == []
|
||||
assert (await _judgment(world["lesson"]))["rule_judgment"] == "unjudged"
|
||||
|
||||
|
||||
async def test_confirming_a_suggestion_keeps_what_it_rested_on(world):
|
||||
for prompt in ("first situation here", "second situation there", "third situation elsewhere"):
|
||||
await _arrive(world, prompt)
|
||||
async def test_confirming_a_suggested_pair_puts_it_in_the_rules_read(world):
|
||||
await _suggest(world["lesson"], world["r1"])
|
||||
out = await links_svc.judge_link(world["owner"], world["lesson"], world["r1"], "confirm", "same failure class")
|
||||
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 ────────────────────────────────────────────
|
||||
|
||||
|
||||
async def test_only_a_confirmed_link_can_carry_its_rule(world):
|
||||
"""A suggested link never expands: it would manufacture the co-arrival
|
||||
that co-surfacing counts, and prove itself. A rejected one obviously not."""
|
||||
"""A suggested link never carries its rule: nothing judged it. A rejected
|
||||
one obviously not."""
|
||||
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")
|
||||
assert await links_svc.confirmed_lessons(owner) == set()
|
||||
assert await links_svc.confirmed_rules_in_scope(owner, [lesson], world["mine"]) == {}
|
||||
|
||||
@@ -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,101 @@
|
||||
"""Real-Postgres tests for `record_links.issues_for_path`: an issue naming the
|
||||
file in its body or a log comes first; an open issue in the file's area comes
|
||||
next; a closed one there, another project's and a plain task are
|
||||
left out, as is everything for a reader without access; and a path is
|
||||
matched literally."""
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.note import Note
|
||||
from grimoire.models.project import Project
|
||||
from grimoire.models.system import RecordSystem, System
|
||||
from grimoire.models.task_log import TaskLog
|
||||
from grimoire.services import record_links
|
||||
from tests.helpers import ensure_user
|
||||
|
||||
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
|
||||
|
||||
PATH = "src/app/lock_guard.py"
|
||||
|
||||
|
||||
async def _world():
|
||||
async with async_session() as s:
|
||||
owner = await ensure_user(s, "record_links_owner")
|
||||
stranger = await ensure_user(s, "record_links_stranger")
|
||||
project = Project(user_id=owner.id, title="record links project")
|
||||
other = Project(user_id=owner.id, title="record links other")
|
||||
s.add_all([project, other])
|
||||
await s.flush()
|
||||
area = System(user_id=owner.id, project_id=project.id, name="locks",
|
||||
path_patterns=["src/app/**"])
|
||||
s.add(area)
|
||||
await s.flush()
|
||||
|
||||
def issue(title, status="done", body="", pid=project.id, uid=owner.id, kind="issue"):
|
||||
return Note(user_id=uid, project_id=pid, title=title, status=status,
|
||||
task_kind=kind, body=body)
|
||||
|
||||
made = {
|
||||
"in_body": issue("names it in its body", body=f"fixed in {PATH}"),
|
||||
"in_log": issue("names it in a log"),
|
||||
"open_area": issue("open in the area", status="todo"),
|
||||
"closed_area": issue("closed in the area"),
|
||||
"other_project": issue("other project", body=f"see {PATH}", pid=other.id),
|
||||
"work_task": issue("a work task naming it", body=f"edit {PATH}", kind="work"),
|
||||
# `_` is a single-character wildcard to LIKE; matched literally it
|
||||
# must not stand in for the `_` in the path.
|
||||
"near_miss": issue("a near miss", body="src/app/lockXguard.py"),
|
||||
}
|
||||
s.add_all(made.values())
|
||||
await s.flush()
|
||||
s.add(TaskLog(task_id=made["in_log"].id, user_id=owner.id, content=f"touched {PATH}"))
|
||||
s.add_all(RecordSystem(note_id=made[k].id, system_id=area.id)
|
||||
for k in ("open_area", "closed_area"))
|
||||
await s.commit()
|
||||
ids = {k: n.id for k, n in made.items()}
|
||||
return owner.id, project.id, ids, stranger.id
|
||||
|
||||
|
||||
async def test_issues_naming_the_file_come_first_then_open_ones_in_its_area():
|
||||
uid, pid, ids, _stranger = await _world()
|
||||
found = await record_links.issues_for_path(uid, pid, PATH, limit=5)
|
||||
got = [(link, int(n.id)) for link, n in found]
|
||||
named = {i for link, i in got if link == record_links.NAMES_FILE}
|
||||
assert named == {ids["in_body"], ids["in_log"]}
|
||||
assert got[:2] == [(link, i) for link, i in got if link == record_links.NAMES_FILE]
|
||||
assert (record_links.OPEN_IN_AREA, ids["open_area"]) in got
|
||||
left_out = {"closed_area", "other_project", "work_task", "near_miss"}
|
||||
assert not {ids[k] for k in left_out} & {i for _l, i in got}
|
||||
|
||||
|
||||
async def test_the_limit_and_the_exclusions_hold():
|
||||
uid, pid, ids, stranger = await _world()
|
||||
assert len(await record_links.issues_for_path(uid, pid, PATH, limit=1)) == 1
|
||||
found = await record_links.issues_for_path(
|
||||
uid, pid, PATH, limit=5, exclude={ids["in_body"], ids["in_log"]},
|
||||
)
|
||||
assert [int(n.id) for _l, n in found] == [ids["open_area"]]
|
||||
assert await record_links.issues_for_path(uid, 0, PATH, limit=5) == []
|
||||
# A reader who cannot read the project is shown none of its issues.
|
||||
assert await record_links.issues_for_path(stranger, pid, PATH, limit=5) == []
|
||||
|
||||
|
||||
async def test_a_tasks_areas_name_their_notes_and_open_issues_but_not_the_task_or_closed_work():
|
||||
uid, pid, ids, stranger = await _world()
|
||||
async with async_session() as s:
|
||||
area = (await s.execute(
|
||||
select(System.id).where(System.project_id == pid)
|
||||
)).scalar_one()
|
||||
task = Note(user_id=uid, project_id=pid, title="taking this up", status="in_progress",
|
||||
task_kind="work")
|
||||
note = Note(user_id=uid, project_id=pid, title="how locks work here", note_type="note")
|
||||
s.add_all([task, note])
|
||||
await s.flush()
|
||||
s.add_all(RecordSystem(note_id=n, system_id=area) for n in (task.id, note.id))
|
||||
await s.commit()
|
||||
task_id, note_id = task.id, note.id
|
||||
found = await record_links.area_records(uid, task_id, ["note", "task:issue"])
|
||||
assert found == {"note": [note_id], "task:issue": [ids["open_area"]]}
|
||||
assert await record_links.area_records(uid, task_id, ["note"]) == {"note": [note_id]}
|
||||
assert await record_links.area_records(stranger, task_id, ["note", "task:issue"]) == {}
|
||||
@@ -20,7 +20,6 @@ import inspect
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from grimoire.models.lesson_rule_link import LINK_STATES
|
||||
from grimoire.services import lesson_rules as links_svc
|
||||
from grimoire.services.access import PERMISSION_RANK
|
||||
|
||||
@@ -48,8 +47,8 @@ def test_the_client_judgment_union_is_the_services_three_answers():
|
||||
}
|
||||
|
||||
|
||||
def test_the_client_link_states_are_the_models():
|
||||
assert _union(_read("api/lessons.ts"), "LinkState") == set(LINK_STATES)
|
||||
def test_the_client_link_states_are_the_ones_a_read_returns():
|
||||
assert _union(_read("api/lessons.ts"), "LinkState") == set(links_svc.READ_STATES)
|
||||
|
||||
|
||||
def test_the_lesson_page_answers_all_three_judgments():
|
||||
|
||||
@@ -9,7 +9,6 @@ is tested against Postgres in tests/test_integration_lesson_rule_links.py.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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():
|
||||
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
|
||||
|
||||
@@ -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/**`"
|
||||
@@ -84,11 +84,11 @@ async def test_the_prompt_menu_looks_beyond_the_bound_project_for_a_lesson():
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_write_path_asks_for_lessons_at_all():
|
||||
"""The founding example of the kind is a lesson about a code shape, and
|
||||
this is the arm that fires when code is written. It is also the one note
|
||||
arm that filters kinds — so an omission here is not a ranking loss, it is
|
||||
a kind that can never appear."""
|
||||
async def test_the_write_path_leaves_lessons_to_their_situation():
|
||||
"""An edit's words resemble a lesson far more often than the edit is its
|
||||
situation, so the edit door's search by meaning leaves lessons out; a
|
||||
lesson reaches an edit through a situation confirmed for it
|
||||
(`lesson_situations`). The kinds the door does consider stay."""
|
||||
search = AsyncMock(return_value=[])
|
||||
with patch.object(pc, "get_writepath_config",
|
||||
AsyncMock(return_value=writepath_cfg(threshold=0.6))), \
|
||||
@@ -101,9 +101,7 @@ async def test_the_write_path_asks_for_lessons_at_all():
|
||||
await pc.build_write_path_hint(1, "src/ui/Badge.vue", code="x" * 400)
|
||||
|
||||
kw = search.await_args.kwargs
|
||||
assert LESSON_NOTE_TYPE in kw["record_kinds"]
|
||||
# The kinds it already carried must survive the addition — a set rewritten
|
||||
# rather than extended would trade one unreachable kind for another.
|
||||
assert LESSON_NOTE_TYPE not in kw["record_kinds"]
|
||||
assert {"snippet", "note"} <= set(kw["record_kinds"])
|
||||
assert kw["include_global_kinds"] is True
|
||||
|
||||
|
||||
@@ -154,9 +154,10 @@ async def test_this_responses_menu_is_withheld_but_a_pulled_one_is_still_scored(
|
||||
)
|
||||
(call,) = calls
|
||||
# The listed one never reaches the search; the pulled one does, and the
|
||||
# limit covers it so the menu still gets its full budget.
|
||||
# limit covers it so the menu still gets its full budget, plus the
|
||||
# pointer line's depth.
|
||||
assert call["exclude_ids"] == {listed}
|
||||
assert call["limit"] == 3
|
||||
assert call["limit"] == 3 + rp.POINTER_DEPTH
|
||||
assert [int(n.id) for _s, n in result.answered] == [pulled, 7]
|
||||
assert [int(n.id) for _s, n in result.menu] == [7]
|
||||
# Something was withheld after the search answered, so the score it
|
||||
@@ -280,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"]
|
||||
@@ -305,3 +306,37 @@ async def test_a_slot_whose_kind_the_door_turned_off_is_not_reserved():
|
||||
# The reuse slot narrows to processes; the lesson slot does not run.
|
||||
assert [c.get("note_type") for c in calls] == [None, ("process",)]
|
||||
assert "lesson_slot" not in result.slot_ids
|
||||
|
||||
|
||||
# ── the pointer: what cleared the floor and was not shown ─────────────────
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_what_the_menu_did_not_show_is_kept_for_the_pointer_by_kind():
|
||||
hits = [_note(1, 0.90), _note(2, 0.60), _note(3, 0.59, note_type="snippet"),
|
||||
_note(4, 0.58, is_task=True, task_kind="issue"), _note(5, 0.57)]
|
||||
result, _io_, _calls = await _run(
|
||||
rp.WRITE_PATH, lambda kw: hits, budget=3, seen=frozenset({5}),
|
||||
)
|
||||
on_menu = {int(n.id) for _s, n in result.menu}
|
||||
pointed = {i for ids in result.pointers.values() for i in ids}
|
||||
assert not on_menu & pointed
|
||||
# A record this session already has is not pointed at again.
|
||||
assert 5 not in pointed
|
||||
assert result.pointers.get("task:issue") == [4]
|
||||
|
||||
|
||||
def test_the_pointer_line_names_ids_per_kind_with_the_call_that_opens_them():
|
||||
from grimoire.services import record_kinds
|
||||
|
||||
line, ids = record_kinds.pointer_line(
|
||||
{"task:issue": [4, 8, 9, 12], "snippet": [3]}, "Also resembling this, not shown",
|
||||
)
|
||||
assert line == (
|
||||
"> Also resembling this, not shown: snippets #3 (`get_snippet(id)`); "
|
||||
"4 issues #4, #8, #9 (`get_task(id)`). Open one if it may bear on the work."
|
||||
)
|
||||
assert ids == [3, 4, 8, 9]
|
||||
assert record_kinds.pointer_line({}, "x") is None
|
||||
capped, _ = record_kinds.pointer_line({"note": list(range(1, 21))}, "x", capped_at=20)
|
||||
assert "20+ notes" in capped
|
||||
|
||||
@@ -43,7 +43,6 @@ async def _retrieve(query_string, turn_context="CORE SHAPE"):
|
||||
"shown_rule_ids": [11]})), \
|
||||
patch.object(routes.plugin_ctx_svc, "build_autoinject_hint",
|
||||
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):
|
||||
resp = await inspect.unwrap(routes.autoinject_retrieve)()
|
||||
return await resp.get_json(), turn
|
||||
|
||||
@@ -22,7 +22,7 @@ def test_backup_version_is_current():
|
||||
"""The bump is the point of the test — a payload section added without
|
||||
moving the version produces backups that are structurally different and
|
||||
indistinguishable by inspection."""
|
||||
assert backup.BACKUP_VERSION == 30
|
||||
assert backup.BACKUP_VERSION == 31
|
||||
|
||||
|
||||
def _exportable_note(**over):
|
||||
@@ -141,6 +141,7 @@ def _column_guard_targets():
|
||||
)
|
||||
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
|
||||
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
|
||||
from grimoire.models.lesson_situation import LessonSituation
|
||||
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
|
||||
from grimoire.models.rule_field_judgment import RuleFieldJudgment
|
||||
from grimoire.models.design_system import DesignSystem, DesignToken
|
||||
@@ -183,6 +184,7 @@ def _column_guard_targets():
|
||||
"rule_relations": (RuleRelation, backup._rule_relation_rows),
|
||||
"lesson_rule_links": (LessonRuleLink, backup._lesson_rule_link_rows),
|
||||
"lesson_no_rule": (LessonNoRule, backup._lesson_no_rule_rows),
|
||||
"lesson_situations": (LessonSituation, backup._lesson_situation_rows),
|
||||
"rule_moment_judgments": (RuleMomentJudgment, backup._rule_moment_judgment_rows),
|
||||
"rule_field_judgments": (RuleFieldJudgment, backup._rule_field_judgment_rows),
|
||||
"note_usage_events": (NoteUsageEvent, backup._usage_event_rows),
|
||||
@@ -315,6 +317,7 @@ def _import_guard_targets():
|
||||
"rule_relations": backup._build_rule_relation,
|
||||
"lesson_rule_links": backup._build_lesson_rule_link,
|
||||
"lesson_no_rule": backup._build_lesson_no_rule,
|
||||
"lesson_situations": backup._build_lesson_situation,
|
||||
"rule_moment_judgments": backup._build_rule_moment_judgment,
|
||||
"rule_field_judgments": backup._build_rule_field_judgment,
|
||||
"note_usage_events": backup._build_usage_event,
|
||||
@@ -595,6 +598,8 @@ async def test_export_full_backup_contains_every_declared_section():
|
||||
"rule_triggers",
|
||||
# v30: the weighed enforcement, salience and triggers.
|
||||
"rule_field_judgments",
|
||||
# v31: the moments and triggers each lesson arrives at.
|
||||
"lesson_situations",
|
||||
# v25: family canon.
|
||||
"platforms", "project_platforms", "family_ideas",
|
||||
"family_idea_platforms", "family_idea_references",
|
||||
|
||||
@@ -78,7 +78,9 @@ async def test_build_autoinject_hint_titles_only_with_margin_gate():
|
||||
# Margin gate kept the top two, dropped the straggler.
|
||||
assert out["note_ids"] == [11, 22]
|
||||
assert '#11 [note] "Pool sizing decision" (0.80)' in out["context"]
|
||||
assert "#33" not in out["context"]
|
||||
# Below the band: not given a line, but named by id in the pointer.
|
||||
assert '#33 [' not in out["context"]
|
||||
assert "not shown: notes #33 (`get_note(id)`)" in out["context"]
|
||||
# Title-first when the search reports no matched passage — which is this
|
||||
# test, whose mock returns bare (score, note) pairs and fills no report.
|
||||
# A record whose passage IS known gets it on a second line; that is
|
||||
@@ -485,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
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""The write path's structural issue arm: an issue that names the file being
|
||||
written, or is open in its area, is listed before anything found by meaning,
|
||||
withheld from that search, measured under its own source, and not looked for
|
||||
at all when the user's table turns issues off at this door."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from grimoire.services import record_kinds, record_links
|
||||
from tests.helpers import fake_note, fake_task
|
||||
from tests.test_write_path_trigger import REAL_CODE, _cfg
|
||||
|
||||
|
||||
async def _hint(linked, *, semantic=(), kinds=None, project_id=2):
|
||||
from grimoire.services import plugin_context as pc
|
||||
|
||||
search = AsyncMock(return_value=list(semantic))
|
||||
surfaced = MagicMock()
|
||||
lookup = AsyncMock(return_value=linked)
|
||||
patches = [
|
||||
patch.object(pc, "get_writepath_config", AsyncMock(return_value=_cfg())),
|
||||
patch.object(pc.snippets_svc, "list_snippets", AsyncMock(return_value=([], 0))),
|
||||
patch.object(pc, "semantic_search_notes", search),
|
||||
patch.object(pc, "record_retrieval", MagicMock()),
|
||||
patch.object(pc, "record_surfaced", surfaced),
|
||||
patch.object(pc, "owner_names_for", AsyncMock(return_value={})),
|
||||
patch.object(record_links, "issues_for_path", lookup),
|
||||
]
|
||||
if kinds is not None:
|
||||
patches.append(patch.object(record_kinds, "kinds_for", AsyncMock(return_value=kinds)))
|
||||
for p in patches:
|
||||
p.start()
|
||||
try:
|
||||
out = await pc.build_write_path_hint(1, "src/x.py", code=REAL_CODE, project_id=project_id)
|
||||
finally:
|
||||
for p in reversed(patches):
|
||||
p.stop()
|
||||
return out, search, surfaced, lookup
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_linked_issue_is_listed_before_meaning_and_withheld_from_it():
|
||||
issue = fake_task(id=41, title="the lock leaked in x.py", task_kind="issue", status="done",
|
||||
user_id=1, note_type="note", data=None)
|
||||
similar = (0.90, fake_note(id=7, title="a snippet like it", note_type="snippet", user_id=1))
|
||||
out, search, surfaced, lookup = await _hint(
|
||||
[(record_links.NAMES_FILE, issue)], semantic=[similar],
|
||||
)
|
||||
lines = [ln for ln in out["context"].splitlines() if ln.startswith("> - #")]
|
||||
assert lines[0].startswith('> - #41 [names this file · issue (done)]')
|
||||
assert lookup.await_args.args[:3] == (1, 2, "src/x.py")
|
||||
# The search by meaning is told the linked issue is already listed.
|
||||
assert 41 in search.await_args.kwargs["exclude_ids"]
|
||||
by_source = {c.kwargs["source"]: c.kwargs["note_ids"] for c in surfaced.call_args_list}
|
||||
assert by_source["write_path_linked"] == [41]
|
||||
assert "write_path_place" not in by_source
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_issue_is_looked_up_when_the_door_turned_issues_off():
|
||||
_out, _search, _surfaced, lookup = await _hint(
|
||||
[], kinds=frozenset({"snippet", "note", "lesson"}),
|
||||
)
|
||||
lookup.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_issue_is_looked_up_without_a_project():
|
||||
_out, _search, _surfaced, lookup = await _hint([], project_id=0)
|
||||
lookup.assert_not_awaited()
|
||||
@@ -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"
|
||||
|
||||
@@ -271,7 +271,9 @@ async def test_margin_gate_applies_to_the_semantic_arm():
|
||||
patch.object(pc, "owner_names_for", AsyncMock(return_value={})):
|
||||
out = await pc.build_write_path_hint(1, "src/x.py", code=REAL_CODE)
|
||||
assert out["note_ids"] == [11, 22]
|
||||
assert "#33" not in out["context"]
|
||||
# Past the margin: no line of its own, only its id in the pointer.
|
||||
assert "#33 [" not in out["context"]
|
||||
assert "not shown: snippets #33 (`get_snippet(id)`)" in out["context"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -327,7 +329,8 @@ async def test_semantic_arm_only_asks_for_the_budget_the_place_arm_left():
|
||||
patch.object(pc, "semantic_search_notes", search), \
|
||||
patch.object(pc, "record_retrieval", MagicMock()):
|
||||
await pc.build_write_path_hint(1, "src/x.py", code=REAL_CODE)
|
||||
assert search.await_args.kwargs["limit"] == 2
|
||||
from grimoire.services.retrieval_pipeline import POINTER_DEPTH
|
||||
assert search.await_args.kwargs["limit"] == 2 + POINTER_DEPTH
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1322,7 +1325,8 @@ async def test_a_pulled_snippet_already_seen_is_evidence_not_menu():
|
||||
# nothing is dropped between the search and the menu.
|
||||
kw = search.call_args.kwargs
|
||||
assert 7 not in kw["exclude_ids"]
|
||||
assert kw["limit"] == 3
|
||||
from grimoire.services.retrieval_pipeline import POINTER_DEPTH
|
||||
assert kw["limit"] == 3 + POINTER_DEPTH
|
||||
# ...and the menu carries it, marked.
|
||||
seven = next(line for line in out["context"].splitlines() if "#7" in line)
|
||||
assert "seen" in seven
|
||||
|
||||
Reference in New Issue
Block a user