Merge pull request 'Milestone 639 steps 5–6: enforced rules refuse the act, only hold rules hold, and a pass weighs each rule' (#226) from dev into main
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python tests (push) Successful in 2m1s
CI & Build / integration (push) Successful in 2m10s
CI & Build / Build & push image (push) Successful in 16s

This commit was merged in pull request #226.
This commit is contained in:
2026-11-23 13:21:22 -05:00
43 changed files with 1966 additions and 203 deletions
@@ -0,0 +1,51 @@
"""rule field judgments — proposed and judged enforcement, salience and triggers
Revision ID: 0132
Revises: 0131
Create Date: 2026-11-23
A pass reads each rule with its delivery history and proposes how strongly it
should arrive and what should reach it; a person confirms or rejects each
value. One row per (rule, field, value), so a rejected value is never proposed
again and a rule the pass agreed with reads as looked at.
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0132"
down_revision = "0131"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"rule_field_judgments",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("rule_id", sa.BigInteger(),
sa.ForeignKey("rules.id", ondelete="CASCADE"), nullable=False),
sa.Column("field", sa.Text(), nullable=False),
sa.Column("value", sa.Text(), nullable=False),
sa.Column("state", sa.Text(), nullable=False, server_default="suggested"),
sa.Column("source", sa.Text(), nullable=False, server_default="pass"),
sa.Column("note", sa.Text(), nullable=True),
sa.Column("evidence", postgresql.JSONB(), nullable=True),
sa.Column("judged_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.UniqueConstraint("rule_id", "field", "value", name="uq_rule_field_judgments_value"),
sa.CheckConstraint(
"field IN ('enforcement', 'salience', 'trigger')", name="ck_rule_field_judgments_field",
),
sa.CheckConstraint(
"state IN ('suggested', 'confirmed', 'rejected')", name="ck_rule_field_judgments_state",
),
sa.CheckConstraint("source IN ('pass', 'edit')", name="ck_rule_field_judgments_source"),
)
op.create_index("ix_rule_field_judgments_rule_id", "rule_field_judgments", ["rule_id"])
def downgrade() -> None:
op.drop_index("ix_rule_field_judgments_rule_id", table_name="rule_field_judgments")
op.drop_table("rule_field_judgments")
+75
View File
@@ -1,4 +1,5 @@
import { apiGet, apiPost, apiDelete } from "@/api/client";
import type { RuleEnforcement, RuleSalience, RuleTrigger } from "@/api/rulebooks";
/**
* The moments of work rules mount on, and the actions that
@@ -180,3 +181,77 @@ export function getProposals(ruleId?: number): Promise<ProposalsPayload> {
export function judgeProposals(judgments: MomentJudgment[]): Promise<JudgeResult> {
return apiPost("/api/retrieval/moments/proposals/judge", { judgments });
}
/**
* Suggestions for how strongly a rule arrives (`enforcement`, `salience`) and
* which typed triggers reach it, from a pass that read the rule beside its
* delivery history. Nothing changes until a person confirms one.
* `GET /api/retrieval/weights/proposals`, the payload the
* `rule_weight_proposals` MCP tool returns.
*/
export type WeightField = "enforcement" | "salience" | "trigger";
/** What happened when the rule reached a session, over `days`. */
export interface WeightEvidence {
days?: number;
delivered?: number;
opened?: number;
places?: { at: string; delivered: number; opened: number }[];
pulled?: number;
applied?: number;
departed?: number;
misfire_days?: number;
}
export interface WeightProposal {
field: WeightField;
/** The enforcement or salience name; for a trigger, its stored form. */
value: string;
trigger?: RuleTrigger;
why: string;
source: "pass" | "edit";
evidence: WeightEvidence;
created_at: string | null;
}
export interface RuleWeightProposals {
id: number;
title: string;
kind: string;
statement: string;
when_to_apply: string;
home: "global" | "project";
enforcement: RuleEnforcement;
salience: RuleSalience;
mounted: string[];
triggers: RuleTrigger[];
proposals: WeightProposal[];
}
export interface WeightProposalsPayload {
rules: RuleWeightProposals[];
total: number;
}
export interface WeightJudgment {
rule_id: number;
field: WeightField;
value: string | RuleTrigger;
verdict: Verdict;
note?: string;
}
export interface WeightJudgeResult {
judged: { rule_id: number; field: WeightField; value: string; state: string }[];
refused: { rule_id: number; field?: string; error: string }[];
}
export function getWeightProposals(ruleId?: number): Promise<WeightProposalsPayload> {
return apiGet(`/api/retrieval/weights/proposals${ruleId ? `?rule_id=${ruleId}` : ""}`);
}
/** A confirm sets the field on the rule (a trigger is added beside its
* others); a reject stops that value being proposed again. */
export function judgeWeightProposals(judgments: WeightJudgment[]): Promise<WeightJudgeResult> {
return apiPost("/api/retrieval/weights/proposals/judge", { judgments });
}
+3 -2
View File
@@ -56,8 +56,9 @@ export type RuleKind = "rule" | "preference";
/**
* What a rule does when it arrives, declared by its author. `inform` puts a
* line beside the work; `hold` makes the reply or act it governs wait for one
* read; `enforce` checks the act itself. A preference is always `inform`.
* line beside the work; `hold` makes the reply or command it governs wait for
* one read; `enforce` refuses an act its moment or trigger reaches. A
* preference is always `inform`.
*/
export type RuleEnforcement = "enforce" | "hold" | "inform";
/** How a rule ranks among rules of the same enforcement at a crowded moment. */
+29
View File
@@ -0,0 +1,29 @@
/* A proposal about a rule waiting on a person — the panels under
Settings › Moments that list mount proposals and weight suggestions.
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); }
.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);
background: var(--fs-surface-page);
border: 1px dashed var(--fs-border-color);
border-radius: var(--fs-radius-md);
}
.rule-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.rule-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
.rule-mounted { display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-1); font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.rule-statement { margin: var(--fs-space-1) 0 var(--fs-space-2); font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); line-height: var(--fs-leading-body); }
.proposal-items { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.proposal-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: var(--fs-size-body-sm); }
.proposal-why { flex: 1 1 16rem; color: var(--fs-text-secondary); }
.proposal-source { color: var(--fs-text-tertiary); font-size: var(--fs-size-tiny); }
.proposal-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
.proposal-kind { font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.proposal-reasons {
flex-basis: 100%;
margin: 0;
padding-left: var(--fs-space-4);
font-size: var(--fs-size-tiny);
color: var(--fs-text-tertiary);
}
+1 -28
View File
@@ -158,33 +158,6 @@ onMounted(load);
</section>
</template>
<style scoped>
.proposals { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.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);
background: var(--fs-surface-page);
border: 1px dashed var(--fs-border-color);
border-radius: var(--fs-radius-md);
}
.rule-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.rule-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
.rule-mounted { display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-1); font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.rule-statement { margin: var(--fs-space-1) 0 var(--fs-space-2); font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); line-height: var(--fs-leading-body); }
.proposal-items { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.proposal-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: var(--fs-size-body-sm); }
.proposal-why { flex: 1 1 16rem; color: var(--fs-text-secondary); }
.proposal-source { color: var(--fs-text-tertiary); font-size: var(--fs-size-tiny); }
.proposal-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
.proposal-kind { font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.proposal-reasons {
flex-basis: 100%;
margin: 0;
padding-left: var(--fs-space-4);
font-size: var(--fs-size-tiny);
color: var(--fs-text-tertiary);
}
</style>
<style scoped src="@/assets/rule-proposals.css" />
<style src="@/assets/moments-shared.css" />
@@ -3,6 +3,7 @@ import { computed, onMounted, ref } from "vue";
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 { fmtDate } from "@/utils/dateFormat";
@@ -126,6 +127,7 @@ onMounted(() => store.load(true));
</p>
<MomentProposals />
<WeightProposals />
<ul class="moment-list">
<li v-for="m in catalog" :key="m.name" class="moment-row">
+154
View File
@@ -0,0 +1,154 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { getWeightProposals, judgeWeightProposals } from "@/api/moments";
import type {
RuleWeightProposals, Verdict, WeightEvidence, WeightProposal, WeightProposalsPayload,
} from "@/api/moments";
import type { RuleTrigger } from "@/api/rulebooks";
import { apiErrorMessage } from "@/api/client";
import { useToastStore } from "@/stores/toast";
/**
* 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.
*/
const toast = useToastStore();
const data = ref<WeightProposalsPayload | null>(null);
const failed = ref(false);
const busy = ref<string | null>(null);
const rules = computed<RuleWeightProposals[]>(() => data.value?.rules ?? []);
// What each enforcement does when the rule arrives — said beside the change,
// since "hold" and "enforce" stop work and the person applying one should
// know how.
const FORCE: Record<string, string> = {
inform: "a line beside the work",
hold: "the act or reply waits until it has been read once",
enforce: "the act it governs is refused, every time",
};
async function load() {
try {
data.value = await getWeightProposals();
failed.value = false;
} catch {
failed.value = true;
}
}
function key(rule: RuleWeightProposals, p: WeightProposal): string {
return `${rule.id}:${p.field}:${p.value}`;
}
function triggerText(t: RuleTrigger): string {
return `${t.kind} ${t.pattern}${t.moment ? ` at ${t.moment}` : ""}`;
}
function change(rule: RuleWeightProposals, p: WeightProposal): string {
if (p.field === "trigger" && p.trigger) return `add trigger ${triggerText(p.trigger)}`;
const from = p.field === "enforcement" ? rule.enforcement : rule.salience;
return `${p.field} ${from} → ${p.value}`;
}
function history(e: WeightEvidence): string {
if (!e || e.delivered === undefined) return "";
const parts = [`delivered ${e.delivered}`, `opened ${e.opened ?? 0}`];
if (e.applied) parts.push(`applied ${e.applied}`);
if (e.departed) parts.push(`departed ${e.departed}`);
if (e.misfire_days) parts.push(`misfired on ${e.misfire_days} days`);
return `${parts.join(" · ")} in ${e.days ?? 90} days`;
}
async function decide(rule: RuleWeightProposals, p: WeightProposal, verdict: Verdict) {
busy.value = key(rule, p);
try {
const out = await judgeWeightProposals([{
rule_id: rule.id, field: p.field, value: p.trigger ?? p.value, verdict,
note: verdict === "confirm" ? "Applied in Settings." : "Declined in Settings.",
}]);
if (out.refused.length) {
toast.show(out.refused[0].error, "error");
return;
}
await load();
} catch (e) {
toast.show(apiErrorMessage(e, "Could not record that"), "error");
} finally {
busy.value = null;
}
}
onMounted(load);
</script>
<template>
<section v-if="failed || rules.length" class="proposals" aria-labelledby="weights-title">
<h3 id="weights-title" class="sub-title">How strongly rules arrive — waiting on you</h3>
<p v-if="failed" class="error-msg">
The suggestions could not be loaded.
<button type="button" class="btn-text" @click="load">Try again</button>
</p>
<template v-else>
<p class="field-hint">
Suggested from each rule's text and what happened when it reached sessions. Inform is a
line beside the work; hold makes the act or reply wait until the rule has been read once
(file edits are never held); enforce refuses the act it governs. A trigger reaches the
rule exactly, by the tool, path, command or word the act carries.
</p>
<ul class="proposal-list">
<li v-for="rule in rules" :key="rule.id" class="proposal-rule">
<div class="rule-head">
<span class="rule-title">#{{ rule.id }} {{ rule.title }}</span>
<span class="rule-mounted">
{{ rule.enforcement }} · {{ rule.salience }}
<template v-if="rule.mounted.length">
· on <code v-for="m in rule.mounted" :key="m" class="moment-name">{{ m }}</code>
</template>
<template v-if="rule.triggers.length">
· triggered by
<code v-for="t in rule.triggers" :key="triggerText(t)" class="moment-name">{{ triggerText(t) }}</code>
</template>
</span>
</div>
<p class="rule-statement">{{ rule.statement }}</p>
<ul class="proposal-items">
<li v-for="p in rule.proposals" :key="key(rule, p)" class="proposal-item">
<code class="moment-name">{{ change(rule, p) }}</code>
<span class="proposal-why">
{{ p.why }}
<span v-if="p.field === 'enforcement'" class="proposal-source">
· {{ FORCE[p.value] }}
</span>
<span v-if="history(p.evidence)" class="proposal-source">
· {{ history(p.evidence) }}
</span>
</span>
<span class="proposal-actions">
<button
type="button" class="btn-primary btn-sm"
:disabled="busy !== null"
@click="decide(rule, p, 'confirm')"
>Apply</button>
<button
type="button" class="btn-text"
:disabled="busy !== null"
@click="decide(rule, p, 'reject')"
>Not this</button>
</span>
</li>
</ul>
</li>
</ul>
</template>
</section>
</template>
<style scoped src="@/assets/rule-proposals.css" />
<style src="@/assets/moments-shared.css" />
@@ -344,14 +344,16 @@ watch(() => props.ruleId, load);
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="hold" />
<span>
<strong>Hold</strong> — the reply or act it governs waits for one
read of it. For a rule whose miss costs a rewrite.
<strong>Hold</strong> — the reply or command it governs waits until
the rule has been read once. File edits are never held. For a rule
whose miss costs a rewrite.
</span>
</label>
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="enforce" />
<span>
<strong>Enforce</strong> — the act itself is checked. For a hard
<strong>Enforce</strong> — an act its moment or trigger reaches
does not run, every time, until you change the rule. For a hard
boundary.
</span>
</label>
@@ -33,8 +33,8 @@ const emit = defineEmits<{
v-if="r.enforcement === 'hold' || r.enforcement === 'enforce'"
class="rule-chip"
:title="r.enforcement === 'hold'
? 'The reply or act it governs waits for one read of it'
: 'The act it governs is checked against it'"
? 'The reply or command it governs waits until it has been read once'
: 'An act it is reached by does not run until the rule changes'"
>{{ r.enforcement === "hold" ? "holds" : "enforced" }}</span>
<!-- Marked only when something is WRONG: every rule arrives by
retrieval now, so "conditional" stopped distinguishing anything.
+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.0004",
"version": "2026.11.23.1802",
"author": {
"name": "Bryan Van Deusen"
},
+3 -3
View File
@@ -15,7 +15,7 @@ another one means adding files, not moving or rewriting any.
|---|---|---|
| **The skills** | `plugin/skills/*/SKILL.md` | Agent Skills (the open SKILL.md format). They state every Grimoire reflex in full and name no client. `tests/test_guidance_ownership.py` fails if a skill names a particular client, or references anything outside its own folder. Every client package ships this folder verbatim. |
| **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — the workflow across tools (≤1,600 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. |
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule or — when the turn closed a task — for missing completion sections). |
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule set to hold or — when the turn closed a task — for missing completion sections). |
| **The API key** | Grimoire → Settings → MCP Access | One `fmcp_` key per install. Write scope covers the MCP tools and every hook; a read key runs only the `GET` hooks. |
## Added by each client
@@ -40,9 +40,9 @@ another one means adding files, not moving or rewriting any.
| `hooks/grimoire_after_write.sh` | PostToolUse on shell commands: the same check for code written through the shell. |
| `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`. |
| `hooks/grimoire_project_fence.sh` | PreToolUse on editor writes, shell commands and Grimoire's tools: `GET /api/plugin/write-scope` for an act aimed at another project, answered `ask` with the reason; PostToolUse on `enter_project` remembers the project a session without one entered. |
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). |
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). Denies the call when the response's `decision` is `enforce` (every time) or `hold` (once per rule and session). |
| `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite. |
| `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check`; blocks once, with the reason the server returns, so the agent judges what it built. |
| `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check` and keeps the `note` it returns for the next prompt, which `grimoire_autoinject.sh` carries as `carry`, so the agent judges what it built. Never blocks. |
| `hooks/grimoire_record_opened.sh` | PostToolUse on `get_rule`: notes the rule as read in the session ledger and `POST /api/plugin/rule-opened`. |
| `hooks/grimoire_record_outcome.sh` | PostToolUse on `rule_outcome`: notes the rule as acted on, locally, for the session-scoped readout. |
| `hooks/grimoire_claim_session.sh` | PostToolUse on `update_task` / `add_task_log`: `GET /api/plugin/claim-session`, so the task comes back after a compaction. |
+11 -7
View File
@@ -97,7 +97,9 @@ On install you'll be asked for:
→ `POST /api/plugin/moment`: the rules mounted on the moments the call
reaches. It skips tools that `GET /api/plugin/moment-tools` says reach
nothing mounted, and Grimoire's own tools, whose responses carry
`moment_rules`.
`moment_rules`. A rule set to enforce refuses the call (every time it is
reached); one set to hold denies it once until it has been read, never on a
file edit.
- `hooks/hooks.json` → PostToolUse hooks on Grimoire's `get_rule`,
`rule_outcome`, `update_task` and `add_task_log`: they keep the session's
ledgers of rules opened and acted on (`get_rule` also reports to
@@ -115,7 +117,8 @@ On install you'll be asked for:
duplicate arm and the outage line are shared in `hooks/grimoire_defs.sh`.
- `hooks/hooks.json` → Stop hook (`hooks/grimoire_reply_check.sh`): sends the
reply that ends the turn to `POST /api/plugin/reply-rules`, which holds it
once for an unopened rule mounted on the reply moments or matching the reply.
once for an unopened rule set to hold (or enforce) that is mounted on the
reply moments or matches the reply. A rule set to inform never holds it.
When the turn closed a Grimoire task (`update_task`/`create_task` with status
done), the same request has the server check the reply for the completion
sections — where the work sits, what needs you, what comes next. If they are
@@ -127,11 +130,12 @@ On install you'll be asked for:
write hooks note every definition a write names (and every new file) in a
session ledger; at the end of the turn this sends them to
`GET /api/plugin/shape-check`, which answers with the ones nobody has judged.
If any are, it blocks once with the server's reason, asking the agent that
wrote them to say what each is — reusable (record a snippet), an instance or
variant of one, or a one-off — in one `classify_shapes` call. Same discipline
as the report check: never twice, never without a recorded check. Outcomes
land under category `plugin`, action `shape_check`.
If any are, the server's note rides the next prompt (the prompt hook sends it
as `carry`), asking the agent that wrote them to say what each is — reusable
(record a snippet), an instance or variant of one, or a one-off — in one
`classify_shapes` call. It never holds the reply; the stop after that prompt
records whether the lines were judged. Outcomes land under category
`plugin`, action `shape_check`.
- `skills/` → the universal process-skills, surfaced by description match.
- `hooks/grimoire_sync_processes.sh` (a 2nd SessionStart hook) + the `/grimoire:sync`
command → generate `~/.claude/skills/grimoire-proc-*` stubs from your Grimoire
+15 -1
View File
@@ -134,10 +134,24 @@ if [ -n "$session_id" ]; then
[ -n "$shapes_seen" ] && exclude_q="${exclude_q}&shapes_seen=${shapes_seen}"
fi
# What the last stop left for this prompt: the definitions its turn wrote
# that nobody has judged (grimoire_shape_check.sh). Carried to the server, which
# fits it into the one payload, and removed once the server has answered.
carry_q=""
carry_file=""
if [ -n "$session_id" ]; then
carry_file="${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}.note"
if [ -s "$carry_file" ]; then
carry_enc=$(head -c 2000 "$carry_file" 2>/dev/null | grimoire_urlenc) || carry_enc=""
[ -n "$carry_enc" ] && carry_q="&carry=${carry_enc}"
fi
fi
body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}" 2>/dev/null) || exit 0
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}${carry_q}" 2>/dev/null) || exit 0
[ -n "$body" ] || exit 0
[ -n "$carry_q" ] && rm -f "$carry_file" 2>/dev/null
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
context=$(grimoire_json_pick "$body_flat" '.context')
+30 -1
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
# Grimoire — PreToolUse moment arm: rules MOUNTED on a moment arrive when the
# moment happens.
# moment happens — beside the act, or, for a rule set to enforce or hold, in
# front of it.
#
# The other PreToolUse arms search: they turn the act into a query and hope a
# rule's words resemble it. A mount needs no resemblance. The operator said
@@ -148,6 +149,34 @@ body_flat=$(printf '%s' "$body" | grimoire_json_flat)
grimoire_json_list "$body_flat" '.rule_ids' | grimoire_rules_append "$rulefile"
grimoire_json_list "$body_flat" '.shape_keys' | grimoire_shapes_append "$shapefile"
# ── The act itself: refused, held for one read, or let through ───────────
#
# The server decides and supplies the words (`decision`); this hook only
# carries them. A rule set to ENFORCE refuses the call every time it is
# reached — the operator drew that line, and it moves when they change the
# rule, not when the agent has read it. A rule set to HOLD asks for one read
# before the act, once per rule and under the session cap that the act
# checkpoint and the reply hold share, so a mis-set rule costs one round trip
# rather than a session that cannot move.
d_kind=$(grimoire_json_pick "$body_flat" '.decision.kind')
d_reason=$(grimoire_json_pick "$body_flat" '.decision.reason')
d_rule=$(grimoire_json_list "$body_flat" '.decision.rule_ids' | head -n 1)
if [ -n "$d_reason" ]; then
case "$d_kind" in
enforce)
grimoire_json_deny PreToolUse "$d_reason"
exit 0
;;
hold)
if [ -n "$d_rule" ] \
&& grimoire_checkpoint_allowed "$state_dir/${safe_sid}.checkpoint.ids" "$d_rule"; then
grimoire_json_deny PreToolUse "$d_reason"
exit 0
fi
;;
esac
fi
context=$(grimoire_json_pick "$body_flat" '.context')
[ -n "$context" ] || exit 0
grimoire_json_out PreToolUse "$context"
+3 -1
View File
@@ -6,7 +6,9 @@
# tool call misses it. This hook sends the finished reply to the server, which
# checks it twice over: the rules MOUNTED on the reply moments, and the reply
# text against every rule's trigger, as the backstop for whatever the earlier
# arms missed. An unopened rule from either half holds the reply for one read.
# arms missed. An unopened rule set to hold, from either half, holds the reply
# for one read; a rule set to inform was delivered before the reply and never
# holds it.
#
# ONE END-OF-TURN REQUEST. When the turn closed a task, the same request
# carries the task ids and the server also checks the reply for the completion
+6 -5
View File
@@ -31,13 +31,14 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
[ -n "$session_id" ] || exit 0
# The moment arm's per-session files (its tool cache and the acts ledger) and
# the fence's (the project the session entered, its outage marker) describe a
# session that is over, on any exit — a clear included, since the next
# conversation is a new session id.
# The moment arm's per-session files (its tool cache and the acts ledger), the
# shape check's (a note waiting for a prompt) and the fence's (the project the
# session entered, its outage marker) describe a session that is over, on any
# exit — a clear included, since the next conversation is a new session id.
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* \
"${TMPDIR:-/tmp}/grimoire-fence/${safe_sid}".* 2>/dev/null || true
"${TMPDIR:-/tmp}/grimoire-fence/${safe_sid}".* \
"${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}".* 2>/dev/null || true
reason=$(grimoire_json_pick "$event_flat" '.reason')
[ "$reason" = "clear" ] && exit 0
+61 -48
View File
@@ -1,29 +1,31 @@
#!/usr/bin/env bash
# Grimoire plugin — Stop hook: the turn's new shapes are judged by the agent
# that wrote them.
# that wrote them, at the start of its next turn.
#
# The write hooks (grimoire_prior_art.sh, grimoire_after_write.sh) append every
# definition a write names to a session ledger, `<sid>.written.ids`
# (`path<TAB>kind<TAB>name`, see grimoire_written_append). At the end of the
# turn this hook sends that ledger to the instance, which answers with what
# nobody has judged yet. If anything is, the hook blocks ONCE, in the server's
# words: the agent that built the code is the one participant who knows what
# it is, and the end of the turn is the last moment that is still true.
# nobody has judged yet as a `note`. The hook leaves the note for
# grimoire_autoinject.sh, which carries it into the next prompt's payload: the
# agent that built the code is the one participant who knows what it is, and
# the next turn of the same session still does.
#
# THE SAME DISCIPLINE AS the completion-section check in grimoire_reply_check.sh:
# - it blocks only on a `reason` the instance returned, which it returns
# only for a block it RECORDED — an unconfigured or unreachable instance
# never stops a session, and every intervention is one the numbers see;
# - never twice for one turn: the stop that follows its own block
# (`stop_hook_active` with this hook's marker present) is recorded as
# judged_after_block / left_after_block and let through;
# - another plugin's block loop is left alone (active, no marker).
# IT NEVER HOLDS THE REPLY. A held reply is rewritten, and a hold on every turn
# that wrote code made most replies cost two. The question waits one prompt
# instead, and is asked inside that prompt's budget.
#
# THE LEDGER IS CONSUMED, NOT TURN-STAMPED. Everything written since the last
# stop this hook answered is "this turn". It is emptied once the instance has
# answered — after a pass, or after the post-block stop — and KEPT when the
# instance could not be reached, so the question is asked at the next stop
# that can be answered rather than silently dropped.
# THE STATE, in <TMPDIR>/grimoire-shapecheck:
# <sid>.note — the note, until a prompt carries it (the prompt hook
# removes it once the instance has answered);
# <sid>.asked — the lines that note named. At the first stop after the note
# was carried, they go back as `phase=after`, which records
# whether they were judged, and are then forgotten.
# A note no prompt has carried yet (two stops in a row) is asked again with
# that turn's writes added, so nothing is dropped and nothing is asked twice.
#
# Silent on outage: the ledger is kept when the instance could not be reached,
# so the question is asked at the next stop that can be answered.
#
# Config (same as the other hooks):
# CLAUDE_PLUGIN_OPTION_API_ENDPOINT base URL, no trailing slash
@@ -43,36 +45,33 @@ session_id=$(grimoire_json_pick "$event_flat" '.session_id')
active=$(grimoire_json_pick "$event_flat" '.stop_hook_active')
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
[ -n "$session_id" ] || exit 0
# The stop after another hook held the reply: this turn's writes were already
# sent at the stop before it.
[ "$active" = "true" ] && exit 0
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
ledger="${TMPDIR:-/tmp}/grimoire-priorart/${safe_sid}.written.ids"
state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck"
mkdir -p "$state_dir" 2>/dev/null || true
marker="$state_dir/${safe_sid}.blocked"
note_file="$state_dir/${safe_sid}.note"
asked_file="$state_dir/${safe_sid}.asked"
if [ "$active" = "true" ]; then
# A Stop hook already blocked this stop. Another plugin's → nothing to add.
[ -f "$marker" ] || exit 0
phase=after
else
rm -f "$marker" 2>/dev/null || true
phase=check
# A note no prompt has carried: its lines join this turn's, asked afresh.
if [ -f "$note_file" ]; then
if [ -s "$asked_file" ]; then
mkdir -p "$(dirname "$ledger")" 2>/dev/null || true
cat "$asked_file" >> "$ledger" 2>/dev/null || true
fi
rm -f "$note_file" "$asked_file" 2>/dev/null || true
fi
if [ ! -s "$ledger" ]; then
rm -f "$marker" 2>/dev/null || true
exit 0
fi
[ -s "$asked_file" ] || [ -s "$ledger" ] || exit 0
grimoire_config || exit 0
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
# key runs the plugin), and a turn that wrote more than this generated code.
written=$(awk '!seen[$0]++' "$ledger" 2>/dev/null | head -n 80)
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}"
q="phase=${phase}&written=${written_enc}"
scope_q=""
scope=$(grimoire_scope_query "$dir")
[ -n "$scope" ] && q="${q}&${scope}"
[ -n "$scope" ] && scope_q="&${scope}"
# The repo rides along even when a marker names the project: the instance
# needs it to tell the agent which repo a just-written shape belongs to.
case "$scope" in
@@ -81,25 +80,39 @@ case "$scope" in
remote=$(git -C "$dir" remote get-url origin 2>/dev/null || true)
if [ -n "$remote" ]; then
remote_enc=$(printf '%s' "$remote" | grimoire_urlenc) || remote_enc=""
[ -n "$remote_enc" ] && q="${q}&repo=${remote_enc}"
[ -n "$remote_enc" ] && scope_q="${scope_q}&repo=${remote_enc}"
fi
;;
esac
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
# key runs the plugin), and a turn that wrote more than this generated code.
_unique() { awk '!seen[$0]++' "$1" 2>/dev/null | head -n 80; }
# The note a prompt carried: were its lines judged since?
if [ -s "$asked_file" ]; then
asked=$(_unique "$asked_file")
asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc=""
if [ -n "$asked_enc" ] && curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \
"${url%/}/api/plugin/shape-check?phase=after&written=${asked_enc}${scope_q}" \
>/dev/null 2>&1; then
rm -f "$asked_file" 2>/dev/null || true
fi
fi
[ -s "$ledger" ] || exit 0
written=$(_unique "$ledger")
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
answer=$(curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \
"${url%/}/api/plugin/shape-check?${q}" 2>/dev/null) || exit 0 # unreachable: keep the ledger
"${url%/}/api/plugin/shape-check?phase=check&written=${written_enc}${scope_q}" 2>/dev/null) \
|| exit 0 # unreachable: keep the ledger
if [ "$phase" = "after" ]; then
rm -f "$marker" "$ledger" 2>/dev/null || true
exit 0
note=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.note')
if [ -n "$note" ]; then
printf '%s' "$note" > "$note_file" 2>/dev/null || true
printf '%s\n' "$written" > "$asked_file" 2>/dev/null || true
fi
reason=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.reason')
if [ -z "$reason" ]; then
rm -f "$ledger" 2>/dev/null || true
exit 0
fi
: > "$marker" 2>/dev/null || true
printf '{"decision":"block","reason":"%s"}\n' "$(printf '%s' "$reason" | grimoire_json_escape)"
rm -f "$ledger" 2>/dev/null || true
exit 0
+7
View File
@@ -89,3 +89,10 @@ The same tool answers proposals from a pass over the rules
proposes, and only the operator's yes mounts. Writing a NEW rule is different
— its moments are part of writing it, and the
skill's guide to writing records says how.
A second pass weighs each rule: how strongly it arrives once reached
(`enforcement`: inform, hold or enforce; `salience`), and which typed
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.
+4
View File
@@ -168,6 +168,7 @@ _READ_ONLY_TOOLS = frozenset({
# rules are unjudged and which proposals wait. Reads of the caller's own
# rules, as list_rules is.
"rules_to_mount", "rule_moment_proposals",
"rules_to_weigh", "rule_weight_proposals",
})
# Every tool that WRITES, by name. Nothing reads this set at runtime — a tool
@@ -229,6 +230,9 @@ _WRITE_TOOLS = frozenset({
# Proposing moments for a rule writes a judgment row; judging one mounts
# or unmounts the rule.
"propose_rule_moments", "judge_rule_moments",
# Proposing a rule's enforcement, salience or triggers writes a judgment
# row; judging one changes how the rule arrives.
"propose_rule_weights", "judge_rule_weights",
# A misfire report writes a counted row that can become an unmount
# proposal.
"rule_misfired",
+89
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_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc
@@ -232,6 +233,90 @@ async def rule_misfired(rule_id: int, moment: str, why: str,
)
async def rules_to_weigh(limit: int = 25, offset: int = 0) -> dict:
"""The rules nobody has weighed, each with what happened when it reached a session — a page at a time.
Weighing a rule is deciding how strongly it arrives once the work reaches
it, and what reaches it exactly:
- `enforcement`: `inform` is a line beside the work, and is right for
most rules. `hold` makes the act or reply wait until the rule has been
read once in the session (file edits are never held). `enforce` refuses
the act the rule governs, in the rule's own words, every time — for a
rule whose breach an act commits and that must never be crossed without
the operator (pushing to a protected branch, a destructive command). A
preference is always `inform`.
- `salience`: `high`, `normal` or `low` — how it ranks beside rules of the
same enforcement when a moment has more to say than fits.
- `triggers`: typed predicates on the act (`tool`, `path`, `command`,
`keyword`, optionally scoped to a moment) that reach the rule exactly.
Propose one when the rule names the act it governs; an `enforce` rule
needs one, or a mount on an act's moment, to have an act to refuse.
Each rule carries its current `enforcement`, `salience`, `mounted` and
`triggers`, and `history` over the last 90 days: `delivered` and `opened`
in total and at each place (`places`), `pulled`, `applied`, `departed`
and `misfire_days`. Read the history as evidence about the rule's
weight, not as the decision: a rule delivered often and rarely opened is
either reaching the wrong work (a trigger fixes that) or arriving too
loudly for what it asks (lower salience); a rule sessions keep departing
from or breaching may need `hold`.
Record the answer with `propose_rule_weights`. A rule leaves this list as
soon as an answer is recorded, so the next call returns the next rules.
Returns `rules`, `total_unweighed` and `offset`.
"""
return await weights_svc.unweighed_rules(current_user_id(), limit=limit, offset=offset)
async def propose_rule_weights(proposals: list[dict]) -> dict:
"""Propose rules' enforcement, salience and triggers — for the operator to confirm; nothing changes on this call.
Each item is
`{"rule_id": N, "enforcement": "inform"|"hold"|"enforce",
"salience": "high"|"normal"|"low", "triggers": [{"kind": "command",
"pattern": "git push", "moment": ""}], "why": "…"}`.
Give both enforcement and salience for every rule, even where they match
what it has: a value equal to the rule's own is recorded as agreed, which
is what marks the rule as weighed. A different value waits as a
suggestion. `triggers` lists only triggers to add; omit it when none fits.
`why` is shown to the operator beside each suggestion: say what in the
rule and its history led to it, so they can say yes or no without opening
the rule.
Refused alone, under `refused`, with why: an unknown value, a preference
proposed to hold or enforce, and `enforce` on a rule no act reaches.
A value the operator already rejected is listed under `skipped`. Then show
the operator what is waiting (`rule_weight_proposals`) and let them
decide.
"""
return await weights_svc.propose(current_user_id(), proposals)
async def rule_weight_proposals(rule_id: int = 0) -> dict:
"""The enforcement, salience and trigger suggestions waiting on the operator, grouped by rule.
Each rule carries its current enforcement, salience, mounts and triggers
beside its `proposals`: each a `field`, the suggested `value` (a trigger
also as `trigger`), `why`, and the delivery history the proposer read
(`evidence`). `rule_id` narrows to one rule.
"""
return await weights_svc.pending(current_user_id(), rule_id=rule_id or None)
async def judge_rule_weights(judgments: list[dict]) -> dict:
"""Confirm or reject weight suggestions — on the operator's word, since a confirm changes how the rule arrives.
Each item is `{"rule_id": N, "field": "enforcement"|"salience"|"trigger",
"value": "hold" (or the trigger object), "verdict": "confirm"|"reject",
"note": "why"}`. Confirm sets the field on the rule (a trigger is added
beside the rule's others); reject records that the value is wrong for this
rule, so it is never proposed again. Put the operator's reason in `note`.
"""
return await weights_svc.judge(current_user_id(), judgments)
def register(mcp) -> None:
mcp.tool(name="list_moments")(list_moments)
mcp.tool(name="list_reply_shapes")(list_reply_shapes)
@@ -242,3 +327,7 @@ def register(mcp) -> None:
mcp.tool(name="rule_moment_proposals")(rule_moment_proposals)
mcp.tool(name="judge_rule_moments")(judge_rule_moments)
mcp.tool(name="rule_misfired")(rule_misfired)
mcp.tool(name="rules_to_weigh")(rules_to_weigh)
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)
+1
View File
@@ -84,6 +84,7 @@ from grimoire.models.rulebook import ( # noqa: E402, F401
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401
# After rules: it foreign-keys them.
from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E402, F401
from grimoire.models.rule_field_judgment import RuleFieldJudgment # noqa: E402, F401
from grimoire.models.repo_binding import RepoBinding # noqa: E402, F401
from grimoire.models.forge_connection import ForgeConnection # noqa: E402, F401
from grimoire.models.code_shape import CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse # noqa: E402, F401
@@ -0,0 +1,73 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import CreatedAtMixin, iso
from grimoire.models.lesson_rule_link import CONFIRMED, LINK_STATES, REJECTED, SUGGESTED
__all__ = [
"CONFIRMED", "ENFORCEMENT", "FIELDS", "REJECTED", "SALIENCE", "SUGGESTED",
"TRIGGER", "RuleFieldJudgment",
]
# The fields of a rule that decide how it arrives once it is reached: what it
# does (`enforcement`), how it ranks beside rules of the same force
# (`salience`), and the typed predicates that reach it (`trigger`).
ENFORCEMENT, SALIENCE, TRIGGER = "enforcement", "salience", "trigger"
FIELDS = (ENFORCEMENT, SALIENCE, TRIGGER)
class RuleFieldJudgment(Base, CreatedAtMixin):
"""A proposed or judged value for one of a rule's delivery fields.
The rule row holds the current value; this holds the reasoning behind it
and the values that were turned down. One row per (rule, field, value):
- ``suggested`` — a pass read the rule and its delivery history and
proposed this value. Changes nothing until a person confirms it.
- ``confirmed`` — the value was judged right. For a proposal equal to
what the rule already carries, the pass's agreement is recorded this way,
so a rule that was looked at and left alone does not read as one nobody
looked at.
- ``rejected`` — judged wrong, kept with its reason so it is never
proposed again.
`value` is the enforcement or salience name, or for a trigger
`kind<TAB>pattern<TAB>moment` — one string, so the pair is unique.
`evidence` is the delivery history the proposer read, as it stood then.
"""
__tablename__ = "rule_field_judgments"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
rule_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("rules.id", ondelete="CASCADE"), index=True,
)
field: Mapped[str] = mapped_column(Text)
value: Mapped[str] = mapped_column(Text)
state: Mapped[str] = mapped_column(Text, default=SUGGESTED, server_default=SUGGESTED)
# `pass` — an agent proposed it; `edit` — a person set the field directly.
source: Mapped[str] = mapped_column(Text, default="pass", server_default="pass")
note: Mapped[str | None] = mapped_column(Text, nullable=True)
evidence: Mapped[dict | None] = mapped_column(JSONB, nullable=True)
judged_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
__table_args__ = (
UniqueConstraint("rule_id", "field", "value", name="uq_rule_field_judgments_value"),
)
def to_dict(self) -> dict:
return {
"rule_id": self.rule_id,
"field": self.field,
"value": self.value,
"state": self.state,
"source": self.source,
"note": self.note or "",
"evidence": self.evidence or {},
"judged_at": iso(self.judged_at),
"created_at": iso(self.created_at),
}
+30 -7
View File
@@ -123,6 +123,11 @@ async def session_context():
return jsonify(result)
# The longest carried note a prompt takes: the shape check's note names a
# few definitions and the call that lists the rest.
_CARRY_CHARS = 3000
@plugin_bp.get("/retrieve")
@login_required
@memoized_query_embeddings
@@ -166,6 +171,10 @@ async def autoinject_retrieve():
one-line reminder when present; the hook's
ledger is swept on compaction, which is how the
full core comes back after one.
carry (opt) — a note the session's last stop left for this
prompt: the definitions its turn wrote that
nobody has judged (/shape-check's `note`).
Fitted after the reply shape, before the records.
ONE PAYLOAD, IN ONE ORDER, UNDER ONE BUDGET (`hook_payload`): the rules
this prompt reaches and those mounted on `reply.report`, then the turn's
@@ -216,7 +225,9 @@ async def autoinject_retrieve():
record=False,
)
# One payload, in the one order: the rules, then the reply shape, then
# the records menu, then the lesson-rule proposal, fitted to the budget.
# what the last turn left unjudged, then the records menu, then the
# lesson-rule proposal, fitted to the budget.
carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS]
turn_parts = (
[*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn
else [hook_payload_svc.Part(text=turn.get("context") or "", ids={
@@ -227,6 +238,7 @@ async def autoinject_retrieve():
fitted = await hook_payload_svc.fit(g.user.id, [
*hook_payload_svc.parts_of(rules, {hook_payload_svc.RULE: "shown_rule_ids"}),
*turn_parts,
*([hook_payload_svc.Part(text=carry)] if carry else []),
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}),
*([hook_payload_svc.Part(text=proposal)] if proposal else []),
])
@@ -365,12 +377,20 @@ async def moment():
rules: in full unless `shapes_seen` names it, then as its reminder. The
payload is fitted to the user's budget (`hook_payload`), and `shape_keys`
are the ones sent in full and kept, for the hook's ledger.
`decision` is the answer for the act itself (`retrieval_pipeline.
act_decision`): `{}` when it goes ahead; `kind: "enforce"` when a rule set
to enforce refuses it — the hook denies the call with `reason`, every
time; `kind: "hold"` when an unopened rule set to hold asks for one read
first — the hook denies once per rule and session, under the act
checkpoint's cap. A write is never held, only refused.
"""
event = await request.get_json(silent=True) or {}
tool = str(event.get("tool_name") or "").strip()
tool_input = event.get("tool_input")
if not tool:
return jsonify({"context": "", "rule_ids": [], "moments": [], "shape_keys": []})
return jsonify({"context": "", "rule_ids": [], "moments": [], "shape_keys": [],
"decision": {}})
project_id, _repo, _unbound = await _project_scope()
reached, result = await moment_delivery_svc.deliver_for_act(
g.user.id, tool, tool_input if isinstance(tool_input, dict) else {},
@@ -394,6 +414,7 @@ async def moment():
"rule_ids": fitted.keep_only(hook_payload_svc.RULE, result.rule_ids),
"moments": [hit["moment"] for hit in reached],
"shape_keys": [k for k, form in forms.items() if form == reply_shapes_svc.FULL],
"decision": result.decision,
})
@@ -633,9 +654,11 @@ async def shape_check():
The client's write hooks keep a ledger of the definitions each turn wrote;
its Stop hook sends them here. The server decides which carry no judgment
— against the ledger and the project's recorded snippets — records the
outcome, and for a block returns the `reason` the agent is sent back with.
A hook blocks only on a reason it received, so only on a block that was
recorded, and never on the stop that follows one (`phase=after`).
outcome, and returns the `note` the agent reads at the start of its next
turn. Nothing here holds the reply: the question rides the next prompt,
in the same session, while the code is still in view. `phase=after` is
the stop after that prompt, sent with the lines the note named, and
records whether they were judged.
A GET like every plugin endpoint: a read-scoped key runs the plugin, and
this records telemetry the way /reply-rules records its section check. It changes no ledger
@@ -682,8 +705,8 @@ async def shape_check():
)
body["outcome"] = outcome
body["unjudged"] = unjudged
if outcome == "blocked":
body["reason"] = shape_check_svc.block_reason(
if outcome == "noted":
body["note"] = shape_check_svc.note_text(
unjudged, project_id=project_id, repo=repo_key or repo,
)
return jsonify(body)
+26
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_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc
from grimoire.services import rulebooks as rulebooks_svc
from grimoire.services.retrieval_telemetry import moment_usage
@@ -238,3 +239,28 @@ async def judge_moment_proposals_route():
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
return jsonify(await judgments_svc.judge(get_current_user_id(), data["judgments"]))
@retrieval_bp.route("/weights/proposals", methods=["GET"])
@login_required
async def weight_proposals_route():
"""The enforcement, salience and trigger suggestions waiting on a judgment
— `rule_weight_proposals`' payload, from the same service. `?rule_id=`
narrows to one rule."""
try:
rule_id = int(request.args.get("rule_id") or 0)
except ValueError:
return jsonify({"error": "rule_id must be a whole number"}), 400
return jsonify(await weights_svc.pending(get_current_user_id(), rule_id=rule_id or None))
@retrieval_bp.route("/weights/proposals/judge", methods=["POST"])
@login_required
async def judge_weight_proposals_route():
"""Confirm or reject suggestions: `{"judgments": [{rule_id, field, value,
verdict, note}]}` — `judge_rule_weights` from the browser. A confirm
changes the rule."""
data = await request.get_json(silent=True)
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
return jsonify(await weights_svc.judge(get_current_user_id(), data["judgments"]))
+62 -2
View File
@@ -26,6 +26,7 @@ from grimoire.models.rulebook import (
rule_triggers as rule_triggers_t,
)
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
from grimoire.models.rule_field_judgment import RuleFieldJudgment
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
from grimoire.models.project import Project
@@ -116,7 +117,10 @@ logger = logging.getLogger(__name__)
# from. A live instance rolls back only to a backup with its own id.
# v29 rule_triggers: the typed predicates on the act that deliver a rule or
# make its mount conditional. Nothing in the rule's text records them.
BACKUP_VERSION = 29
# v30 rule_field_judgments: suggested, agreed and rejected values for a rule's
# enforcement, salience and triggers. Lose them and a weighed corpus reads
# as unweighed, and every rejected value is proposed again.
BACKUP_VERSION = 30
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED
# below, these two lists must together account for the entire schema — which is
@@ -162,6 +166,7 @@ _BACKED_UP = [
"rule_moments",
"rule_moment_judgments",
"rule_triggers",
"rule_field_judgments",
# Family canon. `platforms` is global like
# canonical_systems and rides every export for the same reason: the rows
# below name platforms by slug, and a partial catalog restores partial
@@ -269,6 +274,8 @@ _COLUMN_EXCLUSIONS: dict[str, set[str]] = {
"lesson_rule_links": {"id"},
# The same shape: the (rule, moment) pair is the row.
"rule_moment_judgments": {"id"},
# And again: the (rule, field, value) triple is the row.
"rule_field_judgments": {"id"},
# Keyed by the lesson itself; nothing to exclude, every column travels.
"lesson_no_rule": set(),
"note_usage_events": {"id"},
@@ -376,6 +383,7 @@ _IMPORT_COLUMN_EXCLUSIONS: dict[str, set[str]] = {
"rule_relations": {"id", "created_at"},
"lesson_rule_links": {"id"},
"rule_moment_judgments": {"id"},
"rule_field_judgments": {"id"},
"lesson_no_rule": set(),
"note_usage_events": {"id"},
"rule_usage_events": {"id"},
@@ -830,6 +838,21 @@ def _rule_moment_judgment_rows(rows) -> list[dict]:
]
def _rule_field_judgment_rows(rows) -> list[dict]:
"""Suggested, agreed and rejected values for a rule's enforcement,
salience and triggers (v30). The rule id is a SOURCE id, remapped at
restore."""
return [
{
"rule_id": r.rule_id, "field": r.field, "value": r.value, "state": r.state,
"source": r.source, "note": r.note, "evidence": r.evidence,
"judged_at": r.judged_at.isoformat() if r.judged_at else None,
"created_at": r.created_at.isoformat() if r.created_at else None,
}
for r in rows
]
def _rule_system_rows(rows) -> list[dict]:
"""A rule's area tags, carried by canonical SLUG for the same reason the
Systems are: the catalog is global and its ids are per-install."""
@@ -1042,6 +1065,9 @@ async def export_full_backup() -> dict:
rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).order_by(RuleMomentJudgment.id)
)).scalars().all()
rule_field_judgments = (await session.execute(
select(RuleFieldJudgment).order_by(RuleFieldJudgment.id)
)).scalars().all()
rule_relations = (await session.execute(select(RuleRelation).order_by(RuleRelation.id))).scalars().all()
lesson_rule_links = (await session.execute(select(LessonRuleLink).order_by(LessonRuleLink.id))).scalars().all()
lesson_no_rule = (await session.execute(select(LessonNoRule).order_by(LessonNoRule.lesson_id))).scalars().all()
@@ -1133,6 +1159,7 @@ async def export_full_backup() -> dict:
"rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
"rule_field_judgments": _rule_field_judgment_rows(rule_field_judgments),
"rule_relations": _rule_relation_rows(rule_relations),
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
@@ -1301,6 +1328,10 @@ async def export_user_backup(user_id: int) -> dict:
rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).where(RuleMomentJudgment.rule_id.in_(_rule_ids))
)).scalars().all() if _rule_ids else []
rule_field_judgments = (await session.execute(
select(RuleFieldJudgment).where(RuleFieldJudgment.rule_id.in_(_rule_ids))
.order_by(RuleFieldJudgment.id)
)).scalars().all() if _rule_ids else []
# Scoped through the RULE, not the version's user_id. That column is
# the ACTOR, so filtering on it would carry the
# versions this user wrote on someone ELSE's rule and drop the ones
@@ -1426,6 +1457,7 @@ async def export_user_backup(user_id: int) -> dict:
"rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
"rule_field_judgments": _rule_field_judgment_rows(rule_field_judgments),
"rule_relations": _rule_relation_rows(rule_relations),
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
@@ -1857,6 +1889,25 @@ def _build_rule_moment_judgment(row: dict, maps: _Maps) -> RuleMomentJudgment |
)
def _build_rule_field_judgment(row: dict, maps: _Maps) -> RuleFieldJudgment | None:
"""Skipped when its rule did not restore, for the reason a moment
judgment is."""
rule = maps.rules.get(row.get("rule_id", 0))
if rule is None or not row.get("field") or row.get("value") is None:
return None
return RuleFieldJudgment(
rule_id=rule,
field=row["field"],
value=row["value"],
state=row.get("state") or "suggested",
source=row.get("source") or "pass",
note=row.get("note") or None,
evidence=row.get("evidence"),
judged_at=_dt_or_none(row.get("judged_at")),
created_at=_dt(row.get("created_at")),
)
def _build_platform(row: dict, maps: _Maps) -> Platform | None:
"""Matched on SLUG, like a canonical system: this install seeded the
standard platforms from its migrations, so the common case creates nothing
@@ -2447,7 +2498,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
"code_shape_uses": 0, "canonical_systems": 0,
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
"rule_triggers": 0,
"rule_triggers": 0, "rule_field_judgments": 0,
"rule_relations": 0, "rule_versions": 0,
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
"lesson_no_rule": 0, "moment_mappings": 0,
@@ -2666,6 +2717,15 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
session.add(judgment)
stats["rule_moment_judgments"] += 1
# Weighed values for each rule (v30); archives before v30 carry none, and
# every rule restores unweighed.
for rf in data.get("rule_field_judgments", []):
weighed = _build_rule_field_judgment(rf, maps)
if weighed is None:
continue
session.add(weighed)
stats["rule_field_judgments"] += 1
for rr in data.get("rule_relations", []):
relation = _build_rule_relation(rr, maps)
if relation is None:
+43 -7
View File
@@ -16,7 +16,7 @@ from __future__ import annotations
import logging
from grimoire.services import hook_payload, moment_actions, reply_shapes
from grimoire.services import hook_payload, moment_actions, reply_shapes, rule_order
from grimoire.services import retrieval_pipeline as rp
logger = logging.getLogger(__name__)
@@ -121,9 +121,43 @@ async def deliver_for_act(
result = await deliver_moments(
user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board,
)
# A write is never held for a read: a recall aid does not stand in the
# way of the work. A rule set to enforce still refuses one — that is a
# boundary the operator drew, not a reminder.
if result.decision.get("kind") == "hold" and moment_actions.tool_key(tool) in WRITE_TOOLS:
result.decision = {}
return reached, result
# The file-writing tools, as tool keys: a `hold` rule never holds these.
WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"})
async def routed_to_acts(user_id: int, project_id: int | None = None) -> frozenset[int]:
"""The rules that arrive at an act, so the prompt arm leaves them there.
A rule mounted on a moment some action is mapped to (every moment but the
reply moments), or carrying a `tool`, `path` or `command` trigger, reaches
the session at the call it governs. Delivered at the prompt too, it would
arrive twice, and the first time beside a request it competes with. A
keyword trigger can also match a reply, so it does not count.
"""
from grimoire.services import rule_triggers, rulebooks
mappings = await moment_actions.list_mappings(user_id)
act_moments = sorted({
action.moment for action, _via in moment_actions.effective_actions(mappings)
if not action.moment.startswith("reply.")
})
out = {rule.id for rule, _at in await rulebooks.rules_on_moments(
user_id, act_moments, project_id or None,
)} if act_moments else set()
for rule, triggers in await rule_triggers._in_scope(user_id, project_id or None):
if any(t.kind in ("tool", "path", "command") and not t.moment for t in triggers):
out.add(rule.id)
return frozenset(out)
def shapes_for_act(reached: list[dict], seen: frozenset[str] = frozenset()) -> tuple[list[str], dict[str, str]]:
"""The default reply shapes riding the moments this act reached.
@@ -238,8 +272,8 @@ async def attach_moment_rules(
# your end" gets said — so it is checked twice over: the rules MOUNTED on the
# reply moments (deterministic, somebody said they belong here), and the
# reply text against every rule's trigger (the backstop for whatever the
# earlier arms missed). An unopened rule from either half HOLDS the reply for
# one read, in these words; the hook never holds the rewrite.
# earlier arms missed). An unopened rule set to hold, from either half, HOLDS
# the reply for one read, in these words; the hook never holds the rewrite.
# The reply's head and tail. The embedder reads ~512 tokens, and the part of
# a report that asks something of the reader — "let me know if it works" —
@@ -339,13 +373,15 @@ async def reply_hold(
room = pc.CHECKPOINT_SESSION_CAP - len(stopped)
out: list[dict] = []
# The mounted half: deterministic, so every unopened RULE on these
# moments holds. A preference claims no such force. A mount
# conditional on a trigger holds only when the reply meets it.
# The mounted half: deterministic, so every unopened rule on these
# moments that is declared to hold (`hold` or `enforce`) holds. An
# `inform` rule was put in front of the turn before the reply was
# written, and a preference claims no force. A mount conditional on
# a trigger holds only when the reply meets it.
board = await _board(user_id, project_id, text=reply)
gated = board.gated if board is not None else set()
for rule, at in await rulebooks.rules_on_moments(user_id, names, project_id or None):
if rule.id in skip or rule.kind == "preference" or (rule.id, at) in gated:
if rule.id in skip or not rule_order.holds(rule) or (rule.id, at) in gated:
continue
out.append({"rule_id": rule.id, "title": rule.title, "moment": at,
"trigger": (rule.when_to_apply or "").strip()})
+14
View File
@@ -985,6 +985,7 @@ async def build_prompt_rule_hint(
# the bound project's own. An unbound session (project_id 0) gets
# global rules only — this surface speaks unasked, and a whole-rulebook
# answer is only right for someone who asked the whole rulebook.
# A rule that reaches the session at an act is left for that act.
result = await _rule_moment(
rp.PROMPT_RULE,
rp.RuleMoment(
@@ -992,6 +993,7 @@ async def build_prompt_rule_hint(
where="to this request",
exclude=frozenset(exclude_rule_ids or []),
held=frozenset(held_rule_ids or []),
elsewhere=await _routed_for(user_id, project_id),
),
floor=await floor_for(user_id, "prompt_rule"),
budget=await budget_for(user_id, "prompt_rule"),
@@ -1011,6 +1013,18 @@ async def build_prompt_rule_hint(
return out
async def _routed_for(user_id: int, project_id: int) -> frozenset[int]:
"""The rules that arrive at an act (`moment_delivery.routed_to_acts`);
empty when they cannot be read, so the prompt arm delivers as before."""
from grimoire.services import moment_delivery
try:
return await moment_delivery.routed_to_acts(user_id, project_id or None)
except Exception: # noqa: BLE001 - a recall aid never breaks the prompt
logger.debug("act-routed rules unreadable", exc_info=True)
return frozenset()
def _rule_io() -> rp.RuleIO:
"""The ranker and recorders the rule arms report to, read at call time.
+101 -8
View File
@@ -105,12 +105,11 @@ def checkpoint_for(
floor; only a hit the corpus is confident about is allowed to stop
anything.
2. IT IS A RULE, NEVER A PREFERENCE. A preference says how something has
been done before and following it is what keeps work consistent; a rule
says what happens if you do not. Stopping an act over a preference
would assert a force the record explicitly does not claim, and
`_rule_hint_line` already keeps that distinction in the one word that
names it.
2. IT IS A RULE DECLARED TO HOLD (`rule_order.holds`): `hold` or
`enforce`, never `inform`, never a preference. A preference says how
something has been done before; an `inform` rule asked to be put beside
the work. Stopping an act over either would assert a force the record
does not claim.
3. THE SESSION HAS NOT OPENED IT. `held` is observable — a PostToolUse
hook watches for the `get_rule` call — so this is a recorded
@@ -134,7 +133,7 @@ def checkpoint_for(
score, rule = kept[0]
if score < floor:
return {}
if getattr(rule, "kind", "") == "preference":
if not rule_order.holds(rule):
return {}
if rule.id in held:
return {}
@@ -545,6 +544,12 @@ class RuleMoment:
held: frozenset[int] = frozenset()
"""Rules the session has OPENED."""
elsewhere: frozenset[int] = frozenset()
"""Rules that arrive at an act — mounted on a moment a tool call reaches,
or triggered by a tool, path or command — and so are not delivered here
by resemblance. A reminder read at the act is the one acted on; the same
line at the prompt competes with the request it came beside."""
@dataclass
class RuleResult:
@@ -563,6 +568,11 @@ class RuleResult:
checkpoint: dict = field(default_factory=dict)
decision: dict = field(default_factory=dict)
"""The moment arm's answer for the act itself, empty when the act goes
ahead: `{"kind": "enforce" | "hold", "rule_ids", "reason"}`. See
`act_decision`."""
line_rule_ids: list[int] = field(default_factory=list)
"""The rule behind each of `lines`, in order, when a caller added lines
of its own after the arm's; empty means `shown_rule_ids` lines up."""
@@ -644,6 +654,8 @@ async def _ranked(
# this done" asserts a force the record does not have.
hits = [(score, rule) for score, rule in hits
if getattr(rule, "kind", None) == kind]
if moment.elsewhere:
hits = [(score, rule) for score, rule in hits if rule.id not in moment.elsewhere]
kept = _rule_band(hits) if band else hits
# The gate is part of the cut, like the band: what it turns away is not
# shown, so it is not in the row's results either.
@@ -1749,11 +1761,16 @@ async def run_moment_arm(
taken.add(rule.id)
cands.append((rule, trig.key, f"its trigger {trig.describe()} matched this act",
rule_order.BY_TRIGGER))
# Read before retirement: a rule that enforces does so on every act it
# reaches, however often this session has been shown it.
decision = act_decision(
[(rule, at, where) for rule, at, where, _s in cands], held=moment.held,
)
gone = await _retired(io, moment, [rule for rule, _a, _w, _s in cands])
if gone:
cands = [c for c in cands if c[0].id not in gone]
if not cands:
return RuleResult()
return RuleResult(decision=decision)
# The one delivery order (services/rule_order.py), then the cap — so
# what a crowded moment drops is the lowest-ranked, not the last
# mounted. Ties keep catalog order.
@@ -1798,7 +1815,83 @@ async def run_moment_arm(
lines=lines, rule_ids=rule_ids,
shown_rule_ids=[rule.id for rule, _at, _where in shown],
shown=[(None, rule) for rule, _at, _where in shown],
decision=decision,
)
except Exception: # noqa: BLE001 - a recall aid never breaks its act
logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True)
return RuleResult()
def act_decision(reached: list[tuple], *, held: frozenset[int] = frozenset()) -> dict:
"""What the act itself is told, from the rules its moments and triggers reached.
`reached` is `(rule, at, where)` for every rule the act reached, in any
order. Sync and pure, so it can be read against a fixed list.
- A rule declared `enforce` REFUSES the act, every time it is reached:
`{"kind": "enforce", ...}` with the rules' own words as the reason. It
is a boundary the operator drew, and the act is the place it is drawn —
reaching it by mount or trigger is a structural fact, never a
resemblance. Opening the rule does not lift it; changing the rule does.
- Otherwise the first rule declared `hold` that the session has not
opened HOLDS the act for one read: `{"kind": "hold", ...}`. The client
holds a rule once per session and caps holds per session, as at the act
checkpoint.
- Otherwise `{}`: the act goes ahead, with any lines beside it.
A preference never refuses or holds (`rule_order.force`).
"""
enforced = [item for item in reached if rule_order.force(item[0]) == "enforce"]
if enforced:
return {"kind": "enforce", "rule_ids": [rule.id for rule, _a, _w in enforced],
"reason": enforce_reason(enforced)}
for rule, at, where in reached:
if rule_order.force(rule) == "hold" and rule.id not in held:
return {"kind": "hold", "rule_ids": [rule.id],
"reason": hold_reason(rule, at=at, where=where)}
return {}
def enforce_reason(enforced: list[tuple]) -> str:
"""The text the agent reads instead of the act running, for an `enforce` rule.
Says which rule drew the line and where, gives its own words, and names
who can move it: the operator, by changing the rule. A rule reached by
the wrong act is a misfire the reader can record in one call.
"""
parts = []
for rule, at, where in enforced:
statement = _statement_excerpt(rule)
parts.append(
f"“{rule.title}” (Rule {rule.id}, {where})"
+ (f": {statement}" if statement else "")
)
first_rule, first_at, _w = enforced[0]
noun = "a rule" if len(enforced) == 1 else "rules"
return (
f"Not run: this act reaches {noun} the operator set to enforce. "
+ " · ".join(parts)
+ ". An enforced rule stops the act rather than sitting beside it, and "
"opening it does not lift it. If the operator has asked for this act, "
"tell them which rule stopped it: they lift it by changing the rule's "
"enforcement or its trigger. If the rule has nothing to do with this "
f"act, rule_misfired({first_rule.id}, \"{first_at}\", why) records that."
)
def hold_reason(rule, *, at: str, where: str) -> str:
"""The text the agent reads instead of the act running, for a `hold` rule.
A practice on the act checkpoint's model: one read, then the act may be
re-submitted unchanged.
"""
trigger = (getattr(rule, "when_to_apply", "") or "").strip()
return (
f"Held for one read. “{rule.title}” (Rule {rule.id}, {where}) is set to "
f"hold the work it governs, and this session has not opened it"
+ (f" — it applies when {trigger}" if trigger else "")
+ f". Read it with get_rule({rule.id}), then re-submit this call — "
"unchanged if the rule does not apply, which is a judgement only you "
"can make. If it has nothing to do with this act, "
f"rule_misfired({rule.id}, \"{at}\", why) records that."
)
@@ -0,0 +1,501 @@
"""How strongly each rule arrives, and what reaches it — proposals and judgments.
A rule carries three fields that decide what happens once the work reaches it:
- `enforcement` — `inform` (a line beside the work), `hold` (the act or reply
waits for one read of the rule) or `enforce` (the act it governs is refused,
in the rule's own words, every time). A preference is always `inform`.
- `salience` — `high`, `normal` or `low`: how it ranks beside rules of the same
enforcement when a moment has more to say than fits.
- `trigger` — typed predicates on the act (tool, path, command, keyword) that
reach the rule exactly, with no resemblance involved.
Every rule written before these fields existed carries the defaults, which
say nothing about whether anyone judged them. This service records that
judgment the way moment mounts are recorded (`rule_moment_judgments`):
- THE PASS. An agent reads each rule nobody has weighed, with its delivery
history — how often it reached a session, at which places, how often it was
opened there, how often sessions said it applied or departed from it — and
proposes its enforcement and salience, and any triggers it should have
(`propose`). A value equal to what the rule already has is recorded as the
pass's agreement; a different one waits as a suggestion and changes nothing.
- THE JUDGMENT. A person confirms or rejects each suggestion (`judge`). A
confirm writes the field through the one rule write path; a reject is kept
so the value is never proposed again.
A person setting a rule's enforcement or salience directly is judging it too
(`record_edit`, called from `rulebooks.update_rule`), so a suggestion that an
edit already answered does not wait in the list.
ACL: rules are owner-scoped; every read and write goes through
`rulebooks._owned_rules_clause`.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from sqlalchemy import case, exists, func, not_, select
from grimoire.models import async_session
from grimoire.models.rule_delivery import RuleDelivery
from grimoire.models.rule_field_judgment import (
CONFIRMED, ENFORCEMENT, FIELDS, REJECTED, SALIENCE, SUGGESTED, TRIGGER,
RuleFieldJudgment,
)
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.rule_usage import RuleUsageEvent
from grimoire.models.rulebook import Rule
from grimoire.services import lesson_rules, rule_order
from grimoire.services import rule_triggers as triggers_svc
from grimoire.services.rule_moment_judgments import _int, _mounts, _owned_rules as _owned
from grimoire.services.rulebooks import ENFORCEMENTS, SALIENCES
VERDICTS = {"confirm": CONFIRMED, "reject": REJECTED}
# Rules per pass page: enough to batch the reading, few enough that each rule
# and its history is actually read.
PASS_PAGE = 25
# The delivery history a pass reads. Matches what the delivery order reads
# (`rule_deliveries.HISTORY_DAYS`), so a proposal and the ranking it changes
# look at the same window.
HISTORY_DAYS = 90
# Places listed per rule in its history, busiest first. Past this the counts
# stop changing what the proposer would say.
_PLACES = 8
_WHY_CHARS = 600
_EDIT_NOTE = "set by an edit"
def _text(v) -> str:
return v.strip() if isinstance(v, str) else ""
def trigger_value(trigger: triggers_svc.Trigger) -> str:
"""A trigger as one string, so (rule, field, value) is unique."""
return f"{trigger.kind}\t{trigger.pattern}\t{trigger.moment}"
def parse_trigger_value(value: str) -> triggers_svc.Trigger:
kind, pattern, moment = (value.split("\t", 2) + ["", ""])[:3]
return triggers_svc.Trigger(kind, pattern, moment)
def current_value(rule: Rule, field: str) -> str:
if field == ENFORCEMENT:
return rule_order.force(rule)
return rule.salience or "normal"
def _act_routed(mounts: set[str], triggers: list) -> bool:
"""Whether some act can reach the rule — what `enforce` refuses.
A trigger is matched against an act; a mount reaches an act unless it is
on the reply. A rule reached only at the reply has no act to refuse, so
enforcing it would hold the reply and claim more than it does.
"""
return bool(triggers) or any(not m.startswith("reply.") for m in mounts)
# ── reading ───────────────────────────────────────────────────────────────
async def history(session, user_id: int, rule_ids) -> dict[int, dict]:
"""What happened when each rule reached a session, over HISTORY_DAYS.
`delivered` / `opened` in total and at each place it was delivered
(`at`: a moment, or the arm that found it), busiest first; `pulled`,
`applied` and `departed` from the usage events; `misfire_days`, the days
sessions reported a mount of it arriving where it did not apply.
"""
ids = sorted({int(r) for r in rule_ids or []})
out = {rid: {"days": HISTORY_DAYS, "delivered": 0, "opened": 0, "places": [],
"pulled": 0, "applied": 0, "departed": 0, "misfire_days": 0}
for rid in ids}
if not ids:
return out
since = datetime.now(timezone.utc) - timedelta(days=HISTORY_DAYS)
rows = (await session.execute(
select(
RuleDelivery.rule_id, RuleDelivery.at, func.count(RuleDelivery.id),
func.sum(case((RuleDelivery.opened_at.is_not(None), 1), else_=0)),
)
.where(RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since,
RuleDelivery.rule_id.in_(ids))
.group_by(RuleDelivery.rule_id, RuleDelivery.at)
)).all()
for rid, at, delivered, opened in rows:
h = out[int(rid)]
h["delivered"] += int(delivered)
h["opened"] += int(opened or 0)
h["places"].append({"at": at, "delivered": int(delivered), "opened": int(opened or 0)})
for h in out.values():
h["places"] = sorted(h["places"], key=lambda p: (-p["delivered"], p["at"]))[:_PLACES]
events = (await session.execute(
select(RuleUsageEvent.rule_id, RuleUsageEvent.event, func.count())
.where(RuleUsageEvent.user_id == user_id, RuleUsageEvent.created_at >= since,
RuleUsageEvent.rule_id.in_(ids),
RuleUsageEvent.event.in_(("pulled", "applied", "departed")))
.group_by(RuleUsageEvent.rule_id, RuleUsageEvent.event)
)).all()
for rid, event, n in events:
out[int(rid)][event] = int(n)
misfires = (await session.execute(
select(RuleMomentJudgment.rule_id, RuleMomentJudgment.misfire)
.where(RuleMomentJudgment.rule_id.in_(ids), RuleMomentJudgment.misfire.isnot(None))
)).all()
for rid, mf in misfires:
out[int(rid)]["misfire_days"] += lesson_rules.evidence_summary(mf)["situations"]
return out
def _brief(rule: Rule, mounts: set[str], triggers: list[dict]) -> dict:
return {
"id": rule.id,
"title": rule.title,
"kind": rule.kind or "rule",
"statement": rule.statement,
"when_to_apply": rule.when_to_apply or "",
"home": "project" if rule.project_id else "global",
"enforcement": current_value(rule, ENFORCEMENT),
"salience": current_value(rule, SALIENCE),
"mounted": sorted(mounts),
"triggers": triggers,
}
def _unweighed_clause():
"""No enforcement or salience judgment of any kind — a rule nobody weighed."""
return not_(exists().where(
RuleFieldJudgment.rule_id == Rule.id,
RuleFieldJudgment.field.in_((ENFORCEMENT, SALIENCE)),
))
async def unweighed_rules(user_id: int, limit: int = PASS_PAGE, offset: int = 0) -> dict:
"""The caller's rules nobody has weighed, a page at a time, each with its history.
A rule leaves this list once its enforcement and salience have any answer
— a proposal, the pass's agreement, or a direct edit — so a pass run in
pieces does not read a rule twice.
"""
from grimoire.services.rulebooks import _owned_rules_clause
limit = max(1, min(int(limit or PASS_PAGE), 100))
offset = max(0, int(offset or 0))
clauses = (_owned_rules_clause(user_id), _unweighed_clause())
async with async_session() as session:
total = (await session.execute(
select(func.count()).select_from(Rule).where(*clauses)
)).scalar_one()
rules = (await session.execute(
select(Rule).where(*clauses).order_by(Rule.id).limit(limit).offset(offset)
)).scalars().all()
ids = [r.id for r in rules]
mounts = await _mounts(session, ids)
hist = await history(session, user_id, ids)
triggers = await triggers_svc.list_rule_triggers(ids)
return {
"rules": [{**_brief(r, mounts.get(r.id, set()), triggers.get(r.id, [])),
"history": hist[r.id]} for r in rules],
"total_unweighed": int(total),
"offset": offset,
}
# ── the pass ──────────────────────────────────────────────────────────────
async def _rows(session, rule_ids) -> dict[tuple[int, str, str], RuleFieldJudgment]:
if not rule_ids:
return {}
rows = (await session.execute(
select(RuleFieldJudgment).where(RuleFieldJudgment.rule_id.in_(list(rule_ids)))
)).scalars().all()
return {(r.rule_id, r.field, r.value): r for r in rows}
async def propose(user_id: int, proposals: list[dict]) -> dict:
"""Record a pass's proposals for rules' enforcement, salience and triggers.
Each item is `{rule_id, enforcement, salience, triggers?: [...], why}`.
Enforcement and salience are both required: they are the answer to "how
strongly does this rule arrive", and answering one leaves the rule half
weighed. A value equal to the rule's own is recorded as agreed and changes
nothing; a different one lands `suggested`, replacing any earlier
suggestion for that field. A trigger the rule does not have lands
`suggested`. A value already rejected is skipped and said so.
Refused alone, with why: a rule the caller does not own, an unknown value,
a preference proposed to hold or enforce, and `enforce` on a rule no act
can reach (no trigger, none proposed, and mounted only at the reply).
"""
now = datetime.now(timezone.utc)
suggested = agreed = 0
skipped: list[dict] = []
refused: list[dict] = []
items = [p for p in proposals or [] if isinstance(p, dict)]
refused += [{"item": p, "error": "each proposal is an object"}
for p in proposals or [] if not isinstance(p, dict)]
async with async_session() as session:
owned = await _owned(session, user_id, [p.get("rule_id") for p in items])
mounts = await _mounts(session, list(owned))
hist = await history(session, user_id, list(owned))
existing = await _rows(session, list(owned))
have = await triggers_svc.list_rule_triggers(list(owned))
for item in items:
rid = _int(item.get("rule_id"))
rule = owned.get(rid) if rid else None
if rule is None:
refused.append({"rule_id": item.get("rule_id"), "error": "not a rule you own"})
continue
enforcement = _text(item.get("enforcement")).lower()
salience = _text(item.get("salience")).lower()
why = _text(item.get("why"))[:_WHY_CHARS]
if enforcement not in ENFORCEMENTS or salience not in SALIENCES:
refused.append({"rule_id": rid, "error": (
f"give both enforcement (one of {', '.join(ENFORCEMENTS)}) and salience "
f"(one of {', '.join(SALIENCES)})")})
continue
if not why:
refused.append({"rule_id": rid, "error": (
"why is required: it is what the operator reads to say yes or no "
"without opening the rule")})
continue
if rule.kind == "preference" and enforcement != "inform":
refused.append({"rule_id": rid, "error": (
"a preference is always `inform`: it says how work is liked, and "
"claims no force that could stop it. Propose it as a rule's "
"enforcement only after it is made a rule")})
continue
try:
wanted = triggers_svc.require_triggers(item.get("triggers") or []) or []
except ValueError as exc:
refused.append({"rule_id": rid, "error": str(exc)})
continue
current_triggers = {trigger_value(triggers_svc.require_trigger(t))
for t in have.get(rid, [])}
new_triggers = [t for t in wanted if trigger_value(t) not in current_triggers]
if enforcement == "enforce" and not _act_routed(mounts.get(rid, set()),
have.get(rid, []) + new_triggers):
refused.append({"rule_id": rid, "error": (
"`enforce` refuses the act a rule governs, and nothing routes an act "
"to this one: it has no trigger and is mounted only at the reply, if "
"anywhere. Propose the trigger that names the act (a command, a path, "
"a tool) with it, or propose `hold`")})
continue
evidence = hist[rid]
def put(field: str, value: str, state: str) -> None:
row = existing.get((rid, field, value))
if row is None:
row = RuleFieldJudgment(rule_id=rid, field=field, value=value, source="pass")
session.add(row)
existing[(rid, field, value)] = row
row.state, row.note, row.evidence = state, why, evidence
if state != SUGGESTED:
row.judged_at = now
for field, value in ((ENFORCEMENT, enforcement), (SALIENCE, salience)):
row = existing.get((rid, field, value))
if value == current_value(rule, field):
if row is None or row.state == SUGGESTED:
put(field, value, CONFIRMED)
agreed += 1
continue
if row is not None and row.state == REJECTED:
skipped.append({"rule_id": rid, "field": field, "value": value,
"why": "already rejected" + (f": {row.note}" if row.note else "")})
continue
# One open suggestion per field: a newer reading replaces an older one.
for key, other in list(existing.items()):
if key[0] == rid and key[1] == field and key[2] != value and other.state == SUGGESTED:
await session.delete(other)
existing.pop(key)
put(field, value, SUGGESTED)
suggested += 1
for trigger in new_triggers:
value = trigger_value(trigger)
row = existing.get((rid, TRIGGER, value))
if row is not None and row.state != SUGGESTED:
skipped.append({"rule_id": rid, "field": TRIGGER, "value": trigger.to_dict(),
"why": f"already {row.state}" + (f": {row.note}" if row.note else "")})
continue
put(TRIGGER, value, SUGGESTED)
suggested += 1
await session.commit()
return {"suggested": suggested, "agreed": agreed, "skipped": skipped, "refused": refused}
# ── waiting on a person ───────────────────────────────────────────────────
def _proposal_item(row: RuleFieldJudgment) -> dict:
out = {"field": row.field, "value": row.value, "why": row.note or "",
"source": row.source, "evidence": row.evidence or {},
"created_at": row.created_at.isoformat() if row.created_at else None}
if row.field == TRIGGER:
out["trigger"] = parse_trigger_value(row.value).to_dict()
return out
async def pending(user_id: int, rule_id: int | None = None, limit: int = 200) -> dict:
"""The suggestions waiting on a judgment, grouped by rule.
Each rule carries its current enforcement, salience, mounts and triggers,
so a suggestion is read beside what it would change. A suggestion the rule
already carries — set by an edit since, or a trigger added by hand — is
left out: there is nothing left to decide.
"""
from grimoire.services.rulebooks import _owned_rules_clause
limit = max(1, min(int(limit or 200), 500))
async with async_session() as session:
stmt = (
select(RuleFieldJudgment, Rule)
.join(Rule, Rule.id == RuleFieldJudgment.rule_id)
.where(RuleFieldJudgment.state == SUGGESTED, _owned_rules_clause(user_id))
)
if rule_id:
stmt = stmt.where(Rule.id == int(rule_id))
rows = (await session.execute(
stmt.order_by(Rule.id, RuleFieldJudgment.field, RuleFieldJudgment.value).limit(limit)
)).all()
ids = sorted({r.id for _, r in rows})
mounts = await _mounts(session, ids)
triggers = await triggers_svc.list_rule_triggers(ids)
order = {f: i for i, f in enumerate(FIELDS)}
grouped: dict[int, dict] = {}
for row, rule in rows:
have = triggers.get(rule.id, [])
if row.field == TRIGGER:
if parse_trigger_value(row.value).to_dict() in have:
continue
elif row.value == current_value(rule, row.field):
continue
entry = grouped.setdefault(rule.id, {
**_brief(rule, mounts.get(rule.id, set()), have), "proposals": [],
})
entry["proposals"].append(_proposal_item(row))
for entry in grouped.values():
entry["proposals"].sort(key=lambda p: (order.get(p["field"], 9), p["value"]))
rules = sorted(grouped.values(), key=lambda r: r["id"])
return {"rules": rules, "total": sum(len(r["proposals"]) for r in rules)}
# ── judging ───────────────────────────────────────────────────────────────
def _judged_value(field: str, raw) -> str:
"""The value a judgment names, normalised the way proposals store it."""
if field == TRIGGER:
trigger = raw if isinstance(raw, dict) else None
if trigger is None and isinstance(raw, str) and "\t" in raw:
return trigger_value(parse_trigger_value(raw))
return trigger_value(triggers_svc.require_trigger(trigger))
value = _text(raw).lower()
allowed = ENFORCEMENTS if field == ENFORCEMENT else SALIENCES
if value not in allowed:
raise ValueError(f"{field} must be one of {', '.join(allowed)}")
return value
async def judge(user_id: int, judgments: list[dict]) -> dict:
"""Confirm or reject suggestions — on a person's word, since a confirm changes the rule.
Each item is `{rule_id, field, value, verdict, note?}`; for a trigger,
`value` is the trigger `{kind, pattern, moment?}`. Confirm writes the
field through `rulebooks.update_rule` (enforcement, salience) or adds the
trigger beside the rule's others; reject records that the value is wrong
here, so it is never proposed again. A bad item is refused alone.
"""
from grimoire.services.rulebooks import update_rule
done: list[dict] = []
refused: list[dict] = []
for item in judgments or []:
if not isinstance(item, dict):
refused.append({"item": item, "error": "each judgment is an object"})
continue
rid = _int(item.get("rule_id"))
field = _text(item.get("field")).lower()
state = VERDICTS.get(_text(item.get("verdict")).lower())
if rid is None or field not in FIELDS or state is None:
refused.append({"rule_id": item.get("rule_id"), "field": item.get("field"), "error": (
f"needs rule_id, a field (one of {', '.join(FIELDS)}) and a verdict "
f"(one of {', '.join(sorted(VERDICTS))})")})
continue
try:
value = _judged_value(field, item.get("value"))
except ValueError as exc:
refused.append({"rule_id": rid, "field": field, "error": str(exc)})
continue
note = _text(item.get("note"))[:_WHY_CHARS]
async with async_session() as session:
if not await _owned(session, user_id, [rid]):
refused.append({"rule_id": rid, "field": field, "error": "not a rule you own"})
continue
if state == CONFIRMED:
try:
if field == TRIGGER:
await _add_trigger(rid, parse_trigger_value(value))
elif await update_rule(rid, user_id, **{field: value}) is None:
refused.append({"rule_id": rid, "field": field, "error": "not a rule you own"})
continue
except ValueError as exc:
refused.append({"rule_id": rid, "field": field, "error": str(exc)})
continue
await _record(rid, field, value, state, note)
done.append({"rule_id": rid, "field": field, "value": value, "state": state})
return {"judged": done, "refused": refused}
async def _add_trigger(rule_id: int, trigger: triggers_svc.Trigger) -> None:
have = (await triggers_svc.list_rule_triggers([rule_id])).get(rule_id, [])
triggers = triggers_svc.require_triggers(have + [trigger.to_dict()]) or []
await triggers_svc.set_rule_triggers(rule_id, triggers)
async def _record(rule_id: int, field: str, value: str, state: str, note: str) -> None:
now = datetime.now(timezone.utc)
async with async_session() as session:
row = (await session.execute(
select(RuleFieldJudgment).where(
RuleFieldJudgment.rule_id == rule_id, RuleFieldJudgment.field == field,
RuleFieldJudgment.value == value)
)).scalar_one_or_none()
if row is None:
row = RuleFieldJudgment(rule_id=rule_id, field=field, value=value, source="edit")
session.add(row)
row.state, row.judged_at = state, now
row.note = note or row.note
await session.commit()
async def record_edit(session, rule_id: int, field: str, before: str, after: str) -> None:
"""Record a direct change of enforcement or salience, in the caller's session.
The new value is confirmed; a suggestion for any other value of that field
is rejected — the edit answered it. A rule edited this way has been
weighed, so the pass does not read it again.
"""
if field not in (ENFORCEMENT, SALIENCE) or before == after:
return
now = datetime.now(timezone.utc)
rows = (await session.execute(
select(RuleFieldJudgment).where(
RuleFieldJudgment.rule_id == rule_id, RuleFieldJudgment.field == field)
)).scalars().all()
by_value = {r.value: r for r in rows}
row = by_value.get(after)
if row is None:
row = RuleFieldJudgment(rule_id=rule_id, field=field, value=after,
source="edit", note=_EDIT_NOTE)
session.add(row)
row.state, row.judged_at = CONFIRMED, now
for value, other in by_value.items():
if value != after and other.state == SUGGESTED:
other.state, other.judged_at = REJECTED, now
other.note = f"{field} set to {after} by an edit"
+23
View File
@@ -32,6 +32,29 @@ from typing import Any
ENFORCEMENT_RANK = {"enforce": 0, "hold": 1, "inform": 2}
SALIENCE_RANK = {"high": 0, "normal": 1, "low": 2}
def force(rule: Any) -> str:
"""What this rule does when it arrives: `enforce`, `hold` or `inform`.
A preference is always `inform`, whatever the field says: it records how
work is liked, and claims no force that could stop it.
"""
if getattr(rule, "kind", None) == "preference":
return "inform"
value = getattr(rule, "enforcement", None)
return value if value in ENFORCEMENT_RANK else "inform"
def holds(rule: Any) -> bool:
"""Whether this rule may make a reply or an act wait for one read.
Only a rule declared `hold` or `enforce` may. Every other rule is a line
beside the work: holding the work on a rule nobody declared as one that
holds made each reply after a write cost a rewrite, for rules that asked
only to be read.
"""
return force(rule) in ("enforce", "hold")
# How narrowly a rule was reached, larger is narrower.
BY_RESEMBLANCE = 0
BY_MOUNT = 1
+8
View File
@@ -763,6 +763,8 @@ async def update_rule(
# to survive the mutation below. A rule's history is the only record
# of what it used to say; the edit itself destroys that.
text_before = rule_versions.snapshot(rule)
weight_before = {"enforcement": rule.enforcement or "inform",
"salience": rule.salience or "normal"}
for key in clear:
if key in allowed and key in NULLABLE_RULE_TEXT:
setattr(rule, key, None)
@@ -808,6 +810,12 @@ async def update_rule(
# wording was written — which is why it is taken before the loop and
# not here.
rule_versions.record_if_changed(session, rule, user_id, text_before)
# Setting how strongly a rule arrives is a judgment of it: recorded
# beside the pass's suggestions, so one this edit answered stops waiting.
from grimoire.services import rule_field_judgments
for field, before in weight_before.items():
await rule_field_judgments.record_edit(
session, rule.id, field, before, getattr(rule, field) or before)
await session.commit()
await session.refresh(rule)
_refresh_rule_embedding(rule)
+31 -24
View File
@@ -33,15 +33,21 @@ from sqlalchemy import select
from grimoire.models import async_session
from grimoire.models.app_log import AppLog
# check — the turn's first stop: block if anything is unjudged.
# after — the stop that follows a block: never block again, only record
# whether the agent answered.
# check — a turn's stop: note what is unjudged, for the next prompt.
# after — the stop after the note was read: record whether the agent
# answered it.
PHASES = ("check", "after")
OUTCOMES = ("passed", "blocked", "judged_after_block", "left_after_block")
# `blocked` and its two answers are the outcomes of the end-of-turn hold this
# check once was; they stay readable so a window spanning both still sums.
OUTCOMES = ("passed", "noted", "judged_after_note", "left_after_note",
"blocked", "judged_after_block", "left_after_block")
ASKED = ("noted", "blocked")
LEFT = ("left_after_note", "left_after_block")
# How many shapes the reason names before "+N more". Enough to judge a normal
# turn in one call; a turn that wrote more than this generated something.
_LISTED = 25
# How many shapes the note names before "+N more". It rides the next prompt
# inside the payload budget, so it names the first few and the call that
# lists the rest.
_LISTED = 8
def _evidence_note(evidence: dict) -> str:
@@ -62,8 +68,9 @@ def _evidence_note(evidence: dict) -> str:
return f" ({'; '.join(parts)})" if parts else ""
def block_reason(unjudged: list[dict], *, project_id: int, repo: str) -> str:
"""What the agent is told at the end of a turn that wrote unjudged shapes.
def note_text(unjudged: list[dict], *, project_id: int, repo: str) -> str:
"""What the agent reads at the start of the turn after one that wrote
unjudged shapes.
Phrased as a practice: what to decide and the one
call that records it, not a prohibition. The reusing-code skill owns the
@@ -81,10 +88,10 @@ def block_reason(unjudged: list[dict], *, project_id: int, repo: str) -> str:
lines.append(f"- … and {more} more (list_shapes(project_id={project_id}, path=…) shows them)")
repo_arg = f', repo="{repo}"' if repo else ""
return (
f"This turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} "
f"Your last turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} "
"that nobody has judged yet. You built them, so you know what each one is — "
"record it now, while that is still true, so the next session starts from your "
"answer instead of rebuilding it:\n"
"record it alongside this turn's work, while that is still true, so the next "
"session starts from your answer instead of rebuilding it:\n"
+ "\n".join(lines)
+ "\n\nFor each: something another part of the code should reuse → record it "
"with create_snippet (name, code, when to reach for it, location); built from a "
@@ -122,11 +129,11 @@ async def record_shape_check(
def outcome_for(phase: str, unjudged: list[dict]) -> str:
"""The recorded outcome: a first stop blocks or passes; the stop after a
block records whether the agent answered, and never blocks."""
"""The recorded outcome: a turn's stop notes or passes; the stop after
the note was read records whether the agent answered it."""
if phase == "after":
return "left_after_block" if unjudged else "judged_after_block"
return "blocked" if unjudged else "passed"
return "left_after_note" if unjudged else "judged_after_note"
return "noted" if unjudged else "passed"
def parse_written(raw: str, *, cap: int = 200) -> list[tuple[str, str, str]]:
@@ -158,14 +165,14 @@ WINDOW_DAYS = 7
def summarise(outcomes: list[str]) -> dict:
"""{checked, asked, left} from a list of recorded outcomes.
`checked` is turns the question was put to (a first stop that wrote
something): passed + blocked. `asked` is the blocked ones. `left` is
asks the agent walked past — the stop after a block that still had
unjudged shapes. That last number is the slip this check exists to make
visible."""
checked = sum(1 for o in outcomes if o in ("passed", "blocked"))
asked = sum(1 for o in outcomes if o == "blocked")
left = sum(1 for o in outcomes if o == "left_after_block")
`checked` is turns the question was put to (a stop after a turn that
wrote something): passed + asked. `asked` is the ones that found
something unjudged. `left` is asks the agent walked past — answered by a
stop that still had unjudged shapes. That last number is the slip this
check exists to make visible."""
checked = sum(1 for o in outcomes if o == "passed" or o in ASKED)
asked = sum(1 for o in outcomes if o in ASKED)
left = sum(1 for o in outcomes if o in LEFT)
return {"checked": checked, "asked": asked, "left": left}
+2
View File
@@ -134,6 +134,8 @@ WRITE_TARGETS: dict[str, dict[str, str]] = {
"unmap_action": {},
"propose_rule_moments": {},
"judge_rule_moments": {},
"propose_rule_weights": {},
"judge_rule_weights": {},
"rule_misfired": {},
"judge_menu": {},
# trash: a batch can hold rows from several projects
+4 -1
View File
@@ -381,5 +381,8 @@ def _ungated_doors(request):
return
from grimoire.services import plugin_context
with patch.object(plugin_context, "_gate_for", AsyncMock(return_value=None)):
# The same holds for the rules routed to acts, which read mounts and
# triggers a test about something else has not written.
with patch.object(plugin_context, "_gate_for", AsyncMock(return_value=None)), \
patch.object(plugin_context, "_routed_for", AsyncMock(return_value=frozenset())):
yield
@@ -0,0 +1,222 @@
"""Real-Postgres tests for weighing rules: proposed and judged enforcement,
salience and triggers.
What the feature promises, against the real tables:
- the pass reads each rule beside its delivery history, and any answer takes
the rule off the pass;
- a value equal to the rule's own is recorded as agreed and changes nothing;
a different one waits, changes nothing, and a confirm sets it;
- a rejected value is never proposed again, and a newer suggestion for a
field replaces an older one;
- `enforce` needs an act to refuse, and a preference never holds;
- a direct edit answers a waiting suggestion;
- only the owner can propose or judge.
"""
from datetime import datetime, timezone
import pytest
import pytest_asyncio
from sqlalchemy import select
from grimoire.models import async_session
from grimoire.models.rule_delivery import RuleDelivery
from grimoire.models.rule_field_judgment import RuleFieldJudgment
from grimoire.models.rule_usage import RuleUsageEvent
from grimoire.models.rulebook import Rule, Rulebook
from grimoire.models.user import User
from grimoire.services import rule_field_judgments as weights_svc
from grimoire.services import rule_triggers
from grimoire.services import rulebooks as rulebooks_svc
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
OWNER_USERNAME = "rule_weights_owner"
STRANGER_USERNAME = "rule_weights_stranger"
async def _purge_books(username: str) -> None:
async with async_session() as s:
for user in (await s.execute(
select(User).where(User.username == username)
)).scalars().all():
for book in (await s.execute(
select(Rulebook).where(Rulebook.owner_user_id == user.id)
)).scalars().all():
await s.delete(book)
await s.commit()
@pytest_asyncio.fixture
async def world():
for name in (OWNER_USERNAME, STRANGER_USERNAME):
await _purge_books(name)
async with async_session() as s:
owner = await ensure_user(s, OWNER_USERNAME)
stranger = await ensure_user(s, STRANGER_USERNAME)
await s.commit()
uid, sid = owner.id, stranger.id
book = await rulebooks_svc.create_rulebook(uid, "Weight fixtures")
topic = await rulebooks_svc.create_topic(book.id, uid, "delivery")
push = await rulebooks_svc.create_rule(
topic.id, uid, "Push to main only when asked",
"Never push to main unless the operator asked for it in this conversation.",
when_to_apply="about to push a branch",
)
dates = await rulebooks_svc.create_rule(
topic.id, uid, "Dates are written day first",
"Every date shown to a person is written day, month, year.",
when_to_apply="formatting a date for display",
)
terse = await rulebooks_svc.create_rule(
topic.id, uid, "Replies stay short",
"Lead with the answer and stop.", when_to_apply="writing a reply",
kind="preference",
)
return {"uid": uid, "sid": sid, "push": push, "dates": dates, "terse": terse}
def _item(rule, enforcement="inform", salience="normal", why="read from the rule", **extra):
return {"rule_id": rule.id, "enforcement": enforcement, "salience": salience,
"why": why, **extra}
async def _rule(rule_id: int) -> Rule:
async with async_session() as s:
return await s.get(Rule, rule_id)
async def _unweighed_ids(uid: int) -> set[int]:
return {r["id"] for r in (await weights_svc.unweighed_rules(uid, limit=100))["rules"]}
async def _pending(uid: int) -> dict[int, list[tuple[str, str]]]:
out = (await weights_svc.pending(uid))["rules"]
return {r["id"]: [(p["field"], p["value"]) for p in r["proposals"]] for r in out}
async def test_agreeing_marks_a_rule_weighed_and_changes_nothing(world):
uid, dates = world["uid"], world["dates"]
assert dates.id in await _unweighed_ids(uid)
out = await weights_svc.propose(uid, [_item(dates)])
assert out == {"suggested": 0, "agreed": 2, "skipped": [], "refused": []}
assert dates.id not in await _unweighed_ids(uid)
assert dates.id not in await _pending(uid)
rule = await _rule(dates.id)
assert (rule.enforcement, rule.salience) == ("inform", "normal")
async def test_a_suggestion_changes_nothing_until_a_confirm_sets_it(world):
uid, push = world["uid"], world["push"]
out = await weights_svc.propose(uid, [_item(
push, "hold", "high", why="sessions pushed past it twice",
)])
assert out["suggested"] == 2 and not out["refused"]
assert (await _rule(push.id)).enforcement == "inform"
assert sorted((await _pending(uid))[push.id]) == [("enforcement", "hold"), ("salience", "high")]
judged = await weights_svc.judge(uid, [
{"rule_id": push.id, "field": "enforcement", "value": "hold", "verdict": "confirm"},
{"rule_id": push.id, "field": "salience", "value": "high", "verdict": "confirm"},
])
assert not judged["refused"] and len(judged["judged"]) == 2
rule = await _rule(push.id)
assert (rule.enforcement, rule.salience) == ("hold", "high")
assert push.id not in await _pending(uid)
async def test_a_rejected_value_is_never_proposed_again(world):
uid, push = world["uid"], world["push"]
await weights_svc.propose(uid, [_item(push, "hold")])
await weights_svc.judge(uid, [{"rule_id": push.id, "field": "enforcement",
"value": "hold", "verdict": "reject", "note": "too loud"}])
again = await weights_svc.propose(uid, [_item(push, "hold")])
assert again["suggested"] == 0
assert again["skipped"][0]["field"] == "enforcement"
assert "too loud" in again["skipped"][0]["why"]
assert (await _rule(push.id)).enforcement == "inform"
async def test_a_newer_suggestion_for_a_field_replaces_the_older(world):
uid, dates = world["uid"], world["dates"]
await weights_svc.propose(uid, [_item(dates, salience="high")])
await weights_svc.propose(uid, [_item(dates, salience="low")])
assert (await _pending(uid))[dates.id] == [("salience", "low")]
async def test_enforce_needs_an_act_to_refuse(world):
uid, push = world["uid"], world["push"]
alone = await weights_svc.propose(uid, [_item(push, "enforce")])
assert alone["refused"] and "nothing routes an act" in alone["refused"][0]["error"]
assert push.id in await _unweighed_ids(uid)
trigger = {"kind": "command", "pattern": "git push"}
routed = await weights_svc.propose(uid, [_item(push, "enforce", triggers=[trigger])])
assert not routed["refused"] and routed["suggested"] == 2
pending = (await weights_svc.pending(uid))["rules"][0]["proposals"]
proposed = next(p for p in pending if p["field"] == "trigger")
assert proposed["trigger"] == {"kind": "command", "pattern": "git push"}
await weights_svc.judge(uid, [{"rule_id": push.id, "field": "trigger",
"value": trigger, "verdict": "confirm"}])
have = (await rule_triggers.list_rule_triggers([push.id]))[push.id]
assert have == [{"kind": "command", "pattern": "git push"}]
async def test_a_preference_never_holds(world):
uid, terse = world["uid"], world["terse"]
out = await weights_svc.propose(uid, [_item(terse, "hold")])
assert out["refused"] and "preference" in out["refused"][0]["error"]
ok = await weights_svc.propose(uid, [_item(terse, "inform", "low")])
assert not ok["refused"] and ok["agreed"] == 1 and ok["suggested"] == 1
async def test_a_direct_edit_answers_a_waiting_suggestion(world):
uid, push = world["uid"], world["push"]
await weights_svc.propose(uid, [_item(push, "hold")])
await rulebooks_svc.update_rule(push.id, uid, enforcement="inform", salience="high")
# Enforcement did not change, so the suggestion still waits; salience did,
# and is recorded as the edit's judgment.
assert (await _pending(uid))[push.id] == [("enforcement", "hold")]
await rulebooks_svc.update_rule(push.id, uid, enforcement="hold")
assert push.id not in await _pending(uid)
async with async_session() as s:
states = {(r.field, r.value): (r.state, r.source) for r in (await s.execute(
select(RuleFieldJudgment).where(RuleFieldJudgment.rule_id == push.id)
)).scalars().all()}
assert states[("salience", "high")] == ("confirmed", "edit")
assert states[("enforcement", "hold")][0] == "confirmed"
async def test_the_pass_reads_each_rule_with_its_history(world):
uid, push = world["uid"], world["push"]
now = datetime.now(timezone.utc)
async with async_session() as s:
for i, (at, opened) in enumerate([("work.deliver", True), ("work.deliver", False),
("pre_tool_rule", False)]):
s.add(RuleDelivery(user_id=uid, session_id=f"s{i}", rule_id=push.id,
source="hook", at=at, form="full",
opened_at=now if opened else None))
s.add(RuleUsageEvent(user_id=uid, rule_id=push.id, event="departed",
source="mcp_rule_outcome", detail="the operator asked"))
await s.commit()
page = await weights_svc.unweighed_rules(uid, limit=100)
h = next(r for r in page["rules"] if r["id"] == push.id)["history"]
assert (h["delivered"], h["opened"], h["departed"]) == (3, 1, 1)
assert h["places"][0] == {"at": "work.deliver", "delivered": 2, "opened": 1}
await weights_svc.propose(uid, [_item(push, "hold")])
evidence = (await weights_svc.pending(uid))["rules"][0]["proposals"][0]["evidence"]
assert evidence["delivered"] == 3
async def test_only_the_owner_can_propose_or_judge(world):
uid, sid, push = world["uid"], world["sid"], world["push"]
out = await weights_svc.propose(sid, [_item(push, "hold")])
assert out["refused"][0]["error"] == "not a rule you own"
await weights_svc.propose(uid, [_item(push, "hold")])
judged = await weights_svc.judge(sid, [{"rule_id": push.id, "field": "enforcement",
"value": "hold", "verdict": "confirm"}])
assert judged["refused"] and not judged["judged"]
assert (await _rule(push.id)).enforcement == "inform"
assert (await weights_svc.pending(sid))["rules"] == []
+136 -5
View File
@@ -7,6 +7,8 @@ tests/test_integration_rule_moments.py. These pin what is decided above it:
- a rule the session was already shown is cited, not repeated, and only the
fresh ones are recorded, each with its moment;
- every door fails open;
- a rule set to enforce refuses the act every time, one set to hold holds it
once for a read (never a write), and an `inform` rule only sits beside it;
- the plugin is told which tools can reach anything, and nothing more;
- every Grimoire tool the shipped mappings name carries the attach, and the
hook and the route agree on every name between them.
@@ -238,7 +240,7 @@ async def test_the_route_reads_the_event_and_the_ledger():
resp = await routes.moment.__wrapped__()
body = await resp.get_json()
assert body == {"context": "a line", "rule_ids": [5], "moments": ["work.deliver"],
"shape_keys": []}
"shape_keys": [], "decision": {}}
args, kw = deliver.await_args
assert args == (7, "Bash", {"command": "git push"})
assert kw == {"project_id": 3, "exclude": frozenset({9}), "held": frozenset({4})}
@@ -252,7 +254,7 @@ async def test_the_route_answers_an_empty_event_with_nothing():
g.user = SimpleNamespace(id=7)
resp = await routes.moment.__wrapped__()
assert await resp.get_json() == {"context": "", "rule_ids": [], "moments": [],
"shape_keys": []}
"shape_keys": [], "decision": {}}
def test_both_routes_are_on_the_app():
@@ -296,10 +298,18 @@ def test_the_hook_leaves_grimoires_own_tools_to_their_responses():
assert "mcp__*grimoire*__*) exit 0" in HOOK.read_text()
def test_the_hook_never_returns_a_permission_decision():
"""A mount is a recall aid: it informs the act and never holds it."""
def test_the_hook_holds_only_behind_the_session_guard_and_refuses_only_on_enforce():
"""Structural, and able to fail: every deny the hook emits is either the
`enforce` branch or sits behind `grimoire_checkpoint_allowed`. A hold
emitted outside the guard is a session the same rule can stop on every
call."""
code = [ln for ln in HOOK.read_text().splitlines() if not ln.lstrip().startswith("#")]
assert not any("permissionDecision" in ln or "grimoire_json_deny" in ln for ln in code)
denies = [i for i, ln in enumerate(code) if "grimoire_json_deny" in ln]
assert len(denies) == 2, "one deny for enforce, one for hold"
enforce, hold = denies
assert "enforce)" in "\n".join(code[max(0, enforce - 3):enforce])
assert "grimoire_checkpoint_allowed" in "\n".join(code[max(0, hold - 4):hold])
assert "permissionDecision" not in "\n".join(code), "decisions go through grimoire_json_deny"
def _hook(tmp_path, port, tool="Bash", command="git push origin dev", session="s-moment"):
@@ -496,3 +506,124 @@ def test_the_hook_carries_the_shape_ledger_between_calls(tmp_path):
assert "shapes_seen" not in moment_calls[0]
assert moment_calls[1]["shapes_seen"] == ["asks"]
# ── what the act itself is told ─────────────────────────────────────────
def _forced(rid, enforcement, kind="rule"):
return fake_rule(id=rid, title=f"rule {rid}", kind=kind, enforcement=enforcement,
statement=f"The words of rule {rid}.", when_to_apply="when it applies")
async def _arm(pairs, **moment):
io = rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock())
return await rp.run_moment_arm(PUSH, _moment(**moment), io=io)
async def test_a_rule_set_to_enforce_refuses_the_act_in_its_own_words():
result = await _arm([(_forced(5, "inform"), "work.deliver"),
(_forced(6, "enforce"), "work.deliver")])
d = result.decision
assert d["kind"] == "enforce" and d["rule_ids"] == [6]
assert "The words of rule 6." in d["reason"]
assert "at work.deliver, reached by `git push`" in d["reason"]
assert 'rule_misfired(6, "work.deliver", why)' in d["reason"]
# The lines still go out beside it, for a door that shows them.
assert result.lines
async def test_opening_an_enforced_rule_does_not_lift_it():
result = await _arm([(_forced(6, "enforce"), "work.deliver")], held=frozenset({6}),
exclude=frozenset({6}))
assert result.decision["kind"] == "enforce"
async def test_a_rule_set_to_hold_holds_until_the_session_opens_it():
pairs = [(_forced(7, "hold"), "work.deliver")]
held = (await _arm(pairs)).decision
assert held["kind"] == "hold" and held["rule_ids"] == [7]
assert "get_rule(7)" in held["reason"] and "re-submit" in held["reason"]
assert (await _arm(pairs, held=frozenset({7}))).decision == {}
async def test_an_inform_rule_and_a_preference_never_stop_the_act():
pairs = [(_forced(8, "inform"), "work.deliver"),
(_forced(9, "enforce", kind="preference"), "work.deliver")]
assert (await _arm(pairs)).decision == {}
async def _deliver_for(tool, decision):
from grimoire.services import moment_actions as ma
with patch.object(ma, "moments_for", AsyncMock(return_value=PUSH)), \
patch.object(md, "_board", AsyncMock(return_value=None)), \
patch.object(md, "deliver_moments",
AsyncMock(return_value=rp.RuleResult(decision=dict(decision)))):
_reached, result = await _REAL_DELIVER(1, tool, {})
return result.decision
async def test_a_write_is_refused_by_an_enforced_rule_but_never_held():
hold = {"kind": "hold", "rule_ids": [7], "reason": "read it"}
enforce = {"kind": "enforce", "rule_ids": [6], "reason": "not run"}
assert await _deliver_for("Edit", hold) == {}
assert await _deliver_for("Bash", hold) == hold
assert await _deliver_for("Write", enforce) == enforce
def _decided(tmp_path, decision, session="s-decide"):
replies = dict(TOOLS)
replies["/api/plugin/moment"] = json.dumps(
{"context": "a line beside it", "rule_ids": [], "moments": ["work.deliver"],
"decision": decision}).encode()
with http_sink(by_path=replies) as (port, _seen):
return [_hook(tmp_path, port, session=session) for _ in range(2)]
def test_the_hook_refuses_an_enforced_act_every_time(tmp_path):
outs = _decided(tmp_path, {"kind": "enforce", "rule_ids": [6], "reason": "Not run: rule 6"})
for out in outs:
body = json.loads(out)["hookSpecificOutput"]
assert body["permissionDecision"] == "deny"
assert body["permissionDecisionReason"] == "Not run: rule 6"
def test_the_hook_holds_an_act_once_then_lets_it_through_with_its_lines(tmp_path):
first, second = _decided(tmp_path, {"kind": "hold", "rule_ids": [7], "reason": "Read rule 7"})
assert json.loads(first)["hookSpecificOutput"]["permissionDecision"] == "deny"
after = json.loads(second)["hookSpecificOutput"]
assert "permissionDecision" not in after
assert after["additionalContext"] == "a line beside it"
# ── reminders wait for the act ──────────────────────────────────────────
async def test_the_prompt_arm_leaves_a_rule_that_arrives_at_an_act_to_the_act():
hits = [(0.9, _forced(21, "inform")), (0.89, _forced(22, "inform"))]
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
record_rule_surfaced=MagicMock())
moment = rp.RuleMoment(user_id=1, query="merge it", project_id=2, where="to this request",
elsewhere=frozenset({21}))
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
assert result.shown_rule_ids == [22]
async def test_a_rule_arrives_at_an_act_by_a_mount_off_the_reply_or_an_act_trigger():
from grimoire.services import rule_triggers
lookup = AsyncMock(return_value=[(_forced(31, "inform"), "work.deliver")])
scoped = [
(_forced(32, "inform"), [rule_triggers.Trigger("path", "alembic/**")]),
(_forced(33, "inform"), [rule_triggers.Trigger("keyword", "let me know")]),
(_forced(34, "inform"), [rule_triggers.Trigger("command", "git push", "work.deliver")]),
]
with patch.object(moment_actions, "list_mappings", AsyncMock(return_value=[])), \
patch.object(rulebooks, "rules_on_moments", lookup), \
patch.object(rule_triggers, "_in_scope", AsyncMock(return_value=scoped)):
routed = await md.routed_to_acts(1, 2)
# A keyword can match a reply; a trigger scoped to a moment is that moment's mount.
assert routed == frozenset({31, 32})
moments = lookup.await_args.args[1]
assert moments and not any(m.startswith("reply.") for m in moments)
+6 -2
View File
@@ -111,12 +111,16 @@ def test_the_tools_are_registered_and_classified():
"list_moments", "list_reply_shapes", "map_action", "unmap_action",
"rules_to_mount", "propose_rule_moments", "rule_moment_proposals",
"judge_rule_moments", "rule_misfired",
"rules_to_weigh", "propose_rule_weights", "rule_weight_proposals",
"judge_rule_weights",
]
assert {"list_moments", "list_reply_shapes",
"rules_to_mount", "rule_moment_proposals"} <= _READ_ONLY_TOOLS
"rules_to_mount", "rule_moment_proposals",
"rules_to_weigh", "rule_weight_proposals"} <= _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"} <= _WRITE_TOOLS
"propose_rule_moments", "judge_rule_moments", "rule_misfired",
"propose_rule_weights", "judge_rule_weights"} <= _WRITE_TOOLS
def test_both_doors_read_one_catalog():
+11 -2
View File
@@ -15,7 +15,8 @@ unchanged.
WHAT THIS PINS, AND WHAT IT DELIBERATELY DOES NOT
Pinned: the four conditions under which an act may be held, the two guards
Pinned: the conditions under which an act may be held — among them that the
rule is declared to hold — the two guards
that stop it recurring, and the shape of the envelope. Not pinned: the bar
itself (a tuning value, and a test asserting 0.80 would fail on every retune
while proving nothing) or the wording of the reason (prose, and it will be
@@ -58,7 +59,8 @@ def hit(score: float, rule_id: int, **attrs):
# `attrs` overrides rather than duplicates: passing `when_to_apply=""` for
# the no-trigger case alongside a hard-coded default is a duplicate keyword
# and a TypeError, not a test.
fields = {"id": rule_id, "title": f"rule {rule_id}", "when_to_apply": TRIGGER}
fields = {"id": rule_id, "title": f"rule {rule_id}", "when_to_apply": TRIGGER,
"enforcement": "hold"}
fields.update(attrs)
return (score, fake_rule(**fields))
@@ -97,6 +99,13 @@ def test_a_preference_never_holds_an_act():
assert hold([hit(0.99, 2, kind="preference")]) == {}
def test_a_rule_set_to_inform_never_holds_an_act():
"""Only a rule declared to hold may stop the work; an `inform` rule asked
to be put beside it, however confident the score."""
assert hold([hit(0.99, 2, enforcement="inform")]) == {}
assert hold([hit(0.99, 2, enforcement="enforce")])["rule_id"] == 2
def test_a_rule_the_session_already_opened_never_holds_an_act():
"""`held` is observable — a PostToolUse hook watches for the `get_rule`
call — so this is a recorded event, not a model's self-report
+19 -8
View File
@@ -4,9 +4,10 @@ An unopened rule above the stop bar HOLDS the reply
once, in the server's words — the backstop for whatever the earlier arms
missed — and the rewrite is never held. These pin, with the database stubbed:
- which moments a reply reaches;
- what holds: a mounted RULE the session has not opened, or the reply's top
semantic hit above the reply surface's bar — never a preference, never a
rule already opened or already held once, never past the session cap;
- what holds: a mounted rule declared to hold that the session has not
opened, or the reply's top semantic hit above the reply surface's bar when
it is declared to hold — never an `inform` rule, never a preference, never
a rule already opened or already held once, never past the session cap;
- that the stop-only arm records surfacing for the held rule alone;
- the hook's contract: blocks only on the server's reason, records the hold
before emitting it, and never holds the rewrite.
@@ -32,7 +33,7 @@ from tests.helpers import fake_rule, http_sink, need_tools
ROOT = Path(__file__).resolve().parents[1]
HOOK = ROOT / "plugin" / "hooks" / "grimoire_reply_check.sh"
DONE = fake_rule(id=11, title="Definition of done", kind="rule",
DONE = fake_rule(id=11, title="Definition of done", kind="rule", enforcement="hold",
when_to_apply="about to tell the operator work is finished")
@@ -100,13 +101,22 @@ async def test_a_mounted_rule_the_session_has_not_opened_holds_the_reply():
async def test_an_opened_rule_a_preference_and_an_earlier_hold_do_not_hold():
pref = fake_rule(id=12, title="Lead with the outcome", kind="preference")
other = fake_rule(id=13, title="Name the commit", kind="rule")
other = fake_rule(id=13, title="Name the commit", kind="rule", enforcement="hold")
mounted = [(DONE, "reply.report"), (pref, "reply.report"), (other, "reply.report")]
_arm, surfaced, _lookup, stack = _stubs(mounted=mounted)
assert await _hold(stack, held=frozenset({11}), stopped=frozenset({13})) == {}
surfaced.assert_not_called()
async def test_a_mounted_rule_set_to_inform_does_not_hold_the_reply():
"""It was put in front of the turn before the reply was written; holding
the reply on it again costs a rewrite for a rule that asked to be read."""
inform = fake_rule(id=14, title="Lead with the outcome", kind="rule", enforcement="inform")
_arm, surfaced, _lookup, stack = _stubs(mounted=[(inform, "reply.report")])
assert await _hold(stack) == {}
surfaced.assert_not_called()
async def test_the_semantic_backstop_holds_and_never_names_a_mounted_rule_twice():
cp = {"rule_id": 40, "title": "Read the job log first", "score": 0.84,
"trigger": "a CI run overran"}
@@ -130,7 +140,8 @@ async def test_past_the_session_cap_nothing_holds_and_nothing_is_asked():
async def test_the_cap_trims_before_anything_is_recorded():
rules = [(fake_rule(id=i, title=f"rule {i}", kind="rule"), "reply.report") for i in range(1, 9)]
rules = [(fake_rule(id=i, title=f"rule {i}", kind="rule", enforcement="hold"), "reply.report")
for i in range(1, 9)]
_arm, surfaced, _lookup, stack = _stubs(mounted=rules)
out = await _hold(stack, stopped=frozenset({50, 51}))
room = pc.CHECKPOINT_SESSION_CAP - 2
@@ -149,8 +160,8 @@ async def test_the_reply_check_fails_open():
async def test_the_stop_only_arm_records_only_the_rule_that_holds():
hits = [(0.86, fake_rule(id=40, title="a", kind="rule", when_to_apply="t")),
(0.82, fake_rule(id=41, title="b", kind="rule", when_to_apply="t"))]
hits = [(0.86, fake_rule(id=40, title="a", kind="rule", when_to_apply="t", enforcement="hold")),
(0.82, fake_rule(id=41, title="b", kind="rule", when_to_apply="t", enforcement="hold"))]
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
record_rule_surfaced=MagicMock())
moment = rp.RuleMoment(user_id=1, query="the reply", project_id=2,
+2
View File
@@ -46,6 +46,8 @@ def test_every_endpoint_is_reachable_on_the_app():
"/api/retrieval/moments/mappings",
"/api/retrieval/moments/proposals",
"/api/retrieval/moments/proposals/judge",
"/api/retrieval/weights/proposals",
"/api/retrieval/weights/proposals/judge",
"/api/retrieval/reply-shapes",
}
+6 -1
View File
@@ -22,7 +22,7 @@ def test_backup_version_is_current():
"""The bump is the point of the test — a payload section added without
moving the version produces backups that are structurally different and
indistinguishable by inspection."""
assert backup.BACKUP_VERSION == 29
assert backup.BACKUP_VERSION == 30
def _exportable_note(**over):
@@ -142,6 +142,7 @@ def _column_guard_targets():
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.rule_field_judgment import RuleFieldJudgment
from grimoire.models.design_system import DesignSystem, DesignToken
from grimoire.models.milestone import Milestone
from grimoire.models.note import Note
@@ -183,6 +184,7 @@ def _column_guard_targets():
"lesson_rule_links": (LessonRuleLink, backup._lesson_rule_link_rows),
"lesson_no_rule": (LessonNoRule, backup._lesson_no_rule_rows),
"rule_moment_judgments": (RuleMomentJudgment, backup._rule_moment_judgment_rows),
"rule_field_judgments": (RuleFieldJudgment, backup._rule_field_judgment_rows),
"note_usage_events": (NoteUsageEvent, backup._usage_event_rows),
"rule_usage_events": (RuleUsageEvent, backup._rule_usage_event_rows),
"system_usage_events": (SystemUsageEvent, backup._system_usage_event_rows),
@@ -314,6 +316,7 @@ def _import_guard_targets():
"lesson_rule_links": backup._build_lesson_rule_link,
"lesson_no_rule": backup._build_lesson_no_rule,
"rule_moment_judgments": backup._build_rule_moment_judgment,
"rule_field_judgments": backup._build_rule_field_judgment,
"note_usage_events": backup._build_usage_event,
"rule_usage_events": backup._build_rule_usage_event,
"system_usage_events": backup._build_system_usage_event,
@@ -590,6 +593,8 @@ async def test_export_full_backup_contains_every_declared_section():
"rule_moment_judgments",
# v29: the acts that trigger a rule.
"rule_triggers",
# v30: the weighed enforcement, salience and triggers.
"rule_field_judgments",
# v25: family canon.
"platforms", "project_platforms", "family_ideas",
"family_idea_platforms", "family_idea_references",
+18 -14
View File
@@ -1,5 +1,6 @@
"""The server half of the end-of-turn shape check: what the
agent is asked, what the hook's ledger may say, and the outcome record."""
agent is asked at its next prompt, what the hook's ledger may say, and the
outcome record."""
import json
from unittest.mock import patch
@@ -21,18 +22,18 @@ def test_the_ledger_lines_parse_and_garbage_is_dropped():
assert len(parse_written("".join(f"p\tsym\tn{i}\n" for i in range(500)), cap=7)) == 7
def test_a_first_stop_blocks_or_passes_and_the_next_never_blocks():
def test_a_stop_notes_or_passes_and_the_stop_after_the_note_records_the_answer():
from grimoire.services.shape_check import outcome_for
one = [{"path": "a", "kind": "sym", "symbol": "b"}]
assert outcome_for("check", one) == "blocked"
assert outcome_for("check", one) == "noted"
assert outcome_for("check", []) == "passed"
assert outcome_for("after", one) == "left_after_block"
assert outcome_for("after", []) == "judged_after_block"
assert outcome_for("after", one) == "left_after_note"
assert outcome_for("after", []) == "judged_after_note"
def test_the_reason_names_each_shape_its_evidence_and_the_one_call():
from grimoire.services.shape_check import block_reason
def test_the_note_names_each_shape_its_evidence_and_the_one_call():
from grimoire.services.shape_check import note_text
unjudged = [
{"path": "web/A.svelte", "kind": "file", "symbol": "A", "status": "new", "evidence": {}},
@@ -40,8 +41,8 @@ def test_the_reason_names_each_shape_its_evidence_and_the_one_call():
"evidence": {"looks_like": {"snippet_id": 12, "basis": "semantic", "score": 0.84},
"diverges_from": 9}},
]
reason = block_reason(unjudged, project_id=3, repo="git.example.com/a/w")
assert "2 definitions" in reason
reason = note_text(unjudged, project_id=3, repo="git.example.com/a/w")
assert "last turn wrote 2 definitions" in reason
assert "web/A.svelte · A (file) — new" in reason
assert "looks like #12 0.84" in reason and "#9 is canon in this directory" in reason
assert 'classify_shapes(project_id=3, repo="git.example.com/a/w"' in reason
@@ -50,11 +51,11 @@ def test_the_reason_names_each_shape_its_evidence_and_the_one_call():
def test_a_long_turn_is_listed_with_a_tail_not_dropped():
from grimoire.services.shape_check import _LISTED, block_reason
from grimoire.services.shape_check import _LISTED, note_text
many = [{"path": "p.py", "kind": "sym", "symbol": f"f{i}", "status": "new", "evidence": {}}
for i in range(_LISTED + 3)]
reason = block_reason(many, project_id=1, repo="")
reason = note_text(many, project_id=1, repo="")
assert "… and 3 more" in reason
assert "repo=" not in reason
@@ -64,10 +65,10 @@ async def test_the_outcome_is_recorded_as_a_plugin_event():
session = make_mock_session()
with patch("grimoire.services.shape_check.async_session", return_value=session):
await record_shape_check(7, "blocked", written=5, unjudged=2, project_id=2)
await record_shape_check(7, "noted", written=5, unjudged=2, project_id=2)
row = session.add.call_args.args[0]
assert (row.category, row.action, row.user_id) == ("plugin", "shape_check", 7)
assert json.loads(row.details) == {"outcome": "blocked", "written": 5,
assert json.loads(row.details) == {"outcome": "noted", "written": 5,
"unjudged": 2, "project_id": 2}
@@ -85,5 +86,8 @@ def test_the_window_counts_turns_asks_and_asks_walked_past():
from grimoire.services.shape_check import summarise
assert summarise([]) == {"checked": 0, "asked": 0, "left": 0}
got = summarise(["passed", "blocked", "judged_after_block", "blocked", "left_after_block"])
got = summarise(["passed", "noted", "judged_after_note", "noted", "left_after_note"])
assert got == {"checked": 3, "asked": 2, "left": 1}
# A window that spans the end-of-turn hold this check once was still sums.
mixed = summarise(["blocked", "left_after_block", "noted", "judged_after_note"])
assert mixed == {"checked": 2, "asked": 2, "left": 1}
+75 -20
View File
@@ -1,12 +1,14 @@
"""The end-of-turn shape check: the write hooks note what each
write defined, and the Stop hook asks the instance which of those nobody has
judged, blocking once in the server's words.
write defined, the Stop hook asks the instance which of those nobody has
judged, and the answer rides the next prompt rather than holding the reply.
Runs the real shell against the shared HTTP sink. What it pins: the write
hooks' ledger (a Write of a new file adds a `file` line; a skipped path adds
nothing); silence with nothing written; a block only on a reason the instance
returned; the post-block stop recorded and let through; another hook's block
loop left alone; the ledger kept when the instance could not be reached.
nothing); silence with nothing written; the Stop hook never blocks; a note
only when the instance returned one, carried by the next prompt and then
gone; the stop after that prompt records the answer; a note no prompt carried
is asked again with the next turn's writes; another hook's block loop left
alone; the ledger kept when the instance could not be reached.
"""
from __future__ import annotations
@@ -23,7 +25,8 @@ from tests.helpers import http_sink
HOOKS = Path(__file__).resolve().parents[1] / "plugin" / "hooks"
CHECK = HOOKS / "grimoire_shape_check.sh"
PRIOR_ART = HOOKS / "grimoire_prior_art.sh"
REASON = "SERVER REASON: judge what you wrote"
PROMPT = HOOKS / "grimoire_autoinject.sh"
NOTE = "SERVER NOTE: judge what you wrote"
def _env(tmp_path, url="http://127.0.0.1:9"):
@@ -127,7 +130,7 @@ def test_a_skipped_path_notes_nothing(tmp_path):
# ── the Stop hook asks ────────────────────────────────────────────────────
def test_nothing_written_is_silent_and_asks_nothing(tmp_path):
with http_sink(b'{"status":"ok","reason":"x"}') as (port, seen):
with http_sink(b'{"status":"ok","note":"x"}') as (port, seen):
env = _env(tmp_path, f"http://127.0.0.1:{port}")
assert _stop(env, _repo(tmp_path)) == ""
assert seen == []
@@ -144,32 +147,84 @@ def test_all_judged_passes_silently_and_empties_the_ledger(tmp_path):
assert not ledger.exists()
def test_unjudged_blocks_once_in_the_servers_words_then_records_the_answer(tmp_path):
reply = json.dumps({"status": "ok", "outcome": "blocked", "reason": REASON}).encode()
def _note_file(tmp_path, session="s1"):
return tmp_path / "grimoire-shapecheck" / f"{session}.note"
def _asked_file(tmp_path, session="s1"):
return tmp_path / "grimoire-shapecheck" / f"{session}.asked"
def _prompt(env, cwd, text="carry on", session="s1"):
out = subprocess.run(
["bash", str(PROMPT)],
input=json.dumps({"session_id": session, "prompt": text, "cwd": str(cwd),
"transcript_path": "/nonexistent",
"hook_event_name": "UserPromptSubmit"}),
capture_output=True, text=True, env=env, timeout=30,
)
assert out.returncode == 0, out.stderr
return out.stdout.strip()
def test_unjudged_is_noted_for_the_next_prompt_and_never_holds_the_reply(tmp_path):
reply = json.dumps({"status": "ok", "outcome": "noted", "note": NOTE,
"context": "", "note_ids": []}).encode()
with http_sink(reply) as (port, seen):
env = _env(tmp_path, f"http://127.0.0.1:{port}")
repo = _repo(tmp_path)
ledger = _write_ledger(tmp_path, ["web/A.svelte\tfile\tA"])
assert json.loads(_stop(env, repo)) == {"decision": "block", "reason": REASON}
assert ledger.exists(), "kept, so the stop after the block asks about the same set"
# The stop after the block: recorded, never blocked, ledger consumed.
assert _stop(env, repo, active=True) == ""
assert [q["phase"] for q in seen] == [["check"], ["after"]]
assert _stop(env, repo) == "", "the reply goes out as written"
assert _note_file(tmp_path).read_text() == NOTE
assert _asked_file(tmp_path).read_text().splitlines() == ["web/A.svelte\tfile\tA"]
assert not ledger.exists()
assert _stop(env, repo, active=True) == ""
assert len(seen) == 2
# The next prompt carries the note, and it is gone once answered.
_prompt(env, repo)
assert seen[-1]["carry"] == [NOTE]
assert not _note_file(tmp_path).exists()
# The stop after it records whether the noted lines were judged.
assert _stop(env, repo) == ""
assert seen[-1]["phase"] == ["after"]
assert seen[-1]["written"] == ["web/A.svelte\tfile\tA"]
assert not _asked_file(tmp_path).exists()
before = len(seen)
assert _stop(env, repo) == ""
assert len(seen) == before, "asked once, recorded once"
def test_no_block_without_a_reason_from_the_instance(tmp_path):
def test_a_note_no_prompt_carried_is_asked_again_with_the_next_turns_writes(tmp_path):
reply = json.dumps({"status": "ok", "outcome": "noted", "note": NOTE}).encode()
with http_sink(reply) as (port, seen):
env = _env(tmp_path, f"http://127.0.0.1:{port}")
repo = _repo(tmp_path)
_write_ledger(tmp_path, ["a.py\tsym\tfirst"])
_stop(env, repo)
_write_ledger(tmp_path, ["b.py\tsym\tsecond"])
_stop(env, repo)
assert seen[-1]["phase"] == ["check"]
assert seen[-1]["written"] == ["b.py\tsym\tsecond\na.py\tsym\tfirst"]
assert [q["phase"] for q in seen] == [["check"], ["check"]], "no prompt read it: no answer to record"
def test_the_stop_hook_never_blocks(tmp_path):
"""Structural, and able to fail: no decision is ever printed."""
code = [ln for ln in CHECK.read_text().splitlines() if not ln.lstrip().startswith("#")]
assert not any('"decision"' in ln or "block" in ln for ln in code)
def test_no_note_without_one_from_the_instance(tmp_path):
with http_sink(b'{"status":"ok"}') as (port, _seen):
env = _env(tmp_path, f"http://127.0.0.1:{port}")
_write_ledger(tmp_path, ["a.py\tsym\thelper"])
ledger = _write_ledger(tmp_path, ["a.py\tsym\thelper"])
assert _stop(env, _repo(tmp_path)) == ""
assert not _note_file(tmp_path).exists()
assert not ledger.exists()
def test_another_hooks_block_loop_is_left_alone(tmp_path):
with http_sink(b'{"status":"ok","reason":"x"}') as (port, seen):
with http_sink(b'{"status":"ok","note":"x"}') as (port, seen):
env = _env(tmp_path, f"http://127.0.0.1:{port}")
ledger = _write_ledger(tmp_path, ["a.py\tsym\thelper"])
assert _stop(env, _repo(tmp_path), active=True) == ""