feat(7733): adherence is measured per rule and per moment, and shown
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Python tests (push) Failing after 1m48s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Skipped
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Python tests (push) Failing after 1m48s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Skipped
A rule is in force at a moment of a session when it was delivered there. Each (session, rule, place) now carries at most one verdict (rule_adherence, migration 0134): followed, departed, broken or not applicable, with where it came from: - an enforce rule refusing the act: followed, recorded by the moment arm, and never replaced; - the session's own rule_outcome (applied, departed) and rule_misfired calls, which the plugin's outcome hook now also posts with the session id (/api/plugin/rule-verdict) onto the delivery being answered; - a transcript review: adherence_to_judge lists what has no verdict yet, by session, and judge_adherence records verdicts with their evidence. rule_adherence (MCP) and /api/retrieval/adherence give the readout: sessions in force, opened and each verdict per rule and per place. Settings > Moments shows it in a "Were they followed" panel, beside each moment's delivered and opened counts, and per rule inside each moment. Verdicts are pruned with their deliveries and left out of backups like them. Plugin 2026.11.23.2227. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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")
|
||||
@@ -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,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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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" />
|
||||
@@ -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.2227",
|
||||
"author": {
|
||||
"name": "Bryan Van Deusen"
|
||||
},
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -82,7 +82,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "mcp__.*__rule_outcome",
|
||||
"matcher": "mcp__.*__(rule_outcome|rule_misfired)",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
|
||||
@@ -96,3 +96,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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -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"] == []
|
||||
@@ -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():
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
|
||||
|
||||
@@ -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")]),
|
||||
|
||||
Reference in New Issue
Block a user