Merge pull request 'Adherence per rule and per moment; Apply all; quoted text and heredocs are not commands; the instruction surfaces teach enforcement and salience' (#228) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python tests (push) Successful in 2m9s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Successful in 18s

This commit was merged in pull request #228.
This commit is contained in:
2026-11-23 18:21:44 -05:00
35 changed files with 1409 additions and 41 deletions
+43
View File
@@ -0,0 +1,43 @@
"""rule adherence: whether a rule in force at a moment of a session was followed
Revision ID: 0134
Revises: 0133
Create Date: 2026-11-23
One verdict per rule, per place it was delivered, per session — the unit
`rule_deliveries` records — from an `enforce` refusal, the session's own
`rule_outcome` / `rule_misfired`, or a transcript review.
"""
import sqlalchemy as sa
from alembic import op
revision = "0134"
down_revision = "0133"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"rule_adherence",
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("at", sa.Text(), nullable=False),
sa.Column("verdict", sa.Text(), nullable=False),
sa.Column("source", sa.Text(), nullable=False),
sa.Column("evidence", sa.Text(), nullable=True),
sa.Column("judged_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.UniqueConstraint("user_id", "session_id", "rule_id", "at",
name="uq_rule_adherence_session_rule_at"),
)
op.create_index("ix_rule_adherence_rule_at", "rule_adherence", ["rule_id", "at"])
op.create_index("ix_rule_adherence_judged_at", "rule_adherence", ["judged_at"])
def downgrade() -> None:
op.drop_index("ix_rule_adherence_judged_at", table_name="rule_adherence")
op.drop_index("ix_rule_adherence_rule_at", table_name="rule_adherence")
op.drop_table("rule_adherence")
+38
View File
@@ -246,6 +246,44 @@ export interface WeightJudgeResult {
refused: { rule_id: number; field?: string; error: string }[];
}
/** One rule at one place, or a sum of them: how many sessions it was in
* force in, opened in, and what each was judged. */
export interface AdherenceCounts {
in_force: number;
opened: number;
followed: number;
/** Read and deliberately not followed, with a stated reason. */
departed: number;
broken: number;
not_applicable: number;
unjudged: number;
}
export interface RuleAdherenceRow extends AdherenceCounts {
rule_id: number;
/** Null for a rule deleted since. */
title: string | null;
by_moment: (AdherenceCounts & { at: string })[];
}
export interface MomentAdherenceRow extends AdherenceCounts {
/** A moment (`work.deliver`) or an arm (`pre_tool_rule`). */
at: string;
by_rule: (AdherenceCounts & { rule_id: number; title: string | null })[];
}
export interface AdherencePayload {
days: number;
totals: AdherenceCounts;
by_rule: RuleAdherenceRow[];
by_moment: MomentAdherenceRow[];
}
/** Whether the rules in force at each moment were followed there. */
export function getAdherence(days = 30): Promise<AdherencePayload> {
return apiGet(`/api/retrieval/adherence?days=${days}`);
}
export function getWeightProposals(ruleId?: number): Promise<WeightProposalsPayload> {
return apiGet(`/api/retrieval/weights/proposals${ruleId ? `?rule_id=${ruleId}` : ""}`);
}
+1
View File
@@ -3,6 +3,7 @@
Loaded scoped by each, so these class names stay local to the panels. */
.proposals { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.proposals-bar { display: flex; justify-content: flex-end; }
.proposal-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.proposal-rule {
padding: var(--fs-space-3);
+20 -5
View File
@@ -1,12 +1,26 @@
<script setup lang="ts">
import type { MomentRuleUsage } from "@/api/moments";
import type { AdherenceCounts, MomentRuleUsage } from "@/api/moments";
/**
* Which rules a moment delivered, and whether an agent went on to read each.
* The moment's own counts cannot say this once two rules are mounted there.
* Closed by default: the counts in the row above are what most visits want.
* Which rules a moment delivered, whether an agent went on to read each, and
* — where a verdict exists — whether it was followed there. The moment's own
* counts cannot say this once two rules are mounted there. Closed by default:
* the counts in the row above are what most visits want.
*/
defineProps<{ rules: MomentRuleUsage[] }>();
withDefaults(defineProps<{
rules: MomentRuleUsage[];
/** This moment's adherence per rule id, from the adherence readout. */
adherence?: Record<number, AdherenceCounts>;
}>(), { adherence: () => ({}) });
function verdicts(c: AdherenceCounts | undefined): string {
if (!c) return "";
const parts = [`followed ${c.followed} of ${c.in_force}`];
if (c.broken) parts.push(`broken ${c.broken}`);
if (c.departed) parts.push(`departed ${c.departed}`);
if (c.not_applicable) parts.push(`not applicable ${c.not_applicable}`);
return parts.join(" · ");
}
</script>
<template>
@@ -19,6 +33,7 @@ defineProps<{ rules: MomentRuleUsage[] }>();
<span :class="r.opened ? 'delivered-opened' : 'delivered-unopened'">
{{ r.opened ? "opened" : "not opened" }}
</span>
<span v-if="adherence[r.rule_id]" class="delivered-count">{{ verdicts(adherence[r.rule_id]) }}</span>
</li>
</ul>
</details>
+42 -4
View File
@@ -4,7 +4,9 @@ import { useMomentsStore } from "@/stores/moments";
import MomentProposals from "@/components/MomentProposals.vue";
import MomentRuleUsage from "@/components/MomentRuleUsage.vue";
import WeightProposals from "@/components/WeightProposals.vue";
import type { MomentAction, MomentUsage } from "@/api/moments";
import RuleAdherence from "@/components/RuleAdherence.vue";
import { getAdherence } from "@/api/moments";
import type { AdherencePayload, MomentAction, MomentAdherenceRow, MomentUsage } from "@/api/moments";
import { fmtDate } from "@/utils/dateFormat";
/**
@@ -32,6 +34,28 @@ function usage(moment: string): MomentUsage | null {
return data.value?.usage.by_moment[moment] ?? null;
}
// Adherence is read on its own, so a failure there leaves the catalog and the
// delivery counts standing and says so in its own panel.
const adherence = ref<AdherencePayload | null>(null);
const adherenceFailed = ref(false);
async function loadAdherence() {
try {
adherence.value = await getAdherence(days.value);
adherenceFailed.value = false;
} catch {
adherenceFailed.value = true;
}
}
function followed(moment: string): MomentAdherenceRow | null {
return adherence.value?.by_moment.find((m) => m.at === moment) ?? null;
}
function verdictsByRule(moment: string): Record<number, MomentAdherenceRow["by_rule"][number]> {
return Object.fromEntries((followed(moment)?.by_rule ?? []).map((r) => [r.rule_id, r]));
}
// A named procedure is its own moment (`skill.<name>`), so it appears here
// only once something is mounted on it or has been delivered at it — the
// catalog cannot list procedures it has never heard of.
@@ -102,7 +126,10 @@ async function addMapping() {
}
}
onMounted(() => store.load(true));
onMounted(async () => {
await store.load(true);
await loadAdherence();
});
</script>
<template>
@@ -128,6 +155,7 @@ onMounted(() => store.load(true));
<MomentProposals />
<WeightProposals />
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
<ul class="moment-list">
<li v-for="m in catalog" :key="m.name" class="moment-row">
@@ -144,6 +172,9 @@ onMounted(() => store.load(true));
last {{ fmtDate(usage(m.name)!.last_delivered_at!) }}
</span>
</template>
<span v-if="followed(m.name)">
followed {{ followed(m.name)!.followed }} of {{ followed(m.name)!.in_force }} in force
</span>
</span>
</div>
<p class="moment-desc">{{ m.means }}</p>
@@ -170,7 +201,9 @@ onMounted(() => store.load(true));
>×</button>
</span>
</div>
<MomentRuleUsage v-if="usage(m.name)" :rules="usage(m.name)!.by_rule" />
<MomentRuleUsage
v-if="usage(m.name)" :rules="usage(m.name)!.by_rule" :adherence="verdictsByRule(m.name)"
/>
</li>
</ul>
@@ -188,9 +221,14 @@ onMounted(() => store.load(true));
<span>delivered {{ usage(name)!.delivered }}</span>
<span>opened {{ usage(name)!.opened }} of {{ usage(name)!.rules }}</span>
</template>
<span v-if="followed(name)">
followed {{ followed(name)!.followed }} of {{ followed(name)!.in_force }} in force
</span>
</span>
</div>
<MomentRuleUsage v-if="usage(name)" :rules="usage(name)!.by_rule" />
<MomentRuleUsage
v-if="usage(name)" :rules="usage(name)!.by_rule" :adherence="verdictsByRule(name)"
/>
</li>
</ul>
</template>
+107
View File
@@ -0,0 +1,107 @@
<script setup lang="ts">
import { computed } from "vue";
import type { AdherenceCounts, AdherencePayload } from "@/api/moments";
/**
* Whether the rules in force at each moment were followed there. A rule is in
* force at a moment of a session when it was delivered there; each such case
* is followed, departed from (with a stated reason), broken, not applicable,
* or not judged yet. Verdicts come from a refused act, the session's own
* `rule_outcome` / `rule_misfired`, and transcript reviews
* (`adherence_to_judge`). One row per rule; open a row for its places.
*/
const props = defineProps<{
data: AdherencePayload | null;
failed: boolean;
}>();
const emit = defineEmits<{ retry: [] }>();
const rows = computed(() => props.data?.by_rule ?? []);
// The verdict counts in reading order, each shown only when it is not zero,
// so a row says what happened rather than listing zeros.
const PARTS: [keyof AdherenceCounts, string][] = [
["followed", "followed"],
["departed", "departed"],
["broken", "broken"],
["not_applicable", "not applicable"],
["unjudged", "not judged"],
];
function parts(c: AdherenceCounts): { key: string; text: string }[] {
return PARTS.filter(([k]) => c[k] > 0).map(([k, label]) => ({ key: k, text: `${label} ${c[k]}` }));
}
</script>
<template>
<section class="adherence" aria-labelledby="adherence-title">
<h3 id="adherence-title" class="sub-title">Were they followed</h3>
<p v-if="failed" class="error-msg">
Adherence could not be loaded.
<button type="button" class="btn-text" @click="emit('retry')">Try again</button>
</p>
<p v-else-if="!data" class="empty-msg">Loading adherence…</p>
<p v-else-if="!rows.length" class="empty-msg">
No rule was in force at a moment in the last {{ data.days }} days.
</p>
<template v-else>
<p class="field-hint">
Sessions each rule was in force in over the last {{ data.days }} days, and what each was
judged. A review fills in the rest from transcripts with <code>adherence_to_judge</code>.
</p>
<div class="adherence-totals">
<span>in force {{ data.totals.in_force }}</span>
<span>opened {{ data.totals.opened }}</span>
<span v-for="p in parts(data.totals)" :key="p.key" :class="`v-${p.key}`">{{ p.text }}</span>
</div>
<ul class="adherence-list">
<li v-for="r in rows" :key="r.rule_id" class="adherence-rule">
<details>
<summary class="adherence-row">
<span class="adherence-title">{{ r.title ?? `Rule ${r.rule_id} (deleted)` }}</span>
<span class="adherence-counts">
<span>in force {{ r.in_force }}</span>
<span>opened {{ r.opened }}</span>
<span v-for="p in parts(r)" :key="p.key" :class="`v-${p.key}`">{{ p.text }}</span>
</span>
</summary>
<ul class="adherence-places">
<li v-for="m in r.by_moment" :key="m.at" class="adherence-row">
<code class="moment-name">{{ m.at }}</code>
<span class="adherence-counts">
<span>in force {{ m.in_force }}</span>
<span>opened {{ m.opened }}</span>
<span v-for="p in parts(m)" :key="p.key" :class="`v-${p.key}`">{{ p.text }}</span>
</span>
</li>
</ul>
</details>
</li>
</ul>
</template>
</section>
</template>
<style scoped>
.adherence { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.adherence-totals,
.adherence-counts {
display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-2);
font-size: var(--fs-size-tiny); color: var(--fs-text-secondary);
font-variant-numeric: tabular-nums;
}
.adherence-counts { margin-left: auto; justify-content: flex-end; }
.adherence-list,
.adherence-places { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
.adherence-places { margin: var(--fs-space-1) 0 var(--fs-space-2) var(--fs-space-4); }
.adherence-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.adherence-rule summary { cursor: pointer; }
.adherence-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
/* Broken is the one count a person acts on, so it is the one that stands out;
not judged is a gap in the record, not a fault, and stays quiet. */
.v-broken { color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
.v-unjudged { color: var(--fs-text-tertiary); font-style: italic; }
</style>
<style src="@/assets/moments-shared.css" />
+62 -2
View File
@@ -7,22 +7,41 @@ import type {
import type { RuleTrigger } from "@/api/rulebooks";
import { apiErrorMessage } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import ConfirmDialog from "@/components/ConfirmDialog.vue";
/**
* Suggestions for how strongly a rule arrives and what reaches it, waiting on
* a person. A pass read each rule beside what happened when it reached
* sessions, and proposed its enforcement (inform, hold, enforce), its salience,
* or a typed trigger. Nothing changes until "Apply" is pressed; "Not this"
* keeps the value from being proposed again. The same judgment
* `judge_rule_weights` makes in a session, through the same service.
* keeps the value from being proposed again. "Apply all" confirms every
* listed suggestion at once, after a dialog that counts what changes. The
* same judgment `judge_rule_weights` makes in a session, through the same
* service.
*/
const toast = useToastStore();
const data = ref<WeightProposalsPayload | null>(null);
const failed = ref(false);
const busy = ref<string | null>(null);
const confirmingAll = ref(false);
const rules = computed<RuleWeightProposals[]>(() => data.value?.rules ?? []);
const proposalCount = computed(() => rules.value.reduce((n, r) => n + r.proposals.length, 0));
// The dialog names how many rules would start stopping work, since a hold or
// an enforce is the change a person notices in their next session.
const allSummary = computed(() => {
const stopping = rules.value.filter((r) => r.proposals.some(
(p) => p.field === "enforcement" && p.value !== "inform",
)).length;
const changes = `${proposalCount.value} change${proposalCount.value === 1 ? "" : "s"}`;
const across = `${rules.value.length} rule${rules.value.length === 1 ? "" : "s"}`;
const stops = stopping
? ` ${stopping} of them will hold or refuse the acts they govern.`
: "";
return `${changes} across ${across} take effect at once.${stops}`;
});
// What each enforcement does when the rule arrives — said beside the change,
// since "hold" and "enforce" stop work and the person applying one should
@@ -84,6 +103,31 @@ async function decide(rule: RuleWeightProposals, p: WeightProposal, verdict: Ver
}
}
async function applyAll() {
confirmingAll.value = false;
busy.value = "all";
try {
const out = await judgeWeightProposals(rules.value.flatMap((rule) => rule.proposals.map((p) => ({
rule_id: rule.id, field: p.field, value: p.trigger ?? p.value,
verdict: "confirm" as Verdict, note: "Applied with Apply all in Settings.",
}))));
if (out.refused.length) {
const first = out.refused[0];
toast.show(
`${out.judged.length} applied; ${out.refused.length} refused — #${first.rule_id}: ${first.error}`,
"error",
);
} else {
toast.show(`${out.judged.length} applied.`, "success");
}
await load();
} catch (e) {
toast.show(apiErrorMessage(e, "Could not apply the suggestions"), "error");
} finally {
busy.value = null;
}
}
onMounted(load);
</script>
@@ -102,6 +146,13 @@ onMounted(load);
rule exactly, by the tool, path, command or word the act carries; a rule with triggers
holds or refuses only the acts they match, and elsewhere it is a line.
</p>
<div class="proposals-bar">
<button
type="button" class="btn-primary btn-sm"
:disabled="busy !== null"
@click="confirmingAll = true"
>Apply all {{ proposalCount }}</button>
</div>
<ul class="proposal-list">
<li v-for="rule in rules" :key="rule.id" class="proposal-rule">
<div class="rule-head">
@@ -147,6 +198,15 @@ onMounted(load);
</li>
</ul>
</template>
<ConfirmDialog
v-if="confirmingAll"
title="Apply every suggestion?"
:message="allSummary"
confirm-label="Apply all"
:danger="false"
@confirm="applyAll"
@cancel="confirmingAll = false"
/>
</section>
</template>
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.11.23.2051",
"version": "2026.11.23.2305",
"author": {
"name": "Bryan Van Deusen"
},
+35 -1
View File
@@ -24,6 +24,16 @@
# honest. It records that an outcome was declared. The value of that is not the
# claim itself — it is that the absence of one becomes visible.
#
# `rule_misfired` closes the same gap from the other side: the rule arrived
# at a moment and did not bear on the work there. It is an answer too, so it
# goes in the same ledger.
#
# BOTH ALSO GO TO THE SERVER, with the session id the MCP call cannot carry,
# as an adherence verdict on this session's delivery of the rule: applied is
# followed, departed is departed, a misfire is not applicable at the moment it
# names (`/api/plugin/rule-verdict`). That is what lets the adherence readout
# put "followed" beside "delivered" and "opened" per rule and per moment.
#
# EXIT 0, ALWAYS. This decorates a ledger; a bookkeeping failure must never
# turn a successful tool call into a hook error.
set -uo pipefail
@@ -38,7 +48,7 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
[ -n "$session_id" ] || exit 0
# The matcher in hooks.json narrows to the rule_outcome tools, but the server
# The matcher in hooks.json narrows to the rule_outcome and rule_misfired tools, but the server
# segment of an MCP tool name varies with how the plugin was installed, so the
# id is read from the field rather than from an assumed tool name — the same
# reasoning grimoire_record_opened.sh gives.
@@ -52,4 +62,28 @@ safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
# Stamped and append-only like its two siblings, so one reader ages them all.
printf '%s\n' "$rule_id" | grimoire_rules_append "$state_dir/${safe_sid}.acted.ids"
# ── The verdict, to the server ───────────────────────────────────────────
command -v curl >/dev/null 2>&1 || exit 0
grimoire_config || exit 0
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
why=$(grimoire_json_pick "$event_flat" '.tool_input.why')
outcome=""
moment=""
case "$tool_name" in
*rule_misfired) moment=$(grimoire_json_pick "$event_flat" '.tool_input.moment') ;;
*) outcome=$(grimoire_json_pick "$event_flat" '.tool_input.outcome') ;;
esac
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
outcome_esc=$(printf '%s' "$outcome" | grimoire_json_escape) || exit 0
moment_esc=$(printf '%s' "$moment" | grimoire_json_escape) || exit 0
why_esc=$(printf '%s' "$why" | grimoire_json_escape) || exit 0
printf '{"rule_id":%s,"session_id":"%s","outcome":"%s","moment":"%s","why":"%s"}' \
"$rule_id" "$sid_esc" "$outcome_esc" "$moment_esc" "$why_esc" \
| curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/rule-verdict" >/dev/null 2>&1 || true
exit 0
+4
View File
@@ -20,6 +20,10 @@ What only Claude Code needs said:
or the reply ending a turn reaches a moment of work, the rules mounted on
it. Open the ones that apply; using-grimoire says what a quiet turn means and
how to correct a moment that fired wrongly.
- **A rule can hold or refuse a tool call.** A held call names its rule and
goes ahead once the rule has been read: read it, then make the call again.
A refused call is a boundary the operator drew; it moves when they change
the rule, so tell them what the rule said.
- **Compact at clean seams.** Because work is recorded as you go, a compaction
is safe once in-flight state is logged. After finishing a block of work in a
long session, log it to Grimoire, then tell the operator it's a good moment to
+1 -1
View File
@@ -82,7 +82,7 @@
]
},
{
"matcher": "mcp__.*__rule_outcome",
"matcher": "mcp__.*__(rule_outcome|rule_misfired)",
"hooks": [
{
"type": "command",
+32
View File
@@ -5,6 +5,13 @@ moment, when a reply is held for one read, when an action reached the wrong
moment or none, when a mounted rule arrived and did not apply, and when a line
proposes mounting or unmounting a rule.
## Contents
- What a moment is
- Reading a line that arrived at a moment — and a held or refused call
- When the moment is wrong — correct it in the session
- When a mounted rule arrives and does not apply
- When a line proposes a mount — and how rules are weighed and measured
## What a moment is
Most rules reach you by resemblance: what you are doing looks like what the
@@ -34,6 +41,22 @@ The reply that ends a turn is a moment too. When a rule mounted at
with its name: open it, then send the reply — unchanged, if it already does
what the rule asks. The same rule is never held twice.
A call can be held the same way. A rule declared `hold` that the call reaches
stops it once, naming the rule: read it, then make the call again — unchanged
if the rule does not bear on it, and then `rule_misfired` says so. A rule
declared `enforce` refuses the call every time, in its own words: that is a
boundary the operator drew, and it moves only when they change the rule, so
tell them what you were doing and what the rule said. A rule with triggers of
its own holds or refuses only the acts those triggers match; at the rest of
its moments it arrives as a line.
A moment sends a few lines, not every rule mounted there: ordered by
enforcement, then salience, then how exactly the act reached the rule, then
how often it has been opened there. What did not fit was left out, and a
rule already shown this session comes back as a short reminder, then not at
all. So a quiet moment means nothing more needed saying there, not that no
rule applies — `what_might_apply` asks for the whole list.
## When the moment is wrong — correct it in the session
A moment can fire on an action that is not that moment here, or an action can
@@ -96,3 +119,12 @@ triggers reach it exactly (`rules_to_weigh`, `propose_rule_weights`,
`rule_weight_proposals`, `judge_rule_weights`). It reads each rule beside its
delivery history and proposes; the operator confirms each change, in the
session or under Settings › Moments.
Whether a rule was followed where it arrived is measured per rule and per
moment (`rule_adherence`, and under Settings › Moments). Your own
`rule_outcome` and `rule_misfired` calls are the session's half of that
record: each lands as a verdict on the delivery you were answering. A
transcript review fills in the rest when the operator asks for one:
`adherence_to_judge` lists the rules in force at a moment of a session with
no verdict yet, and `judge_adherence` records followed, broken, departed or
not applicable, with what the transcript shows.
@@ -10,6 +10,7 @@ decides how some area of the work must behave; and before filling
## Contents
- Where a new rule goes — its home, its trigger, what already covers the moment
- When it applies — the moments a rule, a preference or a process is for
- How strongly it arrives — enforcement, salience, and the act it governs
- A ruling goes on the System it governs
- A lesson grows each time it proves itself
- A lesson names the rule it is an instance of
@@ -33,7 +34,10 @@ departs from a global rule writes its own and links it with
`relate_rules(kind="overrides")`, which says why. A rule that turns out to be
in the wrong home — a project rule that holds everywhere, a global one only a
single project needs — moves with `move_rule`, which keeps its id, history,
areas and edges. Propose the move and make it on a yes.
areas and edges. Propose the move and make it on a yes. Editing a rule that
lives on another project is curation, not that project's work: the plugin
names the rule and asks, and the edit goes ahead on the operator's yes rather
than becoming an issue there.
**Whichever home it gets, a rule needs `when_to_apply`.** It is the only thing
that decides whether the rule is ever seen: nothing is preloaded, so a rule
@@ -57,6 +61,35 @@ names the moments the procedure is for, so loading it reaches them and the
rules mounted there arrive with it. A rule that only applies inside one
procedure mounts on that procedure's own moment, `skill.<name>`.
## How strongly it arrives
A rule that reaches the work says one of three things, and you declare which
(`enforcement` on `create_rule`, `create_project_rule`, `update_rule`):
- **`inform`** — a line beside the work. The default, and right for most
rules: the session reads it and applies it.
- **`hold`** — the act or reply it governs waits until the session has read
the rule once; then it goes ahead. For a rule whose miss costs a rewrite: a
merge style, a release step, a check before a reply.
- **`enforce`** — the act is refused, in the rule's own words, every time,
and only a change to the rule moves it. For a boundary the operator draws
with no exceptions a session may judge. Most hard rules have an exit ("unless
the operator asks"), and a rule with an exit is a hold.
A hold or a refusal stops an act, so give it the act: a `triggers` entry
naming the command head (`git push origin main`), the tool (`create_release`)
or the path (`alembic/versions/*.py`) it governs. A rule with triggers stops
only the acts they match; at the rest of its moments it is a line. Without
one, it stops every act its moment reaches — a rule about pushing to `main`
mounted on `work.deliver` would hold every push to `dev`.
**`salience`** (`high`, `normal`, `low`) orders it against rules of the same
enforcement when a moment has more to say than fits. A moment sends a few
lines, highest first, and drops the rest — so `high` is for the rule that must
win a crowded moment, and `low` for one worth seeing but rarely decisive.
A preference never holds or refuses: it arrives as a line, with a salience.
**Before writing one, ask what already covers that moment.**
`what_might_apply("the moment you are about to write a record for")` — fifty
candidates and no bar, so an existing record cannot hide under a threshold the
+4
View File
@@ -169,6 +169,8 @@ _READ_ONLY_TOOLS = frozenset({
# rules, as list_rules is.
"rules_to_mount", "rule_moment_proposals",
"rules_to_weigh", "rule_weight_proposals",
# Adherence: the readout, and the queue a transcript review works from.
"rule_adherence", "adherence_to_judge",
})
# Every tool that WRITES, by name. Nothing reads this set at runtime — a tool
@@ -236,6 +238,8 @@ _WRITE_TOOLS = frozenset({
# A misfire report writes a counted row that can become an unmount
# proposal.
"rule_misfired",
# A transcript review's adherence verdicts, with the evidence it wrote.
"judge_adherence",
# A reviewer's verdicts on logged menu lines — rows carrying free
# prose the agent authored, `rule_outcome`'s reason for being a write.
"judge_menu",
+64
View File
@@ -16,6 +16,7 @@ from grimoire.mcp._context import current_user_id
from grimoire.services import moment_actions as actions_svc
from grimoire.services import moments as moments_svc
from grimoire.services import reply_shapes as shapes_svc
from grimoire.services import rule_adherence as adherence_svc
from grimoire.services import rule_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc
@@ -317,6 +318,66 @@ async def judge_rule_weights(judgments: list[dict]) -> dict:
return await weights_svc.judge(current_user_id(), judgments)
async def rule_adherence(days: int = 30, rule_id: int = 0) -> dict:
"""Whether the rules in force at each moment were followed there — per rule and per moment.
A rule is in force at a moment of a session when it was delivered there.
For each rule at each place (a moment such as `work.deliver`, or an arm
such as `pre_tool_rule`) over the last `days`: `in_force` (sessions it
was delivered there in), `opened` (sessions that opened it), and one
count per verdict — `followed`, `departed` (read and deliberately not
followed, with a reason), `broken` (the work went against it),
`not_applicable` (it did not bear on the work there) — and `unjudged`.
Verdicts come from an `enforce` refusal (the act did not happen), from
the session's own `rule_outcome` and `rule_misfired` calls, and from a
review of the transcript (`adherence_to_judge` / `judge_adherence`).
Returns `by_rule` (each with its places), `by_moment` (each with its
rules) and `totals`. `rule_id` narrows to one rule.
"""
return await adherence_svc.summary(current_user_id(), days=days, rule_id=rule_id or None)
async def adherence_to_judge(session_id: str = "", sessions: int = 3, per_session: int = 40) -> dict:
"""The rules that were in force at a moment of a session and have no verdict yet — for a transcript review.
Grouped by session, most recent first. Each item is one rule at one place
in that session: the rule's `statement` and `when_to_apply`, where it
arrived (`at`), how often and when (`delivered`, `first_at`, `last_at`),
and whether the session `opened` it. `how` says where the session's
transcript is kept.
To review a session: read its transcript around each item's times, see
what the work was at that moment, and decide whether it kept the rule.
Record the verdicts with `judge_adherence`, quoting or describing what in
the transcript shows each one. An item that did not bear on the work
there is `not_applicable`; that is a finding about where the rule is
delivered, and is as useful as the rest. `unjudged` is the total waiting.
`session_id` narrows to one session.
"""
return await adherence_svc.to_judge(
current_user_id(), session_id, sessions=sessions, per_session=per_session,
)
async def judge_adherence(verdicts: list[dict]) -> dict:
"""Record a transcript review's verdicts on rules in force at a moment of a session.
Each item is `{"session_id": "…", "rule_id": N, "at": "work.deliver",
"verdict": "followed"|"broken"|"departed"|"not_applicable",
"evidence": "…"}`, the `session_id`, `rule_id` and `at` as
`adherence_to_judge` listed them. `evidence` is required: what the
transcript shows — the act, the reply, or the passage — so a later reader
can check the verdict. `departed` is for a session that said why it did
not follow the rule; `broken` for work that went against it without one.
A review replaces the session's own account (a later, closer reading
wins), except where an `enforce` rule refused the act, which stands.
Returns `judged` and `refused`, each refused item with why.
"""
return await adherence_svc.judge(current_user_id(), verdicts)
def register(mcp) -> None:
mcp.tool(name="list_moments")(list_moments)
mcp.tool(name="list_reply_shapes")(list_reply_shapes)
@@ -331,3 +392,6 @@ def register(mcp) -> None:
mcp.tool(name="propose_rule_weights")(propose_rule_weights)
mcp.tool(name="rule_weight_proposals")(rule_weight_proposals)
mcp.tool(name="judge_rule_weights")(judge_rule_weights)
mcp.tool(name="rule_adherence")(rule_adherence)
mcp.tool(name="adherence_to_judge")(adherence_to_judge)
mcp.tool(name="judge_adherence")(judge_adherence)
+24 -9
View File
@@ -535,9 +535,14 @@ async def create_rule(
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.
act it governs wait until the session has read the rule once
(file edits are never held) — for a rule whose miss costs a
rewrite. `enforce` refuses the act it governs, in the rule's own
words, every time — for a boundary only the operator moves; it
needs a trigger, or a mount on a moment an act reaches, to have
an act to refuse. A rule with triggers holds or refuses only the
acts they match; reached by its mount alone it is a line. 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
@@ -668,9 +673,14 @@ async def create_project_rule(
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.
act it governs wait until the session has read the rule once
(file edits are never held) — for a rule whose miss costs a
rewrite. `enforce` refuses the act it governs, in the rule's own
words, every time — for a boundary only the operator moves; it
needs a trigger, or a mount on a moment an act reaches, to have
an act to refuse. A rule with triggers holds or refuses only the
acts they match; reached by its mount alone it is a line. 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
@@ -786,9 +796,14 @@ async def update_rule(
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.
act it governs wait until the session has read the rule once
(file edits are never held) — for a rule whose miss costs a
rewrite. `enforce` refuses the act it governs, in the rule's own
words, every time — for a boundary only the operator moves; it
needs a trigger, or a mount on a moment an act reaches, to have
an act to refuse. A rule with triggers holds or refuses only the
acts they match; reached by its mount alone it is a line. 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
+1
View File
@@ -61,6 +61,7 @@ from grimoire.models.retrieval_tuning import RetrievalTuningEvent # noqa: E402,
from grimoire.models.note_usage import NoteUsageEvent # 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.rule_adherence import RuleAdherence # 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.moment_mapping import MomentMapping # noqa: E402, F401
+86
View File
@@ -0,0 +1,86 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, Index, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import iso
# What happened to a rule that was in force at a moment of a session.
FOLLOWED = "followed"
DEPARTED = "departed"
BROKEN = "broken"
NOT_APPLICABLE = "not_applicable"
VERDICTS = (FOLLOWED, DEPARTED, BROKEN, NOT_APPLICABLE)
# Where the verdict came from.
REFUSED = "refused" # the act was refused by an `enforce` rule: kept by construction
OUTCOME = "outcome" # the session declared it with `rule_outcome`
MISFIRE = "misfire" # the session reported it with `rule_misfired`
JUDGE = "judge" # a review of the session's transcript
SOURCES = (REFUSED, OUTCOME, MISFIRE, JUDGE)
class RuleAdherence(Base):
"""Whether a rule in force at a moment of a session was followed there.
The unit is a rule delivered at one place (`at`: a moment such as
`work.deliver`, or an arm such as `pre_tool_rule`) in one session — the
same unit `rule_deliveries` records, so every verdict sits on a delivery
and the readout can put "followed" beside "delivered" and "opened". A
rule delivered ten times at one moment of one session gets one verdict:
it was followed there or it was not.
`verdict` is one of:
- `followed` — the work kept the rule;
- `departed` — the session read it and deliberately did not follow it,
with its reason in `evidence`. A departure is an answer, not a fault;
- `broken` — the work went against it with no stated reason;
- `not_applicable` — the rule arrived but did not bear on what the
session was doing there (a misfire).
`source` says how it is known, strongest first: `refused` (an `enforce`
rule refused the act, so the act did not happen), `outcome` and
`misfire` (the session said so in a tool call, watched by the plugin),
`judge` (a later review read the transcript). A `refused` verdict is a
fact and is never replaced; any other is replaced by a later one, so a
review can correct a session's own account.
FK-free on `rule_id` and `user_id` like the other telemetry tables, and
pruned with the deliveries it describes.
"""
__tablename__ = "rule_adherence"
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)
at: Mapped[str] = mapped_column(Text, nullable=False)
verdict: Mapped[str] = mapped_column(Text, nullable=False)
source: Mapped[str] = mapped_column(Text, nullable=False)
evidence: Mapped[str | None] = mapped_column(Text, nullable=True)
judged_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
__table_args__ = (
UniqueConstraint("user_id", "session_id", "rule_id", "at",
name="uq_rule_adherence_session_rule_at"),
Index("ix_rule_adherence_rule_at", "rule_id", "at"),
Index("ix_rule_adherence_judged_at", "judged_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,
"at": self.at,
"verdict": self.verdict,
"source": self.source,
"evidence": self.evidence,
"judged_at": iso(self.judged_at),
}
+32
View File
@@ -20,6 +20,7 @@ from grimoire.services import moment_delivery as moment_delivery_svc
from grimoire.services import plugin_context as plugin_ctx_svc
from grimoire.services import reply_shapes as reply_shapes_svc
from grimoire.services import repo_bindings as repo_bindings_svc
from grimoire.services import rule_adherence as rule_adherence_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
@@ -458,6 +459,37 @@ async def rule_opened():
))
@plugin_bp.post("/rule-verdict")
@login_required
async def rule_verdict():
"""A session said what a rule it was delivered did there.
Body: `{"session_id", "rule_id", "outcome"?, "moment"?, "why"?}`, posted
by the plugin after a `rule_outcome` call (`outcome`: applied or
departed) or a `rule_misfired` call (`moment`: where it arrived and did
not apply). The verdict lands on this session's latest delivery of the
rule — at that moment, for a misfire — and is the adherence readout's
evidence that the rule was followed, departed from, or did not bear on
the work. A rule the session was never delivered records nothing.
Returns `{"recorded", "at"}`.
"""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict):
return jsonify({"recorded": False, "at": ""})
try:
rule_id = int(data.get("rule_id") or 0)
except (TypeError, ValueError):
rule_id = 0
if rule_id <= 0:
return jsonify({"recorded": False, "at": ""})
return jsonify(await rule_adherence_svc.from_session(
g.user.id, str(data.get("session_id") or ""), rule_id,
outcome=str(data.get("outcome") or ""),
misfired_at=str(data.get("moment") or ""),
why=str(data.get("why") or ""),
))
@plugin_bp.post("/reply-rules")
@login_required
@memoized_query_embeddings
+17
View File
@@ -21,6 +21,7 @@ from grimoire.auth import get_current_user_id, login_required
from grimoire.services import moment_actions as moment_actions_svc
from grimoire.services import moments as moments_svc
from grimoire.services import reply_shapes as shapes_svc
from grimoire.services import rule_adherence as adherence_svc
from grimoire.services import rule_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc
from grimoire.services import rulebooks as rulebooks_svc
@@ -241,6 +242,22 @@ async def judge_moment_proposals_route():
return jsonify(await judgments_svc.judge(get_current_user_id(), data["judgments"]))
@retrieval_bp.route("/adherence", methods=["GET"])
@login_required
async def adherence_route():
"""Whether the rules in force at each moment were followed there —
`rule_adherence`'s payload, from the same service. `?days=` sets the
window (default 30); `?rule_id=` narrows to one rule."""
try:
days = int(request.args.get("days") or adherence_svc.SUMMARY_DAYS)
rule_id = int(request.args.get("rule_id") or 0)
except ValueError:
return jsonify({"error": "days and rule_id must be whole numbers"}), 400
return jsonify(await adherence_svc.summary(
get_current_user_id(), days=days, rule_id=rule_id or None,
))
@retrieval_bp.route("/weights/proposals", methods=["GET"])
@login_required
async def weight_proposals_route():
+3
View File
@@ -196,6 +196,9 @@ _NOT_INCLUDED = [
# another instance and pruned after months anyway. The ordering reads
# them as history; a restored instance rebuilds it within weeks.
"rule_deliveries",
# Adherence verdicts on those deliveries, keyed by the same session ids
# and pruned with them.
"rule_adherence",
# 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
# leave a verdict on nothing. A sample, re-takeable by the review pass.
+75 -4
View File
@@ -91,8 +91,10 @@ PROCESS_SKILL_PREFIX = "grimoire-proc-"
PROCESS_MOMENTS_FIELD = "moments"
PROCESS = "process"
_SEGMENT_SPLIT = re.compile(r"&&|\|\||[;|\n]")
_ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=\S*\s+")
# `<<WORD`, `<<-WORD`, `<<'WORD'`, `<<"WORD"`: a heredoc whose body follows
# the line and ends at a line holding only WORD (`<<<` is a here-string).
_HEREDOC = re.compile(r"""<<(-?)[ \t]*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2""")
@dataclass(frozen=True)
@@ -169,14 +171,83 @@ def _squash(text: str) -> str:
def _segments(command: str) -> list[str]:
out = []
for part in _SEGMENT_SPLIT.split(command or ""):
seg = part.strip().lstrip("(").strip()
"""The commands a shell line runs, each from its head.
Split where the shell separates commands (`&&`, `||`, `;`, `|`, a
newline) — but only outside quotes, and never inside a heredoc's body. A
quoted argument and the text a heredoc feeds a program are data, not
commands: `grep "a && git push"` runs grep, and a script written with
`cat <<EOF` that contains `curl` reaches no host.
"""
text = command or ""
out: list[str] = []
buf: list[str] = []
heredocs: list[tuple[str, bool]] = []
def flush() -> None:
seg = "".join(buf).strip().lstrip("(").strip()
buf.clear()
while _ENV_ASSIGN.match(seg):
seg = _ENV_ASSIGN.sub("", seg, count=1)
seg = _squash(seg)
if seg:
out.append(seg)
i, n, quote = 0, len(text), ""
while i < n:
c = text[i]
if quote:
if c == "\\" and quote == '"' and i + 1 < n:
buf.append(text[i:i + 2])
i += 2
continue
buf.append(c)
if c == quote:
quote = ""
i += 1
continue
if c == "\\" and i + 1 < n:
# A backslash-newline continues the line; anything else is escaped.
if text[i + 1] != "\n":
buf.append(text[i:i + 2])
i += 2
continue
if c in "'\"":
quote = c
buf.append(c)
i += 1
continue
if text.startswith("<<", i) and not text.startswith("<<<", i):
m = _HEREDOC.match(text, i)
if m:
heredocs.append((m.group(3), m.group(1) == "-"))
buf.append(m.group(0))
i = m.end()
continue
if text.startswith("&&", i) or text.startswith("||", i):
flush()
i += 2
continue
if c in ";|":
flush()
i += 1
continue
if c == "\n":
flush()
i += 1
# The bodies of this line's heredocs, in order, are skipped whole.
for word, tabs in heredocs:
while i < n:
end = text.find("\n", i)
line = text[i:end if end != -1 else n]
i = end + 1 if end != -1 else n
if (line.lstrip("\t") if tabs else line) == word:
break
heredocs.clear()
continue
buf.append(c)
i += 1
flush()
return out
+2 -1
View File
@@ -24,7 +24,7 @@ logger = logging.getLogger(__name__)
def _io() -> rp.MomentIO:
"""Resolved at CALL time, so a test patching either module's name is seen."""
from grimoire.services import rule_deliveries, rule_usage, rulebooks
from grimoire.services import rule_adherence, rule_deliveries, rule_usage, rulebooks
bound = rule_deliveries.bound()
return rp.MomentIO(
@@ -33,6 +33,7 @@ def _io() -> rp.MomentIO:
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,
record_refusal=rule_adherence.note_refused if bound else None,
)
+16 -5
View File
@@ -1713,6 +1713,10 @@ class MomentIO:
"""As on `RuleIO`."""
retired: Callable[..., Any] | None = None
"""As on `RuleIO`."""
record_refusal: Callable[..., Any] | None = None
"""`rule_adherence.note_refused(user_id, [(rule_id, at, where)])`: an
`enforce` rule refused this act, so it was kept there. None where the door
keeps no deliveries."""
def _reached_by(hit: dict) -> str:
@@ -1771,11 +1775,18 @@ async def run_moment_arm(
# rule about pushing to `main` mounted on work.deliver would hold
# every push to `dev`). Reached by the mount alone, it is a line.
triggered = board.triggered if board is not None else set()
decision = act_decision(
[(rule, at, where) for rule, at, where, spec in cands
if spec == rule_order.BY_TRIGGER or rule.id not in triggered],
held=moment.held,
)
acting = [(rule, at, where) for rule, at, where, spec in cands
if spec == rule_order.BY_TRIGGER or rule.id not in triggered]
decision = act_decision(acting, held=moment.held)
if decision.get("kind") == "enforce" and io.record_refusal is not None:
# A refusal is the one adherence verdict known at the act itself.
refused = set(decision["rule_ids"])
try:
io.record_refusal(moment.user_id, [
(rule.id, at, where) for rule, at, where in acting if rule.id in refused
])
except Exception: # noqa: BLE001 - observation never breaks the observed
_telemetry_failed(MOMENT_RULE_SOURCE)
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]
+358
View File
@@ -0,0 +1,358 @@
"""Whether the rules in force at each moment were followed there.
A rule is IN FORCE at a moment of a session when it was delivered there: one
`rule_deliveries` row or more for that (session, rule, place). Each such
triple gets at most one verdict (`models/rule_adherence.py`), from the
strongest evidence there is:
- `note_refused` — an `enforce` rule refused the act, so the act did not
happen: followed, by construction. Recorded by the moment arm as it decides.
- `from_session` — the session declared what the rule did (`rule_outcome`:
applied → followed, departed → departed) or that it did not bear on the
work (`rule_misfired` → not applicable). The plugin watches both calls and
posts them with the session id, so the verdict lands on the delivery the
session was answering.
- `judge` — a review read the session's transcript and says followed,
broken, departed or not applicable, with the evidence. `to_judge` lists
what is waiting for one.
`summary` is the readout: per rule and per place (a moment or an arm), how
many sessions it was in force in, opened in, and each verdict, with the rest
counted as unjudged. Only deliveries whose plugin reports opens are counted
(`rule_deliveries.REPORTS_OPENS`), so "opened" beside "followed" means the
same thing on every row.
"""
from __future__ import annotations
import logging
from datetime import datetime, timedelta, timezone
from sqlalchemy import and_, case, delete, func, select, true
from sqlalchemy.dialects.postgresql import insert
from grimoire.models import async_session
from grimoire.models.rule_adherence import (
BROKEN, DEPARTED, FOLLOWED, JUDGE, MISFIRE, NOT_APPLICABLE, OUTCOME, REFUSED,
VERDICTS, RuleAdherence,
)
from grimoire.models.rule_delivery import RuleDelivery
from grimoire.models.rulebook import Rule
from grimoire.services import rule_deliveries
from grimoire.services.background import spawn
logger = logging.getLogger(__name__)
SUMMARY_DAYS = 30
_EVIDENCE_CHARS = 1000
_EXCERPT_CHARS = 400
JUDGE_SESSIONS = 3
JUDGE_PER_SESSION = 40
# A session's own word, mapped to a verdict.
OUTCOME_VERDICTS = {"applied": FOLLOWED, "departed": DEPARTED}
# Where Claude Code keeps a session's transcript, for the reviewer: the file
# is named for the session id the deliveries carry.
TRANSCRIPT_HINT = (
"Each session's transcript is a JSONL file named for its session id. Claude Code keeps "
"them under ~/.claude/projects/<project directory>/<session_id>.jsonl, so "
"`ls ~/.claude/projects/*/<session_id>.jsonl` finds one. Read it around each rule's "
"delivered times: what was the work at that moment, and did it keep the rule?"
)
def _evidence(text) -> str:
return " ".join(str(text or "").split())[:_EVIDENCE_CHARS]
def _excerpt(text) -> str:
text = " ".join(str(text or "").split())
return text if len(text) <= _EXCERPT_CHARS else text[:_EXCERPT_CHARS - 1] + "…"
async def record(
user_id: int, session_id: str, rule_id: int, at: str,
verdict: str, source: str, evidence: str = "",
) -> bool:
"""Set the verdict for one rule at one place in one session.
Replaces an earlier verdict unless that one came from a refusal, which is
a fact about the act and stands. Returns whether a row was written.
"""
if verdict not in VERDICTS or not session_id or not at:
return False
stmt = insert(RuleAdherence).values(
user_id=int(user_id), session_id=session_id, rule_id=int(rule_id), at=str(at),
verdict=verdict, source=source, evidence=_evidence(evidence) or None,
)
stmt = stmt.on_conflict_do_update(
constraint="uq_rule_adherence_session_rule_at",
set_={"verdict": stmt.excluded.verdict, "source": stmt.excluded.source,
"evidence": stmt.excluded.evidence, "judged_at": func.now()},
where=RuleAdherence.source != REFUSED,
)
async with async_session() as session:
result = await session.execute(stmt)
await session.commit()
return bool(result.rowcount)
def note_refused(user_id: int, refused: list[tuple[int, str, str]]) -> None:
"""Record that `enforce` rules refused an act in the bound session.
`refused` is `(rule_id, at, where)` for each rule that drew the line;
`where` says what reached it and goes in as the evidence. A no-op outside
a plugin request, which has no session to record against.
"""
sid = rule_deliveries.current_session()
if not sid or not refused:
return
async def _write() -> None:
for rid, at, where in refused:
await record(user_id, sid, rid, at, FOLLOWED, REFUSED, f"The act was refused ({where}).")
spawn(_write(), site="rule_adherence_refused")
async def from_session(
user_id: int, session_id: str, rule_id: int, *,
outcome: str = "", misfired_at: str = "", why: str = "",
) -> dict:
"""Turn a session's own `rule_outcome` or `rule_misfired` into a verdict.
The verdict lands on the place the session last had the rule delivered —
for a misfire, the moment it names. A rule the session was never
delivered (looked up unprompted) gets none: adherence is about rules that
reached a moment. Returns `{"recorded": bool, "at": str}`.
"""
sid = rule_deliveries.clean_session(session_id)
if misfired_at:
verdict, source = NOT_APPLICABLE, MISFIRE
else:
verdict, source = OUTCOME_VERDICTS.get((outcome or "").strip().lower(), ""), OUTCOME
if not sid or not rule_id or not verdict:
return {"recorded": False, "at": ""}
clauses = [RuleDelivery.user_id == user_id, RuleDelivery.session_id == sid,
RuleDelivery.rule_id == int(rule_id)]
if misfired_at:
clauses.append(RuleDelivery.at == misfired_at.strip())
async with async_session() as session:
at = (await session.execute(
select(RuleDelivery.at).where(*clauses)
.order_by(RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc()).limit(1)
)).scalar_one_or_none()
if at is None:
return {"recorded": False, "at": ""}
done = await record(user_id, sid, int(rule_id), at, verdict, source, why)
return {"recorded": done, "at": at}
def _triples(user_id: int, since):
"""One row per (session, rule, place) delivered since `since`, from
plugins that report opens: how often, when, and whether it was opened."""
return (
select(
RuleDelivery.session_id, RuleDelivery.rule_id, RuleDelivery.at,
func.count(RuleDelivery.id).label("delivered"),
func.min(RuleDelivery.delivered_at).label("first_at"),
func.max(RuleDelivery.delivered_at).label("last_at"),
func.bool_or(RuleDelivery.opened_at.is_not(None)).label("opened"),
)
.where(RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since,
rule_deliveries.REPORTS_OPENS)
.group_by(RuleDelivery.session_id, RuleDelivery.rule_id, RuleDelivery.at)
.subquery()
)
def _verdict_join(t, user_id: int):
return and_(RuleAdherence.user_id == user_id, RuleAdherence.session_id == t.c.session_id,
RuleAdherence.rule_id == t.c.rule_id, RuleAdherence.at == t.c.at)
async def to_judge(
user_id: int, session_id: str = "", *,
sessions: int = JUDGE_SESSIONS, per_session: int = JUDGE_PER_SESSION,
) -> dict:
"""The rules in force at a moment of a session that have no verdict yet.
Grouped by session, most recent first, each with what the reviewer needs
to judge it from the transcript: the rule's statement and when it
applies, the place it arrived, how often and when, and whether it was
opened. `session_id` narrows to one session.
"""
sessions = max(1, min(int(sessions or JUDGE_SESSIONS), 10))
per_session = max(1, min(int(per_session or JUDGE_PER_SESSION), 100))
since = datetime.now(timezone.utc) - timedelta(days=rule_deliveries.RETAIN_DAYS)
t = _triples(user_id, since)
one = rule_deliveries.clean_session(session_id) if session_id else ""
waiting = and_(RuleAdherence.id.is_(None), t.c.session_id == one if one else true())
async with async_session() as session:
total = (await session.execute(
select(func.count()).select_from(t).outerjoin(RuleAdherence, _verdict_join(t, user_id))
.where(waiting)
)).scalar_one()
recent = (await session.execute(
select(t.c.session_id, func.min(t.c.first_at), func.max(t.c.last_at))
.select_from(t).outerjoin(RuleAdherence, _verdict_join(t, user_id))
.where(waiting)
.group_by(t.c.session_id)
.order_by(func.max(t.c.last_at).desc())
.limit(sessions)
)).all()
out = []
for sid, first_at, last_at in recent:
rows = (await session.execute(
select(t.c.rule_id, t.c.at, t.c.delivered, t.c.first_at, t.c.last_at, t.c.opened,
Rule.title, Rule.statement, Rule.when_to_apply, Rule.kind)
.select_from(t)
.outerjoin(RuleAdherence, _verdict_join(t, user_id))
.outerjoin(Rule, Rule.id == t.c.rule_id)
.where(RuleAdherence.id.is_(None), t.c.session_id == sid)
.order_by(t.c.first_at, t.c.rule_id)
.limit(per_session)
)).all()
out.append({
"session_id": sid,
"first_at": first_at.isoformat() if first_at else None,
"last_at": last_at.isoformat() if last_at else None,
"items": [{
"rule_id": int(rid), "at": at, "title": title,
"kind": kind, "statement": _excerpt(statement),
"when_to_apply": _excerpt(when),
"delivered": int(n), "opened": bool(opened),
"first_at": f.isoformat() if f else None,
"last_at": last.isoformat() if last else None,
} for rid, at, n, f, last, opened, title, statement, when, kind in rows],
})
return {"sessions": out, "unjudged": int(total or 0), "how": TRANSCRIPT_HINT}
async def judge(user_id: int, items: list[dict]) -> dict:
"""Record a review's verdicts: `{session_id, rule_id, at, verdict, evidence}` each.
`verdict` is followed, broken, departed or not_applicable, and
`evidence` — what in the transcript shows it — is required: a verdict a
later reader cannot check is no better than none. The triple must be one
this user was delivered. A bad item is refused alone; a refusal's verdict
is never replaced.
"""
done: list[dict] = []
refused: list[dict] = []
for item in items or []:
if not isinstance(item, dict):
refused.append({"item": item, "error": "each verdict is an object"})
continue
sid = rule_deliveries.clean_session(str(item.get("session_id") or ""))
at = str(item.get("at") or "").strip()
verdict = str(item.get("verdict") or "").strip().lower()
evidence = _evidence(item.get("evidence"))
try:
rid = int(item.get("rule_id") or 0)
except (TypeError, ValueError):
rid = 0
key = {"session_id": sid, "rule_id": rid, "at": at}
if not sid or rid <= 0 or not at:
refused.append({**key, "error": "needs session_id, rule_id and at"})
continue
if verdict not in VERDICTS:
refused.append({**key, "error": f"verdict is one of {', '.join(VERDICTS)}"})
continue
if not evidence:
refused.append({**key, "error": "evidence is required: what in the transcript shows it"})
continue
async with async_session() as session:
delivered = (await session.execute(
select(RuleDelivery.id).where(
RuleDelivery.user_id == user_id, RuleDelivery.session_id == sid,
RuleDelivery.rule_id == rid, RuleDelivery.at == at,
).limit(1)
)).scalar_one_or_none()
if delivered is None:
refused.append({**key, "error": "no delivery of this rule there in that session"})
continue
if not await record(user_id, sid, rid, at, verdict, JUDGE, evidence):
refused.append({**key, "error": "an enforce refusal already settled it"})
continue
done.append({**key, "verdict": verdict})
return {"judged": done, "refused": refused}
def _counts() -> dict:
return {"in_force": 0, "opened": 0, FOLLOWED: 0, DEPARTED: 0, BROKEN: 0,
NOT_APPLICABLE: 0, "unjudged": 0}
def _add(slot: dict, row: dict) -> None:
for k in _counts():
slot[k] += row[k]
async def summary(user_id: int, days: int = SUMMARY_DAYS, rule_id: int | None = None) -> dict:
"""Adherence per rule and per place, over the last `days`.
For each (rule, place): `in_force` is how many sessions the rule was
delivered there in; `opened` how many of those opened it; then one count
per verdict, and `unjudged` for the sessions with none yet. `by_rule`
lists each rule with its places; `by_moment` lists each place with its
rules; `totals` sums them. Counts only — a person reads "in force 12,
followed 9, broken 1, unjudged 2" more truly than a rate that hides the
unjudged.
"""
days = max(1, min(int(days or SUMMARY_DAYS), rule_deliveries.RETAIN_DAYS))
since = datetime.now(timezone.utc) - timedelta(days=days)
t = _triples(user_id, since)
v = RuleAdherence.verdict
def n(cond):
return func.sum(case((cond, 1), else_=0))
stmt = (
select(
t.c.rule_id, t.c.at, Rule.title,
func.count().label("in_force"),
n(t.c.opened).label("opened"),
n(v == FOLLOWED).label(FOLLOWED), n(v == DEPARTED).label(DEPARTED),
n(v == BROKEN).label(BROKEN), n(v == NOT_APPLICABLE).label(NOT_APPLICABLE),
n(RuleAdherence.id.is_(None)).label("unjudged"),
)
.select_from(t)
.outerjoin(RuleAdherence, _verdict_join(t, user_id))
.outerjoin(Rule, Rule.id == t.c.rule_id)
.group_by(t.c.rule_id, t.c.at, Rule.title)
.order_by(t.c.rule_id, t.c.at)
)
if rule_id:
stmt = stmt.where(t.c.rule_id == int(rule_id))
async with async_session() as session:
rows = (await session.execute(stmt)).mappings().all()
by_rule: dict[int, dict] = {}
by_moment: dict[str, dict] = {}
totals = _counts()
for raw in rows:
row = {k: int(raw[k] or 0) for k in _counts()}
rid, at = int(raw["rule_id"]), raw["at"]
rule_slot = by_rule.setdefault(rid, {"rule_id": rid, "title": raw["title"],
**_counts(), "by_moment": []})
_add(rule_slot, row)
rule_slot["by_moment"].append({"at": at, **row})
moment_slot = by_moment.setdefault(at, {"at": at, **_counts(), "by_rule": []})
_add(moment_slot, row)
moment_slot["by_rule"].append({"rule_id": rid, "title": raw["title"], **row})
_add(totals, row)
return {
"days": days,
"totals": totals,
"by_rule": sorted(by_rule.values(), key=lambda r: (-r["in_force"], r["rule_id"])),
"by_moment": sorted(by_moment.values(), key=lambda m: (-m["in_force"], m["at"])),
}
async def prune(cutoff) -> int:
"""Delete verdicts older than `cutoff`, with the deliveries they describe."""
async with async_session() as session:
result = await session.execute(delete(RuleAdherence).where(RuleAdherence.judged_at < cutoff))
await session.commit()
return int(result.rowcount or 0)
+15 -5
View File
@@ -59,7 +59,7 @@ REPORTS_OPENS = RuleDelivery.plugin.is_not(None)
def bind_session(session_id: str | None, plugin: str | None = None) -> None:
_session.set(_clean_session(session_id))
_session.set(clean_session(session_id))
_plugin.set(_UNSAFE.sub("_", (plugin or "").strip())[:_PLUGIN_MAX])
_pending.set([])
@@ -84,7 +84,12 @@ def bound() -> bool:
return bool(_session.get())
def _clean_session(session_id: str | None) -> str:
def current_session() -> str:
"""The session this request delivers to, or "" outside a plugin request."""
return _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]
@@ -97,7 +102,7 @@ def record(
"""Record delivered lines: `(rule_id, at, form)` each. A no-op without a
session, since an open could never be tied back. `session_id` None means
the one bound for this request, whose rows wait for `flush`."""
sid = _clean_session(_session.get() if session_id is None else session_id)
sid = clean_session(_session.get() if session_id is None else session_id)
if not sid or not lines:
return
plugin = _plugin.get() or None
@@ -131,7 +136,7 @@ async def mark_opened(user_id: int, session_id: str | None, rule_id: int) -> boo
five times and opened once was opened after the fifth line, and the four
before it were passed over.
"""
sid = _clean_session(session_id)
sid = clean_session(session_id)
if not sid or not rule_id:
return False
now = datetime.now(timezone.utc)
@@ -217,13 +222,18 @@ async def retired(user_id: int, rule_ids: list[int]) -> set[int]:
async def prune(retain_days: int = RETAIN_DAYS) -> int:
"""Delete deliveries older than `retain_days`, and the adherence verdicts
on them (`rule_adherence`), which mean nothing without their delivery."""
from grimoire.services import rule_adherence
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)
await rule_adherence.prune(cutoff)
return int(result.rowcount or 0)
_prune_task = None
+21
View File
@@ -137,6 +137,7 @@ WRITE_TARGETS: dict[str, dict[str, str]] = {
"propose_rule_weights": {},
"judge_rule_weights": {},
"rule_misfired": {},
"judge_adherence": {},
"judge_menu": {},
# trash: a batch can hold rows from several projects
"restore": {"deleted_batch_id": TRASH},
@@ -187,6 +188,17 @@ READ_PREFIXES = (
ISSUE_STATUSES = frozenset({"", "todo"})
# Curating a rule that lives on another project: editing, moving, verifying,
# relating or deleting it. A rule is the operator's standing instruction, not
# that project's work in progress, so the guard names the rule it changes and
# leaves the call to them rather than suggesting an issue in its place.
RULE_CURATION_TOOLS = frozenset({
"update_rule", "update_preference", "delete_rule", "move_rule",
"mark_rule_verified", "relate_rules", "unrelate_rules",
})
_RULE_ARGS = ("rule_id", "from_rule_id", "to_rule_id")
def is_issue_filing(tool: str, args: dict) -> bool:
"""True for create_task(kind="issue") that opens a fresh, unplanned issue."""
if tool != "create_task":
@@ -329,6 +341,15 @@ async def check_act(
if tool and is_issue_filing(tool, args):
return {"allowed": True, "targets": targets, "issue": True, "reason": ""}
there = ", ".join(_named(p, titles) for p in others)
if tool in RULE_CURATION_TOOLS:
rules = sorted({r for name in _RULE_ARGS for r in _positive_ints(args.get(name))})
which = ", ".join(f"rule {r}" for r in rules) or "a rule"
reason = (
f"This session belongs to {_named(session_project, titles)}. {tool} changes "
f"{which} of {there}, a different project. Rules are the operator's to "
f"curate from any session: approve if they asked for this change."
)
return {"allowed": False, "targets": targets, "issue": False, "reason": reason}
what = act.strip() or (f"{tool} changes" if tool else "This changes")
first = others[0]
reason = (
+14
View File
@@ -207,6 +207,20 @@ TOPICS: tuple[Topic, ...] = (
Topic("a mount that arrives where it does not apply is reported, and reports become the offer", U,
("rule_misfired",),
"a rule you read and set aside leaves no trace anyone else can see"),
# How strongly a rule arrives (milestone 639). Declared while the rule is
# written (writing-records.md), and met as a held or refused call or a
# quiet moment (moments.md); the static context carries a short form for
# Claude Code, where a hook is what holds the call.
Topic("a rule declares how strongly it arrives: enforcement, salience, the act it governs", U,
("enforcement", "salience", "triggers"),
"a rule with an exit is a hold",
shared_with=("docstrings",)),
Topic("a held call is read and made again; a refused call is the operator's boundary", U,
("held", "refuses the call every time"),
"it moves only when they change the rule"),
Topic("a quiet moment is a budget, not an absence", U,
("what_might_apply", "short reminder"),
"a quiet moment means nothing more needed saying there"),
Topic("a missed when is mounted or mapped, not reworded", U,
("update_rule(moments=",),
"first ask whether it missed a when or a what"),
+162
View File
@@ -0,0 +1,162 @@
"""Real-Postgres tests for `rule_adherence`: a verdict on each rule in force at
a moment of a session, from a refused act, the session's own outcome or
misfire, or a transcript review — and the readout per rule and per moment."""
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import delete, select
from grimoire.models import async_session
from grimoire.models.rule_adherence import RuleAdherence
from grimoire.models.rule_delivery import RuleDelivery
from grimoire.services import background, rule_adherence, rule_deliveries
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
RULE = 9_200_001
OTHER = 9_200_002
PLUGIN = "2026.11.23.2100"
async def _user(name: str = "rule_adherence_owner") -> int:
async with async_session() as s:
user = await ensure_user(s, name)
uid = user.id
await s.commit()
await s.execute(delete(RuleDelivery).where(RuleDelivery.user_id == uid))
await s.execute(delete(RuleAdherence).where(RuleAdherence.user_id == uid))
await s.commit()
return uid
async def _deliver(uid, sid, rule_id, at, *, minutes_ago=0, opened=False, plugin=PLUGIN):
when = datetime.now(timezone.utc) - timedelta(minutes=minutes_ago)
async with async_session() as s:
s.add(RuleDelivery(user_id=uid, session_id=sid, rule_id=rule_id, source="moment_rule",
at=at, form="full", plugin=plugin, delivered_at=when,
opened_at=when if opened else None))
await s.commit()
async def _verdicts(uid) -> dict[tuple[str, int, str], tuple[str, str]]:
async with async_session() as s:
rows = (await s.execute(
select(RuleAdherence).where(RuleAdherence.user_id == uid)
)).scalars().all()
return {(r.session_id, r.rule_id, r.at): (r.verdict, r.source) for r in rows}
async def test_an_outcome_lands_on_the_place_the_session_last_had_the_rule():
uid = await _user()
await _deliver(uid, "s-1", RULE, "work.start", minutes_ago=10)
await _deliver(uid, "s-1", RULE, "work.deliver", minutes_ago=2)
out = await rule_adherence.from_session(uid, "s-1", RULE, outcome="applied")
assert out == {"recorded": True, "at": "work.deliver"}
await rule_adherence.from_session(uid, "s-1", RULE, outcome="departed", why="the operator asked")
assert await _verdicts(uid) == {("s-1", RULE, "work.deliver"): ("departed", "outcome")}
async def test_a_misfire_is_not_applicable_at_the_moment_it_names():
uid = await _user()
await _deliver(uid, "s-1", RULE, "work.start", minutes_ago=10)
await _deliver(uid, "s-1", RULE, "work.deliver", minutes_ago=2)
out = await rule_adherence.from_session(uid, "s-1", RULE, misfired_at="work.start", why="not this act")
assert out == {"recorded": True, "at": "work.start"}
assert await _verdicts(uid) == {("s-1", RULE, "work.start"): ("not_applicable", "misfire")}
async def test_a_rule_the_session_was_never_delivered_gets_no_verdict():
uid = await _user()
await _deliver(uid, "s-2", RULE, "work.deliver")
assert (await rule_adherence.from_session(uid, "s-1", RULE, outcome="applied"))["recorded"] is False
assert (await rule_adherence.from_session(uid, "s-2", RULE, outcome="ignored"))["recorded"] is False
assert await _verdicts(uid) == {}
async def test_a_refusal_stands_and_any_other_verdict_is_replaced_by_a_later_one():
uid = await _user()
await _deliver(uid, "s-1", RULE, "work.deliver")
await _deliver(uid, "s-1", OTHER, "work.deliver")
rule_deliveries.bind_session("s-1", PLUGIN)
try:
rule_adherence.note_refused(uid, [(RULE, "work.deliver", "at work.deliver, reached by `git push`")])
await background.drain()
finally:
rule_deliveries.bind_session("")
await rule_adherence.from_session(uid, "s-1", RULE, outcome="departed", why="x")
judged = await rule_adherence.judge(uid, [
{"session_id": "s-1", "rule_id": RULE, "at": "work.deliver", "verdict": "broken",
"evidence": "pushed anyway"},
])
assert judged["refused"] and not judged["judged"]
assert (await _verdicts(uid))[("s-1", RULE, "work.deliver")] == ("followed", "refused")
await rule_adherence.from_session(uid, "s-1", OTHER, outcome="applied")
judged = await rule_adherence.judge(uid, [
{"session_id": "s-1", "rule_id": OTHER, "at": "work.deliver", "verdict": "broken",
"evidence": "the reply skipped the check the rule asks for"},
])
assert judged["judged"] == [{"session_id": "s-1", "rule_id": OTHER, "at": "work.deliver",
"verdict": "broken"}]
assert (await _verdicts(uid))[("s-1", OTHER, "work.deliver")] == ("broken", "judge")
async def test_a_review_needs_evidence_and_a_delivery_to_judge():
uid = await _user()
stranger = await _user("rule_adherence_stranger")
await _deliver(uid, "s-1", RULE, "work.deliver")
out = await rule_adherence.judge(uid, [
{"session_id": "s-1", "rule_id": RULE, "at": "work.deliver", "verdict": "followed"},
{"session_id": "s-1", "rule_id": RULE, "at": "work.start", "verdict": "followed", "evidence": "e"},
{"session_id": "s-1", "rule_id": RULE, "at": "work.deliver", "verdict": "fine", "evidence": "e"},
])
errors = [r["error"] for r in out["refused"]]
assert len(errors) == 3 and "evidence" in errors[0] and "no delivery" in errors[1]
assert "verdict is one of" in errors[2]
other = await rule_adherence.judge(stranger, [
{"session_id": "s-1", "rule_id": RULE, "at": "work.deliver", "verdict": "followed", "evidence": "e"},
])
assert other["refused"] and await _verdicts(uid) == {}
async def test_the_review_queue_lists_unjudged_rules_by_session_newest_first():
uid = await _user()
await _deliver(uid, "s-old", RULE, "work.deliver", minutes_ago=60)
await _deliver(uid, "s-new", RULE, "work.deliver", minutes_ago=5, opened=True)
await _deliver(uid, "s-new", OTHER, "pre_tool_rule", minutes_ago=4)
# From a plugin that does not report opens: not part of the record.
await _deliver(uid, "s-blind", RULE, "work.deliver", plugin=None)
await rule_adherence.from_session(uid, "s-new", OTHER, outcome="applied")
queue = await rule_adherence.to_judge(uid)
assert [s["session_id"] for s in queue["sessions"]] == ["s-new", "s-old"]
assert queue["unjudged"] == 2
item = queue["sessions"][0]["items"][0]
assert (item["rule_id"], item["at"], item["opened"], item["delivered"]) == (RULE, "work.deliver", True, 1)
assert "jsonl" in queue["how"]
one = await rule_adherence.to_judge(uid, "s-old")
assert [s["session_id"] for s in one["sessions"]] == ["s-old"]
async def test_the_readout_counts_sessions_per_rule_and_per_moment():
uid = await _user()
for sid in ("a", "b", "c"):
await _deliver(uid, sid, RULE, "work.deliver", opened=sid != "c")
await _deliver(uid, "a", RULE, "work.deliver") # a second delivery in one session is one case
await _deliver(uid, "a", RULE, "pre_tool_rule")
await rule_adherence.from_session(uid, "a", RULE, misfired_at="pre_tool_rule", why="x")
await rule_adherence.judge(uid, [
{"session_id": "a", "rule_id": RULE, "at": "work.deliver", "verdict": "followed", "evidence": "e"},
{"session_id": "b", "rule_id": RULE, "at": "work.deliver", "verdict": "broken", "evidence": "e"},
])
out = await rule_adherence.summary(uid, days=30)
rule = next(r for r in out["by_rule"] if r["rule_id"] == RULE)
assert {k: rule[k] for k in ("in_force", "opened", "followed", "broken", "not_applicable", "unjudged")} \
== {"in_force": 4, "opened": 2, "followed": 1, "broken": 1, "not_applicable": 1, "unjudged": 1}
deliver = next(m for m in out["by_moment"] if m["at"] == "work.deliver")
assert (deliver["in_force"], deliver["followed"], deliver["broken"], deliver["unjudged"]) == (3, 1, 1, 1)
assert deliver["by_rule"][0]["rule_id"] == RULE
assert out["totals"]["in_force"] == 4
assert (await rule_adherence.summary(uid, rule_id=OTHER))["by_rule"] == []
+24
View File
@@ -62,6 +62,30 @@ def test_a_command_prefix_needs_a_word_boundary_and_the_head_of_a_segment(comman
assert "work.deliver" not in _reached("Bash", {"command": command})
@pytest.mark.parametrize("command", [
# A heredoc's body is data fed to a program, whatever its lines say.
"python3 - <<'EOF'\nimport os\n | curl -fsS http://x\nEOF",
"cat > hook.sh <<EOF\ncurl http://x\nEOF\nchmod +x hook.sh",
"cat <<-END\n\tcurl http://x\n\tEND",
# Quoted text is an argument, separators inside it included.
'grep -n "a && curl http://x" file',
"echo 'step; curl http://x'",
'git commit -m "fix: curl | wget"',
])
def test_quoted_text_and_heredoc_bodies_are_not_commands(command):
assert "env.reach" not in _reached("Bash", {"command": command})
@pytest.mark.parametrize("command", [
"cat > x.sh <<'EOF'\necho hi\nEOF\ncurl http://x",
"python3 - <<EOF && curl http://x\nprint(1)\nEOF",
'echo "a;b" ; curl http://x',
"make build \\\n && curl http://x",
])
def test_a_command_after_a_heredoc_or_a_quote_is_still_one(command):
assert "env.reach" in _reached("Bash", {"command": command})
def test_one_action_reaches_every_moment_it_is():
"""`kubectl apply` is a run, a deliver and a reach outside the workspace."""
assert _reached("Bash", {"command": "kubectl apply -f deploy.yaml"}) == [
+4 -2
View File
@@ -113,14 +113,16 @@ def test_the_tools_are_registered_and_classified():
"judge_rule_moments", "rule_misfired",
"rules_to_weigh", "propose_rule_weights", "rule_weight_proposals",
"judge_rule_weights",
"rule_adherence", "adherence_to_judge", "judge_adherence",
]
assert {"list_moments", "list_reply_shapes",
"rules_to_mount", "rule_moment_proposals",
"rules_to_weigh", "rule_weight_proposals"} <= _READ_ONLY_TOOLS
"rules_to_weigh", "rule_weight_proposals",
"rule_adherence", "adherence_to_judge"} <= _READ_ONLY_TOOLS
# A confirm mounts a rule, so a read key must not reach it.
assert {"map_action", "unmap_action",
"propose_rule_moments", "judge_rule_moments", "rule_misfired",
"propose_rule_weights", "judge_rule_weights"} <= _WRITE_TOOLS
"propose_rule_weights", "judge_rule_weights", "judge_adherence"} <= _WRITE_TOOLS
def test_both_doors_read_one_catalog():
+1
View File
@@ -40,6 +40,7 @@ def test_every_endpoint_is_reachable_on_the_app():
assert rules == {
"/api/retrieval/surfaces",
"/api/retrieval/surfaces/<surface>",
"/api/retrieval/adherence",
"/api/retrieval/gate",
"/api/retrieval/tuning-history",
"/api/retrieval/moments",
+27
View File
@@ -227,3 +227,30 @@ def test_the_hook_and_the_route_agree_on_the_body():
assert f'"{field}"' in src and f'"{field}"' in route
assert "'.context'" in src
assert '"context"' in inspect.getsource(judgments_svc.opened_after)
def test_an_outcome_is_sent_as_a_verdict_with_the_session(sandbox):
tmp, env = sandbox
_run("grimoire_record_outcome.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__rule_outcome",
"tool_input": {"rule_id": 11, "outcome": "departed", "why": 'the operator said "ship"'}},
env)
assert json.loads((tmp / "curl.body").read_text()) == {
"rule_id": 11, "session_id": "s1", "outcome": "departed", "moment": "",
"why": 'the operator said "ship"',
}
assert "/api/plugin/rule-verdict" in (tmp / "curl.log").read_text()
assert (tmp / "grimoire-priorart" / "s1.acted.ids").exists()
def test_a_misfire_is_sent_as_a_verdict_at_the_moment_it_names(sandbox):
tmp, env = sandbox
_run("grimoire_record_outcome.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__rule_misfired",
"tool_input": {"rule_id": 4, "moment": "work.deliver", "why": "a redeploy, not a release"}},
env)
assert json.loads((tmp / "curl.body").read_text()) == {
"rule_id": 4, "session_id": "s1", "outcome": "", "moment": "work.deliver",
"why": "a redeploy, not a release",
}
+26
View File
@@ -165,6 +165,32 @@ async def test_a_rule_with_triggers_stops_only_the_acts_they_match():
assert result.decision["kind"] == "hold"
async def test_a_refused_act_is_recorded_as_the_rule_kept_there():
# An enforce rule that refuses the act kept the rule at that moment by
# construction; a hold, which lets the act go on after a read, does not.
refusals = MagicMock()
guard = _r(2, enforcement="enforce")
note = _r(3, enforcement="hold")
deliver = [{"moment": "work.deliver", "tool": "Bash", "match": "git push", "via": "default"}]
result = await rp.run_moment_arm(
deliver, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=[(guard, "work.deliver"), (note, "work.deliver")]),
record_rule_surfaced=MagicMock(), record_refusal=refusals),
board=rt.Board(),
)
assert result.decision["kind"] == "enforce"
refusals.assert_called_once_with(1, [(2, "work.deliver", "at work.deliver, reached by `git push`")])
refusals.reset_mock()
await rp.run_moment_arm(
deliver, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=[(note, "work.deliver")]),
record_rule_surfaced=MagicMock(), record_refusal=refusals),
board=rt.Board(),
)
refusals.assert_not_called()
async def test_the_board_lists_every_rule_that_has_a_trigger(monkeypatch):
monkeypatch.setattr(rt, "_in_scope", AsyncMock(return_value=[
(_r(1), [T("path", "alembic/**", "work.change")]),
+13
View File
@@ -152,6 +152,19 @@ async def test_a_write_in_another_project_asks_and_says_how_to_file_an_issue_ins
assert 'create_task(project_id=9, kind="issue")' in out["reason"]
async def test_a_rule_edit_in_another_project_names_the_rule_and_suggests_no_issue():
a, b, c = _patched({9})
with a, b, c:
out = await check_act(1, 2, tool="update_rule", args={"rule_id": 130, "salience": "low"})
assert out["allowed"] is False
assert "rule 130 of Elsewhere (project 9)" in out["reason"]
assert "create_task" not in out["reason"]
with a, b, c:
related = await check_act(1, 2, tool="relate_rules",
args={"from_rule_id": 4, "to_rule_id": 130, "kind": "overrides"})
assert "rule 4, rule 130 of" in related["reason"]
async def test_filing_an_issue_in_another_project_goes_ahead():
a, b, c = _patched({9})
with a, b, c: