Merge pull request 'Milestone 639 step 2: typed rules, one delivery order, per-delivery records, triggers, lifecycle' (#224) from dev into main
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m58s
CI & Build / integration (push) Successful in 2m14s
CI & Build / Build & push image (push) Successful in 23s

This commit was merged in pull request #224.
This commit is contained in:
2026-11-22 18:51:03 -05:00
38 changed files with 2258 additions and 69 deletions
+48
View File
@@ -0,0 +1,48 @@
"""rule enforcement and salience — what a rule does when it arrives, and how much it outranks
Revision ID: 0128
Revises: 0127
Create Date: 2026-11-22
Two declared columns on a rule, read by the one function that orders what
reaches a moment:
- `enforcement`: `enforce` (the act itself is checked), `hold` (the reply or act
waits for one read), `inform` (a line beside the work). Every existing rule
starts as `inform`; declaring which ones hold is the author's call.
- `salience`: `high`, `normal`, `low` — the author's ranking among rules of
the same enforcement.
"""
import sqlalchemy as sa
from alembic import op
revision = "0128"
down_revision = "0127"
branch_labels = None
depends_on = None
_ENFORCEMENTS = ("enforce", "hold", "inform")
_SALIENCES = ("high", "normal", "low")
def _in_list(column: str, values: tuple[str, ...]) -> str:
return f"{column} IN ({', '.join(repr(v) for v in values)})"
def upgrade() -> None:
op.add_column("rules", sa.Column("enforcement", sa.Text(), nullable=False, server_default="inform"))
op.add_column("rules", sa.Column("salience", sa.Text(), nullable=False, server_default="normal"))
op.create_check_constraint("ck_rules_enforcement", "rules", _in_list("enforcement", _ENFORCEMENTS))
op.create_check_constraint("ck_rules_salience", "rules", _in_list("salience", _SALIENCES))
# A preference claims no force: it is how work is liked done, not a bar.
op.create_check_constraint(
"ck_rules_preference_informs", "rules", "kind <> 'preference' OR enforcement = 'inform'",
)
def downgrade() -> None:
op.drop_constraint("ck_rules_preference_informs", "rules", type_="check")
op.drop_constraint("ck_rules_salience", "rules", type_="check")
op.drop_constraint("ck_rules_enforcement", "rules", type_="check")
op.drop_column("rules", "salience")
op.drop_column("rules", "enforcement")
+42
View File
@@ -0,0 +1,42 @@
"""rule deliveries — each rule line a session was shown, and whether it was opened after
Revision ID: 0129
Revises: 0128
Create Date: 2026-11-22
One row per rule line delivered to a session, with the open stamped on the
delivery it followed. The open rate per rule and moment is read from it, both
for the ordering of what reaches a moment and for the adherence readout.
"""
import sqlalchemy as sa
from alembic import op
revision = "0129"
down_revision = "0128"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"rule_deliveries",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("user_id", sa.BigInteger(), nullable=False),
sa.Column("session_id", sa.Text(), nullable=False),
sa.Column("rule_id", sa.BigInteger(), nullable=False),
sa.Column("source", sa.Text(), nullable=False),
sa.Column("at", sa.Text(), nullable=False),
sa.Column("form", sa.Text(), nullable=False),
sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.Column("opened_at", sa.DateTime(timezone=True), nullable=True),
sa.CheckConstraint("form IN ('full', 'repeat')", name="ck_rule_deliveries_form"),
)
op.create_index("ix_rule_deliveries_session_rule", "rule_deliveries",
["user_id", "session_id", "rule_id", "delivered_at"])
op.create_index("ix_rule_deliveries_rule_at", "rule_deliveries", ["rule_id", "at"])
op.create_index("ix_rule_deliveries_delivered_at", "rule_deliveries", ["delivered_at"])
def downgrade() -> None:
op.drop_table("rule_deliveries")
+38
View File
@@ -0,0 +1,38 @@
"""rule triggers — typed predicates on the act that deliver a rule, checked in code
Revision ID: 0130
Revises: 0129
Create Date: 2026-11-22
A trigger is a kind (tool, path, command, keyword) and a pattern, optionally
scoped to a moment. Unscoped, it delivers the rule on any act that matches;
scoped, it makes the rule's mount on that moment conditional on the act
matching. Matched in code against the act, never by embedding.
"""
import sqlalchemy as sa
from alembic import op
revision = "0130"
down_revision = "0129"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"rule_triggers",
sa.Column("rule_id", sa.BigInteger(),
sa.ForeignKey("rules.id", ondelete="CASCADE"), primary_key=True),
sa.Column("kind", sa.Text(), primary_key=True),
sa.Column("pattern", sa.Text(), primary_key=True),
sa.Column("moment", sa.Text(), primary_key=True, server_default=""),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=True),
sa.CheckConstraint(
"kind IN ('tool', 'path', 'command', 'keyword')", name="ck_rule_triggers_kind",
),
sa.CheckConstraint("length(pattern) > 0", name="ck_rule_triggers_pattern"),
)
def downgrade() -> None:
op.drop_table("rule_triggers")
+32
View File
@@ -54,6 +54,26 @@ export interface RulebookTopic {
*/ */
export type RuleKind = "rule" | "preference"; export type RuleKind = "rule" | "preference";
/**
* What a rule does when it arrives, declared by its author. `inform` puts a
* line beside the work; `hold` makes the reply or act it governs wait for one
* read; `enforce` checks the act itself. A preference is always `inform`.
*/
export type RuleEnforcement = "enforce" | "hold" | "inform";
/** How a rule ranks among rules of the same enforcement at a crowded moment. */
export type RuleSalience = "high" | "normal" | "low";
/** What a trigger is matched against on the act: the tool called, a path it
* touches, the head of a command it runs, or a word in what it writes. */
export type RuleTriggerKind = "tool" | "path" | "command" | "keyword";
/** A typed predicate on the act, checked exactly. With no `moment` it
* delivers the rule on any matching act; with one, it makes the rule's
* mount on that moment conditional on the act matching. */
export interface RuleTrigger {
kind: RuleTriggerKind;
pattern: string;
moment?: string;
}
/** A new record opened from somewhere that already knows what it is for — /** A new record opened from somewhere that already knows what it is for —
* "Adjust this" on a reply shape opens a preference mounted on that shape's * "Adjust this" on a reply shape opens a preference mounted on that shape's
* moment. The editor applies it once, when creating. */ * moment. The editor applies it once, when creating. */
@@ -70,6 +90,8 @@ export interface Rule {
title: string; title: string;
statement: string; statement: string;
kind: RuleKind; kind: RuleKind;
enforcement: RuleEnforcement;
salience: RuleSalience;
/** WHEN this rule fires — the trigger, not the instruction. */ /** WHEN this rule fires — the trigger, not the instruction. */
when_to_apply: string; when_to_apply: string;
why: string; why: string;
@@ -94,6 +116,8 @@ export interface Rule {
/** The moments this rule arrives at whenever they happen, /** The moments this rule arrives at whenever they happen,
* in catalog order. Present only when the rule is mounted. */ * in catalog order. Present only when the rule is mounted. */
moments?: string[]; moments?: string[];
/** Present only when the rule has triggers. */
triggers?: RuleTrigger[];
relations?: RuleRelation[]; relations?: RuleRelation[];
/** The lessons that point at this rule — the concrete /** The lessons that point at this rule — the concrete
* situations judged instances of it, plus any suggested and awaiting a * situations judged instances of it, plus any suggested and awaiting a
@@ -113,6 +137,10 @@ export interface RuleHeader {
topic_id: number | null; topic_id: number | null;
/** Unconditional on the wire (services.rulebooks.rule_brief). */ /** Unconditional on the wire (services.rulebooks.rule_brief). */
kind: RuleKind; kind: RuleKind;
/** Unconditional on the wire, like `kind`. */
enforcement: RuleEnforcement;
/** Present only when raised or lowered from `normal`. */
salience?: RuleSalience;
/** A date (YYYY-MM-DD), not a timestamp. */ /** A date (YYYY-MM-DD), not a timestamp. */
updated_at: string | null; updated_at: string | null;
when_to_apply?: string; when_to_apply?: string;
@@ -217,6 +245,8 @@ export interface RuleWrite {
/** Writable from the editor: a preference is not a lesser rule, it is a /** Writable from the editor: a preference is not a lesser rule, it is a
* different force, and the person writing it is the one who knows which. */ * different force, and the person writing it is the one who knows which. */
kind: RuleKind; kind: RuleKind;
enforcement: RuleEnforcement;
salience: RuleSalience;
when_to_apply: string; when_to_apply: string;
why: string; why: string;
how_to_apply: string; how_to_apply: string;
@@ -224,6 +254,8 @@ export interface RuleWrite {
system_ids: number[]; system_ids: number[];
/** Replaces the set; [] unmounts the rule from every moment. */ /** Replaces the set; [] unmounts the rule from every moment. */
moments: string[]; moments: string[];
/** Replaces the set; [] clears every trigger. */
triggers: RuleTrigger[];
arose_from_id: number | null; arose_from_id: number | null;
verify_with: string; verify_with: string;
expires_when: string; expires_when: string;
@@ -6,7 +6,11 @@ import { useMomentsStore } from "@/stores/moments";
import RuleHistoryPanel from "@/components/rules/RuleHistoryPanel.vue"; import RuleHistoryPanel from "@/components/rules/RuleHistoryPanel.vue";
import RuleHomePicker from "@/components/rules/RuleHomePicker.vue"; import RuleHomePicker from "@/components/rules/RuleHomePicker.vue";
import { apiErrorMessage } from "@/api/client"; import { apiErrorMessage } from "@/api/client";
import { listRulebooks, listTopics, type Rule, type RuleKind, type RulePreset } from "@/api/rulebooks"; import {
listRulebooks, listTopics,
type Rule, type RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience,
type RuleTrigger, type RuleTriggerKind,
} from "@/api/rulebooks";
const props = defineProps<{ const props = defineProps<{
ruleId: number | null; ruleId: number | null;
@@ -26,6 +30,14 @@ const whenToApply = ref("");
// followed too faithfully, where a rule mislabelled as a preference is one a // followed too faithfully, where a rule mislabelled as a preference is one a
// session may quietly rewrite. // session may quietly rewrite.
const kind = ref<RuleKind>("rule"); const kind = ref<RuleKind>("rule");
// The server's defaults: a line beside the work, at normal rank.
const enforcement = ref<RuleEnforcement>("inform");
const salience = ref<RuleSalience>("normal");
// A preference carries no force but `inform`, and the server refuses any
// other, so switching kind settles it here rather than as a failed save.
watch(kind, (k) => {
if (k === "preference") enforcement.value = "inform";
});
const systemIds = ref<number[]>([]); const systemIds = ref<number[]>([]);
// The moments this rule is mounted on. Catalog moments are // The moments this rule is mounted on. Catalog moments are
// ticked; a named procedure's moment (`skill.<name>`) is typed, since its // ticked; a named procedure's moment (`skill.<name>`) is typed, since its
@@ -39,6 +51,44 @@ const momentCatalog = computed(() => momentsStore.data?.moments ?? []);
const procedureMoments = computed(() => const procedureMoments = computed(() =>
ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)), ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)),
); );
// The acts this rule is triggered by, checked exactly on the server.
const triggers = ref<RuleTrigger[]>([]);
const triggerKind = ref<RuleTriggerKind>("path");
const triggerPattern = ref("");
const triggerMoment = ref("");
const triggerError = ref("");
const TRIGGER_KINDS: { value: RuleTriggerKind; label: string; placeholder: string }[] = [
{ value: "path", label: "Path", placeholder: "alembic/versions/*.py — a file the act touches" },
{ value: "command", label: "Command", placeholder: "git push — the head of a command it runs" },
{ value: "tool", label: "Tool", placeholder: "update_task — the tool it calls" },
{ value: "keyword", label: "Keyword", placeholder: "migration — a word in what it writes" },
];
const triggerPlaceholder = computed(
() => TRIGGER_KINDS.find((k) => k.value === triggerKind.value)?.placeholder ?? "",
);
function triggerLabel(t: RuleTrigger) {
return TRIGGER_KINDS.find((k) => k.value === t.kind)?.label ?? t.kind;
}
function addTrigger() {
const pattern = triggerPattern.value.trim().replace(/\s+/g, " ");
if (!pattern) return;
const moment = triggerMoment.value || undefined;
const same = (t: RuleTrigger) =>
t.kind === triggerKind.value && t.pattern === pattern && (t.moment ?? "") === (moment ?? "");
if (triggers.value.some(same)) {
triggerError.value = "This rule already has that trigger.";
return;
}
triggerError.value = "";
triggers.value.push({ kind: triggerKind.value, pattern, ...(moment ? { moment } : {}) });
triggerPattern.value = "";
}
function removeTrigger(at: number) {
triggers.value.splice(at, 1);
}
const why = ref(""); const why = ref("");
const howToApply = ref(""); const howToApply = ref("");
const verifyWith = ref(""); const verifyWith = ref("");
@@ -123,8 +173,11 @@ async function load() {
statement.value = r.statement; statement.value = r.statement;
whenToApply.value = r.when_to_apply || ""; whenToApply.value = r.when_to_apply || "";
kind.value = r.kind; kind.value = r.kind;
enforcement.value = r.enforcement ?? "inform";
salience.value = r.salience ?? "normal";
systemIds.value = (r.systems ?? []).map((sys) => sys.id); systemIds.value = (r.systems ?? []).map((sys) => sys.id);
ruleMoments.value = [...(r.moments ?? [])]; ruleMoments.value = [...(r.moments ?? [])];
triggers.value = (r.triggers ?? []).map((t) => ({ ...t }));
why.value = r.why || ""; why.value = r.why || "";
howToApply.value = r.how_to_apply || ""; howToApply.value = r.how_to_apply || "";
verifyWith.value = r.verify_with || ""; verifyWith.value = r.verify_with || "";
@@ -135,8 +188,11 @@ async function load() {
statement.value = ""; statement.value = "";
whenToApply.value = props.preset?.whenToApply ?? ""; whenToApply.value = props.preset?.whenToApply ?? "";
kind.value = props.preset?.kind ?? "rule"; kind.value = props.preset?.kind ?? "rule";
enforcement.value = "inform";
salience.value = "normal";
systemIds.value = []; systemIds.value = [];
ruleMoments.value = [...(props.preset?.moments ?? [])]; ruleMoments.value = [...(props.preset?.moments ?? [])];
triggers.value = [];
why.value = ""; why.value = "";
howToApply.value = ""; howToApply.value = "";
verifyWith.value = ""; verifyWith.value = "";
@@ -144,6 +200,9 @@ async function load() {
} }
procedureDraft.value = ""; procedureDraft.value = "";
procedureError.value = ""; procedureError.value = "";
triggerPattern.value = "";
triggerMoment.value = "";
triggerError.value = "";
await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]); await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]);
} }
@@ -181,12 +240,16 @@ async function save() {
statement: statement.value, statement: statement.value,
when_to_apply: whenToApply.value, when_to_apply: whenToApply.value,
kind: kind.value, kind: kind.value,
enforcement: enforcement.value,
salience: salience.value,
// Always sent, so clearing the last area actually clears it — the server // Always sent, so clearing the last area actually clears it — the server
// reads a list as "these ARE the areas now". // reads a list as "these ARE the areas now".
system_ids: systemIds.value, system_ids: systemIds.value,
// Always sent, for system_ids' reason: the server reads the list as the // Always sent, for system_ids' reason: the server reads the list as the
// whole set, so unticking the last moment actually unmounts the rule. // whole set, so unticking the last moment actually unmounts the rule.
moments: ruleMoments.value, moments: ruleMoments.value,
// Always sent, for the same reason: the list is the whole set.
triggers: triggers.value,
why: why.value, why: why.value,
how_to_apply: howToApply.value, how_to_apply: howToApply.value,
// Always sent, including empty. The REST door maps "" to NULL, so // Always sent, including empty. The REST door maps "" to NULL, so
@@ -271,6 +334,38 @@ watch(() => props.ruleId, load);
preference. preference.
</p> </p>
</fieldset> </fieldset>
<fieldset class="kind arrival">
<legend>When it arrives</legend>
<template v-if="kind === 'rule'">
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="inform" />
<span><strong>Inform</strong> — a line beside the work. Most rules.</span>
</label>
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="hold" />
<span>
<strong>Hold</strong> — the reply or act it governs waits for one
read of it. For a rule whose miss costs a rewrite.
</span>
</label>
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="enforce" />
<span>
<strong>Enforce</strong> — the act itself is checked. For a hard
boundary.
</span>
</label>
</template>
<p v-else class="field-note">A preference arrives as a line beside the work.</p>
<label class="salience">
Rank among the rest
<select v-model="salience" class="fs-input">
<option value="high">High — shown first when a moment is crowded</option>
<option value="normal">Normal</option>
<option value="low">Low — the first to give way</option>
</select>
</label>
</fieldset>
<p v-if="kind === 'preference'" class="kind-drift"> <p v-if="kind === 'preference'" class="kind-drift">
Sessions rewrite preferences without asking, which is what makes them Sessions rewrite preferences without asking, which is what makes them
stay current. Every rewrite is kept, and stay current. Every rewrite is kept, and
@@ -342,6 +437,55 @@ watch(() => props.ruleId, load);
<p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p> <p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p>
</fieldset> </fieldset>
<fieldset class="moments triggers">
<legend>Acts that trigger it</legend>
<p class="field-note intro">
Matched exactly against what the work does, not by resemblance: a
path it touches, a command it runs, a tool it calls, a word in what it
writes. With no moment, the rule arrives on any act that matches.
With a moment, it arrives at that moment only when the act matches,
so a rule about migrations can sit where files change without arriving
at every edit.
</p>
<ul v-if="triggers.length" class="trigger-list">
<li v-for="(t, i) in triggers" :key="`${t.kind}:${t.pattern}:${t.moment ?? ''}`" class="rule-chip trigger-chip">
<span class="trigger-kind">{{ triggerLabel(t) }}</span>
<code>{{ t.pattern }}</code>
<span v-if="t.moment" class="trigger-at">at <code>{{ t.moment }}</code></span>
<button
type="button"
class="chip-remove"
:aria-label="`Remove the ${triggerLabel(t).toLowerCase()} trigger ${t.pattern}`"
@click="removeTrigger(i)"
>×</button>
</li>
</ul>
<p v-else class="field-note">No triggers: this rule arrives by its moments and by resemblance.</p>
<div class="trigger-add">
<select v-model="triggerKind" class="fs-input" aria-label="What the trigger matches">
<option v-for="k in TRIGGER_KINDS" :key="k.value" :value="k.value">{{ k.label }}</option>
</select>
<input
v-model="triggerPattern"
class="fs-input"
aria-label="The pattern the act must match"
:placeholder="triggerPlaceholder"
@keydown.enter.prevent="addTrigger"
/>
<select v-model="triggerMoment" class="fs-input" aria-label="Only at this moment">
<option value="">Any act</option>
<option v-for="m in momentCatalog" :key="m.name" :value="m.name">Only at {{ m.name }}</option>
</select>
<button
type="button"
class="btn-secondary btn-sm"
:disabled="!triggerPattern.trim()"
@click="addTrigger"
>Add</button>
</div>
<p v-if="triggerError" class="trigger-warning">{{ triggerError }}</p>
</fieldset>
<fieldset v-if="canon.catalog.length" class="areas"> <fieldset v-if="canon.catalog.length" class="areas">
<legend>Areas this rule is about</legend> <legend>Areas this rule is about</legend>
<label v-for="entry in canon.catalog" :key="entry.id" class="area-opt"> <label v-for="entry in canon.catalog" :key="entry.id" class="area-opt">
@@ -520,6 +664,13 @@ legend { padding: 0 0.35rem; font-size: 0.8rem; color: var(--fs-text-tertiary);
.procedure-add { display: flex; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); } .procedure-add { display: flex; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
.procedure-add input { margin-top: 0; } .procedure-add input { margin-top: 0; }
.procedure-add .btn-sm { flex: none; } .procedure-add .btn-sm { flex: none; }
.trigger-list { list-style: none; padding: 0; margin: 0 0 var(--fs-space-2); display: flex; flex-wrap: wrap; gap: var(--fs-space-2); }
.trigger-chip { display: inline-flex; align-items: center; gap: var(--fs-space-1); }
.trigger-kind, .trigger-at { color: var(--fs-text-secondary); font-size: var(--fs-size-tiny); }
.trigger-add { display: flex; flex-wrap: wrap; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
.trigger-add input { flex: 1 1 14rem; margin-top: 0; }
.trigger-add select { flex: none; width: auto; margin-top: 0; }
.trigger-add .btn-sm { flex: none; }
/* --fs-warning-fg, not --fs-warning: the token set draws the distinction /* --fs-warning-fg, not --fs-warning: the token set draws the distinction
between the warning HUE and warning text, and this is text. */ between the warning HUE and warning text, and this is text. */
.trigger-warning { .trigger-warning {
@@ -27,6 +27,15 @@ const emit = defineEmits<{
class="rule-chip rule-chip-preference" class="rule-chip rule-chip-preference"
title="How you want work done. It does not bind, and Grimoire updates it as the work teaches it." title="How you want work done. It does not bind, and Grimoire updates it as the work teaches it."
>preference</span> >preference</span>
<!-- Marked only when the rule stops the work: a line beside the work
is the default, and marking it on every row would mark nothing. -->
<span
v-if="r.enforcement === 'hold' || r.enforcement === 'enforce'"
class="rule-chip"
:title="r.enforcement === 'hold'
? 'The reply or act it governs waits for one read of it'
: 'The act it governs is checked against it'"
>{{ r.enforcement === "hold" ? "holds" : "enforced" }}</span>
<!-- Marked only when something is WRONG: every rule arrives by <!-- Marked only when something is WRONG: every rule arrives by
retrieval now, so "conditional" stopped distinguishing anything. retrieval now, so "conditional" stopped distinguishing anything.
A missing trigger does — it means nothing can retrieve this. --> A missing trigger does — it means nothing can retrieve this. -->
+3
View File
@@ -111,6 +111,9 @@ export const useRulebooksStore = defineStore("rulebooks", () => {
// force as the same row re-fetched, or a preference the operator just // force as the same row re-fetched, or a preference the operator just
// created would sit in the list looking like a rule until a reload. // created would sit in the list looking like a rule until a reload.
kind: rule.kind, kind: rule.kind,
enforcement: rule.enforcement ?? "inform",
// Mirrors rule_brief: present only when raised or lowered.
salience: rule.salience && rule.salience !== "normal" ? rule.salience : undefined,
updated_at: rule.updated_at, updated_at: rule.updated_at,
when_to_apply: rule.when_to_apply || undefined, when_to_apply: rule.when_to_apply || undefined,
arose_from_id: rule.arose_from_id ?? undefined, arose_from_id: rule.arose_from_id ?? undefined,
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "grimoire", "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).", "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.05.0301", "version": "2026.11.22.2312",
"author": { "author": {
"name": "Bryan Van Deusen" "name": "Bryan Van Deusen"
}, },
+2
View File
@@ -125,6 +125,8 @@ if [ -n "$session_id" ]; then
[ -n "$rule_seen" ] && exclude_q="${exclude_q}&exclude_rule_ids=${rule_seen}" [ -n "$rule_seen" ] && exclude_q="${exclude_q}&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown. # What the session actually OPENED, as against what it was shown.
exclude_q="${exclude_q}$(grimoire_held_query "$rule_state_dir/${safe_sid}.opened.ids")" exclude_q="${exclude_q}$(grimoire_held_query "$rule_state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
exclude_q="${exclude_q}&session_id=${safe_sid}"
# Which reply shapes it already holds in full: the core is # Which reply shapes it already holds in full: the core is
# sent whole once, and as its one-line reminder on every later turn. # sent whole once, and as its one-line reminder on every later turn.
shapefile=$(grimoire_shapes_file "$safe_sid") shapefile=$(grimoire_shapes_file "$safe_sid")
+2
View File
@@ -240,6 +240,8 @@ if [ -n "$session_id" ]; then
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}" [ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown. # What the session actually OPENED, as against what it was shown.
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")" rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
rule_exclude_q="${rule_exclude_q}&session_id=${safe_sid}"
fi fi
# Not `|| exit 0`: an unreachable instance must not discard a local finding # Not `|| exit 0`: an unreachable instance must not discard a local finding
+20 -13
View File
@@ -79,23 +79,30 @@ printf '%s\n' "$rule_id" | grimoire_rules_append "$state_dir/${safe_sid}.opened.
# answers with one line putting the question to the reader. Nothing is # answers with one line putting the question to the reader. Nothing is
# mounted by this. # mounted by this.
# #
# An open of a rule a hook has just NAMED is not reported. A ranked arm or a # EVERY OPEN IS REPORTED: the server stamps it on this session's latest
# moment line put it in front of the reader, and that explains the open; the # delivery of the rule, which is how an open rate per delivery is measured.
# moment beside it did not, so counting it would propose mounts on whatever #
# moment happened to fire while search was surfacing the rule. The window is # The acts go with it only when the rule was NOT just named by a hook. A
# short for the same reason: a few minutes of agent work reaches many moments. # ranked arm or a moment line put a named rule in front of the reader, and
# that explains the open; the moment beside it did not, so counting it would
# propose mounts on whatever moment happened to fire while search was
# surfacing the rule. The window is short for the same reason: a few minutes
# of agent work reaches many moments.
command -v curl >/dev/null 2>&1 || exit 0 command -v curl >/dev/null 2>&1 || exit 0
grimoire_config || exit 0 grimoire_config || exit 0
acts=""
case ",$(grimoire_rules_live "$state_dir/${safe_sid}.rules.ids")," in case ",$(grimoire_rules_live "$state_dir/${safe_sid}.rules.ids")," in
*",${rule_id},"*) exit 0 ;; *",${rule_id},"*) ;;
*)
acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts"
now=$(date +%s 2>/dev/null) || now=0
if [ -f "$acts_file" ] && [ "$now" -gt 0 ]; then
acts=$(awk -F '\t' -v since=$((now - 90)) \
'$1 + 0 >= since { sub(/^[^\t]*\t/, ""); print }' "$acts_file" 2>/dev/null \
| tail -n 3 | paste -sd ',' - 2>/dev/null)
fi
;;
esac esac
acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts"
[ -f "$acts_file" ] || exit 0
now=$(date +%s 2>/dev/null) || exit 0
acts=$(awk -F '\t' -v since=$((now - 90)) \
'$1 + 0 >= since { sub(/^[^\t]*\t/, ""); print }' "$acts_file" 2>/dev/null \
| tail -n 3 | paste -sd ',' - 2>/dev/null)
[ -n "$acts" ] || exit 0
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0 sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd') event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
+2
View File
@@ -101,6 +101,8 @@ if [ -n "$session_id" ]; then
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}" [ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown. # What the session actually OPENED, as against what it was shown.
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")" rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
rule_exclude_q="${rule_exclude_q}&session_id=${safe_sid}"
# The Systems whose rulings were shown in full — shared with the write-path # The Systems whose rulings were shown in full — shared with the write-path
# hook, for the reason the rule file is. # hook, for the reason the rule file is.
rulingsfile="$state_dir/${safe_sid}.rulings.ids" rulingsfile="$state_dir/${safe_sid}.rulings.ids"
+3
View File
@@ -198,9 +198,12 @@ def create_app() -> Quart:
from grimoire.services.logging import start_log_retention_loop from grimoire.services.logging import start_log_retention_loop
from grimoire.services.notifications import start_notification_loop from grimoire.services.notifications import start_notification_loop
from grimoire.services.rule_deliveries import start_prune_loop as start_rule_delivery_prune
start_log_retention_loop() start_log_retention_loop()
start_notification_loop() start_notification_loop()
start_auth_token_retention_loop() start_auth_token_retention_loop()
start_rule_delivery_prune()
# The proxy hop count saved in Settings decides every request's client # The proxy hop count saved in Settings decides every request's client
# address, so it is loaded before serving, under a deadline (a failed # address, so it is loaded before serving, under a deadline (a failed
+117 -6
View File
@@ -15,6 +15,7 @@ from datetime import datetime, timedelta, timezone
from grimoire.mcp._context import current_user_id from grimoire.mcp._context import current_user_id
from grimoire.services import dedup as dedup_svc from grimoire.services import dedup as dedup_svc
from grimoire.services import moments as moments_svc from grimoire.services import moments as moments_svc
from grimoire.services import rule_triggers as rule_triggers_svc
from grimoire.services import rulebooks as rulebooks_svc from grimoire.services import rulebooks as rulebooks_svc
from grimoire.services import trash as trash_svc from grimoire.services import trash as trash_svc
from grimoire.services.lesson_rules import confirmed_lesson_counts from grimoire.services.lesson_rules import confirmed_lesson_counts
@@ -342,6 +343,8 @@ async def create_rule(
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "", arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
system_ids: list[int] | None = None, system_ids: list[int] | None = None,
moments: list[str] | None = None, force: bool = False, moments: list[str] | None = None, force: bool = False,
enforcement: str = "inform", salience: str = "normal",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Create a new rule in a rulebook (a SHARED rule — keep it general). """Create a new rule in a rulebook (a SHARED rule — keep it general).
@@ -530,6 +533,25 @@ async def create_rule(
constraint expires when the ground under it moves, not on a constraint expires when the ground under it moves, not on a
schedule. Pairs with verify_with; both empty is the normal case. schedule. Pairs with verify_with; both empty is the normal case.
order_index: Display order within the topic (default 0). order_index: Display order within the topic (default 0).
enforcement: What this rule does when it arrives. `inform` (the
default) puts a line beside the work. `hold` makes the reply or
act it governs wait for one read of it — for a rule whose miss
costs a rewrite. `enforce` checks the act itself — for a hard
boundary. Declare hold or enforce on purpose; most rules inform.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. By default, a title-identical rule force: Bypass the near-duplicate gate. By default, a title-identical rule
already in this topic BLOCKS creation and returns its id so you update already in this topic BLOCKS creation and returns its id so you update
it instead. Set true only for a genuinely distinct rule. A rule or it instead. Set true only for a genuinely distinct rule. A rule or
@@ -539,6 +561,7 @@ async def create_rule(
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
if not force: if not force:
dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id) dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id)
if dup is not None: if dup is not None:
@@ -553,8 +576,9 @@ async def create_rule(
arose_from_id=arose_from_id, arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index, why=why, how_to_apply=how_to_apply, order_index=order_index,
verify_with=verify_with, expires_when=expires_when, verify_with=verify_with, expires_when=expires_when,
enforcement=enforcement, salience=salience,
) )
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
data.update(dedup_svc.overlap_response(overlaps, "rule")) data.update(dedup_svc.overlap_response(overlaps, "rule"))
return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data) return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data)
@@ -565,6 +589,8 @@ async def create_project_rule(
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "", arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
system_ids: list[int] | None = None, system_ids: list[int] | None = None,
moments: list[str] | None = None, force: bool = False, moments: list[str] | None = None, force: bool = False,
enforcement: str = "inform", salience: str = "normal",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Create a rule scoped to a single project (no rulebook needed). """Create a rule scoped to a single project (no rulebook needed).
@@ -640,6 +666,25 @@ async def create_project_rule(
expires_when: The state under which the rule stops being true — see expires_when: The state under which the rule stops being true — see
create_rule. A state, not a date. create_rule. A state, not a date.
order_index: Display order within the project's rule list (default 0). order_index: Display order within the project's rule list (default 0).
enforcement: What this rule does when it arrives. `inform` (the
default) puts a line beside the work. `hold` makes the reply or
act it governs wait for one read of it — for a rule whose miss
costs a rewrite. `enforce` checks the act itself — for a hard
boundary. Declare hold or enforce on purpose; most rules inform.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. By default, a title-identical rule force: Bypass the near-duplicate gate. By default, a title-identical rule
already on this project BLOCKS creation and returns its id so you already on this project BLOCKS creation and returns its id so you
update it instead. Set true only for a genuinely distinct rule. An update it instead. Set true only for a genuinely distinct rule. An
@@ -648,6 +693,7 @@ async def create_project_rule(
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
derived_title = title.strip() or statement.strip().split(".")[0][:50] derived_title = title.strip() or statement.strip().split(".")[0][:50]
if not force: if not force:
dup = await dedup_svc.find_duplicate_rule(derived_title, project_id=project_id) dup = await dedup_svc.find_duplicate_rule(derived_title, project_id=project_id)
@@ -662,8 +708,9 @@ async def create_project_rule(
arose_from_id=arose_from_id, arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index, why=why, how_to_apply=how_to_apply, order_index=order_index,
verify_with=verify_with, expires_when=expires_when, verify_with=verify_with, expires_when=expires_when,
enforcement=enforcement, salience=salience,
) )
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
data.update(dedup_svc.overlap_response(overlaps, "rule")) data.update(dedup_svc.overlap_response(overlaps, "rule"))
return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data) return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data)
@@ -675,6 +722,8 @@ async def update_rule(
moments: list[str] | None = None, arose_from_id: int = 0, moments: list[str] | None = None, arose_from_id: int = 0,
verify_with: str = "", expires_when: str = "", kind: str = "", verify_with: str = "", expires_when: str = "", kind: str = "",
clear_fields: list[str] | None = None, clear_fields: list[str] | None = None,
enforcement: str = "", salience: str = "",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Update a rule. Empty strings / order_index=-1 leave fields unchanged. """Update a rule. Empty strings / order_index=-1 leave fields unchanged.
@@ -735,9 +784,30 @@ async def update_rule(
expires_when: The state under which the rule stops being true. A expires_when: The state under which the rule stops being true. A
state, not a date. See create_rule. state, not a date. See create_rule.
clear_fields: Names of fields to empty, as above. clear_fields: Names of fields to empty, as above.
enforcement: What this rule does when it arrives. `inform` (the
default for a new rule) puts a line beside the work. `hold` makes the reply or
act it governs wait for one read of it — for a rule whose miss
costs a rewrite. `enforce` checks the act itself — for a hard
boundary. Declare hold or enforce on purpose; most rules inform.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
Omit either to leave it unchanged.
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
fields: dict = {} fields: dict = {}
if title: if title:
fields["title"] = title fields["title"] = title
@@ -759,12 +829,16 @@ async def update_rule(
fields["expires_when"] = expires_when fields["expires_when"] = expires_when
if order_index >= 0: if order_index >= 0:
fields["order_index"] = order_index fields["order_index"] = order_index
if enforcement:
fields["enforcement"] = enforcement
if salience:
fields["salience"] = salience
rule = await rulebooks_svc.update_rule( rule = await rulebooks_svc.update_rule(
rule_id, uid, clear=clear_fields or (), **fields, rule_id, uid, clear=clear_fields or (), **fields,
) )
if rule is None: if rule is None:
raise ValueError(f"rule {rule_id} not found") raise ValueError(f"rule {rule_id} not found")
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
# ── Preferences ───────────────────────────────────────────────────────── # ── Preferences ─────────────────────────────────────────────────────────
@@ -786,7 +860,8 @@ async def create_preference(
arose_from_id: int, why: str = "", how_to_apply: str = "", arose_from_id: int, why: str = "", how_to_apply: str = "",
order_index: int = 0, system_ids: list[int] | None = None, order_index: int = 0, system_ids: list[int] | None = None,
moments: list[str] | None = None, moments: list[str] | None = None,
force: bool = False, force: bool = False, salience: str = "normal",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Record how the operator wants work done. No approval loop — write it. """Record how the operator wants work done. No approval loop — write it.
@@ -860,6 +935,20 @@ async def create_preference(
done rather than what it is about: a rule on when work counts as done rather than what it is about: a rule on when work counts as
finished belongs at work.finish and reply.report, where nothing finished belongs at work.finish and reply.report, where nothing
said resembles it. Replaces the set; [] clears it. said resembles it. Replaces the set; [] clears it.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. For a genuinely distinct force: Bypass the near-duplicate gate. For a genuinely distinct
preference, not for one that is "mostly" different — a mostly preference, not for one that is "mostly" different — a mostly
different preference is an update. A RULE that already answers different preference is an update. A RULE that already answers
@@ -869,6 +958,7 @@ async def create_preference(
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
if not when_to_apply.strip(): if not when_to_apply.strip():
raise ValueError( raise ValueError(
"when_to_apply is required: a preference with no trigger never " "when_to_apply is required: a preference with no trigger never "
@@ -893,8 +983,9 @@ async def create_preference(
title=title, statement=statement, when_to_apply=when_to_apply, title=title, statement=statement, when_to_apply=when_to_apply,
kind="preference", arose_from_id=arose_from_id, kind="preference", arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index, why=why, how_to_apply=how_to_apply, order_index=order_index,
salience=salience,
) )
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
data.update(dedup_svc.overlap_response(overlaps, "preference")) data.update(dedup_svc.overlap_response(overlaps, "preference"))
return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data) return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data)
@@ -905,6 +996,8 @@ async def update_preference(
how_to_apply: str = "", order_index: int = -1, how_to_apply: str = "", order_index: int = -1,
system_ids: list[int] | None = None, system_ids: list[int] | None = None,
moments: list[str] | None = None, clear_fields: list[str] | None = None, moments: list[str] | None = None, clear_fields: list[str] | None = None,
salience: str = "",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Bring a preference up to date. Doing this mid-work is expected. """Bring a preference up to date. Doing this mid-work is expected.
@@ -959,9 +1052,25 @@ async def update_preference(
moments: Replaces the moments this preference arrives at (see moments: Replaces the moments this preference arrives at (see
create_preference); omit to leave them alone. create_preference); omit to leave them alone.
when_to_apply: The moment it applies, in session vocabulary. See above. when_to_apply: The moment it applies, in session vocabulary. See above.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
Omit to leave it unchanged.
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
if not arose_from_id: if not arose_from_id:
raise ValueError( raise ValueError(
"arose_from_id is required: this edit is the record of how the " "arose_from_id is required: this edit is the record of how the "
@@ -981,12 +1090,14 @@ async def update_preference(
fields["how_to_apply"] = how_to_apply fields["how_to_apply"] = how_to_apply
if order_index >= 0: if order_index >= 0:
fields["order_index"] = order_index fields["order_index"] = order_index
if salience:
fields["salience"] = salience
rule = await rulebooks_svc.update_rule( rule = await rulebooks_svc.update_rule(
rule_id, uid, clear=clear_fields or (), **fields, rule_id, uid, clear=clear_fields or (), **fields,
) )
if rule is None: if rule is None:
raise ValueError(f"rule {rule_id} not found") raise ValueError(f"rule {rule_id} not found")
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
async def rule_history(rule_id: int, version_id: int = 0) -> dict: async def rule_history(rule_id: int, version_id: int = 0) -> dict:
+1
View File
@@ -60,6 +60,7 @@ from grimoire.models.retrieval_log import RetrievalLog # noqa: E402, F401
from grimoire.models.retrieval_tuning import RetrievalTuningEvent # noqa: E402, F401 from grimoire.models.retrieval_tuning import RetrievalTuningEvent # noqa: E402, F401
from grimoire.models.note_usage import NoteUsageEvent # noqa: E402, F401 from grimoire.models.note_usage import NoteUsageEvent # noqa: E402, F401
from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401 from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401
from grimoire.models.rule_delivery import RuleDelivery # noqa: E402, F401
from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401 from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401
from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401 from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401
from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401 from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401
+69
View File
@@ -0,0 +1,69 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, Index, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import iso
FULL = "full"
REPEAT = "repeat"
FORMS = (FULL, REPEAT)
class RuleDelivery(Base):
"""One rule line put in front of one session, and whether it was opened after.
WHAT IT ANSWERS that `rule_usage_events` cannot. A surfaced event and a
pulled event are counted separately, so "was THIS delivery opened" has no
answer there: a rule opened once in a session reads as pulled whether it
was delivered once or twenty times. Here each delivery is a row, and the
open is stamped on the delivery it followed — so the open rate per rule,
per moment and per arm is a count of rows, and the ordering function reads
it as the rule's history at that moment.
`at` is where the rule was delivered: the moment it was mounted on
(`work.finish`) or the arm that found it (`pre_tool_rule`). `form` is
whether the line carried the rule's trigger (`full`) or only cited it
(`repeat`). Repeats are recorded too: they are deliveries a session can
open, and the case for retiring a rule rests on how rarely they are.
FK-free on `rule_id` and `user_id`, like the other telemetry tables: the
evidence that a rule was delivered forty times and opened never outlives
the rule, because it is the case for having deleted it.
"""
__tablename__ = "rule_deliveries"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
session_id: Mapped[str] = mapped_column(Text, nullable=False)
rule_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
source: Mapped[str] = mapped_column(Text, nullable=False)
at: Mapped[str] = mapped_column(Text, nullable=False)
form: Mapped[str] = mapped_column(Text, nullable=False)
delivered_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
__table_args__ = (
# Stamping an open: this session's latest delivery of this rule.
Index("ix_rule_deliveries_session_rule", "user_id", "session_id", "rule_id", "delivered_at"),
# History: a batch of rules at one moment.
Index("ix_rule_deliveries_rule_at", "rule_id", "at"),
Index("ix_rule_deliveries_delivered_at", "delivered_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"user_id": self.user_id,
"session_id": self.session_id,
"rule_id": self.rule_id,
"source": self.source,
"at": self.at,
"form": self.form,
"delivered_at": iso(self.delivered_at),
"opened_at": iso(self.opened_at),
}
+27
View File
@@ -116,6 +116,15 @@ class Rule(Base, TimestampMixin, SoftDeleteMixin):
# Defaults to `rule` so nothing changes force on upgrade. # Defaults to `rule` so nothing changes force on upgrade.
# CHECK ck_rules_kind (migration 0098). # CHECK ck_rules_kind (migration 0098).
kind: Mapped[str] = mapped_column(Text, default="rule", server_default="rule") kind: Mapped[str] = mapped_column(Text, default="rule", server_default="rule")
# WHAT THE RULE DOES WHEN IT ARRIVES, declared by its author rather than
# guessed from a score. `enforce`: the act it governs is checked. `hold`:
# the reply or act waits for one read of it. `inform`: a line beside the
# work, and never a stop. A preference is always `inform` (CHECK
# ck_rules_preference_informs). CHECK ck_rules_enforcement (migration 0128).
enforcement: Mapped[str] = mapped_column(Text, default="inform", server_default="inform")
# How this rule ranks among rules of the same enforcement when a moment has more
# to say than fits: `high`, `normal`, `low`. CHECK ck_rules_salience.
salience: Mapped[str] = mapped_column(Text, default="normal", server_default="normal")
why: Mapped[str | None] = mapped_column(Text, nullable=True) why: Mapped[str | None] = mapped_column(Text, nullable=True)
how_to_apply: Mapped[str | None] = mapped_column(Text, nullable=True) how_to_apply: Mapped[str | None] = mapped_column(Text, nullable=True)
# The three fields that tell a CONSTRAINT apart from a NORM (milestone # The three fields that tell a CONSTRAINT apart from a NORM (milestone
@@ -161,6 +170,8 @@ class Rule(Base, TimestampMixin, SoftDeleteMixin):
# codebase keeps re-encountering. Twenty bytes buys an answer that # codebase keeps re-encountering. Twenty bytes buys an answer that
# cannot be misread. # cannot be misread.
"kind": self.kind or "rule", "kind": self.kind or "rule",
"enforcement": self.enforcement or "inform",
"salience": self.salience or "normal",
"why": self.why or "", "why": self.why or "",
"how_to_apply": self.how_to_apply or "", "how_to_apply": self.how_to_apply or "",
"verify_with": self.verify_with or "", "verify_with": self.verify_with or "",
@@ -200,6 +211,22 @@ rule_moments = Table(
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)), Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
) )
# What a rule is TRIGGERED by: a typed predicate on the act itself — the tool
# called, a path it touches, the head of a command it runs, or a word in what
# it writes — checked in code with no embedding (`services/rule_triggers.py`).
# `moment` empty means the trigger fires on any act that matches it; a moment
# name makes the rule's mount on that moment conditional on the act matching.
rule_triggers = Table(
"rule_triggers",
Base.metadata,
Column("rule_id", BigInteger, ForeignKey("rules.id", ondelete="CASCADE"), primary_key=True),
Column("kind", Text, primary_key=True),
Column("pattern", Text, primary_key=True),
Column("moment", Text, primary_key=True, default="", server_default=""),
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
)
class RuleRelation(Base, CreatedAtMixin): class RuleRelation(Base, CreatedAtMixin):
"""A typed edge between two rules. Each kind exists because without it a """A typed edge between two rules. Each kind exists because without it a
rulebook needs a workaround. rulebook needs a workaround.
+27 -2
View File
@@ -20,6 +20,7 @@ from grimoire.services import plugin_context as plugin_ctx_svc
from grimoire.services import reply_shapes as reply_shapes_svc from grimoire.services import reply_shapes as reply_shapes_svc
from grimoire.services import repo_bindings as repo_bindings_svc from grimoire.services import repo_bindings as repo_bindings_svc
from grimoire.services import report_check as report_check_svc from grimoire.services import report_check as report_check_svc
from grimoire.services import rule_deliveries as rule_deliveries_svc
from grimoire.services import rule_moment_judgments as judgments_svc from grimoire.services import rule_moment_judgments as judgments_svc
from grimoire.services import shape_check as shape_check_svc from grimoire.services import shape_check as shape_check_svc
from grimoire.services import task_claims as task_claims_svc from grimoire.services import task_claims as task_claims_svc
@@ -36,6 +37,22 @@ plugin_bp = Blueprint("plugin", __name__, url_prefix="/api/plugin")
_MARKETPLACE_KEY = "plugin_marketplace_url" _MARKETPLACE_KEY = "plugin_marketplace_url"
@plugin_bp.before_request
async def _bind_delivery_session() -> None:
"""Bind the session this request delivers to, for the delivery record.
A hook names it as `session_id` in the query, or carries it in the event
it posts (`/moment` sends the PreToolUse event whole). A request that
names none records no deliveries and reads no delivery history.
"""
sid = request.args.get("session_id") or ""
if not sid and request.method == "POST":
body = await request.get_json(silent=True)
if isinstance(body, dict):
sid = str(body.get("session_id") or "")
rule_deliveries_svc.bind_session(sid)
def _int_list(raw: str | None) -> list[int]: def _int_list(raw: str | None) -> list[int]:
"""A comma-separated id list from the query string; non-ints dropped.""" """A comma-separated id list from the query string; non-ints dropped."""
return [int(p) for p in (raw or "").split(",") if p.strip().isdigit()] return [int(p) for p in (raw or "").split(",") if p.strip().isdigit()]
@@ -336,7 +353,10 @@ async def rule_opened():
"""A session opened a rule shortly after these acts. """A session opened a rule shortly after these acts.
Body: `{"rule_id", "session_id", "acts": [<PreToolUse event>, ...]}` — Body: `{"rule_id", "session_id", "acts": [<PreToolUse event>, ...]}` —
the calls the plugin saw in the window before the `get_rule`. Each is the calls the plugin saw in the window before the `get_rule`. Every open
is first stamped on this session's latest delivery of the rule, which is
how the open rate per delivery is measured; `acts` is empty when the
rule was one a hook had just named, which explains the open by itself. Each is
resolved to its moments, and the open is counted as evidence that the resolved to its moments, and the open is counted as evidence that the
rule belongs on them; once a pair has repeated across enough distinct rule belongs on them; once a pair has repeated across enough distinct
sessions, `context` carries the line asking the reader to offer the sessions, `context` carries the line asking the reader to offer the
@@ -349,8 +369,13 @@ async def rule_opened():
rule_id = int(data.get("rule_id") or 0) rule_id = int(data.get("rule_id") or 0)
except (TypeError, ValueError): except (TypeError, ValueError):
rule_id = 0 rule_id = 0
if rule_id > 0:
# The open, against the delivery it followed — whatever the acts say.
await rule_deliveries_svc.mark_opened(
g.user.id, str(data.get("session_id") or ""), rule_id,
)
acts = data.get("acts") acts = data.get("acts")
if rule_id <= 0 or not isinstance(acts, list): if rule_id <= 0 or not isinstance(acts, list) or not acts:
return jsonify({"moments": [], "context": ""}) return jsonify({"moments": [], "context": ""})
project_id, _repo, _unbound = await _project_scope() project_id, _repo, _unbound = await _project_scope()
return jsonify(await judgments_svc.opened_after( return jsonify(await judgments_svc.opened_after(
+50 -5
View File
@@ -18,6 +18,18 @@ from grimoire.services.rule_usage import (
rulebooks_bp = Blueprint("rulebooks", __name__, url_prefix="/api") rulebooks_bp = Blueprint("rulebooks", __name__, url_prefix="/api")
def _declared_or_refusal(data: dict):
"""The request's enforcement and salience, validated before any write, so
a bad value is a 400 naming the choices rather than a half-made rule."""
try:
return (
rulebooks_svc.require_enforcement(data.get("enforcement"), data.get("kind")),
rulebooks_svc.require_salience(data.get("salience")),
), None
except ValueError as exc:
return None, (jsonify({"error": str(exc)}), 400)
def _moments_or_refusal(data: dict): def _moments_or_refusal(data: dict):
"""The request's `moments`, validated BEFORE any write — so an unknown """The request's `moments`, validated BEFORE any write — so an unknown
name is a 400 and not a rule created without the mounts it asked for. name is a 400 and not a rule created without the mounts it asked for.
@@ -28,6 +40,17 @@ def _moments_or_refusal(data: dict):
return None, (jsonify({"error": str(exc)}), 400) return None, (jsonify({"error": str(exc)}), 400)
def _triggers_or_refusal(data: dict):
"""The request's `triggers`, validated before any write, as `moments` is.
Absent means "leave them alone" (None)."""
from grimoire.services.rule_triggers import require_triggers
try:
return require_triggers(data.get("triggers")), None
except ValueError as exc:
return None, (jsonify({"error": str(exc)}), 400)
# ── Rulebooks ─────────────────────────────────────────────────────────── # ── Rulebooks ───────────────────────────────────────────────────────────
@rulebooks_bp.get("/rulebooks") @rulebooks_bp.get("/rulebooks")
@@ -184,6 +207,13 @@ async def create_rule(topic_id: int):
moments, refused = _moments_or_refusal(data) moments, refused = _moments_or_refusal(data)
if refused: if refused:
return refused return refused
triggers, refused = _triggers_or_refusal(data)
if refused:
return refused
declared, refused = _declared_or_refusal(data)
if refused:
return refused
enforcement, salience = declared
try: try:
rule = await rulebooks_svc.create_rule( rule = await rulebooks_svc.create_rule(
topic_id=topic_id, topic_id=topic_id,
@@ -202,11 +232,12 @@ async def create_rule(topic_id: int):
arose_from_id=data.get("arose_from_id", 0) or 0, arose_from_id=data.get("arose_from_id", 0) or 0,
verify_with=data.get("verify_with", ""), verify_with=data.get("verify_with", ""),
expires_when=data.get("expires_when", ""), expires_when=data.get("expires_when", ""),
enforcement=enforcement, salience=salience,
) )
except ValueError as exc: except ValueError as exc:
return jsonify({"error": str(exc)}), 404 return jsonify({"error": str(exc)}), 404
return jsonify(await rulebooks_svc.rule_detail( return jsonify(await rulebooks_svc.rule_detail(
get_current_user_id(), rule, data.get("system_ids"), moments, get_current_user_id(), rule, data.get("system_ids"), moments, triggers=triggers,
)), 201 )), 201
@@ -234,7 +265,7 @@ async def update_rule(rule_id: int):
k: v for k, v in data.items() k: v for k, v in data.items()
if k in ("title", "statement", "why", "how_to_apply", "order_index", if k in ("title", "statement", "why", "how_to_apply", "order_index",
"when_to_apply", "kind", "arose_from_id", "when_to_apply", "kind", "arose_from_id",
"verify_with", "expires_when") "verify_with", "expires_when", "enforcement", "salience")
} }
# No clear_fields here: a form sends "" for an emptied input, and the # No clear_fields here: a form sends "" for an emptied input, and the
# service normalises "" to NULL for every nullable text column. The MCP # service normalises "" to NULL for every nullable text column. The MCP
@@ -243,11 +274,17 @@ async def update_rule(rule_id: int):
moments, refused = _moments_or_refusal(data) moments, refused = _moments_or_refusal(data)
if refused: if refused:
return refused return refused
rule = await rulebooks_svc.update_rule(rule_id, uid, **fields) triggers, refused = _triggers_or_refusal(data)
if refused:
return refused
try:
rule = await rulebooks_svc.update_rule(rule_id, uid, **fields)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
if rule is None: if rule is None:
return jsonify({"error": "rule not found"}), 404 return jsonify({"error": "rule not found"}), 404
return jsonify(await rulebooks_svc.rule_detail( return jsonify(await rulebooks_svc.rule_detail(
uid, rule, data.get("system_ids"), moments, uid, rule, data.get("system_ids"), moments, triggers=triggers,
)) ))
@@ -425,6 +462,13 @@ async def create_project_rule(project_id: int):
moments, refused = _moments_or_refusal(data) moments, refused = _moments_or_refusal(data)
if refused: if refused:
return refused return refused
triggers, refused = _triggers_or_refusal(data)
if refused:
return refused
declared, refused = _declared_or_refusal(data)
if refused:
return refused
enforcement, salience = declared
try: try:
rule = await rulebooks_svc.create_project_rule( rule = await rulebooks_svc.create_project_rule(
project_id=project_id, project_id=project_id,
@@ -443,11 +487,12 @@ async def create_project_rule(project_id: int):
arose_from_id=data.get("arose_from_id", 0) or 0, arose_from_id=data.get("arose_from_id", 0) or 0,
verify_with=data.get("verify_with", ""), verify_with=data.get("verify_with", ""),
expires_when=data.get("expires_when", ""), expires_when=data.get("expires_when", ""),
enforcement=enforcement, salience=salience,
) )
except ValueError as exc: except ValueError as exc:
return jsonify({"error": str(exc)}), 404 return jsonify({"error": str(exc)}), 404
return jsonify(await rulebooks_svc.rule_detail( return jsonify(await rulebooks_svc.rule_detail(
get_current_user_id(), rule, data.get("system_ids"), moments, get_current_user_id(), rule, data.get("system_ids"), moments, triggers=triggers,
)), 201 )), 201
+54 -1
View File
@@ -23,6 +23,7 @@ from grimoire.models.family import (
) )
from grimoire.models.rulebook import ( from grimoire.models.rulebook import (
RuleRelation, rule_moments as rule_moments_t, rule_systems as rule_systems_t, RuleRelation, rule_moments as rule_moments_t, rule_systems as rule_systems_t,
rule_triggers as rule_triggers_t,
) )
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
from grimoire.models.rule_moment_judgment import RuleMomentJudgment from grimoire.models.rule_moment_judgment import RuleMomentJudgment
@@ -113,7 +114,9 @@ logger = logging.getLogger(__name__)
# section still restore — the key is simply not read. # section still restore — the key is simply not read.
# v28 instance_id in the header: the id lineage of the store the backup came # v28 instance_id in the header: the id lineage of the store the backup came
# from. A live instance rolls back only to a backup with its own id. # from. A live instance rolls back only to a backup with its own id.
BACKUP_VERSION = 28 # v29 rule_triggers: the typed predicates on the act that deliver a rule or
# make its mount conditional. Nothing in the rule's text records them.
BACKUP_VERSION = 29
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED # 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 # below, these two lists must together account for the entire schema — which is
@@ -158,6 +161,7 @@ _BACKED_UP = [
"moment_mappings", "moment_mappings",
"rule_moments", "rule_moments",
"rule_moment_judgments", "rule_moment_judgments",
"rule_triggers",
# Family canon. `platforms` is global like # Family canon. `platforms` is global like
# canonical_systems and rides every export for the same reason: the rows # canonical_systems and rides every export for the same reason: the rows
# below name platforms by slug, and a partial catalog restores partial # below name platforms by slug, and a partial catalog restores partial
@@ -183,6 +187,10 @@ _NOT_INCLUDED = [
"app_logs", "notifications", "app_logs", "notifications",
"invitation_tokens", "password_reset_tokens", "invitation_tokens", "password_reset_tokens",
"retrieval_logs", "retrieval_logs",
# Per-session delivery rows, keyed by session ids that mean nothing on
# another instance and pruned after months anyway. The ordering reads
# them as history; a restored instance rebuilds it within weeks.
"rule_deliveries",
# Verdicts on retrieval_logs rows, so they go where their subject # Verdicts on retrieval_logs rows, so they go where their subject
# goes: a restore that carried a judgment of a call it did not carry would # goes: a restore that carried a judgment of a call it did not carry would
# leave a verdict on nothing. A sample, re-takeable by the review pass. # leave a verdict on nothing. A sample, re-takeable by the review pass.
@@ -798,6 +806,15 @@ def _rule_moment_rows(rows) -> list[dict]:
return [{"rule_id": rule_id, "moment": moment} for rule_id, moment in rows] return [{"rule_id": rule_id, "moment": moment} for rule_id, moment in rows]
def _rule_trigger_rows(rows) -> list[dict]:
"""A rule's triggers. Kind, pattern and moment mean the same on every
install, so only the rule id needs remapping on the way back in."""
return [
{"rule_id": rule_id, "kind": kind, "pattern": pattern, "moment": moment or ""}
for rule_id, kind, pattern, moment in rows
]
def _rule_moment_judgment_rows(rows) -> list[dict]: def _rule_moment_judgment_rows(rows) -> list[dict]:
"""Proposals and judgments about a rule's moments (v23). The rule id is a """Proposals and judgments about a rule's moments (v23). The rule id is a
SOURCE id, remapped at restore; the moment is a catalog name.""" SOURCE id, remapped at restore; the moment is a catalog name."""
@@ -959,6 +976,7 @@ def _rule_rows(rows) -> list[dict]:
"title": r.title, "statement": r.statement, "why": r.why, "title": r.title, "statement": r.statement, "why": r.why,
"how_to_apply": r.how_to_apply, "order_index": r.order_index, "how_to_apply": r.how_to_apply, "order_index": r.order_index,
"when_to_apply": r.when_to_apply, "kind": r.kind, "when_to_apply": r.when_to_apply, "kind": r.kind,
"enforcement": r.enforcement, "salience": r.salience,
"verify_with": r.verify_with, "expires_when": r.expires_when, "verify_with": r.verify_with, "expires_when": r.expires_when,
"verified_at": r.verified_at.isoformat() if r.verified_at else None, "verified_at": r.verified_at.isoformat() if r.verified_at else None,
"arose_from_id": r.arose_from_id, "arose_from_id": r.arose_from_id,
@@ -1015,6 +1033,12 @@ async def export_full_backup() -> dict:
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment) select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
.order_by(rule_moments_t.c.rule_id, rule_moments_t.c.moment) .order_by(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
)).all() )).all()
rule_trigger_rows = (await session.execute(
select(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
.order_by(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
)).all()
rule_moment_judgments = (await session.execute( rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).order_by(RuleMomentJudgment.id) select(RuleMomentJudgment).order_by(RuleMomentJudgment.id)
)).scalars().all() )).scalars().all()
@@ -1107,6 +1131,7 @@ async def export_full_backup() -> dict:
"canonical_systems": _canonical_system_rows(canonical_systems), "canonical_systems": _canonical_system_rows(canonical_systems),
"rule_systems": _rule_system_rows(rule_system_rows), "rule_systems": _rule_system_rows(rule_system_rows),
"rule_moments": _rule_moment_rows(rule_moment_rows), "rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments), "rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
"rule_relations": _rule_relation_rows(rule_relations), "rule_relations": _rule_relation_rows(rule_relations),
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links), "lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
@@ -1268,6 +1293,11 @@ async def export_user_backup(user_id: int) -> dict:
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment) select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
.where(rule_moments_t.c.rule_id.in_(_rule_ids)) .where(rule_moments_t.c.rule_id.in_(_rule_ids))
)).all() if _rule_ids else [] )).all() if _rule_ids else []
rule_trigger_rows = (await session.execute(
select(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
.where(rule_triggers_t.c.rule_id.in_(_rule_ids))
)).all() if _rule_ids else []
rule_moment_judgments = (await session.execute( rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).where(RuleMomentJudgment.rule_id.in_(_rule_ids)) select(RuleMomentJudgment).where(RuleMomentJudgment.rule_id.in_(_rule_ids))
)).scalars().all() if _rule_ids else [] )).scalars().all() if _rule_ids else []
@@ -1394,6 +1424,7 @@ async def export_user_backup(user_id: int) -> dict:
"canonical_systems": _canonical_system_rows(canonical_systems), "canonical_systems": _canonical_system_rows(canonical_systems),
"rule_systems": _rule_system_rows(rule_system_rows), "rule_systems": _rule_system_rows(rule_system_rows),
"rule_moments": _rule_moment_rows(rule_moment_rows), "rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments), "rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
"rule_relations": _rule_relation_rows(rule_relations), "rule_relations": _rule_relation_rows(rule_relations),
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links), "lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
@@ -1717,6 +1748,15 @@ def _build_rule(row: dict, maps: _Maps) -> Rule | None:
# way would restore an old backup with things that had always bound # way would restore an old backup with things that had always bound
# quietly not binding. # quietly not binding.
kind=row.get("kind") or "rule", kind=row.get("kind") or "rule",
# An archive from before these columns restores every rule as it
# behaved then: a line beside the work, at normal rank. A preference
# is always `inform`, whatever the archive says, since the CHECK would
# refuse anything else and take the whole restore down with it.
enforcement=(
"inform" if (row.get("kind") or "rule") == "preference"
else (row.get("enforcement") if row.get("enforcement") in ("enforce", "hold", "inform") else "inform")
),
salience=row.get("salience") if row.get("salience") in ("high", "normal", "low") else "normal",
verify_with=row.get("verify_with") or None, verify_with=row.get("verify_with") or None,
expires_when=row.get("expires_when") or None, expires_when=row.get("expires_when") or None,
# Restored as-is, NOT reset to null. `verified_at` records when someone # Restored as-is, NOT reset to null. `verified_at` records when someone
@@ -2407,6 +2447,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0, "note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
"code_shape_uses": 0, "canonical_systems": 0, "code_shape_uses": 0, "canonical_systems": 0,
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0, "rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
"rule_triggers": 0,
"rule_relations": 0, "rule_versions": 0, "rule_relations": 0, "rule_versions": 0,
"retrieval_tuning_events": 0, "lesson_rule_links": 0, "retrieval_tuning_events": 0, "lesson_rule_links": 0,
"lesson_no_rule": 0, "moment_mappings": 0, "lesson_no_rule": 0, "moment_mappings": 0,
@@ -2604,6 +2645,18 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
)) ))
stats["rule_moments"] += 1 stats["rule_moments"] += 1
# A rule's triggers (v29), the same join-table shape; archives before
# v29 carry none.
for rt in data.get("rule_triggers", []):
mapped_rule = maps.rules.get(rt.get("rule_id", 0))
kind, pattern = rt.get("kind"), rt.get("pattern")
if mapped_rule is None or kind not in ("tool", "path", "command", "keyword") or not pattern:
continue
await session.execute(rule_triggers_t.insert().values(
rule_id=mapped_rule, kind=kind, pattern=pattern, moment=rt.get("moment") or "",
))
stats["rule_triggers"] += 1
# Proposals and judgments about those mounts (v23); archives before # Proposals and judgments about those mounts (v23); archives before
# v23 carry none, and every rule restores unjudged. # v23 carry none, and every rule restores unjudged.
for rj in data.get("rule_moment_judgments", []): for rj in data.get("rule_moment_judgments", []):
+46 -9
View File
@@ -24,11 +24,15 @@ logger = logging.getLogger(__name__)
def _io() -> rp.MomentIO: def _io() -> rp.MomentIO:
"""Resolved at CALL time, so a test patching either module's name is seen.""" """Resolved at CALL time, so a test patching either module's name is seen."""
from grimoire.services import rule_usage, rulebooks from grimoire.services import rule_deliveries, rule_usage, rulebooks
bound = rule_deliveries.bound()
return rp.MomentIO( return rp.MomentIO(
lookup=rulebooks.rules_on_moments, lookup=rulebooks.rules_on_moments,
record_rule_surfaced=rule_usage.record_rule_surfaced, record_rule_surfaced=rule_usage.record_rule_surfaced,
history=rule_deliveries.history if bound else None,
record_delivery=rule_deliveries.record if bound else None,
retired=rule_deliveries.retired if bound else None,
) )
@@ -49,6 +53,8 @@ async def reachable_tools(user_id: int) -> list[str]:
# request whether or not anything is mounted on it: the shape is product, # request whether or not anything is mounted on it: the shape is product,
# so every install has it. # so every install has it.
shaped = {s.moment for s in reply_shapes.SHAPES.values() if s.key != reply_shapes.CORE_KEY} shaped = {s.moment for s in reply_shapes.SHAPES.values() if s.key != reply_shapes.CORE_KEY}
from grimoire.services import rule_triggers
mounted = set(await rulebooks.mounted_moments(user_id)) mounted = set(await rulebooks.mounted_moments(user_id))
wanted = mounted | shaped wanted = mounted | shaped
mappings = await moment_actions.list_mappings(user_id) mappings = await moment_actions.list_mappings(user_id)
@@ -59,19 +65,45 @@ async def reachable_tools(user_id: int) -> list[str]:
} }
if mounted: if mounted:
keys.add(moment_actions.SKILL_TOOL) keys.add(moment_actions.SKILL_TOOL)
# A rule triggered with no moment is reached by whatever tool its trigger
# can match, whatever moments those calls reach.
try:
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) return sorted(keys)
async def _board(user_id: int, project_id: int | None, **act):
"""The triggers' answer for this act; None when it cannot be read, which
delivers the mounts unconditionally rather than not at all."""
from grimoire.services import rule_triggers
try:
return await rule_triggers.board(user_id, project_id or None, **act)
except Exception: # noqa: BLE001 - a recall aid never breaks its act
logger.debug("rule triggers unreadable", exc_info=True)
return None
async def deliver_moments( async def deliver_moments(
user_id: int, reached: list[dict], *, project_id: int | None = None, user_id: int, reached: list[dict], *, project_id: int | None = None,
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(), exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
board=None, text: str = "",
) -> rp.RuleResult: ) -> rp.RuleResult:
"""The mounted rules for moments already known to have happened.""" """The mounted rules for moments already known to have happened.
With no `board`, one is built from `text` alone: no act is known here, so
only keyword triggers can be checked, and a mount conditional on any other
kind does not deliver.
"""
if board is None:
board = await _board(user_id, project_id, text=text)
return await rp.run_moment_arm( return await rp.run_moment_arm(
reached, reached,
rp.RuleMoment(user_id=user_id, query="", project_id=project_id, rp.RuleMoment(user_id=user_id, query="", project_id=project_id,
exclude=exclude, held=held), exclude=exclude, held=held),
io=_io(), io=_io(), board=board,
) )
@@ -80,12 +112,14 @@ async def deliver_for_act(
project_id: int | None = None, project_id: int | None = None,
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(), exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
) -> tuple[list[dict], rp.RuleResult]: ) -> tuple[list[dict], rp.RuleResult]:
"""Which moments this act reached, and the mounted rules they deliver.""" """Which moments this act reached, and the rules its mounts and triggers
deliver. An act that reaches no moment can still fire a trigger."""
reached = await moment_actions.moments_for(user_id, tool, tool_input or {}) reached = await moment_actions.moments_for(user_id, tool, tool_input or {})
if not reached: board = await _board(user_id, project_id, tool=tool, tool_input=tool_input or {})
return [], rp.RuleResult() if not reached and not (board and board.fired):
return reached, rp.RuleResult()
result = await deliver_moments( result = await deliver_moments(
user_id, reached, project_id=project_id, exclude=exclude, held=held, user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board,
) )
return reached, result return reached, result
@@ -291,9 +325,12 @@ async def reply_hold(
out: list[dict] = [] out: list[dict] = []
# The mounted half: deterministic, so every unopened RULE on these # The mounted half: deterministic, so every unopened RULE on these
# moments holds. A preference claims no such force. # moments holds. A preference claims no such force. A mount
# conditional on a trigger holds only when the reply meets it.
board = await _board(user_id, project_id, text=reply)
gated = board.gated if board is not None else set()
for rule, at in await rulebooks.rules_on_moments(user_id, names, project_id or None): for rule, at in await rulebooks.rules_on_moments(user_id, names, project_id or None):
if rule.id in skip or rule.kind == "preference": if rule.id in skip or rule.kind == "preference" or (rule.id, at) in gated:
continue continue
out.append({"rule_id": rule.id, "title": rule.title, "moment": at, out.append({"rule_id": rule.id, "title": rule.title, "moment": at,
"trigger": (rule.when_to_apply or "").strip()}) "trigger": (rule.when_to_apply or "").strip()})
+6
View File
@@ -974,10 +974,16 @@ def _rule_io() -> rp.RuleIO:
the pipeline reports to whatever this module's `semantic_search_rules`, the pipeline reports to whatever this module's `semantic_search_rules`,
`record_retrieval` and `record_rule_surfaced` are at the moment it runs. `record_retrieval` and `record_rule_surfaced` are at the moment it runs.
""" """
from grimoire.services import rule_deliveries
bound = rule_deliveries.bound()
return rp.RuleIO( return rp.RuleIO(
search=semantic_search_rules, search=semantic_search_rules,
record_retrieval=record_retrieval, record_retrieval=record_retrieval,
record_rule_surfaced=record_rule_surfaced, record_rule_surfaced=record_rule_surfaced,
history=rule_deliveries.history if bound else None,
record_delivery=rule_deliveries.record if bound else None,
retired=rule_deliveries.retired if bound else None,
) )
+138 -12
View File
@@ -35,6 +35,7 @@ import time
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Callable from typing import Any, Callable
from grimoire.services import rule_order
from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -576,6 +577,15 @@ class RuleIO:
record_retrieval: Callable[..., Any] record_retrieval: Callable[..., Any]
record_rule_surfaced: Callable[..., Any] record_rule_surfaced: Callable[..., Any]
history: Callable[..., Any] | None = None
"""`rule_deliveries.history`: `{rule_id: open rate}` for (rule, at) pairs.
None leaves every rule's history unknown."""
record_delivery: Callable[..., Any] | None = None
"""`rule_deliveries.record`: each line shown, against the session the
door bound. None records nothing."""
retired: Callable[..., Any] | None = None
"""`rule_deliveries.retired`: the repeats this session has already had
its one reminder of. None retires nothing."""
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -773,6 +783,55 @@ async def _reserve_slot_for_preference(
# ── The pipeline ───────────────────────────────────────────────────────── # ── The pipeline ─────────────────────────────────────────────────────────
def _record_delivery(io, moment: RuleMoment, source: str, shown: list[tuple[int, str, bool]]) -> None:
"""Record each line shown — `(rule_id, at, was_a_repeat)` — as a delivery."""
if io.record_delivery is None or not shown:
return
try:
io.record_delivery(moment.user_id, None, source, [
(rid, at, "repeat" if repeat else "full") for rid, at, repeat in shown
])
except Exception: # noqa: BLE001 - observation never breaks the observed
_telemetry_failed(source)
async def _retired(io, moment: RuleMoment, rules) -> set[int]:
"""The rules to leave out because this session has had its reminder.
A rule's life in a session is one full line, one reminder, then silence,
so a long session is not re-pointed at the same rule on every call. Only
a repeat can be retired; a rule the session opened keeps its own line,
and a rule that holds stays armed until it is opened. {} when the door
keeps no deliveries or the read fails.
"""
if io.retired is None:
return set()
ids = [
rule.id for rule in rules
if rule.id in moment.exclude and rule.id not in moment.held
and getattr(rule, "enforcement", "inform") != "hold"
]
if not ids:
return set()
try:
return set(await io.retired(moment.user_id, ids) or ())
except Exception: # noqa: BLE001 - a lifecycle read never withholds a fresh line
logger.debug("rule retirement unreadable", exc_info=True)
return set()
async def _history(io, moment: RuleMoment, pairs: list[tuple[int, str]]) -> dict[int, float]:
"""Each rule's open rate where it is about to be delivered; {} when the
door has no history to read or the read fails — unknown, never an error."""
if io.history is None or not pairs:
return {}
try:
return await io.history(moment.user_id, pairs) or {}
except Exception: # noqa: BLE001 - history orders lines, it never withholds them
logger.debug("rule delivery history unreadable", exc_info=True)
return {}
async def run_rule_arm( async def run_rule_arm(
arm: RuleArm, moment: RuleMoment, *, floor: float, budget: int, io: RuleIO, arm: RuleArm, moment: RuleMoment, *, floor: float, budget: int, io: RuleIO,
checkpoint_floor: float = 0.0, checkpoint_floor: float = 0.0,
@@ -797,10 +856,27 @@ async def run_rule_arm(
shown, _slot_id = await _reserve_slot_for_preference( shown, _slot_id = await _reserve_slot_for_preference(
io, moment, shown, floor=floor, io, moment, shown, floor=floor,
) )
# A repeat already reminded once this session says nothing more.
gone = await _retired(io, moment, [rule for _s, rule in shown])
if gone:
shown = [(s, rule) for s, rule in shown if rule.id not in gone]
# `shown`, not `fresh`: a call whose only hit is a repeat # `shown`, not `fresh`: a call whose only hit is a repeat
# still has something to say, it just says it differently. # still has something to say, it just says it differently.
if not shown: if not shown:
return RuleResult() return RuleResult()
# Into the one delivery order: a rule that holds outranks one that
# informs whatever their scores, and score breaks the last tie.
history = await _history(io, moment, [(rule.id, arm.source) for _s, rule in shown])
shown = [
c.extra for c in rule_order.ordered(
rule_order.Candidate(
rule=rule, specificity=rule_order.BY_RESEMBLANCE,
opened_rate=history.get(rule.id), similarity=score,
seen=rule.id in moment.exclude, extra=(score, rule),
)
for score, rule in shown
)
]
lines = [ lines = [
_rule_hint_line( _rule_hint_line(
@@ -836,6 +912,11 @@ async def run_rule_arm(
) )
except Exception: # noqa: BLE001 - observation never breaks the observed except Exception: # noqa: BLE001 - observation never breaks the observed
_telemetry_failed(source) _telemetry_failed(source)
# A stop-only arm shows its lines to nobody: only a hold speaks.
if not arm.stop_only:
_record_delivery(io, moment, source, [
(rule.id, source, rule.id in moment.exclude) for _s, rule in shown
])
return RuleResult( return RuleResult(
lines=lines, rule_ids=rule_ids, lines=lines, rule_ids=rule_ids,
shown_rule_ids=[rule.id for _score, rule in shown], shown_rule_ids=[rule.id for _score, rule in shown],
@@ -1597,6 +1678,12 @@ class MomentIO:
"""`rulebooks.rules_on_moments`, or a stand-in with its signature.""" """`rulebooks.rules_on_moments`, or a stand-in with its signature."""
record_rule_surfaced: Callable[..., Any] record_rule_surfaced: Callable[..., Any]
history: Callable[..., Any] | None = None
"""As on `RuleIO`."""
record_delivery: Callable[..., Any] | None = None
"""As on `RuleIO`."""
retired: Callable[..., Any] | None = None
"""As on `RuleIO`."""
def _reached_by(hit: dict) -> str: def _reached_by(hit: dict) -> str:
@@ -1606,7 +1693,7 @@ def _reached_by(hit: dict) -> str:
async def run_moment_arm( async def run_moment_arm(
reached: list[dict], moment: RuleMoment, *, io: MomentIO, reached: list[dict], moment: RuleMoment, *, io: MomentIO,
limit: int = MOMENT_RULE_LIMIT, limit: int = MOMENT_RULE_LIMIT, board: Any = None,
) -> RuleResult: ) -> RuleResult:
"""Deliver the rules mounted on the moments this act reached. """Deliver the rules mounted on the moments this act reached.
@@ -1617,30 +1704,66 @@ async def run_moment_arm(
`unmap_action`. Fresh rules come first and carry their `unmap_action`. Fresh rules come first and carry their
trigger; a rule the session was already shown is cited, not repeated in trigger; a rule the session was already shown is cited, not repeated in
full. Fails open to an empty result. full. Fails open to an empty result.
`board` is `rule_triggers.board`'s answer for this act: a conditional
mount whose condition the act missed is dropped, one it met ranks as
triggered, and a rule an unscoped trigger fired joins the mounted ones
with its trigger named as what reached it. None means no triggers.
""" """
try: try:
names = [hit["moment"] for hit in reached] names = [hit["moment"] for hit in reached]
if not names: fired = list(board.fired) if board is not None else []
return RuleResult() if not names and not fired:
pairs = await io.lookup(moment.user_id, names, moment.project_id or None)
if not pairs:
return RuleResult() return RuleResult()
pairs = await io.lookup(moment.user_id, names, moment.project_id or None) if names else []
by_moment = {hit["moment"]: hit for hit in reached} by_moment = {hit["moment"]: hit for hit in reached}
# Stable: catalog order within each half, fresh half first. # (rule, at, where, specificity) for every candidate line.
shown = sorted(pairs, key=lambda pair: pair[0].id in moment.exclude)[:limit] cands = []
for rule, at in pairs or []:
if board is not None and (rule.id, at) in board.gated:
continue
met = board is not None and (rule.id, at) in board.matched
cands.append((rule, at, f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}",
rule_order.BY_TRIGGER if met else rule_order.BY_MOUNT))
taken = {c[0].id for c in cands}
for rule, trig in fired:
if rule.id in taken:
continue
taken.add(rule.id)
cands.append((rule, trig.key, f"its trigger {trig.describe()} matched this act",
rule_order.BY_TRIGGER))
gone = await _retired(io, moment, [rule for rule, _a, _w, _s in cands])
if gone:
cands = [c for c in cands if c[0].id not in gone]
if not cands:
return RuleResult()
# The one delivery order (services/rule_order.py), then the cap — so
# what a crowded moment drops is the lowest-ranked, not the last
# mounted. Ties keep catalog order.
history = await _history(io, moment, [(rule.id, at) for rule, at, _w, _s in cands])
shown = [
c.extra for c in rule_order.ordered(
rule_order.Candidate(
rule=rule, specificity=spec,
opened_rate=history.get(rule.id),
seen=rule.id in moment.exclude, extra=(rule, at, where),
)
for rule, at, where, spec in cands
)
][:limit]
lines = [] lines = []
for rule, at in shown: for rule, at, where in shown:
seen = rule.id in moment.exclude seen = rule.id in moment.exclude
lines.append(_rule_hint_line( lines.append(_rule_hint_line(
rule, rule,
where=f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}", where=where,
seen=seen, held=rule.id in moment.held, seen=seen, held=rule.id in moment.held,
# A repeat is cited rather than quoted: the session was told # A repeat is cited rather than quoted: the session was told
# which moment brought it the first time. # which moment brought it the first time.
compact=seen, compact=seen,
)) ))
fresh = [(rule, at) for rule, at in shown if rule.id not in moment.exclude] fresh = [(rule, at) for rule, at, _where in shown if rule.id not in moment.exclude]
rule_ids = [rule.id for rule, _at in fresh] rule_ids = [rule.id for rule, _at in fresh]
if rule_ids: if rule_ids:
try: try:
@@ -1651,10 +1774,13 @@ async def run_moment_arm(
) )
except Exception: # noqa: BLE001 - observation never breaks the observed except Exception: # noqa: BLE001 - observation never breaks the observed
_telemetry_failed(MOMENT_RULE_SOURCE) _telemetry_failed(MOMENT_RULE_SOURCE)
_record_delivery(io, moment, MOMENT_RULE_SOURCE, [
(rule.id, at, rule.id in moment.exclude) for rule, at, _where in shown
])
return RuleResult( return RuleResult(
lines=lines, rule_ids=rule_ids, lines=lines, rule_ids=rule_ids,
shown_rule_ids=[rule.id for rule, _at in shown], shown_rule_ids=[rule.id for rule, _at, _where in shown],
shown=[(None, rule) for rule, _at in shown], shown=[(None, rule) for rule, _at, _where in shown],
) )
except Exception: # noqa: BLE001 - a recall aid never breaks its act except Exception: # noqa: BLE001 - a recall aid never breaks its act
logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True) logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True)
+207
View File
@@ -0,0 +1,207 @@
"""Each rule line a session is shown, whether it was opened after, and what
that history says about where a rule is worth delivering.
Three calls, one table (`rule_deliveries`):
- `record` — fire-and-forget, from the plugin doors that know the session:
every line an arm put in front of it, full or repeat.
- `mark_opened` — the session opened a rule: the latest unopened delivery of
it in that session gets the stamp. An open with no delivery behind it (the
agent looked a rule up unprompted) stamps nothing.
- `history` — for the ordering function: each rule's smoothed open rate at
the place it is about to be delivered, over the last `HISTORY_DAYS`.
Deliveries are kept `RETAIN_DAYS` and pruned daily: enough history to rank on
and to read adherence from, without a row per tool call accumulating forever.
"""
from __future__ import annotations
import logging
import re
from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from sqlalchemy import and_, case, delete, func, select, tuple_, update
from grimoire.models import async_session
from grimoire.models.rule_delivery import FORMS, FULL, REPEAT, RuleDelivery
from grimoire.services import rule_order
from grimoire.services.background import spawn
logger = logging.getLogger(__name__)
HISTORY_DAYS = 90
RETAIN_DAYS = 180
# An open counts against a delivery made within this window before it; an
# older one was read by a context that is long gone.
OPEN_WINDOW = timedelta(hours=6)
_SESSION_MAX = 200
_UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
# The session a plugin request is delivering to, bound once per request by the
# plugin routes so the arms several calls deep record against it without every
# signature between carrying it. Unbound (the MCP door, a test) records nothing.
_session: ContextVar[str] = ContextVar("rule_delivery_session", default="")
def bind_session(session_id: str | None) -> None:
_session.set(_clean_session(session_id))
def bound() -> bool:
"""Whether this request delivers to a known session — the doors that
record deliveries are the ones that read their history back."""
return bool(_session.get())
def _clean_session(session_id: str | None) -> str:
# The plugin's own filename-safe form of the id, so a hook that sends the
# raw id and one that sends the safe one name the same session.
return _UNSAFE.sub("_", (session_id or "").strip())[:_SESSION_MAX]
def record(
user_id: int, session_id: str | None, source: str,
lines: list[tuple[int, str, str]],
) -> None:
"""Record delivered lines: `(rule_id, at, form)` each. Fire-and-forget,
and a no-op without a session, since an open could never be tied back.
`session_id` None means the one bound for this request."""
sid = _clean_session(_session.get() if session_id is None else session_id)
if not sid or not lines:
return
try:
rows = [
{"user_id": int(user_id), "session_id": sid, "rule_id": int(rid),
"source": source, "at": str(at or source), "form": form if form in FORMS else FULL}
for rid, at, form in lines
]
except Exception: # noqa: BLE001 - observation never breaks the observed
logger.debug("rule delivery payload build failed", exc_info=True)
return
spawn(_insert(rows), site="rule_delivery_write")
async def _insert(rows: list[dict]) -> None:
async with async_session() as session:
session.add_all(RuleDelivery(**row) for row in rows)
await session.commit()
async def mark_opened(user_id: int, session_id: str | None, rule_id: int) -> bool:
"""Stamp the latest unopened delivery of this rule in this session.
Returns whether a delivery was stamped. Only that one: a rule delivered
five times and opened once was opened after the fifth line, and the four
before it were passed over.
"""
sid = _clean_session(session_id)
if not sid or not rule_id:
return False
now = datetime.now(timezone.utc)
async with async_session() as session:
latest = (await session.execute(
select(RuleDelivery.id)
.where(
RuleDelivery.user_id == user_id,
RuleDelivery.session_id == sid,
RuleDelivery.rule_id == rule_id,
RuleDelivery.opened_at.is_(None),
RuleDelivery.delivered_at >= now - OPEN_WINDOW,
)
.order_by(RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc())
.limit(1)
)).scalar_one_or_none()
if latest is None:
return False
await session.execute(
update(RuleDelivery).where(RuleDelivery.id == latest).values(opened_at=now)
)
await session.commit()
return True
async def history(user_id: int, pairs: list[tuple[int, str]]) -> dict[int, float]:
"""`{rule_id: smoothed open rate}` at each pair's place, for this user.
A rule with no delivery there is left out, which the ordering reads as
unknown rather than as never opened.
"""
wanted = list(dict.fromkeys((int(rid), str(at)) for rid, at in pairs))
if not wanted:
return {}
since = datetime.now(timezone.utc) - timedelta(days=HISTORY_DAYS)
async with async_session() as session:
rows = (await session.execute(
select(
RuleDelivery.rule_id, RuleDelivery.at,
func.count(RuleDelivery.id),
func.sum(case((RuleDelivery.opened_at.is_not(None), 1), else_=0)),
)
.where(
RuleDelivery.user_id == user_id,
RuleDelivery.delivered_at >= since,
tuple_(RuleDelivery.rule_id, RuleDelivery.at).in_(wanted),
)
.group_by(RuleDelivery.rule_id, RuleDelivery.at)
)).all()
return {
int(rid): rule_order.opened_rate(int(delivered), int(opened or 0))
for rid, _at, delivered, opened in rows
}
async def retired(user_id: int, rule_ids: list[int]) -> set[int]:
"""Which of these rules this session has already been reminded of.
A rule's life in a session is one full line, then one reminder, then
silence: retired is "the latest delivery of it in the bound session was a
reminder". A full delivery re-arms it, which is what happens once the
plugin's ledger forgets it (after a compaction, or as it ages out): the
next line is full again, then one reminder, then silence again.
"""
sid = _session.get()
wanted = sorted({int(r) for r in rule_ids})
if not sid or not wanted:
return set()
async with async_session() as session:
rows = (await session.execute(
select(RuleDelivery.rule_id, RuleDelivery.form)
.where(
RuleDelivery.user_id == user_id,
RuleDelivery.session_id == sid,
RuleDelivery.rule_id.in_(wanted),
)
.distinct(RuleDelivery.rule_id)
.order_by(RuleDelivery.rule_id, RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc())
)).all()
return {int(rid) for rid, form in rows if form == REPEAT}
async def prune(retain_days: int = RETAIN_DAYS) -> int:
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
async with async_session() as session:
result = await session.execute(
delete(RuleDelivery).where(and_(RuleDelivery.delivered_at < cutoff))
)
await session.commit()
return int(result.rowcount or 0)
_prune_task = None
async def _prune_tick() -> None:
try:
removed = await prune()
if removed:
logger.info("Rule delivery retention: deleted %d row(s)", removed)
except Exception:
logger.exception("Rule delivery retention failed")
def start_prune_loop() -> None:
global _prune_task
if _prune_task is None or _prune_task.done():
from grimoire.services.background import start_periodic
_prune_task = start_periodic(86400, _prune_tick, label="rule_delivery_retention") # daily
+80
View File
@@ -0,0 +1,80 @@
"""The one order in which rules reach a moment.
Every arm that puts rules in front of a session — the rules mounted on a
moment, the rules a typed trigger matched, the rules a semantic search found —
ranks what it has the same way, so a crowded moment drops the same rules
whichever arm brought them:
1. **enforcement** — `enforce`, then `hold`, then `inform`. A rule that stops
the work is never the one cut to make room for a line beside it.
2. **salience** — `high`, `normal`, `low`, as the rule's author declared it.
3. **specificity** — how narrowly the rule was reached. A trigger that named
this command or this path says more than a mount on the whole moment, and a
mount says more than a resemblance.
4. **news** — at the same rank, a rule this session has not been shown yet
comes before one it has, so a cap cuts a reminder rather than a first
mention.
5. **history** — how often this rule was opened when delivered at this
moment before. A rule sessions keep opening here outranks one they keep
passing over.
6. **similarity** — the search score, when there is one. Last, because it is
the one signal that says what the work resembles rather than what it is.
Each key is a declared or recorded fact, read in that order, so the outcome
can be explained line by line: "it outranked that one because it holds".
"""
from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any
ENFORCEMENT_RANK = {"enforce": 0, "hold": 1, "inform": 2}
SALIENCE_RANK = {"high": 0, "normal": 1, "low": 2}
# How narrowly a rule was reached, larger is narrower.
BY_RESEMBLANCE = 0
BY_MOUNT = 1
BY_TRIGGER = 2
# A rule with no delivery history at a moment ranks as if half its deliveries
# there were opened: unknown is neither proof of use nor of neglect.
UNKNOWN_HISTORY = 0.5
@dataclass(frozen=True)
class Candidate:
"""One rule an arm could deliver, with what it knows about how it got here."""
rule: Any
specificity: int = BY_RESEMBLANCE
opened_rate: float | None = None
"""Share of this rule's earlier deliveries at this moment that were opened."""
similarity: float | None = None
seen: bool = False
"""Already shown to this session."""
extra: Any = None
"""Whatever the arm needs back with the rule — the moment it was mounted
on, its score pair — carried through the sort untouched."""
def order_key(c: Candidate) -> tuple:
rule = c.rule
return (
ENFORCEMENT_RANK.get(getattr(rule, "enforcement", None) or "inform", 2),
SALIENCE_RANK.get(getattr(rule, "salience", None) or "normal", 1),
-c.specificity,
c.seen,
-(UNKNOWN_HISTORY if c.opened_rate is None else c.opened_rate),
-(c.similarity or 0.0),
)
def ordered(candidates: Iterable[Candidate]) -> list[Candidate]:
"""The candidates in delivery order. Stable: ties keep the arm's own order."""
return sorted(candidates, key=order_key)
def opened_rate(delivered: int, opened: int) -> float:
"""A smoothed open rate, so one delivery opened once does not read as certainty."""
return (opened + 1) / (delivered + 2)
+289
View File
@@ -0,0 +1,289 @@
"""A rule's triggers: typed predicates on the act, checked in code.
A mount says WHEN a rule applies (a moment of work); a trigger says WHAT act
it applies to, in terms the act itself carries, so it is matched exactly and
never by resemblance:
- `tool` — the tool called, as its key (`bash`, `write`, `update_task`); a
`*` in the pattern matches any run of characters (`*_task`).
- `path` — a file the act touches (`file_path`, `path`, `notebook_path`),
against a glob: `*` within one directory, `**` across directories, `?` one
character. A glob without a leading `/` matches from any directory, so
`migrations/*.py` matches `/repo/alembic/migrations/0001.py`.
- `command` — the head of a command the act runs, segment by segment, the way
moment mappings match it: `git push` matches `git push origin dev` and
`make && git push`, not `git pushx`.
- `keyword` — a word or phrase in the command, the content written or the
reply, matched whole and case-insensitively.
A trigger with no moment delivers its rule on any act that matches it. A
trigger scoped to a moment makes the rule's mount on that moment conditional:
the mount delivers only on an act that matches one of its triggers there, so
a rule about migrations can sit on `work.change` without arriving at every
edit. Where no act is known (the turn's own reply), only keyword triggers can
be checked, against the reply text.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from sqlalchemy import delete, select
from grimoire.models import async_session
from grimoire.services import moment_actions
TOOL, PATH, COMMAND, KEYWORD = "tool", "path", "command", "keyword"
KINDS = (TOOL, PATH, COMMAND, KEYWORD)
PATTERN_MAX = 200
TRIGGERS_MAX = 20
# The input fields a path trigger reads, across the file tools.
PATH_FIELDS = ("file_path", "path", "notebook_path")
# The input fields a keyword trigger reads.
TEXT_FIELDS = ("command", "content", "new_string", "query", "prompt")
# The tools a path, command or keyword trigger can be reached through — what
# the plugin's catch-all hook must forward for such a trigger to be checked.
PATH_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit", "read"})
COMMAND_TOOLS = moment_actions.COMMAND_TOOLS
KEYWORD_TOOLS = COMMAND_TOOLS | frozenset({"write", "edit", "multiedit", "notebookedit"})
@dataclass(frozen=True)
class Trigger:
kind: str
pattern: str
moment: str = ""
def to_dict(self) -> dict:
out = {"kind": self.kind, "pattern": self.pattern}
if self.moment:
out["moment"] = self.moment
return out
def describe(self) -> str:
"""How a delivered line names what fired: "path `alembic/**`"."""
return f"{self.kind} `{self.pattern}`"
@property
def key(self) -> str:
"""Where a trigger delivers, for the delivery record and its history."""
return f"{self.kind}:{self.pattern}"
# ── validation ───────────────────────────────────────────────────────────
def require_trigger(raw) -> Trigger:
"""One trigger, normalised, or a refusal that says what is accepted."""
from grimoire.services.moments import require_moment
if not isinstance(raw, dict):
raise ValueError("a trigger is {kind, pattern, moment?}")
kind = str(raw.get("kind") or "").strip().lower()
if kind not in KINDS:
raise ValueError(f"unknown trigger kind {raw.get('kind')!r}. Kinds are: {', '.join(KINDS)}")
pattern = " ".join(str(raw.get("pattern") or "").split())
if not pattern:
raise ValueError(f"a {kind} trigger needs a pattern")
if len(pattern) > PATTERN_MAX:
raise ValueError(f"a trigger pattern is at most {PATTERN_MAX} characters")
if kind == TOOL:
pattern = moment_actions.tool_key(pattern)
elif kind in (COMMAND, KEYWORD):
pattern = pattern.lower()
moment = str(raw.get("moment") or "").strip()
return Trigger(kind, pattern, require_moment(moment) if moment else "")
def require_triggers(raw) -> list[Trigger] | None:
"""A rule's triggers, or the first refusal. None leaves them alone; a
list, [] included, is the whole set after the write. All are checked
before any is stored."""
if raw is None:
return None
if not isinstance(raw, list):
raise ValueError("triggers is a list of {kind, pattern, moment?}")
out = list(dict.fromkeys(require_trigger(item) for item in raw))
if len(out) > TRIGGERS_MAX:
raise ValueError(f"a rule carries at most {TRIGGERS_MAX} triggers")
return out
# ── matching ─────────────────────────────────────────────────────────────
def _glob(pattern: str) -> re.Pattern:
out, i = [], 0
while i < len(pattern):
if pattern.startswith("**/", i):
out.append("(?:.*/)?")
i += 3
elif pattern.startswith("**", i):
out.append(".*")
i += 2
elif pattern[i] == "*":
out.append("[^/]*")
i += 1
elif pattern[i] == "?":
out.append("[^/]")
i += 1
else:
out.append(re.escape(pattern[i]))
i += 1
body = "".join(out)
anchor = "^" if pattern.startswith("/") else "(?:^|/)"
return re.compile(anchor + body + "$")
def _tool_glob(pattern: str) -> re.Pattern:
return re.compile("^" + ".*".join(re.escape(p) for p in pattern.split("*")) + "$")
def _texts(tool_input: dict) -> list[str]:
return [v for k in TEXT_FIELDS if isinstance(v := tool_input.get(k), str)]
def _has_phrase(text: str, phrase: str) -> bool:
return re.search(r"(?<!\w)" + re.escape(phrase) + r"(?!\w)", text, re.IGNORECASE) is not None
def matches(trigger: Trigger, tool: str | None, tool_input: dict | None, text: str = "") -> bool:
"""Whether this act — or, with no tool, this text — fires the trigger."""
tool_input = tool_input if isinstance(tool_input, dict) else {}
if trigger.kind == KEYWORD:
return any(_has_phrase(t, trigger.pattern) for t in [text, *_texts(tool_input)] if t)
if not tool:
return False
if trigger.kind == TOOL:
return _tool_glob(trigger.pattern).match(moment_actions.tool_key(tool)) is not None
if trigger.kind == PATH:
rx = _glob(trigger.pattern)
return any(isinstance(p := tool_input.get(f), str) and rx.search(p) for f in PATH_FIELDS)
if trigger.kind == COMMAND:
command = tool_input.get(moment_actions.COMMAND_FIELD)
return moment_actions.action_matches(
moment_actions.Action(tool=tool, match=trigger.pattern, moment=""),
tool, {moment_actions.COMMAND_FIELD: command},
) if isinstance(command, str) else False
return False
def tools_for(trigger: Trigger) -> set[str]:
"""The tool keys an act must be made through for this trigger to fire.
A tool pattern with a `*` cannot be listed, and reaches nothing here."""
if trigger.kind == TOOL:
return set() if "*" in trigger.pattern else {trigger.pattern}
if trigger.kind == PATH:
return set(PATH_TOOLS)
if trigger.kind == COMMAND:
return set(COMMAND_TOOLS)
return set(KEYWORD_TOOLS)
# ── storage ──────────────────────────────────────────────────────────────
async def set_rule_triggers(rule_id: int, triggers: list[Trigger]) -> None:
"""Replace a rule's triggers with these. The caller has checked write access."""
from grimoire.models.rulebook import rule_triggers as t
async with async_session() as session:
await session.execute(delete(t).where(t.c.rule_id == rule_id))
if triggers:
await session.execute(t.insert(), [
{"rule_id": rule_id, "kind": tr.kind, "pattern": tr.pattern, "moment": tr.moment}
for tr in triggers
])
await session.commit()
async def list_rule_triggers(rule_ids: list[int]) -> dict[int, list[dict]]:
"""Each rule's triggers, unscoped first, in a stable order."""
from grimoire.models.rulebook import rule_triggers as t
if not rule_ids:
return {}
async with async_session() as session:
rows = (await session.execute(
select(t.c.rule_id, t.c.kind, t.c.pattern, t.c.moment)
.where(t.c.rule_id.in_(rule_ids))
.order_by(t.c.rule_id, t.c.moment, t.c.kind, t.c.pattern)
)).all()
out: dict[int, list[dict]] = {}
for rule_id, kind, pattern, moment in rows:
out.setdefault(rule_id, []).append(Trigger(kind, pattern, moment or "").to_dict())
return out
async def _in_scope(user_id: int, project_id: int | None, *, everywhere: bool = False):
"""Every live rule with a trigger that this caller may be shown here, with
its triggers: `[(Rule, [Trigger, ...])]`."""
from grimoire.models.rulebook import Rule
from grimoire.models.rulebook import rule_triggers as t
from grimoire.services.rule_scope import joined_to_homes, rule_home
home = await rule_home(user_id, project_id, everywhere=everywhere)
async with async_session() as session:
rows = (await session.execute(
joined_to_homes(
select(Rule, t.c.kind, t.c.pattern, t.c.moment)
.select_from(t)
.join(Rule, Rule.id == t.c.rule_id)
)
.where(Rule.deleted_at.is_(None), home)
.order_by(Rule.id, t.c.kind, t.c.pattern)
)).all()
by_rule: dict[int, tuple] = {}
for rule, kind, pattern, moment in rows:
by_rule.setdefault(rule.id, (rule, []))[1].append(Trigger(kind, pattern, moment or ""))
return list(by_rule.values())
# ── the eligibility board ────────────────────────────────────────────────
@dataclass
class Board:
"""What the triggers say about one act, for the moment arm.
`gated` — (rule_id, moment) mounts that are conditional and whose
condition this act did not meet: not delivered. `matched` — conditional
mounts this act met: delivered as triggered. `fired` — rules an unscoped
trigger delivers on this act, each with the trigger that fired.
"""
gated: set[tuple[int, str]] = field(default_factory=set)
matched: set[tuple[int, str]] = field(default_factory=set)
fired: list[tuple[object, Trigger]] = field(default_factory=list)
async def board(
user_id: int, project_id: int | None, *,
tool: str | None = None, tool_input: dict | None = None, text: str = "",
) -> Board:
"""Check every in-scope trigger against this act (or this text)."""
out = Board()
for rule, triggers in await _in_scope(user_id, project_id):
first_unscoped = None
for trig in triggers:
hit = matches(trig, tool, tool_input, text)
if trig.moment:
pair = (rule.id, trig.moment)
if hit:
out.matched.add(pair)
out.gated.discard(pair)
elif pair not in out.matched:
out.gated.add(pair)
elif hit and first_unscoped is None:
first_unscoped = trig
if first_unscoped is not None:
out.fired.append((rule, first_unscoped))
return out
async def reachable_tools(user_id: int) -> set[str]:
"""The tool keys a call to which could fire an unscoped trigger, in any
home — a superset, for the plugin's catch-all filter."""
keys: set[str] = set()
for _rule, triggers in await _in_scope(user_id, None, everywhere=True):
for trig in triggers:
if not trig.moment:
keys |= tools_for(trig)
return keys
+71 -6
View File
@@ -273,6 +273,38 @@ RELATION_KINDS = ("co_surfaces", "overrides", "elaborates")
# Migration 0098's CHECK. `rule` binds; `preference` is how the operator # Migration 0098's CHECK. `rule` binds; `preference` is how the operator
# wants work done — see the model comment for why both live on one table. # wants work done — see the model comment for why both live on one table.
KINDS = ("rule", "preference") KINDS = ("rule", "preference")
# Migration 0128's CHECKs, strongest first — the order the ordering function
# ranks them in (services/rule_order.py).
ENFORCEMENTS = ("enforce", "hold", "inform")
SALIENCES = ("high", "normal", "low")
def require_enforcement(enforcement: str | None, kind: str | None) -> str:
"""The enforcement a rule of this kind may carry, or a refusal naming the choices.
Unlike `kind`, an unknown enforcement is refused rather than mapped: there is no
safe direction to fall in. Mapped up, a typo turns a line into a stop;
mapped down, it turns a stop into a line. A preference is always `inform`
— it says how work is liked done, and a stop would claim a force it does
not have.
"""
clean = (enforcement or "inform").strip().lower()
if clean not in ENFORCEMENTS:
raise ValueError(f"enforcement must be one of {', '.join(ENFORCEMENTS)}, got {enforcement!r}")
if (kind or "rule") == "preference" and clean != "inform":
raise ValueError(
"a preference's enforcement is always `inform`: it says how work is liked "
"done, and holding or enforcing it would make it a rule. Record it "
"as a rule if it must stop the work."
)
return clean
def require_salience(salience: str | None) -> str:
clean = (salience or "normal").strip().lower()
if clean not in SALIENCES:
raise ValueError(f"salience must be one of {', '.join(SALIENCES)}, got {salience!r}")
return clean
# The rule columns that are nullable, and therefore the ones where EMPTY has # The rule columns that are nullable, and therefore the ones where EMPTY has
@@ -339,8 +371,14 @@ def rule_brief(rule: Rule, **extra) -> dict:
# one, and the assumption it would reach for — "this binds" — is the # one, and the assumption it would reach for — "this binds" — is the
# expensive one to get wrong in the other direction. Say it outright. # expensive one to get wrong in the other direction. Say it outright.
"kind": rule.kind or "rule", "kind": rule.kind or "rule",
# Unconditional for the same reason as `kind`: whether a rule stops
# the work is never something a reader should have to assume.
"enforcement": rule.enforcement or "inform",
"updated_at": rule.updated_at.date().isoformat() if rule.updated_at else None, "updated_at": rule.updated_at.date().isoformat() if rule.updated_at else None,
} }
# Salience is attached only when the author raised or lowered it.
if (rule.salience or "normal") != "normal":
out["salience"] = rule.salience
# Attached only when present: never a null key that reads as a # Attached only when present: never a null key that reads as a
# capability the record doesn't have. # capability the record doesn't have.
if rule.when_to_apply: if rule.when_to_apply:
@@ -432,9 +470,9 @@ async def co_surfaced_partners(user_id: int, rule_ids: list[int]) -> list[Rule]:
async def rule_detail( async def rule_detail(
user_id: int, rule: Rule, system_ids: list[int] | None = None, user_id: int, rule: Rule, system_ids: list[int] | None = None,
moments: list[str] | None = None, moments: list[str] | None = None, triggers: list | None = None,
) -> dict: ) -> dict:
"""The full record, with its areas, moments and edges attached. """The full record, with its areas, moments, triggers and edges attached.
ONE seam for both doors and every write path, so create, update and get ONE seam for both doors and every write path, so create, update and get
cannot disagree about what a rule looks like coming back — the same cannot disagree about what a rule looks like coming back — the same
@@ -444,15 +482,21 @@ async def rule_detail(
`system_ids=None` / `moments=None` mean "leave them alone"; a list `system_ids=None` / `moments=None` mean "leave them alone"; a list
(including []) REPLACES them. Doors validate `moments` with (including []) REPLACES them. Doors validate `moments` with
`moments.require_moments` BEFORE their create, so an unknown name is `moments.require_moments` BEFORE their create, so an unknown name is
refused without leaving a rule behind. refused without leaving a rule behind; `triggers` the same way, with
`rule_triggers.require_triggers`, and it replaces them the same way.
""" """
from grimoire.services import rule_triggers
if system_ids is not None: if system_ids is not None:
await set_rule_systems(rule.id, user_id, system_ids) await set_rule_systems(rule.id, user_id, system_ids)
if moments is not None: if moments is not None:
await set_rule_moments(rule.id, user_id, moments) await set_rule_moments(rule.id, user_id, moments)
if triggers is not None:
await rule_triggers.set_rule_triggers(rule.id, triggers)
data = rule.to_dict() data = rule.to_dict()
systems = (await list_rule_systems([rule.id])).get(rule.id, []) systems = (await list_rule_systems([rule.id])).get(rule.id, [])
mounted = (await list_rule_moments([rule.id])).get(rule.id, []) mounted = (await list_rule_moments([rule.id])).get(rule.id, [])
triggered = (await rule_triggers.list_rule_triggers([rule.id])).get(rule.id, [])
relations = (await list_rule_relations([rule.id])).get(rule.id, []) relations = (await list_rule_relations([rule.id])).get(rule.id, [])
# Attached only when present: an empty key reads as a capability # Attached only when present: an empty key reads as a capability
# the record has and isn't using, which is a different claim. # the record has and isn't using, which is a different claim.
@@ -460,6 +504,8 @@ async def rule_detail(
data["systems"] = systems data["systems"] = systems
if mounted: if mounted:
data["moments"] = mounted data["moments"] = mounted
if triggered:
data["triggers"] = triggered
if relations: if relations:
data["relations"] = relations data["relations"] = relations
# The concrete situations judged (or proposed) to be instances of this # The concrete situations judged (or proposed) to be instances of this
@@ -506,8 +552,12 @@ async def create_rule(
why: str = "", how_to_apply: str = "", order_index: int = 0, why: str = "", how_to_apply: str = "", order_index: int = 0,
when_to_apply: str = "", arose_from_id: int = 0, when_to_apply: str = "", arose_from_id: int = 0,
verify_with: str = "", expires_when: str = "", kind: str = "rule", verify_with: str = "", expires_when: str = "", kind: str = "rule",
enforcement: str = "inform", salience: str = "normal",
) -> Rule: ) -> Rule:
_require_trigger(when_to_apply) _require_trigger(when_to_apply)
kind = _valid_kind(kind)
enforcement = require_enforcement(enforcement, kind)
salience = require_salience(salience)
async with async_session() as session: async with async_session() as session:
await _assert_topic_owned(session, topic_id, user_id) await _assert_topic_owned(session, topic_id, user_id)
rule = Rule( rule = Rule(
@@ -515,7 +565,7 @@ async def create_rule(
title=title, title=title,
statement=statement, statement=statement,
when_to_apply=when_to_apply or None, when_to_apply=when_to_apply or None,
kind=_valid_kind(kind), kind=kind, enforcement=enforcement, salience=salience,
why=why or None, why=why or None,
how_to_apply=how_to_apply or None, how_to_apply=how_to_apply or None,
verify_with=verify_with or None, verify_with=verify_with or None,
@@ -535,6 +585,7 @@ async def create_project_rule(
why: str = "", how_to_apply: str = "", order_index: int = 0, why: str = "", how_to_apply: str = "", order_index: int = 0,
when_to_apply: str = "", arose_from_id: int = 0, when_to_apply: str = "", arose_from_id: int = 0,
verify_with: str = "", expires_when: str = "", kind: str = "rule", verify_with: str = "", expires_when: str = "", kind: str = "rule",
enforcement: str = "inform", salience: str = "normal",
) -> Rule: ) -> Rule:
"""Create a rule scoped to a single project (no rulebook ceremony). """Create a rule scoped to a single project (no rulebook ceremony).
@@ -544,6 +595,9 @@ async def create_project_rule(
constraint enforces exactly-one of (topic_id, project_id). constraint enforces exactly-one of (topic_id, project_id).
""" """
_require_trigger(when_to_apply) _require_trigger(when_to_apply)
kind = _valid_kind(kind)
enforcement = require_enforcement(enforcement, kind)
salience = require_salience(salience)
async with async_session() as session: async with async_session() as session:
await _assert_project_owned(session, project_id, user_id) await _assert_project_owned(session, project_id, user_id)
rule = Rule( rule = Rule(
@@ -551,7 +605,7 @@ async def create_project_rule(
title=title, title=title,
statement=statement, statement=statement,
when_to_apply=when_to_apply or None, when_to_apply=when_to_apply or None,
kind=_valid_kind(kind), kind=kind, enforcement=enforcement, salience=salience,
why=why or None, why=why or None,
how_to_apply=how_to_apply or None, how_to_apply=how_to_apply or None,
verify_with=verify_with or None, verify_with=verify_with or None,
@@ -691,7 +745,7 @@ async def update_rule(
allowed = { allowed = {
"title", "statement", "why", "how_to_apply", "order_index", "title", "statement", "why", "how_to_apply", "order_index",
"when_to_apply", "kind", "arose_from_id", "when_to_apply", "kind", "arose_from_id",
"verify_with", "expires_when", "verify_with", "expires_when", "enforcement", "salience",
} }
check_before = rule.verify_with check_before = rule.verify_with
# A create-time guard is worth nothing if an edit can undo it, and # A create-time guard is worth nothing if an edit can undo it, and
@@ -719,6 +773,11 @@ async def update_rule(
continue continue
if key == "kind": if key == "kind":
value = _valid_kind(value) value = _valid_kind(value)
elif key == "salience":
value = require_salience(value)
elif key == "enforcement":
# Checked against the kind after the loop, which may change it.
value = (value or "").strip().lower() or "inform"
elif key in NULLABLE_RULE_TEXT: elif key in NULLABLE_RULE_TEXT:
value = value or None value = value or None
elif key == "arose_from_id": elif key == "arose_from_id":
@@ -731,6 +790,12 @@ async def update_rule(
# rule wrongly vouched for costs the thing the sweep exists to catch. # rule wrongly vouched for costs the thing the sweep exists to catch.
if rule.verify_with != check_before: if rule.verify_with != check_before:
rule.verified_at = None rule.verified_at = None
# A rule turned into a preference without naming an enforcement drops to
# `inform`, since a preference carries no other. Named explicitly
# alongside the new kind, a stronger enforcement is refused instead.
if rule.kind == "preference" and "enforcement" not in fields:
rule.enforcement = "inform"
rule.enforcement = require_enforcement(rule.enforcement, rule.kind)
if trigger_before and not (rule.when_to_apply or "").strip(): if trigger_before and not (rule.when_to_apply or "").strip():
raise ValueError( raise ValueError(
"when_to_apply cannot be cleared: it is how this rule arrives, " "when_to_apply cannot be cleared: it is how this rule arrives, "
+17
View File
@@ -273,6 +273,23 @@ def _no_moment_delivery(request):
yield yield
@pytest.fixture(autouse=True)
def _no_rule_triggers(request):
"""Stub the database read behind a rule's triggers.
Every act the moment door sees checks the in-scope triggers, which is a
read; stubbed to "no rule carries a trigger" so a unit test of mounts sees
mounts only. The matching itself is pure and tested unstubbed in
tests/test_rule_triggers.py; the read against Postgres in
tests/test_integration_rule_triggers.py, which this skips.
"""
if request.node.get_closest_marker("integration"):
yield
return
with patch("grimoire.services.rule_triggers._in_scope", AsyncMock(return_value=[])):
yield
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def _no_rule_arm(): def _no_rule_arm():
"""Stub the write-path hint's standing-RULES arm. """Stub the write-path hint's standing-RULES arm.
+4 -1
View File
@@ -290,6 +290,9 @@ def fake_rule(**attrs) -> MagicMock:
# claim to carry a check and rule_brief would stamp a MagicMock date # claim to carry a check and rule_brief would stamp a MagicMock date
# onto all of them. Most rules have none — that is the default here. # onto all of them. Most rules have none — that is the default here.
"verify_with": None, "expires_when": None, "verified_at": None, "verify_with": None, "expires_when": None, "verified_at": None,
# A MagicMock here would read as a declared enforcement and a raised
# salience on every stand-in; the defaults are what a new rule gets.
"enforcement": "inform", "salience": "normal",
"order_index": 0, "created_at": _now(), "updated_at": _now(), "order_index": 0, "created_at": _now(), "updated_at": _now(),
}, attrs) }, attrs)
@@ -307,7 +310,7 @@ def plain_rule_detail():
stubbing the seam slightly differently is a test asserting something stubbing the seam slightly differently is a test asserting something
slightly different than it appears to. slightly different than it appears to.
""" """
async def _detail(_uid, rule, _system_ids=None, _moments=None): async def _detail(_uid, rule, _system_ids=None, _moments=None, **_kw):
return rule.to_dict() return rule.to_dict()
return patch("grimoire.mcp.tools.rulebooks.rulebooks_svc.rule_detail", _detail) return patch("grimoire.mcp.tools.rulebooks.rulebooks_svc.rule_detail", _detail)
+127
View File
@@ -0,0 +1,127 @@
"""Real-Postgres tests for `rule_deliveries`: a delivery recorded against a
session, the open stamped on the one it followed, and the history read back."""
import asyncio
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import delete, select, update
from grimoire.models import async_session
from grimoire.models.rule_delivery import RuleDelivery
from grimoire.services import background, rule_deliveries
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
RULE = 9_100_001
OTHER = 9_100_002
async def _user() -> int:
async with async_session() as s:
user = await ensure_user(s, "rule_delivery_owner")
uid = user.id
await s.commit()
await s.execute(delete(RuleDelivery).where(RuleDelivery.user_id == uid))
await s.commit()
return uid
async def _rows(uid: int) -> list[RuleDelivery]:
async with async_session() as s:
return list((await s.execute(
select(RuleDelivery).where(RuleDelivery.user_id == uid).order_by(RuleDelivery.id)
)).scalars().all())
async def _record(uid, sid, source, lines):
rule_deliveries.record(uid, sid, source, lines)
await background.drain()
async def test_an_open_is_stamped_on_the_sessions_latest_delivery_only():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full")])
await asyncio.sleep(0.01)
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "repeat")])
await _record(uid, "s-2", "moment_rule", [(RULE, "work.finish", "full")])
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is True
rows = await _rows(uid)
opened = [(r.session_id, r.form) for r in rows if r.opened_at is not None]
assert opened == [("s-1", "repeat")]
# A second open with nothing left unopened in the session stamps the earlier one.
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is True
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is False
async def test_an_open_with_no_delivery_behind_it_stamps_nothing():
uid = await _user()
assert await rule_deliveries.mark_opened(uid, "s-1", OTHER) is False
assert await rule_deliveries.mark_opened(uid, "", RULE) is False
async def test_without_a_session_nothing_is_recorded():
uid = await _user()
rule_deliveries.bind_session("")
await _record(uid, None, "prompt_rule", [(RULE, "prompt_rule", "full")])
assert await _rows(uid) == []
async def test_a_bound_session_is_the_one_recorded():
uid = await _user()
rule_deliveries.bind_session("bound s/3")
await _record(uid, None, "prompt_rule", [(RULE, "prompt_rule", "full")])
# The plugin's filename-safe form, so the raw and safe ids agree.
assert [r.session_id for r in await _rows(uid)] == ["bound_s_3"]
rule_deliveries.bind_session("")
async def test_history_is_the_smoothed_open_rate_at_each_place():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full")] * 3
+ [(RULE, "work.deliver", "full"), (OTHER, "work.finish", "full")])
await rule_deliveries.mark_opened(uid, "s-1", RULE) # one of the five RULE rows
history = await rule_deliveries.history(uid, [(RULE, "work.finish"), (OTHER, "work.finish")])
rows = await _rows(uid)
stamped_at = next(r.at for r in rows if r.opened_at is not None)
finish_opened = 1 if stamped_at == "work.finish" else 0
assert history[RULE] == pytest.approx((finish_opened + 1) / (3 + 2))
assert history[OTHER] == pytest.approx(1 / 3)
# A place with no delivery is unknown, not zero.
assert await rule_deliveries.history(uid, [(RULE, "reply.report")]) == {}
async def test_old_deliveries_are_pruned():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full"), (OTHER, "work.finish", "full")])
async with async_session() as s:
await s.execute(
update(RuleDelivery)
.where(RuleDelivery.user_id == uid, RuleDelivery.rule_id == RULE)
.values(delivered_at=datetime.now(timezone.utc) - timedelta(days=rule_deliveries.RETAIN_DAYS + 1))
)
await s.commit()
assert await rule_deliveries.prune() >= 1
assert [r.rule_id for r in await _rows(uid)] == [OTHER]
async def test_a_rule_retires_after_its_reminder_and_a_full_line_re_arms_it():
uid = await _user()
rule_deliveries.bind_session("s-life")
try:
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "full")])
assert await rule_deliveries.retired(uid, [RULE]) == set()
await asyncio.sleep(0.01)
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "repeat")])
assert await rule_deliveries.retired(uid, [RULE, OTHER]) == {RULE}
await asyncio.sleep(0.01)
# The ledger forgot it (a compaction): the next line is full, and re-arms it.
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "full")])
assert await rule_deliveries.retired(uid, [RULE]) == set()
# Another session's reminder retires nothing here.
await _record(uid, "s-other", "moment_rule", [(OTHER, "work.finish", "repeat")])
assert await rule_deliveries.retired(uid, [OTHER]) == set()
finally:
rule_deliveries.bind_session("")
+116
View File
@@ -0,0 +1,116 @@
"""Real-Postgres tests for `rules.enforcement` and `rules.salience` (migration 0128).
The CHECKs are what a mock cannot show: an unknown value refused, a preference
refused anything but `inform`, and a row written without either reading back
as the defaults every existing rule took on upgrade.
"""
import pytest
import pytest_asyncio
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from grimoire.models import async_session
from grimoire.models.rulebook import Rule, Rulebook
from grimoire.services import rulebooks as rulebooks_svc
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
OWNER_USERNAME = "rule_enforcement_owner"
@pytest_asyncio.fixture
async def topic_id():
# Purged at setup, not teardown: the write path's detached embedding task
# would deadlock against a teardown deleting the rulebook.
async with async_session() as s:
owner = await ensure_user(s, OWNER_USERNAME)
uid = owner.id
await s.commit()
for book in (await s.execute(
select(Rulebook).where(Rulebook.owner_user_id == uid)
)).scalars().all():
await s.delete(book)
await s.commit()
book = await rulebooks_svc.create_rulebook(uid, "Enforcement fixtures")
topic = await rulebooks_svc.create_topic(book.id, uid, "conventions")
return uid, topic.id
async def _write_raw(topic: int, **kw) -> int:
"""Straight to the model, around the service's own checks, to reach the CHECKs."""
async with async_session() as s:
rule = Rule(topic_id=topic, title=kw.pop("title", "t"), statement="s", **kw)
s.add(rule)
await s.commit()
return rule.id
async def _read(rule_id: int) -> Rule:
async with async_session() as s:
return (await s.execute(select(Rule).where(Rule.id == rule_id))).scalar_one()
async def test_a_rule_written_without_either_reads_back_as_the_defaults(topic_id):
_uid, topic = topic_id
rule = await _read(await _write_raw(topic))
assert (rule.enforcement, rule.salience) == ("inform", "normal")
async def test_an_unknown_enforcement_is_refused_by_the_database(topic_id):
_uid, topic = topic_id
with pytest.raises(IntegrityError):
await _write_raw(topic, enforcement="block")
async def test_an_unknown_salience_is_refused_by_the_database(topic_id):
_uid, topic = topic_id
with pytest.raises(IntegrityError):
await _write_raw(topic, salience="urgent")
async def test_a_preference_that_holds_is_refused_by_the_database(topic_id):
_uid, topic = topic_id
with pytest.raises(IntegrityError):
await _write_raw(topic, kind="preference", enforcement="hold")
async def test_the_service_writes_a_declared_hold_and_reads_it_back(topic_id):
uid, topic = topic_id
rule = await rulebooks_svc.create_rule(
topic, uid, "Holds", "Read before replying", when_to_apply="about to reply",
enforcement="hold", salience="high",
)
back = await _read(rule.id)
assert (back.enforcement, back.salience) == ("hold", "high")
assert rulebooks_svc.rule_brief(back)["enforcement"] == "hold"
assert rulebooks_svc.rule_brief(back)["salience"] == "high"
async def test_the_service_refuses_a_preference_that_holds(topic_id):
uid, topic = topic_id
with pytest.raises(ValueError, match="always `inform`"):
await rulebooks_svc.create_rule(
topic, uid, "Pref", "Prefer x", when_to_apply="when x",
kind="preference", enforcement="hold",
)
async def test_a_rule_turned_into_a_preference_drops_to_inform(topic_id):
uid, topic = topic_id
rule = await rulebooks_svc.create_rule(
topic, uid, "Becomes a preference", "Do x", when_to_apply="when x",
enforcement="enforce",
)
updated = await rulebooks_svc.update_rule(rule.id, uid, kind="preference")
assert (updated.kind, updated.enforcement) == ("preference", "inform")
async def test_naming_a_hold_alongside_the_preference_kind_is_refused(topic_id):
uid, topic = topic_id
rule = await rulebooks_svc.create_rule(
topic, uid, "Stays a rule", "Do y", when_to_apply="when y",
)
with pytest.raises(ValueError, match="always `inform`"):
await rulebooks_svc.update_rule(rule.id, uid, kind="preference", enforcement="hold")
assert (await _read(rule.id)).kind == "rule"
+107
View File
@@ -0,0 +1,107 @@
"""Real-Postgres tests for `rule_triggers` (migration 0130): stored through the
rule's own write path, read back on the record, scoped like every rule read,
and checked against an act by the moment door."""
import pytest
import pytest_asyncio
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from grimoire.models import async_session
from grimoire.models.rulebook import Rulebook, rule_triggers
from grimoire.services import moment_delivery
from grimoire.services import rule_triggers as rt
from grimoire.services import rulebooks as rulebooks_svc
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
OWNER_USERNAME = "rule_trigger_owner"
@pytest_asyncio.fixture
async def topic_id():
# Purged at setup, not teardown: the write path's detached embedding task
# would deadlock against a teardown deleting the rulebook.
async with async_session() as s:
owner = await ensure_user(s, OWNER_USERNAME)
uid = owner.id
await s.commit()
for book in (await s.execute(
select(Rulebook).where(Rulebook.owner_user_id == uid)
)).scalars().all():
await s.delete(book)
await s.commit()
book = await rulebooks_svc.create_rulebook(uid, "Trigger fixtures")
topic = await rulebooks_svc.create_topic(book.id, uid, "conventions")
return uid, topic.id
async def _rule(uid, topic, title, triggers, moments=None):
rule = await rulebooks_svc.create_rule(
topic_id=topic, user_id=uid, title=title, statement="s",
when_to_apply="when the fixture's act happens",
)
return await rulebooks_svc.rule_detail(
uid, rule, None, moments, triggers=rt.require_triggers(triggers),
)
async def test_triggers_are_stored_with_the_rule_and_replaced_as_a_set(topic_id):
uid, topic = topic_id
data = await _rule(uid, topic, "Migrations are reviewed", [
{"kind": "path", "pattern": "alembic/versions/*.py"},
{"kind": "command", "pattern": "alembic upgrade", "moment": "work.run"},
])
assert data["triggers"] == [
{"kind": "path", "pattern": "alembic/versions/*.py"},
{"kind": "command", "pattern": "alembic upgrade", "moment": "work.run"},
]
rule = await rulebooks_svc.get_rule(data["id"], uid)
again = await rulebooks_svc.rule_detail(uid, rule, triggers=[])
assert "triggers" not in again
# None leaves them alone.
await rulebooks_svc.rule_detail(uid, rule, triggers=rt.require_triggers([{"kind": "tool", "pattern": "bash"}]))
kept = await rulebooks_svc.rule_detail(uid, rule)
assert kept["triggers"] == [{"kind": "tool", "pattern": "bash"}]
async def test_an_unknown_kind_is_refused_by_the_database(topic_id):
uid, topic = topic_id
data = await _rule(uid, topic, "Raw kind", [])
async with async_session() as s:
with pytest.raises(IntegrityError):
await s.execute(rule_triggers.insert().values(
rule_id=data["id"], kind="regex", pattern="x", moment="",
))
await s.commit()
async def test_an_act_fires_an_unscoped_trigger_with_no_moment_reached(topic_id):
uid, topic = topic_id
data = await _rule(uid, topic, "Notebooks keep outputs cleared",
[{"kind": "path", "pattern": "*.ipynb"}])
reached, result = await moment_delivery.deliver_for_act(
uid, "Read", {"file_path": "/r/analysis/one.ipynb"},
)
assert data["id"] in result.shown_rule_ids
assert any("path `*.ipynb`" in line for line in result.lines)
_, quiet = await moment_delivery.deliver_for_act(uid, "Read", {"file_path": "/r/a.py"})
assert data["id"] not in quiet.shown_rule_ids
async def test_a_conditional_mount_arrives_only_when_the_act_meets_it(topic_id):
uid, topic = topic_id
data = await _rule(uid, topic, "Schema changes get a migration",
[{"kind": "path", "pattern": "models/*.py", "moment": "work.change"}],
moments=["work.change"])
_, missed = await moment_delivery.deliver_for_act(uid, "Edit", {"file_path": "/r/views/a.py"})
assert data["id"] not in missed.shown_rule_ids
_, met = await moment_delivery.deliver_for_act(uid, "Edit", {"file_path": "/r/models/a.py"})
assert data["id"] in met.shown_rule_ids
async def test_the_reachable_tools_include_what_a_trigger_can_match(topic_id):
uid, topic = topic_id
await _rule(uid, topic, "Task closes carry a report",
[{"kind": "tool", "pattern": "update_task"}])
assert "update_task" in await moment_delivery.reachable_tools(uid)
+2 -2
View File
@@ -103,7 +103,7 @@ async def test_an_unknown_moment_is_refused_before_anything_is_written():
async def test_the_door_hands_rule_detail_the_normalised_moments(): async def test_the_door_hands_rule_detail_the_normalised_moments():
seen = {} seen = {}
async def detail(_uid, rule, _system_ids=None, moments=None): async def detail(_uid, rule, _system_ids=None, moments=None, **_kw):
seen["moments"] = moments seen["moments"] = moments
return rule.to_dict() return rule.to_dict()
@@ -119,7 +119,7 @@ async def test_the_door_hands_rule_detail_the_normalised_moments():
async def test_omitting_moments_leaves_the_mounts_alone(): async def test_omitting_moments_leaves_the_mounts_alone():
seen = {} seen = {}
async def detail(_uid, rule, _system_ids=None, moments="unset"): async def detail(_uid, rule, _system_ids=None, moments="unset", **_kw):
seen["moments"] = moments seen["moments"] = moments
return rule.to_dict() return rule.to_dict()
+6 -4
View File
@@ -166,7 +166,9 @@ def test_an_open_of_a_rule_a_hook_just_named_is_not_reported(sandbox):
{"session_id": "s1", "tool_name": "mcp__grimoire__get_rule", {"session_id": "s1", "tool_name": "mcp__grimoire__get_rule",
"tool_input": {"rule_id": 11}}, env) "tool_input": {"rule_id": 11}}, env)
assert out.stdout == "" assert out.stdout == ""
assert not (tmp / "curl.log").exists() # The open is reported for the delivery record, with no acts to count.
assert json.loads((tmp / "curl.body").read_text()) == {
"rule_id": 11, "session_id": "s1", "acts": []}
# The open itself is still recorded. # The open itself is still recorded.
assert (named / "s1.opened.ids").read_text().startswith("11\t") assert (named / "s1.opened.ids").read_text().startswith("11\t")
# A rule no hook named is still reported. # A rule no hook named is still reported.
@@ -176,7 +178,7 @@ def test_an_open_of_a_rule_a_hook_just_named_is_not_reported(sandbox):
assert json.loads((tmp / "curl.body").read_text())["rule_id"] == 1 assert json.loads((tmp / "curl.body").read_text())["rule_id"] == 1
def test_an_open_with_nothing_in_the_window_sends_nothing(sandbox): def test_an_open_with_nothing_in_the_window_sends_only_the_open(sandbox):
tmp, env = sandbox tmp, env = sandbox
ledger = tmp / "grimoire-moment" ledger = tmp / "grimoire-moment"
ledger.mkdir() ledger.mkdir()
@@ -185,9 +187,9 @@ def test_an_open_with_nothing_in_the_window_sends_nothing(sandbox):
) )
out = _run("grimoire_record_opened.sh", out = _run("grimoire_record_opened.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__get_rule", {"session_id": "s1", "tool_name": "mcp__grimoire__get_rule",
"tool_input": {"rule_id": 11}}, env) "tool_input": {"rule_id": 11}}, env, FAKE_CURL_REPLY='{"moments":[],"context":""}')
assert out.stdout == "" assert out.stdout == ""
assert not (tmp / "curl.log").exists() assert json.loads((tmp / "curl.body").read_text())["acts"] == []
def test_session_end_removes_the_sessions_moment_files_and_no_others(sandbox): def test_session_end_removes_the_sessions_moment_files_and_no_others(sandbox):
+174
View File
@@ -0,0 +1,174 @@
"""The one delivery order, key by key, and both rule arms reading it."""
import dataclasses
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from grimoire.services import retrieval_pipeline as rp
from grimoire.services import rule_order as ro
def _r(rid, enforcement="inform", salience="normal"):
return SimpleNamespace(id=rid, title=f"rule {rid}", kind="rule", when_to_apply="when",
enforcement=enforcement, salience=salience)
def _ids(cands):
return [c.rule.id for c in ro.ordered(cands)]
def test_a_rule_that_stops_the_work_outranks_any_line_beside_it():
cands = [ro.Candidate(_r(1), similarity=0.95),
ro.Candidate(_r(2, "hold"), similarity=0.71),
ro.Candidate(_r(3, "enforce"), similarity=0.70)]
assert _ids(cands) == [3, 2, 1]
def test_salience_decides_between_rules_of_the_same_enforcement():
cands = [ro.Candidate(_r(1, salience="low")), ro.Candidate(_r(2)),
ro.Candidate(_r(3, salience="high"))]
assert _ids(cands) == [3, 2, 1]
def test_a_trigger_outranks_a_mount_and_a_mount_outranks_a_resemblance():
cands = [ro.Candidate(_r(1), specificity=ro.BY_RESEMBLANCE, similarity=0.9),
ro.Candidate(_r(2), specificity=ro.BY_MOUNT),
ro.Candidate(_r(3), specificity=ro.BY_TRIGGER)]
assert _ids(cands) == [3, 2, 1]
def test_a_first_mention_outranks_a_reminder_at_the_same_rank():
cands = [ro.Candidate(_r(1), seen=True), ro.Candidate(_r(2))]
assert _ids(cands) == [2, 1]
def test_history_breaks_the_tie_before_similarity_does():
cands = [ro.Candidate(_r(1), opened_rate=0.1, similarity=0.9),
ro.Candidate(_r(2), opened_rate=0.8, similarity=0.7),
ro.Candidate(_r(3), similarity=0.99)]
# Unknown history ranks between them, as an even chance.
assert _ids(cands) == [2, 3, 1]
def test_ties_keep_the_arms_own_order():
cands = [ro.Candidate(_r(i)) for i in (4, 2, 9)]
assert _ids(cands) == [4, 2, 9]
def test_a_rule_with_no_declared_fields_reads_as_inform_normal():
bare = SimpleNamespace(id=1)
assert ro.order_key(ro.Candidate(bare))[:2] == (2, 1)
@pytest.mark.parametrize(("delivered", "opened", "rate"), [(0, 0, 0.5), (1, 1, 2 / 3), (10, 0, 1 / 12)])
def test_the_open_rate_is_smoothed(delivered, opened, rate):
assert ro.opened_rate(delivered, opened) == pytest.approx(rate)
PUSH = [{"moment": "work.deliver", "tool": "Bash", "match": "git push", "via": "default"}]
@pytest.mark.asyncio
async def test_the_moment_arm_delivers_in_that_order_before_its_cap():
pairs = [(_r(i), "work.deliver") for i in range(1, 11)] + [(_r(99, "hold"), "work.deliver")]
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock()),
)
# The holding rule was mounted last and still leads; the cap cut ordinary ones.
assert result.shown_rule_ids[0] == 99
assert len(result.shown_rule_ids) == rp.MOMENT_RULE_LIMIT
@pytest.mark.asyncio
async def test_the_semantic_arm_delivers_in_that_order():
hits = [(0.91, _r(1)), (0.74, _r(2, "hold"))]
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
record_rule_surfaced=MagicMock())
result = await rp.run_rule_arm(
rp.PROMPT_RULE, rp.RuleMoment(user_id=1, query="q", project_id=2, where="here"),
floor=0.5, budget=5, io=io,
)
assert result.shown_rule_ids[:2] == [2, 1]
@pytest.mark.asyncio
async def test_each_line_shown_is_recorded_as_a_delivery_with_its_form():
recorded = MagicMock()
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish")]
await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2, exclude=frozenset({6})),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
record_delivery=recorded),
)
_uid, _sid, source, lines = recorded.call_args.args
assert source == rp.MOMENT_RULE_SOURCE
assert lines == [(5, "work.finish", "full"), (6, "work.finish", "repeat")]
@pytest.mark.asyncio
async def test_history_reorders_rules_of_equal_rank_and_a_failed_read_is_unknown():
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish")]
async def history(_uid, _pairs):
return {6: 0.9, 5: 0.1}
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
history=history),
)
assert result.shown_rule_ids == [6, 5]
async def broken(_uid, _pairs):
raise RuntimeError("no database")
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
history=broken),
)
assert result.shown_rule_ids == [5, 6]
@pytest.mark.asyncio
async def test_a_repeat_already_reminded_once_is_retired_unless_it_holds_or_was_opened():
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish"), (_r(7, "hold"), "work.finish"),
(_r(8), "work.finish")]
asked = {}
async def retired(_uid, ids):
asked["ids"] = sorted(ids)
return set(ids)
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2,
exclude=frozenset({6, 7, 8}), held=frozenset({8})),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
retired=retired),
)
# Only the unopened, non-holding repeat is asked about, and only it goes.
assert asked["ids"] == [6]
assert sorted(result.shown_rule_ids) == [5, 7, 8]
@pytest.mark.asyncio
async def test_the_semantic_arm_retires_the_same_way_and_a_failed_read_retires_nothing():
hits = [(0.91, _r(1)), (0.80, _r(2))]
async def retired(_uid, ids):
return {2}
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
record_rule_surfaced=MagicMock(), retired=retired)
moment = rp.RuleMoment(user_id=1, query="q", project_id=2, where="here", exclude=frozenset({2}))
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
assert result.shown_rule_ids == [1]
async def broken(_uid, ids):
raise RuntimeError("no database")
io = dataclasses.replace(io, retired=broken)
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
assert sorted(result.shown_rule_ids) == [1, 2]
+152
View File
@@ -0,0 +1,152 @@
"""A rule's triggers: what each kind matches, what is refused, and how the
moment arm reads the board they build."""
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from grimoire.services import retrieval_pipeline as rp
from grimoire.services import rule_order
from grimoire.services import rule_triggers as rt
from grimoire.services.rule_triggers import Trigger
def T(kind, pattern, moment=""):
return rt.require_trigger({"kind": kind, "pattern": pattern, "moment": moment})
# ── matching, kind by kind ──────────────────────────────────────────────
@pytest.mark.parametrize(("pattern", "path", "hit"), [
("alembic/versions/*.py", "/repo/alembic/versions/0130_x.py", True),
("alembic/versions/*.py", "alembic/versions/0130_x.py", True),
("alembic/versions/*.py", "/repo/alembic/versions/sub/0130.py", False),
("frontend/**/*.vue", "/r/frontend/src/components/A.vue", True),
("frontend/**/*.vue", "/r/frontend/A.vue", True),
("*.md", "/r/docs/README.md", True),
("/etc/*.conf", "/etc/nginx.conf", True),
("/etc/*.conf", "/srv/etc/nginx.conf", False),
("versions/*.py", "/repo/myversions/x.py", False),
])
def test_a_path_glob_matches_from_any_directory_unless_anchored(pattern, path, hit):
assert rt.matches(T("path", pattern), "Write", {"file_path": path}) is hit
def test_a_path_trigger_reads_every_file_field_and_needs_an_act():
trig = T("path", "*.ipynb")
assert rt.matches(trig, "NotebookEdit", {"notebook_path": "/a/b.ipynb"})
assert rt.matches(trig, "Glob", {"path": "/a/b.ipynb"})
assert not rt.matches(trig, None, None, text="b.ipynb")
@pytest.mark.parametrize(("command", "hit"), [
("git push origin dev", True),
("make test && git push", True),
("FOO=1 git push", True),
("git pushx", False),
("echo git push", False),
])
def test_a_command_trigger_matches_the_head_of_any_segment(command, hit):
assert rt.matches(T("command", "git push"), "Bash", {"command": command}) is hit
def test_a_tool_trigger_matches_the_key_with_or_without_a_server_prefix():
assert rt.matches(T("tool", "update_task"), "mcp__plugin_grimoire_grimoire__update_task", {})
assert rt.matches(T("tool", "*_task"), "mcp__x__create_task", {})
assert not rt.matches(T("tool", "update_task"), "mcp__x__get_task", {})
def test_a_keyword_matches_a_whole_word_in_what_the_act_writes_or_the_reply():
trig = T("keyword", "migration")
assert rt.matches(trig, "Edit", {"new_string": "add a Migration for it"})
assert rt.matches(trig, None, None, text="this migration is done")
assert not rt.matches(trig, "Edit", {"new_string": "migrations"})
assert not rt.matches(trig, "Write", {"file_path": "migration.py"})
# ── validation ──────────────────────────────────────────────────────────
def test_validation_normalises_and_refuses_what_could_never_fire():
assert T("tool", "mcp__x__Update_Task") == Trigger("tool", "update_task")
assert T("command", " Git Push ") == Trigger("command", "git push")
assert T("path", "src/**", " Work.Change ") == Trigger("path", "src/**", "work.change")
for bad in ({"kind": "regex", "pattern": "x"}, {"kind": "path", "pattern": " "},
{"kind": "path", "pattern": "x", "moment": "work.finished"}, "path:x"):
with pytest.raises(ValueError):
rt.require_trigger(bad)
def test_a_set_is_deduplicated_capped_and_none_leaves_it_alone():
assert rt.require_triggers(None) is None
assert rt.require_triggers([]) == []
same = {"kind": "path", "pattern": "a/*"}
assert rt.require_triggers([same, same]) == [Trigger("path", "a/*")]
with pytest.raises(ValueError, match="at most"):
rt.require_triggers([{"kind": "keyword", "pattern": f"w{i}"} for i in range(rt.TRIGGERS_MAX + 1)])
def test_each_kind_names_the_tools_the_catch_all_hook_must_forward():
assert rt.tools_for(T("tool", "update_task")) == {"update_task"}
assert rt.tools_for(T("tool", "*_task")) == set()
assert rt.tools_for(T("command", "git push")) == {"bash"}
assert "write" in rt.tools_for(T("path", "a/*")) and "edit" in rt.tools_for(T("path", "a/*"))
# ── the board ───────────────────────────────────────────────────────────
def _r(rid, enforcement="inform"):
return SimpleNamespace(id=rid, title=f"rule {rid}", kind="rule", when_to_apply="when",
enforcement=enforcement, salience="normal")
async def test_the_board_gates_a_conditional_mount_the_act_missed(monkeypatch):
scoped = _r(1)
free = _r(2)
monkeypatch.setattr(rt, "_in_scope", AsyncMock(return_value=[
(scoped, [T("path", "alembic/**", "work.change")]),
(free, [T("command", "git push"), T("keyword", "deploy")]),
]))
edit = await rt.board(1, 2, tool="Edit", tool_input={"file_path": "/r/src/app.py"})
assert edit.gated == {(1, "work.change")} and not edit.matched and not edit.fired
mig = await rt.board(1, 2, tool="Edit", tool_input={"file_path": "/r/alembic/v/1.py"})
assert mig.matched == {(1, "work.change")} and not mig.gated
push = await rt.board(1, 2, tool="Bash", tool_input={"command": "git push"})
assert [(r.id, t.kind) for r, t in push.fired] == [(2, "command")]
# ── the arm reading it ──────────────────────────────────────────────────
CHANGE = [{"moment": "work.change", "tool": "Edit", "match": "", "via": "default"}]
async def _arm(pairs, board, reached=CHANGE, **kw):
return await rp.run_moment_arm(
reached, rp.RuleMoment(user_id=1, query="", project_id=2, **kw),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock()),
board=board,
)
async def test_a_gated_mount_is_not_delivered_and_a_met_one_ranks_as_triggered():
pairs = [(_r(1), "work.change"), (_r(2), "work.change")]
result = await _arm(pairs, rt.Board(gated={(1, "work.change")}))
assert result.shown_rule_ids == [2]
result = await _arm(pairs, rt.Board(matched={(2, "work.change")}))
assert result.shown_rule_ids == [2, 1]
async def test_an_unscoped_trigger_delivers_with_no_moment_reached_and_says_what_fired():
board = rt.Board(fired=[(_r(7), T("path", "alembic/**"))])
result = await _arm([], board, reached=[])
assert result.shown_rule_ids == [7]
assert "path `alembic/**`" in result.lines[0]
async def test_a_rule_both_mounted_and_fired_is_delivered_once():
board = rt.Board(fired=[(_r(1), T("command", "git push"))])
result = await _arm([(_r(1), "work.change")], board)
assert result.shown_rule_ids == [1]
def test_triggered_outranks_mounted_in_the_one_order():
assert rule_order.BY_TRIGGER > rule_order.BY_MOUNT > rule_order.BY_RESEMBLANCE
+8 -1
View File
@@ -721,7 +721,8 @@ def test_the_hook_and_the_route_agree_on_every_parameter_name():
sent = set(re.findall(r"[?&]([a-z_]+)=", hook)) sent = set(re.findall(r"[?&]([a-z_]+)=", hook))
# `root` and `cwd`: where the command runs, so the paths it # `root` and `cwd`: where the command runs, so the paths it
# names can be made repo-relative for the rulings arm. # names can be made repo-relative for the rulings arm.
assert sent == {"tool", "command", "exclude_rule_ids", "root", "cwd"}, sent # `session_id`: which session the lines go to, for the delivery record.
assert sent == {"tool", "command", "exclude_rule_ids", "root", "cwd", "session_id"}, sent
# The project-scope key is the shared helper's to choose: the hook # The project-scope key is the shared helper's to choose: the hook
# splices in `grimoire_scope_query`'s output, which is `repo=` inside a git # splices in `grimoire_scope_query`'s output, which is `repo=` inside a git
@@ -763,6 +764,12 @@ def test_the_hook_and_the_route_agree_on_every_parameter_name():
assert f'request.args.get("{arg}")' in handler, ( assert f'request.args.get("{arg}")' in handler, (
f"the hook sends {arg!r} and the route never reads it" f"the hook sends {arg!r} and the route never reads it"
) )
# The session is bound for every plugin route at once, before the handler.
binder = route.split("async def _bind_delivery_session")[1].split("\n@plugin_bp")[0]
assert "@plugin_bp.before_request" in route.split("async def _bind_delivery_session")[0][-80:]
assert 'request.args.get("session_id")' in binder, (
"the hook sends session_id and no route reads it"
)
# ── The CALL log is unconditional; the SURFACING log is not ─────────── # ── The CALL log is unconditional; the SURFACING log is not ───────────
+9 -5
View File
@@ -22,7 +22,7 @@ def test_backup_version_is_current():
"""The bump is the point of the test — a payload section added without """The bump is the point of the test — a payload section added without
moving the version produces backups that are structurally different and moving the version produces backups that are structurally different and
indistinguishable by inspection.""" indistinguishable by inspection."""
assert backup.BACKUP_VERSION == 28 assert backup.BACKUP_VERSION == 29
def _exportable_note(**over): def _exportable_note(**over):
@@ -483,7 +483,7 @@ def test_the_column_guard_covers_every_table_with_a_row_helper():
# REAL table names, as _BACKED_UP holds them — not the shorter keys the # REAL table names, as _BACKED_UP holds them — not the shorter keys the
# payload uses for the same sections. Getting this wrong is what the guard # payload uses for the same sections. Getting this wrong is what the guard
# caught on its own first run. # caught on its own first run.
join_tables = {"rule_systems", "rule_moments"} join_tables = {"rule_systems", "rule_moments", "rule_triggers"}
covered = set(_column_guard_targets()) | join_tables covered = set(_column_guard_targets()) | join_tables
assert set(backup._BACKED_UP) - covered == set() assert set(backup._BACKED_UP) - covered == set()
# And no stale entries: every declaration must name a real target. # And no stale entries: every declaration must name a real target.
@@ -588,6 +588,8 @@ async def test_export_full_backup_contains_every_declared_section():
"system_usage_events", "system_usage_events",
# v23: proposals and judgments about a rule's moments. # v23: proposals and judgments about a rule's moments.
"rule_moment_judgments", "rule_moment_judgments",
# v29: the acts that trigger a rule.
"rule_triggers",
# v25: family canon. # v25: family canon.
"platforms", "project_platforms", "family_ideas", "platforms", "project_platforms", "family_ideas",
"family_idea_platforms", "family_idea_references", "family_idea_platforms", "family_idea_references",
@@ -624,13 +626,15 @@ def test_rule_rows_carry_the_verification_fields():
row = SimpleNamespace( row = SimpleNamespace(
id=1, topic_id=2, project_id=None, title="t", statement="s", id=1, topic_id=2, project_id=None, title="t", statement="s",
why="w", how_to_apply="h", order_index=0, why="w", how_to_apply="h", order_index=0,
when_to_apply="when", kind="rule", when_to_apply="when", kind="rule", enforcement="hold", salience="high",
verify_with="cat some/file", expires_when="the file grows a shell", verify_with="cat some/file", expires_when="the file grows a shell",
verified_at=checked, arose_from_id=99, verified_at=checked, arose_from_id=99,
created_at=checked, updated_at=checked, created_at=checked, updated_at=checked,
) )
out = backup._rule_rows([row])[0] out = backup._rule_rows([row])[0]
assert (out["enforcement"], out["salience"]) == ("hold", "high")
assert out["verify_with"] == "cat some/file" assert out["verify_with"] == "cat some/file"
assert out["expires_when"] == "the file grows a shell" assert out["expires_when"] == "the file grows a shell"
assert out["verified_at"] == checked.isoformat() assert out["verified_at"] == checked.isoformat()
@@ -650,7 +654,7 @@ def test_rule_rows_keep_an_unverified_rule_unverified():
row = SimpleNamespace( row = SimpleNamespace(
id=1, topic_id=2, project_id=None, title="t", statement="s", id=1, topic_id=2, project_id=None, title="t", statement="s",
why=None, how_to_apply=None, order_index=0, why=None, how_to_apply=None, order_index=0,
when_to_apply=None, kind="rule", when_to_apply=None, kind="rule", enforcement="inform", salience="normal",
verify_with=None, expires_when=None, verified_at=None, verify_with=None, expires_when=None, verified_at=None,
arose_from_id=None, arose_from_id=None,
created_at=datetime(2026, 8, 27, tzinfo=timezone.utc), created_at=datetime(2026, 8, 27, tzinfo=timezone.utc),
@@ -680,7 +684,7 @@ def test_rule_rows_carry_the_kind_so_a_preference_does_not_restore_as_a_rule():
row = SimpleNamespace( row = SimpleNamespace(
id=1, topic_id=2, project_id=None, title="t", statement="s", id=1, topic_id=2, project_id=None, title="t", statement="s",
why=None, how_to_apply=None, order_index=0, why=None, how_to_apply=None, order_index=0,
when_to_apply="when", kind="preference", when_to_apply="when", kind="preference", enforcement="inform", salience="normal",
verify_with=None, expires_when=None, verified_at=None, verify_with=None, expires_when=None, verified_at=None,
arose_from_id=None, created_at=stamp, updated_at=stamp, arose_from_id=None, created_at=stamp, updated_at=stamp,
) )