Merge pull request 'Gate stops are recorded: every time a rule, the checkpoint, the fence or the reply hold stops work' (#235) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 2m5s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Successful in 16s

This commit was merged in pull request #235.
This commit is contained in:
2026-11-27 23:46:04 -05:00
43 changed files with 1724 additions and 88 deletions
+49
View File
@@ -0,0 +1,49 @@
"""gate stops: each time a Grimoire gate stood in front of a tool call
Revision ID: 0138
Revises: 0137
Create Date: 2026-11-27
A row per stop the plugin made: a moment rule set to enforce or hold, the
act checkpoint, or the project fence asking the operator. With whether the
session then opened the rule (`cleared_at`) and whether the stopped call ran
after all (`ran_at`), so how often each gate stops work, for which rule, and
whether it cleared the way it is meant to can be read.
"""
import sqlalchemy as sa
from alembic import op
revision = "0138"
down_revision = "0137"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"gate_stops",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("user_id", sa.BigInteger(), nullable=False),
sa.Column("session_id", sa.Text(), nullable=False),
sa.Column("gate", sa.Text(), nullable=False),
sa.Column("outcome", sa.Text(), nullable=False),
sa.Column("rule_id", sa.BigInteger(), nullable=True),
sa.Column("tool", sa.Text(), nullable=False),
sa.Column("at", sa.Text(), nullable=True),
sa.Column("target", sa.Text(), nullable=True),
sa.Column("call_id", sa.Text(), nullable=True),
sa.Column("stopped_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.Column("cleared_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("ran_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("plugin", sa.Text(), nullable=True),
)
op.create_index("ix_gate_stops_session_rule", "gate_stops",
["user_id", "session_id", "rule_id", "stopped_at"])
op.create_index("ix_gate_stops_stopped_at", "gate_stops", ["stopped_at"])
def downgrade() -> None:
op.drop_index("ix_gate_stops_stopped_at", table_name="gate_stops")
op.drop_index("ix_gate_stops_session_rule", table_name="gate_stops")
op.drop_table("gate_stops")
+42
View File
@@ -340,6 +340,48 @@ export function getRecordReach(days = 30): Promise<RecordReachPayload> {
return apiGet(`/api/retrieval/record-reach?days=${days}`); return apiGet(`/api/retrieval/record-reach?days=${days}`);
} }
/** The gates that can stop a tool call. */
export type GateName = "enforce" | "hold" | "checkpoint" | "fence" | "reply";
export interface GateCounts {
/** Calls denied, or for the fence, put to the operator. */
stops: number;
/** Calls a hold would have stopped, let through because the session's
* stop budget was spent. */
let_through: number;
/** Stops the session cleared by opening the rule. */
cleared: number;
/** Stops whose rule the session then reported as a misfire. */
misfired: number;
/** Stopped calls that ran after all; for the fence, the operator's yes. */
ran: number;
}
export interface GateRuleRow extends GateCounts {
rule_id: number;
gate: GateName;
/** The moment or arm the rule was reached at. */
at: string | null;
title: string | null;
sessions: number;
last_stopped_at: string | null;
}
export interface GateStopsPayload {
days: number;
by_gate: Record<GateName, GateCounts & { sessions: number }>;
by_rule: GateRuleRow[];
fence: { tool: string; target: string | null; asks: number; ran: number }[];
/** The first stop ever recorded; null when none has been. */
complete_from: string | null;
covers_window: boolean | null;
}
/** How often each gate stood in front of a tool call, and what followed. */
export function getGateStops(days = 30): Promise<GateStopsPayload> {
return apiGet(`/api/retrieval/gate-stops?days=${days}`);
}
/** Whether the rules in force at each moment were followed there. */ /** Whether the rules in force at each moment were followed there. */
export function getAdherence(days = 30): Promise<AdherencePayload> { export function getAdherence(days = 30): Promise<AdherencePayload> {
return apiGet(`/api/retrieval/adherence?days=${days}`); return apiGet(`/api/retrieval/adherence?days=${days}`);
+124
View File
@@ -0,0 +1,124 @@
<script setup lang="ts">
import { computed } from "vue";
import type { GateCounts, GateName, GateStopsPayload } from "@/api/moments";
import { fmtDate } from "@/utils/dateFormat";
/**
* Every time Grimoire stood in front of the work instead of commenting
* beside it: a rule set to enforce or hold, the checkpoint on a command, the
* project fence asking the operator, or a rule holding the finished reply. Per gate and per rule, how often it
* stopped work and what followed — the rule opened (the stop cleared the way
* it is meant to), the rule reported as a misfire (a stop at the wrong
* moment), or a hold let through because the session's stop budget was
* spent.
*/
const props = defineProps<{
data: GateStopsPayload | null;
failed: boolean;
}>();
const emit = defineEmits<{ retry: [] }>();
const GATES: [GateName, string][] = [
["enforce", "Refused (enforce)"],
["hold", "Held for a read (hold)"],
["checkpoint", "Command checkpoint"],
["fence", "Project fence"],
["reply", "Reply held for a read"],
];
const any = computed(() =>
!!props.data && GATES.some(([g]) => (props.data!.by_gate[g]?.stops ?? 0) + (props.data!.by_gate[g]?.let_through ?? 0) > 0),
);
function gateText(gate: GateName, c: GateCounts): string[] {
if (gate === "fence") return [`asked ${c.stops}`, `approved ${c.ran}`];
const parts = [`stopped ${c.stops}`, `cleared by a read ${c.cleared}`, `misfired ${c.misfired}`];
// An enforced refusal has no cap, and the reply's cap is applied by the
// server before anything holds, so neither can let a call through.
if (gate === "hold" || gate === "checkpoint") parts.push(`let through by the cap ${c.let_through}`);
return parts;
}
</script>
<template>
<section class="gates" aria-labelledby="gates-title">
<h3 id="gates-title" class="sub-title">When a rule stopped the work</h3>
<p v-if="failed" class="error-msg">
Gate stops could not be loaded.
<button type="button" class="btn-text" @click="emit('retry')">Try again</button>
</p>
<p v-else-if="!data" class="empty-msg">Loading gate stops…</p>
<p v-else-if="!any" class="empty-msg">
No gate stopped a tool call in the last {{ data.days }} days.
<template v-if="data.complete_from === null">
None has ever been recorded: a session reports its stops once its plugin is updated.
</template>
</p>
<template v-else>
<p class="field-hint">
Over the last {{ data.days }} days. “Cleared by a read” means the session opened the rule
after the stop; “misfired” means it then reported the rule as not applying there; “let
through by the cap” counts calls a hold would have stopped once the session’s budget of
stops was spent.
<template v-if="data.covers_window === false">
Recording began {{ fmtDate(data.complete_from!) }}, so earlier days are missing, not quiet.
</template>
</p>
<ul class="gate-list">
<li v-for="[gate, label] in GATES" :key="gate" class="gate-row">
<span class="gate-title">{{ label }}</span>
<span class="gate-counts" :class="{ 'way-none': !data.by_gate[gate]?.stops && !data.by_gate[gate]?.let_through }">
<span v-for="t in gateText(gate, data.by_gate[gate])" :key="t">{{ t }}</span>
</span>
</li>
</ul>
<details v-if="data.by_rule.length" class="gate-detail">
<summary>By rule</summary>
<ul class="gate-list">
<li v-for="r in data.by_rule" :key="`${r.rule_id}:${r.gate}:${r.at}`" class="gate-row">
<span class="gate-title">
Rule {{ r.rule_id }}<template v-if="r.title"> “{{ r.title }}”</template>
</span>
<code class="moment-name">{{ r.gate }}<template v-if="r.at"> · {{ r.at }}</template></code>
<span class="gate-counts">
<span v-for="t in gateText(r.gate, r)" :key="t">{{ t }}</span>
<span>{{ r.sessions }} {{ r.sessions === 1 ? "session" : "sessions" }}</span>
<span v-if="r.last_stopped_at" class="stat-when">last {{ fmtDate(r.last_stopped_at) }}</span>
</span>
</li>
</ul>
</details>
<details v-if="data.fence.length" class="gate-detail">
<summary>Fence asks by tool</summary>
<ul class="gate-list">
<li v-for="f in data.fence" :key="`${f.tool}:${f.target}`" class="gate-row">
<code class="moment-name">{{ f.tool }}</code>
<span v-if="f.target" class="gate-title">into project {{ f.target }}</span>
<span class="gate-counts">
<span>asked {{ f.asks }}</span>
<span>approved {{ f.ran }}</span>
</span>
</li>
</ul>
</details>
</template>
</section>
</template>
<style scoped>
.gates { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.gate-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
.gate-detail .gate-list { margin: var(--fs-space-1) 0 var(--fs-space-2) var(--fs-space-4); }
.gate-detail summary { cursor: pointer; font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); }
.gate-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.gate-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
.gate-counts {
display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-2); margin-left: auto; justify-content: flex-end;
font-size: var(--fs-size-tiny); color: var(--fs-text-secondary); font-variant-numeric: tabular-nums;
}
/* A gate that stopped nothing is a gap, not a zero to read. */
.way-none { color: var(--fs-text-tertiary); }
</style>
<style src="@/assets/moments-shared.css" />
+20 -3
View File
@@ -7,9 +7,12 @@ import WeightProposals from "@/components/WeightProposals.vue";
import LessonSituationProposals from "@/components/LessonSituationProposals.vue"; import LessonSituationProposals from "@/components/LessonSituationProposals.vue";
import RecordKinds from "@/components/RecordKinds.vue"; import RecordKinds from "@/components/RecordKinds.vue";
import RecordReach from "@/components/RecordReach.vue"; import RecordReach from "@/components/RecordReach.vue";
import GateStops from "@/components/GateStops.vue";
import RuleAdherence from "@/components/RuleAdherence.vue"; import RuleAdherence from "@/components/RuleAdherence.vue";
import { getAdherence, getRecordReach } from "@/api/moments"; import { getAdherence, getGateStops, getRecordReach } from "@/api/moments";
import type { AdherencePayload, MomentAction, MomentAdherenceRow, MomentUsage, RecordReachPayload } from "@/api/moments"; import type {
AdherencePayload, GateStopsPayload, MomentAction, MomentAdherenceRow, MomentUsage, RecordReachPayload,
} from "@/api/moments";
import { fmtDate } from "@/utils/dateFormat"; import { fmtDate } from "@/utils/dateFormat";
/** /**
@@ -65,6 +68,19 @@ async function loadReach() {
} }
} }
// When a gate stopped a tool call, read on its own for the same reason.
const gates = ref<GateStopsPayload | null>(null);
const gatesFailed = ref(false);
async function loadGates() {
try {
gates.value = await getGateStops(days.value);
gatesFailed.value = false;
} catch {
gatesFailed.value = true;
}
}
function followed(moment: string): MomentAdherenceRow | null { function followed(moment: string): MomentAdherenceRow | null {
return adherence.value?.by_moment.find((m) => m.at === moment) ?? null; return adherence.value?.by_moment.find((m) => m.at === moment) ?? null;
} }
@@ -145,7 +161,7 @@ async function addMapping() {
onMounted(async () => { onMounted(async () => {
await store.load(true); await store.load(true);
await Promise.all([loadAdherence(), loadReach()]); await Promise.all([loadAdherence(), loadReach(), loadGates()]);
}); });
</script> </script>
@@ -174,6 +190,7 @@ onMounted(async () => {
<WeightProposals /> <WeightProposals />
<LessonSituationProposals /> <LessonSituationProposals />
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" /> <RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
<GateStops :data="gates" :failed="gatesFailed" @retry="loadGates" />
<RecordReach :data="reach" :failed="reachFailed" @retry="loadReach" /> <RecordReach :data="reach" :failed="reachFailed" @retry="loadReach" />
<RecordKinds :days="days" /> <RecordKinds :days="days" />
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "grimoire", "name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.11.25.1721", "version": "2026.11.27.1932",
"author": { "author": {
"name": "Bryan Van Deusen" "name": "Bryan Van Deusen"
}, },
+5 -4
View File
@@ -38,10 +38,11 @@ another one means adding files, not moving or rewriting any.
| `hooks/grimoire_autoinject.sh` | UserPromptSubmit: `GET /api/plugin/retrieve` for the message. | | `hooks/grimoire_autoinject.sh` | UserPromptSubmit: `GET /api/plugin/retrieve` for the message. |
| `hooks/grimoire_prior_art.sh` | PreToolUse on editor writes: `GET /api/plugin/prior-art`. | | `hooks/grimoire_prior_art.sh` | PreToolUse on editor writes: `GET /api/plugin/prior-art`. |
| `hooks/grimoire_after_write.sh` | PostToolUse on shell commands: the same check for code written through the shell. | | `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_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`; denies the call on its `checkpoint`, under the same caps, and reports it to `POST /api/plugin/gate-stop`. |
| `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_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, and each ask reported to `POST /api/plugin/gate-stop` with the tool call's id; 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`). Denies the call when the response's `decision` is `enforce` (every time) or `hold` (once per rule and session). | | `hooks/grimoire_fence_ran.sh` | PostToolUse on the tools the fence checks: when the call that ran is the one the fence asked about, `POST /api/plugin/gate-ran`, the operator's yes. Exits at once when no ask is pending. |
| `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_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), and reports each stop, and each hold the session's budget let through, to `POST /api/plugin/gate-stop`. |
| `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; reports each rule that held to `POST /api/plugin/gate-stop`. |
| `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_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_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_record_outcome.sh` | PostToolUse on `rule_outcome`: notes the rule as acted on, locally, for the session-scoped readout. |
+46
View File
@@ -1081,6 +1081,52 @@ grimoire_checkpoint_allowed() {
return 0 return 0
} }
grimoire_gate_report() {
# $1 session id, $2 gate (enforce|hold|checkpoint|fence), $3 outcome
# (stopped|let_through|asked), $4 tool name, $5 rule id or "", $6 where the
# rule was reached (a moment or an arm) or "", $7 the target project or "",
# $8 the tool call's id or "".
#
# Tells the server a gate stood in front of this call. The hook reports it,
# not the server, because whether a hold actually stops is decided here, by
# `grimoire_checkpoint_allowed`'s caps. Needs `url`, `token` and
# `plugin_version` from grimoire_config. Short deadline and silent: it runs
# only on a stop, and a stop the server never heard of costs one row, while
# a hook that hangs costs the call it was deciding.
local sid="${1:-}" gate="${2:-}" outcome="${3:-}" tool="${4:-}" rule rest="" v pair
[ -n "$sid" ] && [ -n "$gate" ] && [ -n "$outcome" ] && [ -n "$tool" ] || return 0
[ -n "${url:-}" ] && [ -n "${token:-}" ] || return 0
command -v curl >/dev/null 2>&1 || return 0
rule=$(printf '%s' "${5:-}" | tr -cd '0-9')
for pair in "at=${6:-}" "target=${7:-}" "call_id=${8:-}"; do
v=${pair#*=}
[ -n "$v" ] || continue
rest="${rest},\"${pair%%=*}\":\"$(printf '%s' "$v" | grimoire_json_escape)\""
done
printf '{"session_id":"%s","gate":"%s","outcome":"%s","tool":"%s","rule_id":%s%s}' \
"$(printf '%s' "$sid" | grimoire_json_escape)" "$gate" "$outcome" \
"$(printf '%s' "$tool" | grimoire_json_escape)" "${rule:-null}" "$rest" \
| curl -fsS --max-time 2 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/gate-stop" >/dev/null 2>&1 || true
return 0
}
grimoire_checkpoint_spent() {
# $1 ledger file, $2 rule id. True when `grimoire_checkpoint_allowed` just
# refused because the SESSION's budget is spent, as against this rule
# having held an act already. Only the first is a call the cap let through;
# the second is the per-rule once, working as meant.
local f="$1" id
id=$(printf '%s' "${2:-}" | tr -cd '0-9')
[ -n "$f" ] && [ -n "$id" ] && [ -f "$f" ] || return 1
grep -qx "$id" "$f" 2>/dev/null && return 1
return 0
}
grimoire_json_deny() { grimoire_json_deny() {
# $1 hook event name, $2 the reason the agent reads INSTEAD of the result. # $1 hook event name, $2 the reason the agent reads INSTEAD of the result.
# #
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Grimoire — the operator's answer to a project fence ask, read from what ran.
#
# grimoire_project_fence.sh asks the operator before an act lands in another
# project, reports the ask to the server, and leaves the tool call's id in
# `grimoire-fence/<sid>.fence.pending`. The answer itself never reaches a
# hook, but Claude Code sends PostToolUse only for a call that ran. So when
# this fires for the pending call, the operator said yes, and the server is
# told (POST /api/plugin/gate-ran). An ask that is never followed by this was
# declined, or the call failed.
#
# Registered PostToolUse on the tools the fence checks. Nearly every call has
# no ask pending, so the first thing it does is look for a pending file, and
# with none it exits before reading the event.
#
# EXIT 0, ALWAYS, and silent: it decorates a record.
set -uo pipefail
fence_dir="${TMPDIR:-/tmp}/grimoire-fence"
pending=""
for pending in "$fence_dir"/*.fence.pending; do
[ -e "$pending" ] && break
done
[ -e "$pending" ] || exit 0
# shellcheck source=plugin/hooks/grimoire_defs.sh
. "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh"
event=$(cat 2>/dev/null || true)
[ -n "$event" ] || exit 0
event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
[ -n "$session_id" ] && [ -n "$call_id" ] || exit 0
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
pending_file="$fence_dir/${safe_sid}.fence.pending"
[ -s "$pending_file" ] || exit 0
[ "$(cat "$pending_file" 2>/dev/null)" = "$call_id" ] || exit 0
rm -f "$pending_file" 2>/dev/null || true
grimoire_config || exit 0
command -v curl >/dev/null 2>&1 || exit 0
printf '{"session_id":"%s","call_id":"%s"}' \
"$(printf '%s' "$session_id" | grimoire_json_escape)" \
"$(printf '%s' "$call_id" | grimoire_json_escape)" \
| curl -fsS --max-time 2 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/gate-ran" >/dev/null 2>&1 || true
exit 0
+13 -2
View File
@@ -160,21 +160,32 @@ grimoire_json_list "$body_flat" '.shape_keys' | grimoire_shapes_append "$shapefi
# before the act, once per rule and under the session cap that the act # 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 # checkpoint and the reply hold share, so a mis-set rule costs one round trip
# rather than a session that cannot move. # rather than a session that cannot move.
#
# Every stop is reported (`grimoire_gate_report`), and so is a hold the
# session's budget let through, so how often each gate stops work, and
# whether the cap is what lets calls past, can be read on the server.
d_kind=$(grimoire_json_pick "$body_flat" '.decision.kind') d_kind=$(grimoire_json_pick "$body_flat" '.decision.kind')
d_reason=$(grimoire_json_pick "$body_flat" '.decision.reason') d_reason=$(grimoire_json_pick "$body_flat" '.decision.reason')
d_rule=$(grimoire_json_list "$body_flat" '.decision.rule_ids' | head -n 1) d_rule=$(grimoire_json_list "$body_flat" '.decision.rule_ids' | head -n 1)
d_at=$(grimoire_json_pick "$body_flat" '.decision.at')
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
if [ -n "$d_reason" ]; then if [ -n "$d_reason" ]; then
case "$d_kind" in case "$d_kind" in
enforce) enforce)
grimoire_json_deny PreToolUse "$d_reason" grimoire_json_deny PreToolUse "$d_reason"
grimoire_gate_report "$session_id" enforce stopped "$tool_key" "$d_rule" "$d_at" "" "$call_id"
exit 0 exit 0
;; ;;
hold) hold)
if [ -n "$d_rule" ] \ stops="$state_dir/${safe_sid}.checkpoint.ids"
&& grimoire_checkpoint_allowed "$state_dir/${safe_sid}.checkpoint.ids" "$d_rule"; then if [ -n "$d_rule" ] && grimoire_checkpoint_allowed "$stops" "$d_rule"; then
grimoire_json_deny PreToolUse "$d_reason" grimoire_json_deny PreToolUse "$d_reason"
grimoire_gate_report "$session_id" hold stopped "$tool_key" "$d_rule" "$d_at" "" "$call_id"
exit 0 exit 0
fi fi
if [ -n "$d_rule" ] && grimoire_checkpoint_spent "$stops" "$d_rule"; then
grimoire_gate_report "$session_id" hold let_through "$tool_key" "$d_rule" "$d_at" "" "$call_id"
fi
;; ;;
esac esac
fi fi
+18
View File
@@ -34,6 +34,12 @@
# #
# Run as PostToolUse on enter_project, it records the project a session # Run as PostToolUse on enter_project, it records the project a session
# without one has entered, and says nothing. # without one has entered, and says nothing.
#
# EVERY ASK IS REPORTED (POST /api/plugin/gate-stop), with the tool call's
# id, which is left in `<sid>.fence.pending`. The operator's answer never
# reaches a hook, but a PostToolUse arrives only for a call that ran, so
# grimoire_fence_ran.sh reports the matching call as run: the operator said
# yes. An ask with no run after it was declined, or the call failed.
set -uo pipefail set -uo pipefail
# shellcheck source=plugin/hooks/grimoire_defs.sh # shellcheck source=plugin/hooks/grimoire_defs.sh
@@ -56,6 +62,8 @@ cwd=$(grimoire_json_pick "$event_flat" '.cwd')
state_dir="${TMPDIR:-/tmp}/grimoire-fence" state_dir="${TMPDIR:-/tmp}/grimoire-fence"
safe_sid=$(printf '%s' "${session_id:-none}" | tr -c 'A-Za-z0-9._-' '_') safe_sid=$(printf '%s' "${session_id:-none}" | tr -c 'A-Za-z0-9._-' '_')
entered_file="$state_dir/${safe_sid}.entered" entered_file="$state_dir/${safe_sid}.entered"
pending_file="$state_dir/${safe_sid}.fence.pending"
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
# ── PostToolUse on enter_project: remember the first project entered ───── # ── PostToolUse on enter_project: remember the first project entered ─────
if [ "$hook_event" = "PostToolUse" ]; then if [ "$hook_event" = "PostToolUse" ]; then
@@ -238,6 +246,16 @@ while IFS= read -r check; do
reason=$(grimoire_json_pick "$flat" '.reason') reason=$(grimoire_json_pick "$flat" '.reason')
esc=$(printf '%s' "$reason" | grimoire_json_escape) || exit 0 esc=$(printf '%s' "$reason" | grimoire_json_escape) || exit 0
printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"%s"}}\n' "$esc" printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"%s"}}\n' "$esc"
# The ask, and the call it is about, so the run that follows a yes can
# be matched to it. `at` is what the act was: the tool for a Grimoire
# call, the act phrase ("git push in") for a file or a git command.
if [ "$check" = "tool" ]; then fence_at="$short"; fence_tool="$short"; else fence_at="$act"; fence_tool="$tool_name"; fi
if [ -n "$call_id" ] && [ -n "$session_id" ]; then
mkdir -p "$state_dir" 2>/dev/null || true
printf '%s' "$call_id" > "$pending_file" 2>/dev/null || true
fi
grimoire_gate_report "$session_id" fence asked "$fence_tool" "" "$fence_at" \
"$(grimoire_json_pick "$flat" '.targets[0].id')" "$call_id"
exit 0 exit 0
fi fi
done <<EOF done <<EOF
+11
View File
@@ -126,4 +126,15 @@ done
grimoire_json_list "$answer_flat" '.rule_ids' | grimoire_rules_append "$rulefile" grimoire_json_list "$answer_flat" '.rule_ids' | grimoire_rules_append "$rulefile"
printf '{"decision":"block","reason":"%s"}\n' "$(printf '%s' "$reason" | grimoire_json_escape)" printf '{"decision":"block","reason":"%s"}\n' "$(printf '%s' "$reason" | grimoire_json_escape)"
# Each rule that held the reply, reported as a gate stop with where it was
# reached, as the tool-call gates report theirs. The server already applied
# the per-session cap, so a reason here is a hold. A section hold names no
# rule and is counted by its own check (`report_check`).
i=0
for id in $(grimoire_json_list "$answer_flat" '.rule_ids'); do
grimoire_gate_report "$session_id" reply stopped reply "$id" \
"$(grimoire_json_pick "$answer_flat" ".rule_at[$i]")" "" ""
i=$((i + 1))
done
exit 0 exit 0
+82 -17
View File
@@ -20,7 +20,16 @@
# removes it once the instance has answered); # removes it once the instance has answered);
# <sid>.asked — the lines that note named. At the first stop after the note # <sid>.asked — the lines that note named. At the first stop after the note
# was carried, they go back as `phase=after`, which records # was carried, they go back as `phase=after`, which records
# whether they were judged, and are then forgotten. # whether they were judged;
# <sid>.asked_earlier — the same, for the carried lines the note named
# apart from this turn's;
# <sid>.earlier — what the after phase said is still unjudged, as
# `N<TAB>path<TAB>kind<TAB>name`, N the asks walked past.
# These ride the next check as `earlier=`, so a shape the
# agent moved on from is named again rather than surviving
# only as a count. A line walked past more than
# GRIMOIRE_EARLIER_MAX times is dropped: past that the
# repeat is noise, and the coverage line still counts it.
# A note no prompt has carried yet (two stops in a row) is asked again with # 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. # that turn's writes added, so nothing is dropped and nothing is asked twice.
# #
@@ -55,17 +64,23 @@ state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck"
mkdir -p "$state_dir" 2>/dev/null || true mkdir -p "$state_dir" 2>/dev/null || true
note_file="$state_dir/${safe_sid}.note" note_file="$state_dir/${safe_sid}.note"
asked_file="$state_dir/${safe_sid}.asked" asked_file="$state_dir/${safe_sid}.asked"
asked_earlier_file="$state_dir/${safe_sid}.asked_earlier"
earlier_file="$state_dir/${safe_sid}.earlier"
# Each walked-past shape is asked this many more times, then dropped.
earlier_max="${GRIMOIRE_EARLIER_MAX:-2}"
# A note no prompt has carried: its lines join this turn's, asked afresh. # A note no prompt has carried: its lines join this turn's, asked afresh. Its
# carried lines are still in <sid>.earlier, so they ride the next check too.
if [ -f "$note_file" ]; then if [ -f "$note_file" ]; then
if [ -s "$asked_file" ]; then if [ -s "$asked_file" ]; then
mkdir -p "$(dirname "$ledger")" 2>/dev/null || true mkdir -p "$(dirname "$ledger")" 2>/dev/null || true
cat "$asked_file" >> "$ledger" 2>/dev/null || true cat "$asked_file" >> "$ledger" 2>/dev/null || true
fi fi
rm -f "$note_file" "$asked_file" 2>/dev/null || true rm -f "$note_file" "$asked_file" "$asked_earlier_file" 2>/dev/null || true
fi fi
[ -s "$asked_file" ] || [ -s "$ledger" ] || exit 0 [ -s "$asked_file" ] || [ -s "$asked_earlier_file" ] || [ -s "$ledger" ] \
|| [ -s "$earlier_file" ] || exit 0
grimoire_config || exit 0 grimoire_config || exit 0
dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}" dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}"
@@ -89,32 +104,82 @@ esac
# key runs the plugin), and a turn that wrote more than this generated code. # 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; } _unique() { awk '!seen[$0]++' "$1" 2>/dev/null | head -n 80; }
# The note a prompt carried: were its lines judged since? # The note a prompt carried: were its lines judged since? What is still
if [ -s "$asked_file" ]; then # unjudged comes back as `left`, and becomes the carried set, each line's
asked=$(_unique "$asked_file") # walked-past count one higher than it was.
asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc="" if [ -s "$asked_file" ] || [ -s "$asked_earlier_file" ]; then
if [ -n "$asked_enc" ] && curl -fsS --max-time 4 \ asked=""
[ -s "$asked_file" ] && asked=$(_unique "$asked_file")
asked_q=""
if [ -n "$asked" ]; then
asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc=""
asked_q="&written=${asked_enc}"
fi
if [ -s "$asked_earlier_file" ]; then
prior=$(_unique "$asked_earlier_file")
prior_enc=$(printf '%s' "$prior" | grimoire_urlenc) || prior_enc=""
[ -n "$prior_enc" ] && asked_q="${asked_q}&earlier=${prior_enc}"
fi
if after=$(curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \ -H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/shape-check?phase=after&written=${asked_enc}${scope_q}" \ "${url%/}/api/plugin/shape-check?phase=after${asked_q}${scope_q}" 2>/dev/null); then
>/dev/null 2>&1; then rm -f "$asked_file" "$asked_earlier_file" 2>/dev/null || true
rm -f "$asked_file" 2>/dev/null || true left_file="$state_dir/${safe_sid}.left"
grimoire_json_pick "$(printf '%s' "$after" | grimoire_json_flat)" '.left' \
> "$left_file" 2>/dev/null || true
prev="$earlier_file"
[ -f "$prev" ] || prev=/dev/null
awk -F'\t' -v max="$earlier_max" '
FILENAME == ARGV[1] { if (NF == 4) seen[$2 "\t" $3 "\t" $4] = $1; next }
NF == 3 {
n = (($0 in seen) ? seen[$0] : 0) + 1
if (n <= max) print n "\t" $0
}' "$prev" "$left_file" > "${earlier_file}.new" 2>/dev/null || true
mv -f "${earlier_file}.new" "$earlier_file" 2>/dev/null || true
[ -s "$earlier_file" ] || rm -f "$earlier_file" 2>/dev/null || true
rm -f "$left_file" 2>/dev/null || true
fi fi
fi fi
[ -s "$ledger" ] || exit 0 written=""
written=$(_unique "$ledger") [ -s "$ledger" ] && written=$(_unique "$ledger")
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0 # The carried lines, minus any this turn wrote again (those are this turn's).
earlier=""
if [ -s "$earlier_file" ]; then
mine_file="$state_dir/${safe_sid}.mine"
printf '%s\n' "$written" > "$mine_file" 2>/dev/null || true
earlier=$(awk -F'\t' '
FILENAME == ARGV[1] { if (NF == 3) mine[$0] = 1; next }
NF == 4 { line = $2 "\t" $3 "\t" $4; if (!(line in mine) && !seen[line]++) print line }
' "$mine_file" "$earlier_file" 2>/dev/null | head -n 40)
rm -f "$mine_file" 2>/dev/null || true
fi
[ -n "$written" ] || [ -n "$earlier" ] || exit 0
check_q=""
if [ -n "$written" ]; then
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
check_q="&written=${written_enc}"
fi
if [ -n "$earlier" ]; then
earlier_enc=$(printf '%s' "$earlier" | grimoire_urlenc) || earlier_enc=""
[ -n "$earlier_enc" ] && check_q="${check_q}&earlier=${earlier_enc}"
fi
answer=$(curl -fsS --max-time 4 \ answer=$(curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \ -H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/shape-check?phase=check&written=${written_enc}${scope_q}" 2>/dev/null) \ "${url%/}/api/plugin/shape-check?phase=check${check_q}${scope_q}" 2>/dev/null) \
|| exit 0 # unreachable: keep the ledger || exit 0 # unreachable: keep the ledger
note=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.note') note=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.note')
if [ -n "$note" ]; then if [ -n "$note" ]; then
printf '%s' "$note" > "$note_file" 2>/dev/null || true printf '%s' "$note" > "$note_file" 2>/dev/null || true
printf '%s\n' "$written" > "$asked_file" 2>/dev/null || true [ -n "$written" ] && printf '%s\n' "$written" > "$asked_file" 2>/dev/null
[ -n "$earlier" ] && printf '%s\n' "$earlier" > "$asked_earlier_file" 2>/dev/null
else
# Nothing unjudged, the carried lines included: they were answered.
rm -f "$earlier_file" 2>/dev/null || true
fi fi
rm -f "$ledger" 2>/dev/null || true rm -f "$ledger" 2>/dev/null || true
exit 0 exit 0
+10 -1
View File
@@ -153,13 +153,22 @@ fi
# It cannot recur. `grimoire_checkpoint_allowed` holds at most one act per rule # It cannot recur. `grimoire_checkpoint_allowed` holds at most one act per rule
# and at most five per session, so the worst case of a mis-set floor is a noisy # and at most five per session, so the worst case of a mis-set floor is a noisy
# session rather than one that cannot move. # session rather than one that cannot move.
#
# Each stop is reported to the server, and so is a checkpoint the session's
# budget let through: the cap is decided here, so only this hook knows.
cp_rule=$(grimoire_json_pick "$body_flat" '.checkpoint.rule_id') cp_rule=$(grimoire_json_pick "$body_flat" '.checkpoint.rule_id')
cp_reason=$(grimoire_json_pick "$body_flat" '.checkpoint.reason') cp_reason=$(grimoire_json_pick "$body_flat" '.checkpoint.reason')
if [ -n "$cp_rule" ] && [ -n "$cp_reason" ] && [ -n "$session_id" ]; then if [ -n "$cp_rule" ] && [ -n "$cp_reason" ] && [ -n "$session_id" ]; then
if grimoire_checkpoint_allowed "$state_dir/${safe_sid}.checkpoint.ids" "$cp_rule"; then stops="$state_dir/${safe_sid}.checkpoint.ids"
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
if grimoire_checkpoint_allowed "$stops" "$cp_rule"; then
grimoire_json_deny PreToolUse "$cp_reason" grimoire_json_deny PreToolUse "$cp_reason"
grimoire_gate_report "$session_id" checkpoint stopped "$tool_name" "$cp_rule" pre_tool_rule "" "$call_id"
exit 0 exit 0
fi fi
if grimoire_checkpoint_spent "$stops" "$cp_rule"; then
grimoire_gate_report "$session_id" checkpoint let_through "$tool_name" "$cp_rule" pre_tool_rule "" "$call_id"
fi
fi fi
[ -n "$context" ] || exit 0 [ -n "$context" ] || exit 0
+9
View File
@@ -116,6 +116,15 @@
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_project_fence.sh\"" "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_project_fence.sh\""
} }
] ]
},
{
"matcher": "Write|Edit|MultiEdit|NotebookEdit|Bash|mcp__.*grimoire.*",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_fence_ran.sh\""
}
]
} }
], ],
"PreCompact": [ "PreCompact": [
+4
View File
@@ -45,6 +45,10 @@ face, and if so write the note that carries the idea.
enter_project's `family` key counts what this project owes the family: enter_project's `family` key counts what this project owes the family:
`unassessed`, `owed`, `needs_recheck`, each with the call that lists them. `unassessed`, `owed`, `needs_recheck`, each with the call that lists them.
It also names this project's own records that a trigger proposed and nobody
evaluated (`candidates`): you hold their context, so evaluate each as above,
or `retire_family_idea` one that is not an idea at all (a task, a note about
this project alone).
Answer an idea **when your work reaches its area**, not as a chore list at Answer an idea **when your work reaches its area**, not as a chore list at
session start — the count is there so it is never invisible, not so it session start — the count is there so it is never invisible, not so it
preempts the operator's task. preempts the operator's task.
+5 -2
View File
@@ -53,8 +53,11 @@ unjudged.
The ledger is filled from your answers, given while you still know them. When The ledger is filled from your answers, given while you still know them. When
a turn wrote definitions nobody has judged, the plugin's Stop hook lists them a turn wrote definitions nobody has judged, the plugin's Stop hook lists them
once — with whatever the machinery holds as evidence — and you classify them — with whatever the machinery holds as evidence — and you classify them
in one `classify_shapes(project_id, repo=…, …)` call (the `reusing-code` skill in one `classify_shapes(project_id, repo=…, …)` call. What you move on from is
named again in your next few notes, marked as written earlier in the session,
because nothing else names a shape after that (the coverage line only counts
it) (the `reusing-code` skill
says what each verdict means). `repo` lets a verdict land on a shape the sync says what each verdict means). `repo` lets a verdict land on a shape the sync
has not read yet. So a project worked this way stays accounted as it grows, has not read yet. So a project worked this way stays accounted as it grows,
and an audit pass is a CHECK that the reflex held — the coverage line names and an audit pass is a CHECK that the reflex held — the coverage line names
+7
View File
@@ -402,6 +402,13 @@ SMOKE_EVENTS: dict[str, str] = {
{"session_id": "smoke", "cwd": ".", "hook_event_name": "PreToolUse", {"session_id": "smoke", "cwd": ".", "hook_event_name": "PreToolUse",
"tool_name": "mcp__grimoire__update_task", "tool_input": {"task_id": 1}} "tool_name": "mcp__grimoire__update_task", "tool_input": {"task_id": 1}}
), ),
# The fence's after-call half: with no ask pending it exits before
# reading anything, which is the case on nearly every call.
"grimoire_fence_ran.sh": json.dumps(
{"session_id": "smoke", "cwd": ".", "hook_event_name": "PostToolUse",
"tool_name": "Bash", "tool_use_id": "toolu_smoke",
"tool_input": {"command": "true"}, "tool_response": {}}
),
# The shared library is sourced, never run; executed bare it defines # The shared library is sourced, never run; executed bare it defines
# functions and exits — silent by construction. # functions and exits — silent by construction.
"grimoire_defs.sh": "", "grimoire_defs.sh": "",
+4 -1
View File
@@ -140,7 +140,10 @@ async def enter_project(project_id: int) -> dict:
version (`needs_recheck`) — each with the list_family_adoptions call that version (`needs_recheck`) — each with the list_family_adoptions call that
lists them. Answer an unassessed idea when your work reaches its area lists them. Answer an unassessed idea when your work reaches its area
(get_family_adoption, then assess_family_adoption, or classify the code (get_family_adoption, then assess_family_adoption, or classify the code
against it); the family-canon skill has the order. against it); the family-canon skill has the order. It also counts this
project's own records that a trigger proposed as family ideas and nobody
has evaluated (`candidates`), naming them: this project's session holds
their context, so it is the one asked to promote or retire each.
`inception` appears ONLY when the project is yours and `inception` appears ONLY when the project is yours and
nobody has decided what it inherits: it carries the current defaults nobody has decided what it inherits: it carries the current defaults
+22
View File
@@ -537,6 +537,28 @@ async def retrieval_telemetry(
pushed or by being asked for, which `usage` cannot: a pull there does not pushed or by being asked for, which `usage` cannot: a pull there does not
say which door led to it. Counts only sessions whose plugin reports opens. say which door led to it. Counts only sessions whose plugin reports opens.
`gates` — every time a Grimoire gate stood in front of a tool call, from
`gate_stops`, as the plugin hook that made the stop reported it. In
`by_gate`, for each of `enforce` and `hold` (a moment rule's
enforcement), `checkpoint` (the act checkpoint on a command), `fence`
(the project fence asking the operator) and `reply` (a rule holding the
finished reply for one read), it gives:
- `stops`: calls denied or put to the operator;
- `cleared`: stops the session cleared by opening the rule, which is how
a hold is meant to clear;
- `misfired`: stops whose rule the session then reported with
`rule_misfired`, a stop at the wrong moment;
- `let_through`: calls a hold would have stopped, let through because
the session's stop budget was spent;
- `ran`: stopped calls that ran after all. For the fence that is the
operator's yes; an ask without it was declined, or the call failed.
`by_rule` gives the same per rule and place, most stops first. `fence`
gives the asks per tool and target project. Read `misfired` and
`let_through` before changing a rule's enforcement. A rule that stops
work and is then called a misfire has the wrong moment or trigger; a
budget that keeps letting calls through is spent on rules that stop
too often. `gates_failed: true` means the read broke.
`judged` — whether the lines RELATED, from `retrieval_judgments`: `judged` — whether the lines RELATED, from `retrieval_judgments`:
per source, a reviewer's verdicts (`on_point` / `adjacent` / `unrelated`) per source, a reviewer's verdicts (`on_point` / `adjacent` / `unrelated`)
on a sample of logged menus, `within_budget` against `beyond_budget` and on a sample of logged menus, `within_budget` against `beyond_budget` and
+1
View File
@@ -63,6 +63,7 @@ from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401
from grimoire.models.rule_delivery import RuleDelivery # noqa: E402, F401 from grimoire.models.rule_delivery import RuleDelivery # noqa: E402, F401
from grimoire.models.rule_adherence import RuleAdherence # noqa: E402, F401 from grimoire.models.rule_adherence import RuleAdherence # noqa: E402, F401
from grimoire.models.record_delivery import RecordDelivery # noqa: E402, F401 from grimoire.models.record_delivery import RecordDelivery # noqa: E402, F401
from grimoire.models.gate_stop import GateStop # noqa: E402, F401
from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401 from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401
from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401 from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401
from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401 from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401
+90
View File
@@ -0,0 +1,90 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, Index, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import iso
# The gates that can stop a tool call, as the plugin hooks name them.
ENFORCE = "enforce" # a moment rule set to enforce: refused every time
HOLD = "hold" # a moment rule set to hold: one read before the act
CHECKPOINT = "checkpoint" # the act checkpoint on a command (tool-rules)
FENCE = "fence" # the project fence: the operator is asked
REPLY = "reply" # a rule holding the finished reply for one read
GATES = (ENFORCE, HOLD, CHECKPOINT, FENCE, REPLY)
# What the hook did with it.
STOPPED = "stopped" # the call was denied, the reason shown instead
LET_THROUGH = "let_through" # would have held, but the session cap was spent
ASKED = "asked" # the fence put the call to the operator
OUTCOMES = (STOPPED, LET_THROUGH, ASKED)
class GateStop(Base):
"""One time a Grimoire gate stood in front of a tool call.
WHY IT EXISTS. A rule set to enforce or hold, the act checkpoint, the
project fence and the hold on a finished reply (the Stop hook, `tool` =
"reply") are the only places Grimoire stops work rather than
commenting on it, and a stop that fires at the wrong moment costs a
round trip every time. Whether the plugin actually stops a call is
decided client-side (the per-rule and per-session caps in
`grimoire_checkpoint_allowed`), so the server's own decision is not the
record: the hook reports what it did, here.
`cleared_at` is stamped when the session opened the rule after the stop,
which is how a hold is meant to clear. `ran_at` is stamped when the
stopped call ran after all, which for the fence means the operator said
yes (the harness reports a PostToolUse only for a call that ran); the
tool call's own id (`call_id`) ties the two. A fence ask with no `ran_at`
was declined, or the call failed.
`at` is the moment the rule was reached at, or the arm that found it.
`target` is the project a fenced act would have landed in.
FK-free, like the other telemetry tables: the record that a rule kept
stopping work outlives the rule, since it is the case for changing it.
"""
__tablename__ = "gate_stops"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
session_id: Mapped[str] = mapped_column(Text, nullable=False)
gate: Mapped[str] = mapped_column(Text, nullable=False)
outcome: Mapped[str] = mapped_column(Text, nullable=False)
rule_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
tool: Mapped[str] = mapped_column(Text, nullable=False)
at: Mapped[str | None] = mapped_column(Text, nullable=True)
target: Mapped[str | None] = mapped_column(Text, nullable=True)
call_id: Mapped[str | None] = mapped_column(Text, nullable=True)
stopped_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
cleared_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
ran_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
__table_args__ = (
Index("ix_gate_stops_session_rule", "user_id", "session_id", "rule_id", "stopped_at"),
Index("ix_gate_stops_stopped_at", "stopped_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"user_id": self.user_id,
"session_id": self.session_id,
"gate": self.gate,
"outcome": self.outcome,
"rule_id": self.rule_id,
"tool": self.tool,
"at": self.at,
"target": self.target,
"call_id": self.call_id,
"stopped_at": iso(self.stopped_at),
"cleared_at": iso(self.cleared_at),
"ran_at": iso(self.ran_at),
"plugin": self.plugin,
}
+80 -6
View File
@@ -14,6 +14,7 @@ from quart import Blueprint, g, jsonify, request
from grimoire.auth import admin_required, get_current_user_id, login_required from grimoire.auth import admin_required, get_current_user_id, login_required
from grimoire.config import Config from grimoire.config import Config
from grimoire.services import gate_stops as gate_stops_svc
from grimoire.services import hook_payload as hook_payload_svc from grimoire.services import hook_payload as hook_payload_svc
from grimoire.services import moment_delivery as moment_delivery_svc from grimoire.services import moment_delivery as moment_delivery_svc
from grimoire.services import plugin_context as plugin_ctx_svc from grimoire.services import plugin_context as plugin_ctx_svc
@@ -455,6 +456,10 @@ async def rule_opened():
await rule_deliveries_svc.mark_opened( await rule_deliveries_svc.mark_opened(
g.user.id, str(data.get("session_id") or ""), rule_id, g.user.id, str(data.get("session_id") or ""), rule_id,
) )
# And against the stop it cleared, when a gate had stopped a call on it.
await gate_stops_svc.mark_cleared(
g.user.id, str(data.get("session_id") or ""), rule_id,
)
acts = data.get("acts") acts = data.get("acts")
if rule_id <= 0 or not isinstance(acts, list) or not acts: if rule_id <= 0 or not isinstance(acts, list) or not acts:
return jsonify({"moments": [], "context": ""}) return jsonify({"moments": [], "context": ""})
@@ -465,6 +470,54 @@ async def rule_opened():
)) ))
@plugin_bp.post("/gate-stop")
@login_required
async def gate_stop():
"""A hook stood in front of a tool call.
Body: `{"session_id", "gate", "outcome", "tool", "rule_id"?, "at"?,
"target"?, "call_id"?}`. `gate` is `enforce`, `hold`, `checkpoint` or
`fence`; `outcome` is `stopped` (denied), `let_through` (a hold the
session's stop budget no longer covered) or `asked` (put to the
operator). Posted by the hook that made the stop, since whether a hold
actually stops is decided by caps kept in the plugin. Answers
`{"recorded"}`.
"""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict):
return jsonify({"recorded": False})
try:
rule_id = int(data.get("rule_id") or 0)
except (TypeError, ValueError):
rule_id = 0
recorded = await gate_stops_svc.record(
g.user.id, str(data.get("session_id") or ""),
gate=str(data.get("gate") or ""), outcome=str(data.get("outcome") or ""),
tool=str(data.get("tool") or ""), rule_id=rule_id or None,
at=data.get("at"), target=data.get("target"), call_id=data.get("call_id"),
plugin=rule_deliveries_svc.current_plugin(),
)
return jsonify({"recorded": recorded})
@plugin_bp.post("/gate-ran")
@login_required
async def gate_ran():
"""A tool call a gate stood in front of ran after all.
Body: `{"session_id", "call_id"}`, posted after the call by the hook that
asked about it. For the project fence that is the operator's yes: the
harness reports a call only once it has run. Answers `{"recorded"}`.
"""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict):
return jsonify({"recorded": False})
recorded = await gate_stops_svc.mark_ran(
g.user.id, str(data.get("session_id") or ""), str(data.get("call_id") or ""),
)
return jsonify({"recorded": recorded})
@plugin_bp.post("/record-opened") @plugin_bp.post("/record-opened")
@login_required @login_required
async def record_opened(): async def record_opened():
@@ -571,7 +624,9 @@ async def reply_rules():
holds once, and the per-session cap counts these). holds once, and the per-session cap counts these).
Returns `reason` — the words the hook blocks with, empty when nothing Returns `reason` — the words the hook blocks with, empty when nothing
holds — plus `rule_ids` for the hook's ledger, `moments` reached and holds — plus `rule_ids` for the hook's ledger, `rule_at` beside them
(where each was reached, which the hook reports with the hold),
`moments` reached and
`report_check` (the recorded outcome, or "" when nothing was checked). `report_check` (the recorded outcome, or "" when nothing was checked).
""" """
data = await request.get_json(silent=True) or {} data = await request.get_json(silent=True) or {}
@@ -603,6 +658,7 @@ async def reply_rules():
return jsonify({ return jsonify({
"reason": "\n\n".join(reasons), "reason": "\n\n".join(reasons),
"rule_ids": held.get("rule_ids", []), "rule_ids": held.get("rule_ids", []),
"rule_at": held.get("rule_at", []),
"moments": held.get("moments", []), "moments": held.get("moments", []),
"report_check": checked.get("outcome", ""), "report_check": checked.get("outcome", ""),
}) })
@@ -755,17 +811,28 @@ async def shape_check():
Query: Query:
written (str) — newline-separated `path<TAB>kind<TAB>name` lines, written (str) — newline-separated `path<TAB>kind<TAB>name` lines,
repo-relative, kind css|sym|file. repo-relative, kind css|sym|file.
earlier (opt) — the same lines for shapes this session wrote in an
earlier turn, was asked about and walked past. The
hook carries them for a bounded number of asks;
the note names them apart from this turn's.
phase (str) — check | after. Anything else is a 400. phase (str) — check | after. Anything else is a 400.
repo (opt) — working repo remote, resolved like the other arms. repo (opt) — working repo remote, resolved like the other arms.
project_id (opt) — explicit scope override. project_id (opt) — explicit scope override.
The after phase also answers `left`: the asked lines still unjudged, as
ledger lines, which the hook carries into its next ask.
""" """
phase = (request.args.get("phase") or "check").strip() phase = (request.args.get("phase") or "check").strip()
if phase not in shape_check_svc.PHASES: if phase not in shape_check_svc.PHASES:
return jsonify({"error": f"phase must be one of {list(shape_check_svc.PHASES)}"}), 400 return jsonify({"error": f"phase must be one of {list(shape_check_svc.PHASES)}"}), 400
written = shape_check_svc.parse_written(request.args.get("written") or "") written = shape_check_svc.parse_written(request.args.get("written") or "")
earlier = [
line for line in shape_check_svc.parse_written(request.args.get("earlier") or "")
if line not in written
]
project_id, repo, _unbound = await _project_scope() project_id, repo, _unbound = await _project_scope()
body: dict = {"status": "ok", "unjudged": []} body: dict = {"status": "ok", "unjudged": []}
if not project_id or not written: if not project_id or not (written or earlier):
return jsonify(body) return jsonify(body)
from grimoire.services import access from grimoire.services import access
from grimoire.services import coverage as coverage_svc from grimoire.services import coverage as coverage_svc
@@ -774,7 +841,9 @@ async def shape_check():
if not await access.can_read_project(g.user.id, project_id): if not await access.can_read_project(g.user.id, project_id):
return jsonify(body) return jsonify(body)
repo_key = repo_bindings_svc.normalize_repo_key(repo) if repo else "" repo_key = repo_bindings_svc.normalize_repo_key(repo) if repo else ""
unjudged = await shape_ledger_svc.unjudged_shapes(project_id, written, repo_key=repo_key) unjudged = await shape_ledger_svc.unjudged_shapes(
project_id, written + earlier, repo_key=repo_key,
)
# A snippet recorded AT a shape is the strongest verdict there is — the # A snippet recorded AT a shape is the strongest verdict there is — the
# next refresh stamps that row canonical. Until then the ledger cannot # next refresh stamps that row canonical. Until then the ledger cannot
# know, so the recorded locations answer for it: an agent who just # know, so the recorded locations answer for it: an agent who just
@@ -786,17 +855,22 @@ async def shape_check():
} }
unjudged = [u for u in unjudged if (u["path"], u["symbol"]) not in recorded unjudged = [u for u in unjudged if (u["path"], u["symbol"]) not in recorded
and not (u["kind"] == "file" and (u["path"], "") in recorded)] and not (u["kind"] == "file" and (u["path"], "") in recorded)]
carried = set(earlier)
fresh = [u for u in unjudged if (u["path"], u["kind"], u["symbol"]) not in carried]
repeat = [u for u in unjudged if (u["path"], u["kind"], u["symbol"]) in carried]
outcome = shape_check_svc.outcome_for(phase, unjudged) outcome = shape_check_svc.outcome_for(phase, unjudged)
await shape_check_svc.record_shape_check( await shape_check_svc.record_shape_check(
g.user.id, outcome, written=len(written), unjudged=len(unjudged), g.user.id, outcome, written=len(written) + len(earlier), unjudged=len(unjudged),
project_id=project_id, project_id=project_id, earlier=len(repeat),
) )
body["outcome"] = outcome body["outcome"] = outcome
body["unjudged"] = unjudged body["unjudged"] = unjudged
if outcome == "noted": if outcome == "noted":
body["note"] = shape_check_svc.note_text( body["note"] = shape_check_svc.note_text(
unjudged, project_id=project_id, repo=repo_key or repo, fresh, project_id=project_id, repo=repo_key or repo, earlier=repeat,
) )
if phase == "after":
body["left"] = shape_check_svc.ledger_lines(unjudged)
return jsonify(body) return jsonify(body)
+15
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 moment_actions as moment_actions_svc
from grimoire.services import moments as moments_svc from grimoire.services import moments as moments_svc
from grimoire.services import reply_shapes as shapes_svc from grimoire.services import reply_shapes as shapes_svc
from grimoire.services import gate_stops as gate_stops_svc
from grimoire.services import record_deliveries as record_deliveries_svc from grimoire.services import record_deliveries as record_deliveries_svc
from grimoire.services import record_kinds as record_kinds_svc from grimoire.services import record_kinds as record_kinds_svc
from grimoire.services import rule_adherence as adherence_svc from grimoire.services import rule_adherence as adherence_svc
@@ -306,6 +307,20 @@ async def record_reach_route():
return jsonify(await record_deliveries_svc.summary(get_current_user_id(), days=days)) return jsonify(await record_deliveries_svc.summary(get_current_user_id(), days=days))
@retrieval_bp.route("/gate-stops", methods=["GET"])
@login_required
async def gate_stops_route():
"""How often each gate stood in front of this user's tool calls: per gate
and per rule, stops, cleared by a read, reported as misfires, let through
once the session's stop budget was spent; and the project fence's asks
and how many then ran. `?days=` sets the window (default 30)."""
try:
days = int(request.args.get("days") or 30)
except ValueError:
return jsonify({"error": "days must be a whole number"}), 400
return jsonify(await gate_stops_svc.summary(get_current_user_id(), days=days))
@retrieval_bp.route("/weights/proposals", methods=["GET"]) @retrieval_bp.route("/weights/proposals", methods=["GET"])
@login_required @login_required
async def weight_proposals_route(): async def weight_proposals_route():
+3
View File
@@ -206,6 +206,9 @@ _NOT_INCLUDED = [
"rule_adherence", "rule_adherence",
# The same per-session ledger for every other record kind. # The same per-session ledger for every other record kind.
"record_deliveries", "record_deliveries",
# Each time a gate stopped a tool call, keyed by the same session ids and
# pruned with the deliveries.
"gate_stops",
# Verdicts on retrieval_logs rows, so they go where their subject # Verdicts on retrieval_logs rows, so they go where their subject
# goes: a restore that carried a judgment of a call it did not carry would # goes: a restore that carried a judgment of a call it did not carry would
# leave a verdict on nothing. A sample, re-takeable by the review pass. # leave a verdict on nothing. A sample, re-takeable by the review pass.
+93 -4
View File
@@ -115,6 +115,9 @@ _LINEAGE = re.compile(
) )
# How far before a `#N` the lineage word may sit: the same clause, roughly. # How far before a `#N` the lineage word may sit: the same clause, roughly.
_LINEAGE_WINDOW = 80 _LINEAGE_WINDOW = 80
# A quoted title, straight or curly quotes, on one line. Bounded so a stray
# quote mark cannot blank a whole paragraph.
_QUOTED = re.compile(r'"[^"\n]{1,200}"|\u201c[^\u201d\n]{1,200}\u201d')
# Note kinds the repeat trigger compares: recorded knowledge and shapes, not # Note kinds the repeat trigger compares: recorded knowledge and shapes, not
# the to-do list — and each only against its own kind. A repeat is the same # the to-do list — and each only against its own kind. A repeat is the same
@@ -127,6 +130,38 @@ _LINEAGE_WINDOW = 80
# once the idea is canon. # once the idea is canon.
_REPEAT_KINDS = ("snippet", "note") _REPEAT_KINDS = ("snippet", "note")
def about_its_own_project(title: str | None, project_title: str | None) -> bool:
"""Whether a record's title opens with its own project's name.
"Storehouse: start here", "Torn Stars — Economy System": a record named
for its project describes that project — its overview, its founding
decisions, one system of one game — and cannot carry an idea every
project on a platform shares, however closely another project's
overview resembles it. The name must end at a word boundary, so a
project called "Sync" does not claim "Syncthing relay".
"""
t = (title or "").strip().casefold()
p = (project_title or "").strip().casefold()
if not p or not t.startswith(p):
return False
return len(t) == len(p) or not t[len(p)].isalnum()
def can_carry_idea(*, is_task: bool, note_type: str | None, title: str | None,
project_title: str | None) -> bool:
"""Whether a record is the kind a trigger may open as a family candidate.
A task is a unit of work in one project, so it is never the idea itself:
an idea it carries is written up as a note and proposed. Only recorded
knowledge and shapes (`_REPEAT_KINDS`) qualify, and not a record about
its own project (`about_its_own_project`). The triggers open candidates
without anyone reading them, so they hold to this; an agent who has read
a record may still propose it by hand."""
if is_task or (note_type or "note") not in _REPEAT_KINDS:
return False
return not about_its_own_project(title, project_title)
MEMBER_STATES = ("declared", "detected") MEMBER_STATES = ("declared", "detected")
_IDEA_ACTIONS = ("propose", "promote", "revise", "retire") _IDEA_ACTIONS = ("propose", "promote", "revise", "retire")
@@ -862,9 +897,15 @@ def lineage_citations(text: str | None) -> list[int]:
from grimoire.services.record_refs import REF_RE from grimoire.services.record_refs import REF_RE
found: list[int] = [] found: list[int] = []
for m in REF_RE.finditer(text or ""): text = text or ""
# A quoted span is a record's TITLE, written beside its id by convention
# (#12 "Release parsing and matching"). Its words describe that record,
# not this one's lineage, so they are blanked before the window is read;
# blanked to the same length, so match positions stay valid.
bare = _QUOTED.sub(lambda q: " " * len(q.group(0)), text)
for m in REF_RE.finditer(text):
start = max(0, m.start() - _LINEAGE_WINDOW) start = max(0, m.start() - _LINEAGE_WINDOW)
window = text[start:m.start()] window = bare[start:m.start()]
window = re.split(r"[\n.;]", window)[-1] window = re.split(r"[\n.;]", window)[-1]
if _LINEAGE.search(window): if _LINEAGE.search(window):
n = int(m.group(1)) n = int(m.group(1))
@@ -873,6 +914,41 @@ def lineage_citations(text: str | None) -> list[int]:
return found return found
async def _project_titles(session, project_ids: set[int]) -> dict[int, str]:
return dict((await session.execute(
select(Project.id, Project.title).where(Project.id.in_(project_ids))
)).all())
async def unevaluated_candidates(user_id: int, project_id: int, *, limit: int = 5) -> dict:
"""This project's own records that are family candidates nobody has
evaluated: every decision on them so far is the system's own proposal.
The triggers open candidates; nothing else asks anyone to evaluate one,
so without a reader they only accumulate. The project a candidate lives
in is where its context is, so its own sessions are asked, on entering.
{count, ideas: [{id, title}]}, oldest first, up to ``limit`` named."""
judged = select(FamilyDecision.idea_id).where(
FamilyDecision.idea_id == FamilyIdea.note_id,
FamilyDecision.decided_via != "system",
).exists()
where = (
FamilyIdea.status == "candidate", Note.project_id == project_id,
Note.deleted_at.is_(None), access.readable_notes_clause(user_id), ~judged,
)
async with async_session() as session:
count = (await session.execute(
select(func.count()).select_from(FamilyIdea)
.join(Note, Note.id == FamilyIdea.note_id).where(*where)
)).scalar() or 0
rows = (await session.execute(
select(Note.id, Note.title).select_from(FamilyIdea)
.join(Note, Note.id == FamilyIdea.note_id).where(*where)
.order_by(FamilyIdea.created_at.asc()).limit(limit)
)).all() if count else []
return {"count": int(count), "ideas": [{"id": i, "title": t} for i, t in rows]}
async def _member_platform_ids(session, project_id: int) -> set[int]: async def _member_platform_ids(session, project_id: int) -> set[int]:
return set((await session.execute( return set((await session.execute(
select(ProjectPlatform.platform_id).where( select(ProjectPlatform.platform_id).where(
@@ -902,14 +978,20 @@ async def citation_trigger(user_id: int, note) -> str | None:
return None return None
async with async_session() as session: async with async_session() as session:
rows = (await session.execute( rows = (await session.execute(
select(Note.id, Note.title, Note.project_id, Project.title) select(Note.id, Note.title, Note.project_id, Project.title,
Note.status, Note.note_type)
.join(Project, Project.id == Note.project_id) .join(Project, Project.id == Note.project_id)
.where( .where(
Note.id.in_(cited), Note.deleted_at.is_(None), Note.id.in_(cited), Note.deleted_at.is_(None),
Note.project_id.is_not(None), Note.project_id != note.project_id, Note.project_id.is_not(None), Note.project_id != note.project_id,
) )
)).all() )).all()
for source_id, source_title, _pid, project_title in sorted(rows, key=lambda r: cited.index(r[0])): for source_id, source_title, _pid, project_title, status, note_type in sorted(
rows, key=lambda r: cited.index(r[0]),
):
if not can_carry_idea(is_task=status is not None, note_type=note_type,
title=source_title, project_title=project_title):
continue
if not await access.can_write_note(user_id, source_id): if not await access.can_write_note(user_id, source_id):
continue continue
idea, created = await propose( idea, created = await propose(
@@ -944,6 +1026,9 @@ async def repeat_trigger(user_id: int, note) -> str | None:
if not getattr(note, "project_id", None) or note.is_task or kind not in _REPEAT_KINDS: if not getattr(note, "project_id", None) or note.is_task or kind not in _REPEAT_KINDS:
return None return None
async with async_session() as session: async with async_session() as session:
titles = await _project_titles(session, {note.project_id})
if about_its_own_project(note.title, titles.get(note.project_id)):
return None
mine = await _member_platform_ids(session, note.project_id) mine = await _member_platform_ids(session, note.project_id)
if not mine: if not mine:
return None return None
@@ -958,6 +1043,10 @@ async def repeat_trigger(user_id: int, note) -> str | None:
if (other.note_type or "note") != kind: if (other.note_type or "note") != kind:
continue continue
async with async_session() as session: async with async_session() as session:
other_project = (await _project_titles(session, {other.project_id})).get(other.project_id)
if not can_carry_idea(is_task=other.is_task, note_type=other.note_type,
title=other.title, project_title=other_project):
continue
shared = mine & await _member_platform_ids(session, other.project_id) shared = mine & await _member_platform_ids(session, other.project_id)
if not shared or not await access.can_write_note(user_id, other.id): if not shared or not await access.can_write_note(user_id, other.id):
continue continue
+29 -6
View File
@@ -1222,10 +1222,13 @@ async def _shapes_follow(user_id: int, project_id: int, idea_id: int, outcome: s
# ideas themselves by retrieval, and the owed answers filed while a task was # ideas themselves by retrieval, and the owed answers filed while a task was
# open, handed back when it closes. # open, handed back when it closes.
def family_line(project_id: int, cells: list[dict]) -> dict | None: def family_line(project_id: int, cells: list[dict],
candidates: dict | None = None) -> dict | None:
"""The `family` line enter_project carries: what this project has not """The `family` line enter_project carries: what this project has not
answered, owes, or answered against an older canon version. None when answered, owes, or answered against an older canon version — and which
all three are zero — the key is attached only when it asks something. of its own records are family candidates nobody has evaluated
(`family.unevaluated_candidates`). None when all are zero — the key is
attached only when it asks something.
Shown on EVERY entry (the step settled this), not only when a session Shown on EVERY entry (the step settled this), not only when a session
touches a platform: entering is when the agent chooses what to work on, touches a platform: entering is when the agent chooses what to work on,
@@ -1234,7 +1237,9 @@ def family_line(project_id: int, cells: list[dict]) -> dict | None:
unassessed = sum(1 for c in cells if c["in_scope"] and c["status"] == "unassessed") unassessed = sum(1 for c in cells if c["in_scope"] and c["status"] == "unassessed")
owed = sum(1 for c in cells if c["status"] == "owed") owed = sum(1 for c in cells if c["status"] == "owed")
recheck = sum(1 for c in cells if c["needs_recheck"]) recheck = sum(1 for c in cells if c["needs_recheck"])
if not (unassessed or owed or recheck): candidates = candidates or {}
n_cand = int(candidates.get("count") or 0)
if not (unassessed or owed or recheck or n_cand):
return None return None
parts, calls = [], {} parts, calls = [], {}
if unassessed: if unassessed:
@@ -1246,9 +1251,23 @@ def family_line(project_id: int, cells: list[dict]) -> dict | None:
if recheck: if recheck:
parts.append(f"{recheck} to recheck") parts.append(f"{recheck} to recheck")
calls["needs_recheck"] = f"list_family_adoptions(project_id={project_id}, needs_recheck=true)" calls["needs_recheck"] = f"list_family_adoptions(project_id={project_id}, needs_recheck=true)"
if n_cand:
# Named by id: the list tool pages every project's ideas, and these
# are the few that this project's own session is placed to judge.
named = ", ".join(f"#{c['id']} \"{c['title']}\"" for c in candidates.get("ideas") or [])
more = n_cand - len(candidates.get("ideas") or [])
parts.append(f"{n_cand} of this project's own record{'s' if n_cand != 1 else ''} "
"proposed as family ideas, never evaluated")
calls["candidates"] = (
f"get_family_idea(id) for each — {named}"
+ (f", and {more} more (list_family_ideas(status=\"candidate\"))" if more > 0 else "")
+ "; then promote_family_idea if all three criteria hold, or "
"retire_family_idea if it is not an idea at all"
)
return { return {
"line": "family canon on this project's platforms: " + " · ".join(parts), "line": "family canon on this project's platforms: " + " · ".join(parts),
"unassessed": unassessed, "owed": owed, "needs_recheck": recheck, "unassessed": unassessed, "owed": owed, "needs_recheck": recheck,
"candidates": n_cand,
"calls": calls, "calls": calls,
"answer_with": ("get_family_adoption(project_id, idea_id) reads one with its " "answer_with": ("get_family_adoption(project_id, idea_id) reads one with its "
"precedents; assess_family_adoption answers it — or classify_shapes " "precedents; assess_family_adoption answers it — or classify_shapes "
@@ -1257,8 +1276,11 @@ def family_line(project_id: int, cells: list[dict]) -> dict | None:
async def family_readout(user_id: int, project_id: int) -> dict | None: async def family_readout(user_id: int, project_id: int) -> dict | None:
from grimoire.services import family as family_svc
matrix = await adoption_matrix(user_id, project_id=project_id) matrix = await adoption_matrix(user_id, project_id=project_id)
return family_line(project_id, matrix["cells"]) candidates = await family_svc.unevaluated_candidates(user_id, project_id)
return family_line(project_id, matrix["cells"], candidates)
# --- whether the line reached the project --------------------------------------- # --- whether the line reached the project ---------------------------------------
@@ -1285,7 +1307,8 @@ async def record_entry(user_id: int, project_id: int, line: dict | None, *,
if failed: if failed:
details["readout_failed"] = True details["readout_failed"] = True
if line: if line:
details.update({k: int(line.get(k) or 0) for k in ("unassessed", "owed", "needs_recheck")}) details.update({k: int(line.get(k) or 0)
for k in ("unassessed", "owed", "needs_recheck", "candidates")})
try: try:
async with async_session() as session: async with async_session() as session:
session.add(AppLog( session.add(AppLog(
+217
View File
@@ -0,0 +1,217 @@
"""Each time a Grimoire gate stood in front of a tool call, and what followed.
Three calls, one table (`gate_stops`):
- `record` — from the plugin, the moment a hook stops a call (a moment rule
set to enforce or hold, the act checkpoint), lets one through because the
session's stop budget is spent, or puts one to the operator (the project
fence). The hook reports it, not the server's decision, because the caps
that decide whether a hold actually stops are kept client-side.
- `mark_cleared` — the session opened the rule after the stop: the latest
uncleared stop of it in that session gets the stamp. That is how a hold is
meant to clear.
- `mark_ran` — the stopped call ran after all, matched by its tool-call id.
For the fence that is the operator's yes.
`summary` reads it back per gate and per rule: how often each stops work,
how often a stop cleared by a read, how often the session then reported the
rule as a misfire, and how often the session cap let a call through.
Kept as long as rule deliveries (`rule_deliveries.RETAIN_DAYS`) and pruned
with them.
"""
from __future__ import annotations
import logging
from datetime import datetime, timedelta, timezone
from sqlalchemy import and_, case, delete, exists, func, select, update
from grimoire.models import async_session
from grimoire.models.gate_stop import (
ASKED, FENCE, GATES, LET_THROUGH, OUTCOMES, STOPPED, GateStop,
)
from grimoire.models.rule_adherence import MISFIRE, RuleAdherence
from grimoire.models.rulebook import Rule
from grimoire.services import rule_deliveries
logger = logging.getLogger(__name__)
# A field longer than this is not a tool name, a moment or a project id.
_FIELD_MAX = 200
# Rules listed in the readout, most stops first.
_BY_RULE_LIMIT = 25
def _field(value, limit: int = _FIELD_MAX) -> str | None:
text = str(value or "").strip()[:limit]
return text or None
async def record(
user_id: int, session_id: str | None, *, gate: str, outcome: str, tool: str,
rule_id: int | None = None, at: str | None = None, target: str | None = None,
call_id: str | None = None, plugin: str | None = None,
) -> bool:
"""One stop, as the hook made it. Returns whether a row was written: an
unknown gate or outcome, or a stop with no session, records nothing,
since nothing could later clear it."""
sid = rule_deliveries.clean_session(session_id)
if not sid or gate not in GATES or outcome not in OUTCOMES or not _field(tool):
return False
if gate != FENCE and not rule_id:
return False
async with async_session() as session:
session.add(GateStop(
user_id=int(user_id), session_id=sid, gate=gate, outcome=outcome,
rule_id=int(rule_id) if rule_id else None, tool=_field(tool),
at=_field(at), target=_field(target), call_id=_field(call_id),
plugin=_field(plugin, 64),
))
await session.commit()
return True
async def mark_cleared(user_id: int, session_id: str | None, rule_id: int) -> bool:
"""Stamp the session's latest uncleared stop of this rule as cleared by a
read. A stop older than the open window was made to a context that is
gone, and stays uncleared."""
sid = rule_deliveries.clean_session(session_id)
if not sid or not rule_id:
return False
now = datetime.now(timezone.utc)
async with async_session() as session:
latest = (await session.execute(
select(GateStop.id).where(
GateStop.user_id == user_id, GateStop.session_id == sid,
GateStop.rule_id == int(rule_id), GateStop.cleared_at.is_(None),
GateStop.stopped_at >= now - rule_deliveries.OPEN_WINDOW,
).order_by(GateStop.stopped_at.desc(), GateStop.id.desc()).limit(1)
)).scalar_one_or_none()
if latest is None:
return False
await session.execute(update(GateStop).where(GateStop.id == latest).values(cleared_at=now))
await session.commit()
return True
async def mark_ran(user_id: int, session_id: str | None, call_id: str | None) -> bool:
"""Stamp the stop of this tool call as having run after all."""
sid = rule_deliveries.clean_session(session_id)
cid = _field(call_id)
if not sid or not cid:
return False
async with async_session() as session:
result = await session.execute(
update(GateStop).where(
GateStop.user_id == user_id, GateStop.session_id == sid,
GateStop.call_id == cid, GateStop.ran_at.is_(None),
).values(ran_at=datetime.now(timezone.utc))
)
await session.commit()
return bool(result.rowcount)
def _misfired():
"""Whether the session reported the stopped rule as a misfire."""
return exists().where(
RuleAdherence.user_id == GateStop.user_id,
RuleAdherence.session_id == GateStop.session_id,
RuleAdherence.rule_id == GateStop.rule_id,
RuleAdherence.source == MISFIRE,
)
def _count(cond):
return func.sum(case((cond, 1), else_=0))
async def summary(user_id: int, days: int = 30, *, since: datetime | None = None,
until: datetime | None = None) -> dict:
"""How often each gate stood in front of this user's tool calls over the
last `days`, or over [`since`, `until`).
`by_gate`: per gate, `stops` (calls denied, or put to the operator for
the fence), `let_through` (calls a hold would have stopped once the
session's stop budget was spent), `cleared` (stops the session cleared
by opening the rule), `misfired` (stops whose rule the session then
reported with `rule_misfired`), `ran` (stopped calls that ran after all:
for the fence, the operator's yes) and `sessions`.
`by_rule`: the same per rule and place, most stops first. `fence`: the
asks per tool and target project. `complete_from` is the first stop ever
recorded, so a window reaching further back says so.
"""
until = until or datetime.now(timezone.utc)
if since is None:
days = max(1, min(int(days or 30), rule_deliveries.RETAIN_DAYS))
since = until - timedelta(days=days)
else:
days = round((until - since).total_seconds() / 86400, 2)
window = and_(GateStop.user_id == user_id, GateStop.stopped_at >= since,
GateStop.stopped_at < until)
stopped = GateStop.outcome.in_((STOPPED, ASKED))
counts = (
_count(stopped),
_count(GateStop.outcome == LET_THROUGH),
_count(and_(stopped, GateStop.cleared_at.is_not(None))),
_count(and_(stopped, _misfired())),
_count(and_(stopped, GateStop.ran_at.is_not(None))),
)
async with async_session() as session:
gate_rows = (await session.execute(
select(GateStop.gate, *counts, func.count(func.distinct(GateStop.session_id)))
.where(window).group_by(GateStop.gate)
)).all()
rule_rows = (await session.execute(
select(GateStop.rule_id, GateStop.gate, GateStop.at, Rule.title, *counts,
func.count(func.distinct(GateStop.session_id)),
func.max(GateStop.stopped_at))
.outerjoin(Rule, Rule.id == GateStop.rule_id)
.where(window, GateStop.rule_id.is_not(None))
.group_by(GateStop.rule_id, GateStop.gate, GateStop.at, Rule.title)
.order_by(_count(stopped).desc(), GateStop.rule_id)
.limit(_BY_RULE_LIMIT)
)).all()
fence_rows = (await session.execute(
select(GateStop.tool, GateStop.target, func.count(GateStop.id),
_count(GateStop.ran_at.is_not(None)))
.where(window, GateStop.gate == FENCE)
.group_by(GateStop.tool, GateStop.target)
.order_by(func.count(GateStop.id).desc(), GateStop.tool)
)).all()
first = (await session.execute(
select(func.min(GateStop.stopped_at)).where(GateStop.user_id == user_id)
)).scalar_one_or_none()
def block(s, lt, cl, mis, ran) -> dict:
return {"stops": int(s or 0), "let_through": int(lt or 0), "cleared": int(cl or 0),
"misfired": int(mis or 0), "ran": int(ran or 0)}
by_gate = {g: {**block(0, 0, 0, 0, 0), "sessions": 0} for g in GATES}
for gate, s, lt, cl, mis, ran, sessions in gate_rows:
if gate in by_gate:
by_gate[gate] = {**block(s, lt, cl, mis, ran), "sessions": int(sessions or 0)}
return {
"days": days,
"by_gate": by_gate,
"by_rule": [
{"rule_id": int(rid), "gate": gate, "at": at, "title": title,
**block(s, lt, cl, mis, ran), "sessions": int(sessions or 0),
"last_stopped_at": last.isoformat() if last else None}
for rid, gate, at, title, s, lt, cl, mis, ran, sessions, last in rule_rows
],
"fence": [
{"tool": tool, "target": target, "asks": int(n or 0), "ran": int(ran or 0)}
for tool, target, n, ran in fence_rows
],
"complete_from": first.isoformat() if first else None,
"covers_window": None if first is None else first <= since,
}
async def prune(cutoff: datetime) -> int:
async with async_session() as session:
result = await session.execute(delete(GateStop).where(GateStop.stopped_at < cutoff))
await session.commit()
return int(result.rowcount or 0)
+5 -1
View File
@@ -406,7 +406,7 @@ async def reply_hold(
holds a session once. Past the act checkpoint's per-session cap nothing holds a session once. Past the act checkpoint's per-session cap nothing
holds — a mis-set bar degrades to a quiet session, never a stuck one. holds — a mis-set bar degrades to a quiet session, never a stuck one.
Returns {} or {"reason", "rule_ids", "moments"}. Fails open to {}. Returns {} or {"reason", "rule_ids", "rule_at", "moments"}. Fails open to {}.
""" """
from grimoire.services import plugin_context as pc from grimoire.services import plugin_context as pc
from grimoire.services import rule_usage, rulebooks from grimoire.services import rule_usage, rulebooks
@@ -470,6 +470,10 @@ async def reply_hold(
return { return {
"reason": reply_hold_reason(out), "reason": reply_hold_reason(out),
"rule_ids": [item["rule_id"] for item in out], "rule_ids": [item["rule_id"] for item in out],
# Where each held rule was reached, beside `rule_ids`: the moment
# it is mounted on, or the reply arm that matched it. The hook
# reports each hold with it (`gate_stops`).
"rule_at": [item.get("moment") or rp.REPLY_RULE.source for item in out],
"moments": names, "moments": names,
} }
except Exception: # noqa: BLE001 - a recall aid never stops a session by failing except Exception: # noqa: BLE001 - a recall aid never stops a session by failing
+5 -2
View File
@@ -1914,15 +1914,18 @@ def act_decision(reached: list[tuple], *, held: frozenset[int] = frozenset()) ->
checkpoint. checkpoint.
- Otherwise `{}`: the act goes ahead, with any lines beside it. - Otherwise `{}`: the act goes ahead, with any lines beside it.
`at` is where the deciding rule was reached (a moment, or the trigger),
which the plugin reports with the stop (`gate_stops`).
A preference never refuses or holds (`rule_order.force`). A preference never refuses or holds (`rule_order.force`).
""" """
enforced = [item for item in reached if rule_order.force(item[0]) == "enforce"] enforced = [item for item in reached if rule_order.force(item[0]) == "enforce"]
if enforced: if enforced:
return {"kind": "enforce", "rule_ids": [rule.id for rule, _a, _w in enforced], return {"kind": "enforce", "rule_ids": [rule.id for rule, _a, _w in enforced],
"reason": enforce_reason(enforced)} "at": enforced[0][1], "reason": enforce_reason(enforced)}
for rule, at, where in reached: for rule, at, where in reached:
if rule_order.force(rule) == "hold" and rule.id not in held: if rule_order.force(rule) == "hold" and rule.id not in held:
return {"kind": "hold", "rule_ids": [rule.id], return {"kind": "hold", "rule_ids": [rule.id], "at": at,
"reason": hold_reason(rule, at=at, where=where)} "reason": hold_reason(rule, at=at, where=where)}
return {} return {}
@@ -1781,6 +1781,17 @@ async def retrieval_summary(
out["record_reach"] = None out["record_reach"] = None
out["record_reach_failed"] = True out["record_reach_failed"] = True
# How often each gate stood in front of a tool call, and what followed.
# Its own guard, for record_reach's reason.
try:
from grimoire.services import gate_stops
out["gates"] = (await gate_stops.summary(user_id, since=since, until=until)
if user_id else None)
except Exception:
logger.exception("gate stops read failed")
out["gates"] = None
out["gates_failed"] = True
# ── Judged lines ───────────────────────────────────────────────────── # ── Judged lines ─────────────────────────────────────────────────────
# #
# The relevance readout the usage blocks cannot be: a reviewer's verdict # The relevance readout the usage blocks cannot be: a reviewer's verdict
+4 -2
View File
@@ -262,7 +262,8 @@ async def retired(user_id: int, rule_ids: list[int]) -> set[int]:
async def prune(retain_days: int = RETAIN_DAYS) -> int: async def prune(retain_days: int = RETAIN_DAYS) -> int:
"""Delete deliveries older than `retain_days`, the adherence verdicts on """Delete deliveries older than `retain_days`, the adherence verdicts on
them (`rule_adherence`), which mean nothing without their delivery, and them (`rule_adherence`), which mean nothing without their delivery, and
the record deliveries of the same age (`record_deliveries`).""" the record deliveries and gate stops of the same age (`record_deliveries`,
`gate_stops`)."""
from grimoire.services import rule_adherence from grimoire.services import rule_adherence
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days) cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
@@ -272,8 +273,9 @@ async def prune(retain_days: int = RETAIN_DAYS) -> int:
) )
await session.commit() await session.commit()
await rule_adherence.prune(cutoff) await rule_adherence.prune(cutoff)
from grimoire.services import record_deliveries from grimoire.services import gate_stops, record_deliveries
await record_deliveries.prune(cutoff) await record_deliveries.prune(cutoff)
await gate_stops.prune(cutoff)
return int(result.rowcount or 0) return int(result.rowcount or 0)
+58 -15
View File
@@ -68,31 +68,62 @@ def _evidence_note(evidence: dict) -> str:
return f" ({'; '.join(parts)})" if parts else "" return f" ({'; '.join(parts)})" if parts else ""
def note_text(unjudged: list[dict], *, project_id: int, repo: str) -> str: def _shape_lines(items: list[dict], *, project_id: int) -> list[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
longer version of what each verdict means.
"""
lines = [] lines = []
for item in unjudged[:_LISTED]: for item in items[:_LISTED]:
new = " — new" if item.get("status") == "new" else "" new = " — new" if item.get("status") == "new" else ""
lines.append( lines.append(
f"- {item['path']} · {item['symbol']} ({item['kind']}){new}" f"- {item['path']} · {item['symbol']} ({item['kind']}){new}"
f"{_evidence_note(item.get('evidence') or {})}" f"{_evidence_note(item.get('evidence') or {})}"
) )
more = len(unjudged) - _LISTED more = len(items) - _LISTED
if more > 0: if more > 0:
lines.append(f"- … and {more} more (list_shapes(project_id={project_id}, path=…) shows them)") lines.append(f"- … and {more} more (list_shapes(project_id={project_id}, path=…) shows them)")
return lines
def _count(n: int) -> str:
return f"{n} definition{'s' if n != 1 else ''}"
def note_text(unjudged: list[dict], *, project_id: int, repo: str,
earlier: list[dict] | None = None) -> str:
"""What the agent reads at the start of the turn after one that wrote
unjudged shapes.
``earlier`` is what this session wrote in an earlier turn, was asked
about, and walked past. The per-turn ledger forgets a line once its note
has been answered, and nothing else names a shape by name — the coverage
line carries only a count — so the hook carries walked-past lines into
a bounded number of later asks. The note says plainly that they are a
repeat, and why.
Phrased as a practice: what to decide and the one
call that records it, not a prohibition. The reusing-code skill owns the
longer version of what each verdict means.
"""
earlier = earlier or []
parts = []
if unjudged:
parts.append(
f"Your last turn wrote {_count(len(unjudged))} that nobody has judged yet. "
"You built them, so you know what each one is — 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(_shape_lines(unjudged, project_id=project_id))
)
if earlier:
verb = "is" if len(earlier) == 1 else "are"
parts.append(
f"{'Also: ' if unjudged else ''}{_count(len(earlier))} you wrote earlier in this "
f"session {verb} still unjudged. You were asked and moved on; nothing else will "
"name them again, so they are asked once more while you still know what they "
"are:\n"
+ "\n".join(_shape_lines(earlier, project_id=project_id))
)
repo_arg = f', repo="{repo}"' if repo else "" repo_arg = f', repo="{repo}"' if repo else ""
return ( return (
f"Your last turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} " "\n\n".join(parts)
"that nobody has judged yet. You built them, so you know what each one is — "
"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 " + "\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 " "with create_snippet (name, code, when to reach for it, location); built from a "
"recorded snippet → `instance` of it; a deliberate departure from one → " "recorded snippet → `instance` of it; a deliberate departure from one → "
@@ -105,6 +136,13 @@ def note_text(unjudged: list[dict], *, project_id: int, repo: str) -> str:
) )
def ledger_lines(items: list[dict]) -> str:
"""``items`` back as the hook's own `path<TAB>kind<TAB>name` lines — what
the after phase hands the hook so it can carry the walked-past shapes
forward without parsing a JSON list in shell."""
return "\n".join(f"{i['path']}\t{i['kind']}\t{i['symbol']}" for i in items)
async def record_shape_check( async def record_shape_check(
user_id: int | None, user_id: int | None,
outcome: str, outcome: str,
@@ -112,12 +150,17 @@ async def record_shape_check(
written: int, written: int,
unjudged: int, unjudged: int,
project_id: int | None = None, project_id: int | None = None,
earlier: int = 0,
) -> None: ) -> None:
if outcome not in OUTCOMES: if outcome not in OUTCOMES:
raise ValueError(f"unknown shape-check outcome {outcome!r}") raise ValueError(f"unknown shape-check outcome {outcome!r}")
details: dict = {"outcome": outcome, "written": written, "unjudged": unjudged} details: dict = {"outcome": outcome, "written": written, "unjudged": unjudged}
if project_id: if project_id:
details["project_id"] = project_id details["project_id"] = project_id
# How many of `unjudged` were carried from an earlier turn's walked-past
# ask — so a window can tell a fresh ask from a repeat.
if earlier:
details["earlier"] = earlier
async with async_session() as session: async with async_session() as session:
session.add(AppLog( session.add(AppLog(
category="plugin", category="plugin",
+25 -10
View File
@@ -303,8 +303,21 @@ async def _titles(ids: list[int]) -> dict[int, str]:
def _named(project_id: int, titles: dict[int, str]) -> str: def _named(project_id: int, titles: dict[int, str]) -> str:
title = titles.get(project_id) return titles.get(project_id) or f"project {project_id}"
return f"{title} (project {project_id})" if title else f"project {project_id}"
def _doing(tool: str, act: str) -> str:
"""The act in words a person reads at a glance: "Retire family idea",
"git push", "Editing a file". A tool name is spelled out, not quoted."""
act = act.strip()
if act.endswith(" in"):
act = act[:-3]
if act:
return act[:1].upper() + act[1:]
if tool:
words = tool.replace("_", " ").strip()
return words[:1].upper() + words[1:]
return "This change"
async def check_act( async def check_act(
@@ -343,22 +356,24 @@ async def check_act(
targets = [{"id": p, "title": titles.get(p, "")} for p in others] targets = [{"id": p, "title": titles.get(p, "")} for p in others]
if tool and is_issue_filing(tool, args): if tool and is_issue_filing(tool, args):
return {"allowed": True, "targets": targets, "issue": True, "reason": ""} return {"allowed": True, "targets": targets, "issue": True, "reason": ""}
# The reason is the permission prompt's text: the operator reads it
# first, so it leads with what changes and where, then when to approve.
# The session reads it after a "no", so the last line is for the agent.
there = ", ".join(_named(p, titles) for p in others) there = ", ".join(_named(p, titles) for p in others)
home = _named(session_project, titles)
if tool in RULE_CURATION_TOOLS: if tool in RULE_CURATION_TOOLS:
rules = sorted({r for name in _RULE_ARGS for r in _positive_ints(args.get(name))}) rules = sorted({r for name in _RULE_ARGS for r in _positive_ints(args.get(name))})
which = ", ".join(f"rule {r}" for r in rules) or "a rule" which = ", ".join(f"rule {r}" for r in rules) or "a rule"
reason = ( reason = (
f"This session belongs to {_named(session_project, titles)}. {tool} changes " f"Changing {which} in {there}, but this session is working in {home}.\n"
f"{which} of {there}, a different project. Rules are the operator's to " "Rules are yours to curate from any session. Approve if you asked for this change."
f"curate from any session: approve if they asked for this change."
) )
return {"allowed": False, "targets": targets, "issue": False, "reason": reason} return {"allowed": False, "targets": targets, "issue": False, "reason": reason}
what = act.strip() or (f"{tool} changes" if tool else "This changes")
first = others[0] first = others[0]
reason = ( reason = (
f"This session belongs to {_named(session_project, titles)}. {what} {there}, " f"{_doing(tool, act)} in {there}, but this session is working in {home}.\n"
f"a different project. From here, the one change to make there is filing an " f"Approve only if you asked for this change to {there}.\n"
f"issue: create_task(project_id={first}, kind=\"issue\") with how it was found " f"(If not: the agent can report it there instead, with "
f"and the evidence. Approve only if this session should change {there} itself." f"create_task(project_id={first}, kind=\"issue\").)"
) )
return {"allowed": False, "targets": targets, "issue": False, "reason": reason} return {"allowed": False, "targets": targets, "issue": False, "reason": reason}
+36
View File
@@ -161,3 +161,39 @@ async def test_re_saving_a_closed_milestone_asks_nothing():
out = await update_milestone(project_id=3, milestone_id=5, status="done") out = await update_milestone(project_id=3, milestone_id=5, status="done")
assert "family_hint" not in out assert "family_hint" not in out
trigger.assert_not_awaited() trigger.assert_not_awaited()
def test_a_lineage_word_inside_a_quoted_title_is_not_lineage():
"""Records are cited with their titles beside them; a title's words
describe THAT record, so they cannot claim the next citation's lineage."""
text = ('- Tasks: #3510 "Release parsing and matching, verified", #7407 "Downloads", '
'#20 “mirrors the old flow”, #30')
assert lineage_citations(text) == []
# The convention itself still reads: a lineage word outside the quotes.
assert lineage_citations('Ported from #12 "Signed APK lane".') == [12]
@pytest.mark.parametrize(("title", "project", "about"), [
("Storehouse: start here", "Storehouse", True),
("Torn Stars — Economy System", "Torn Stars", True),
("storehouse", "Storehouse", True),
("Syncthing relay", "Sync", False),
("Signed APK lane", "Storehouse", False),
("Storehouse: start here", "", False),
])
def test_a_record_named_for_its_own_project_is_about_that_project(title, project, about):
from grimoire.services.family import about_its_own_project
assert about_its_own_project(title, project) is about
def test_only_knowledge_and_shapes_not_about_one_project_can_carry_an_idea():
from grimoire.services.family import can_carry_idea
kw = dict(title="Signed APK lane", project_title="android one")
assert can_carry_idea(is_task=False, note_type="note", **kw)
assert can_carry_idea(is_task=False, note_type="snippet", **kw)
assert not can_carry_idea(is_task=True, note_type="note", **kw)
assert not can_carry_idea(is_task=False, note_type="lesson", **kw)
assert not can_carry_idea(is_task=False, note_type="note",
title="android one: start here", project_title="android one")
+12
View File
@@ -97,3 +97,15 @@ def test_every_surface_that_meets_family_canon_points_at_the_skill():
assert "`family`" in tool_doc("grimoire.mcp.tools.projects", "enter_project") assert "`family`" in tool_doc("grimoire.mcp.tools.projects", "enter_project")
assert "family_owed" in tool_doc("grimoire.mcp.tools.tasks", "update_task") assert "family_owed" in tool_doc("grimoire.mcp.tools.tasks", "update_task")
assert "family_owed" in skill_text("reporting-back") assert "family_owed" in skill_text("reporting-back")
def test_the_line_names_this_projects_own_unevaluated_candidates():
cand = {"count": 3, "ideas": [{"id": 7, "title": "Signed APK lane"},
{"id": 9, "title": "Outbox"}]}
line = family_line(5, [], cand)
assert line["candidates"] == 3
assert line["line"].endswith("3 of this project's own records proposed as family ideas, never evaluated")
call = line["calls"]["candidates"]
assert '#7 "Signed APK lane", #9 "Outbox"' in call and "and 1 more" in call
assert "promote_family_idea" in call and "retire_family_idea" in call
assert family_line(5, [], {"count": 0, "ideas": []}) is None
+235
View File
@@ -0,0 +1,235 @@
"""Every gate that stands in front of a tool call reports it, end to end.
The moment hook (a rule set to enforce or hold), the act checkpoint on a
command and the project fence are run through a real shell against a
stand-in server. Each stop is posted to `/api/plugin/gate-stop` with what
the hook did: `stopped`, `let_through` when the session's stop budget is
spent, or `asked` for the fence. A fenced call that then runs is posted to
`/api/plugin/gate-ran` by grimoire_fence_ran.sh, matched by the call's id.
"""
from __future__ import annotations
import json
import os
import subprocess
from pathlib import Path
from tests.helpers import http_sink, need_tools
HOOKS = Path(__file__).resolve().parents[1] / "plugin" / "hooks"
MOMENT = HOOKS / "grimoire_moment.sh"
TOOL_RULES = HOOKS / "grimoire_tool_rules.sh"
FENCE = HOOKS / "grimoire_project_fence.sh"
FENCE_RAN = HOOKS / "grimoire_fence_ran.sh"
STOP = "/api/plugin/gate-stop"
RAN = "/api/plugin/gate-ran"
REPLY_CHECK = HOOKS / "grimoire_reply_check.sh"
TOOLS = {"/api/plugin/moment-tools": b'{"tools":["bash"]}'}
def _env(tmp_path, port, **extra):
return {"PATH": os.environ["PATH"], "GRIMOIRE_URL": f"http://127.0.0.1:{port}",
"GRIMOIRE_TOKEN": "t", "TMPDIR": str(tmp_path / "tmp"), "HOME": str(tmp_path), **extra}
def _run(hook, tmp_path, port, event, **extra):
need_tools("bash", "curl", "awk")
(tmp_path / "tmp").mkdir(exist_ok=True)
out = subprocess.run(["bash", str(hook)], input=json.dumps(event), capture_output=True,
text=True, env=_env(tmp_path, port, **extra), timeout=30)
assert out.returncode == 0, out.stderr
return out.stdout.strip()
def _bash_event(session="s-gate", call="toolu_1", command="git push origin dev", cwd="."):
return {"session_id": session, "cwd": cwd, "hook_event_name": "PreToolUse",
"tool_name": "Bash", "tool_use_id": call, "tool_input": {"command": command}}
def _stops(seen):
return [json.loads(e["_body"]) for e in seen if e.get("_path") == STOP]
def _denied(out):
return json.loads(out)["hookSpecificOutput"].get("permissionDecision") == "deny"
def _moment_replies(decision):
replies = dict(TOOLS)
replies["/api/plugin/moment"] = json.dumps(
{"context": "", "rule_ids": [], "moments": ["work.deliver"], "decision": decision}).encode()
return replies
# ── the moment hook ──────────────────────────────────────────────────────
def test_an_enforced_refusal_is_reported_every_time_with_where_it_was_reached(tmp_path):
decision = {"kind": "enforce", "rule_ids": [6], "at": "work.deliver", "reason": "Not run: rule 6"}
with http_sink(by_path=_moment_replies(decision)) as (port, seen):
outs = [_run(MOMENT, tmp_path, port, _bash_event(call=f"toolu_{i}"), CLAUDE_PROJECT_DIR=str(tmp_path))
for i in range(2)]
assert all(_denied(o) for o in outs)
stops = _stops(seen)
assert [s["call_id"] for s in stops] == ["toolu_0", "toolu_1"]
assert stops[0] == {"session_id": "s-gate", "gate": "enforce", "outcome": "stopped",
"tool": "bash", "rule_id": 6, "at": "work.deliver", "call_id": "toolu_0"}
def test_a_hold_is_reported_once_and_its_repeat_is_not_a_cap_let_through(tmp_path):
"""The per-rule once is the hold working as meant, so the second call on
the same rule reports nothing: only a spent session budget is a call the
cap let through."""
decision = {"kind": "hold", "rule_ids": [7], "at": "work.deliver", "reason": "Read rule 7"}
with http_sink(by_path=_moment_replies(decision)) as (port, seen):
first = _run(MOMENT, tmp_path, port, _bash_event(call="toolu_a"))
second = _run(MOMENT, tmp_path, port, _bash_event(call="toolu_b"))
assert _denied(first)
assert second == ""
assert [(s["gate"], s["outcome"], s["rule_id"]) for s in _stops(seen)] == [("hold", "stopped", 7)]
def test_a_hold_the_spent_session_budget_lets_through_is_reported_as_such(tmp_path):
state = tmp_path / "tmp" / "grimoire-priorart"
state.mkdir(parents=True)
(state / "s-gate.checkpoint.ids").write_text("1\n2\n3\n4\n5\n")
decision = {"kind": "hold", "rule_ids": [7], "at": "work.deliver", "reason": "Read rule 7"}
with http_sink(by_path=_moment_replies(decision)) as (port, seen):
out = _run(MOMENT, tmp_path, port, _bash_event())
assert out == ""
assert [(s["gate"], s["outcome"], s["rule_id"]) for s in _stops(seen)] == [("hold", "let_through", 7)]
def test_a_call_no_gate_stops_reports_nothing(tmp_path):
with http_sink(by_path=_moment_replies({})) as (port, seen):
_run(MOMENT, tmp_path, port, _bash_event())
assert _stops(seen) == []
# ── the act checkpoint ───────────────────────────────────────────────────
def _checkpoint_replies(rule_id=9):
return {"/api/plugin/tool-rules": json.dumps(
{"context": "", "rule_ids": [rule_id],
"checkpoint": {"rule_id": rule_id, "reason": f"Read rule {rule_id} first"}}).encode()}
def test_a_checkpoint_stop_is_reported_with_the_tool_and_the_arm(tmp_path):
with http_sink(by_path=_checkpoint_replies()) as (port, seen):
out = _run(TOOL_RULES, tmp_path, port, _bash_event(command="git commit -m x", cwd=str(tmp_path)))
assert _denied(out)
assert _stops(seen) == [{"session_id": "s-gate", "gate": "checkpoint", "outcome": "stopped",
"tool": "Bash", "rule_id": 9, "at": "pre_tool_rule", "call_id": "toolu_1"}]
def test_a_checkpoint_past_the_session_cap_is_reported_as_let_through(tmp_path):
state = tmp_path / "tmp" / "grimoire-priorart"
state.mkdir(parents=True)
(state / "s-gate.checkpoint.ids").write_text("1\n2\n3\n4\n5\n")
with http_sink(by_path=_checkpoint_replies()) as (port, seen):
out = _run(TOOL_RULES, tmp_path, port, _bash_event(command="git commit -m x", cwd=str(tmp_path)))
assert out == ""
assert [(s["gate"], s["outcome"]) for s in _stops(seen)] == [("checkpoint", "let_through")]
# ── the project fence ────────────────────────────────────────────────────
HOME_URL = "https://forge.example/team/home.git"
ASK = json.dumps({"allowed": False, "targets": [{"id": 9, "title": "Other"}], "issue": False,
"reason": "Retire family idea in Other, but this session is working in Home."}).encode()
def _home(tmp_path):
home = tmp_path / "home"
home.mkdir()
subprocess.run(["git", "init", "-q"], cwd=home, check=True)
subprocess.run(["git", "remote", "add", "origin", HOME_URL], cwd=home, check=True)
return home
def _grimoire_write(home, call="toolu_f"):
return {"session_id": "s-gate", "cwd": str(home), "hook_event_name": "PreToolUse",
"tool_name": "mcp__plugin_grimoire_grimoire__retire_family_idea",
"tool_use_id": call, "tool_input": {"idea_id": 188, "why": "x"}}
def _ran(home, call):
return {"session_id": "s-gate", "cwd": str(home), "hook_event_name": "PostToolUse",
"tool_name": "mcp__plugin_grimoire_grimoire__retire_family_idea",
"tool_use_id": call, "tool_input": {"idea_id": 188}, "tool_response": {}}
def test_a_fence_ask_is_reported_and_the_run_after_a_yes_is_matched_to_it(tmp_path):
need_tools("git")
home = _home(tmp_path)
with http_sink(by_path={"/api/plugin/write-scope": ASK}) as (port, seen):
out = _run(FENCE, tmp_path, port, _grimoire_write(home), CLAUDE_PROJECT_DIR=str(home))
assert json.loads(out)["hookSpecificOutput"]["permissionDecision"] == "ask"
# Another call ran in between: not the one asked about.
_run(FENCE_RAN, tmp_path, port, _ran(home, "toolu_other"))
_run(FENCE_RAN, tmp_path, port, _ran(home, "toolu_f"))
# Matched once; the same id again reports nothing.
_run(FENCE_RAN, tmp_path, port, _ran(home, "toolu_f"))
assert _stops(seen) == [{"session_id": "s-gate", "gate": "fence", "outcome": "asked",
"tool": "retire_family_idea", "rule_id": None,
"at": "retire_family_idea", "target": "9", "call_id": "toolu_f"}]
ran = [json.loads(e["_body"]) for e in seen if e["_path"] == RAN]
assert ran == [{"session_id": "s-gate", "call_id": "toolu_f"}]
def test_with_no_ask_pending_the_after_call_hook_sends_nothing(tmp_path):
with http_sink() as (port, seen):
out = _run(FENCE_RAN, tmp_path, port, _ran(tmp_path, "toolu_x"))
assert out == "" and seen == []
def test_the_after_call_hook_is_registered_only_after_calls_and_on_the_fenced_tools():
"""It must never run before a call: it has nothing to decide there, and the
fence itself is what answers a PreToolUse."""
hooks = json.loads((HOOKS / "hooks.json").read_text())["hooks"]
def matchers(event):
return [m.get("matcher") for m in hooks.get(event, [])
for h in m["hooks"] if "grimoire_fence_ran.sh" in h["command"]]
fence_pre = [m.get("matcher") for m in hooks["PreToolUse"]
for h in m["hooks"] if "grimoire_project_fence.sh" in h["command"]]
assert matchers("PreToolUse") == []
assert matchers("PostToolUse") == fence_pre
# ── the reply hold ───────────────────────────────────────────────────────
def _transcript(tmp_path, reply):
lines = [
{"type": "user", "message": {"role": "user", "content": "is it finished?"}},
{"type": "assistant", "message": {"content": [{"type": "text", "text": reply}]}},
]
path = tmp_path / "t.jsonl"
path.write_text("\n".join(json.dumps(x, separators=(",", ":")) for x in lines) + "\n")
return path
def _stop(tmp_path, transcript):
return {"session_id": "s-gate", "transcript_path": str(transcript), "cwd": str(tmp_path),
"hook_event_name": "Stop", "stop_hook_active": False}
def test_each_rule_that_holds_a_reply_is_reported_with_where_it_was_reached(tmp_path):
held = json.dumps({"reason": "Held for one read.", "rule_ids": [11, 40],
"rule_at": ["reply.report", "reply_rule"],
"moments": ["reply.report"]}).encode()
with http_sink(by_path={"/api/plugin/reply-rules": held}) as (port, seen):
out = _run(REPLY_CHECK, tmp_path, port, _stop(tmp_path, _transcript(tmp_path, "All done.")))
assert json.loads(out)["decision"] == "block"
assert [(s["gate"], s["outcome"], s["tool"], s["rule_id"], s["at"]) for s in _stops(seen)] == [
("reply", "stopped", "reply", 11, "reply.report"),
("reply", "stopped", "reply", 40, "reply_rule"),
]
def test_a_section_hold_names_no_rule_and_reports_no_gate_stop(tmp_path):
"""The completion-section check has its own record (`report_check`)."""
sections = b'{"reason":"Add the sections.","rule_ids":[],"moments":[],"report_check":"blocked"}'
with http_sink(by_path={"/api/plugin/reply-rules": sections}) as (port, seen):
_run(REPLY_CHECK, tmp_path, port, _stop(tmp_path, _transcript(tmp_path, "All done.")))
assert _stops(seen) == []
@@ -396,3 +396,49 @@ async def test_someone_who_cannot_write_the_idea_cannot_link_it(family, topics):
await _promote(family) await _promote(family)
with pytest.raises(ValueError, match="no write access"): with pytest.raises(ValueError, match="no write access"):
await family_svc.set_topic(family["outsider"], family["note"], topics["spare"]) await family_svc.set_topic(family["outsider"], family["note"], topics["spare"])
async def test_a_citation_of_a_task_or_of_a_projects_own_overview_is_silent(family):
"""A task is work in one project and an overview describes one project:
neither carries a shared idea, so citing either with a lineage word opens
nothing."""
async with async_session() as s:
task = Note(user_id=family["owner"], project_id=family["a"], status="todo",
title="Ship the signed lane", body="do it")
overview = Note(user_id=family["owner"], project_id=family["a"],
title="android one: start here", body="what the project is")
s.add_all([task, overview])
await s.commit()
ids = (task.id, overview.id)
for source in ids:
citing = await _note_in(family["b"], family["owner"], f"Matching #{source}.")
assert await family_svc.citation_trigger(family["owner"], citing) is None
assert await _idea(source) is None
async def test_a_repeat_of_a_projects_own_overview_is_silent(family):
async with async_session() as s:
overview = Note(user_id=family["owner"], project_id=family["a"],
title="android one: start here", body="One keystore, two channels.")
s.add(overview)
await s.commit()
await s.refresh(overview)
repeat = await _note_in(family["b"], family["owner"], "One keystore, two channels.")
with patch("grimoire.services.embeddings.semantic_search_notes",
AsyncMock(return_value=[(0.9, overview)])):
assert await family_svc.repeat_trigger(family["owner"], repeat) is None
assert await _idea(overview.id) is None
async def test_a_candidate_counts_as_unevaluated_until_someone_other_than_the_system_decides(family):
await family_svc.propose(family["owner"], family["note"], reason="opened by a trigger",
trigger="repeat", decided_via="system")
got = await family_svc.unevaluated_candidates(family["owner"], family["a"])
assert got == {"count": 1, "ideas": [{"id": family["note"], "title": "Signed APK lane"}]}
assert (await family_svc.unevaluated_candidates(family["owner"], family["b"]))["count"] == 0
# An agent's evaluation that holds it as a candidate is an evaluation.
await family_svc.promote(family["owner"], family["note"], applies_when="",
platforms=["android-app"], criteria={}, evidence=[],
reason="held: not stated for the platform")
assert (await _idea(family["note"])).status == "candidate"
assert (await family_svc.unevaluated_candidates(family["owner"], family["a"]))["count"] == 0
+122
View File
@@ -0,0 +1,122 @@
"""Real-Postgres tests for `gate_stops`: each time a gate stood in front of a
tool call, the read that cleared it, the run that followed a yes, and the
readout per gate and per rule."""
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import delete, select, update
from grimoire.models import async_session
from grimoire.models.gate_stop import GateStop
from grimoire.models.rule_adherence import MISFIRE, NOT_APPLICABLE, RuleAdherence
from grimoire.services import gate_stops, rule_adherence
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
RULE = 9_300_001
OTHER = 9_300_002
async def _user(name: str = "gate_stop_owner") -> int:
async with async_session() as s:
user = await ensure_user(s, name)
uid = user.id
await s.commit()
await s.execute(delete(GateStop).where(GateStop.user_id == uid))
await s.execute(delete(RuleAdherence).where(RuleAdherence.user_id == uid))
await s.commit()
return uid
async def _rows(uid) -> list[GateStop]:
async with async_session() as s:
return list((await s.execute(
select(GateStop).where(GateStop.user_id == uid).order_by(GateStop.id)
)).scalars().all())
async def test_a_stop_without_a_session_gate_or_rule_records_nothing():
uid = await _user()
assert not await gate_stops.record(uid, "", gate="hold", outcome="stopped", tool="bash", rule_id=RULE)
assert not await gate_stops.record(uid, "s", gate="nonsense", outcome="stopped", tool="bash", rule_id=RULE)
assert not await gate_stops.record(uid, "s", gate="hold", outcome="stopped", tool="bash")
# The fence is the one gate with no rule behind it.
assert await gate_stops.record(uid, "s", gate="fence", outcome="asked", tool="update_task", target="9")
assert [(r.gate, r.rule_id, r.target) for r in await _rows(uid)] == [("fence", None, "9")]
async def test_an_open_clears_the_latest_stop_of_that_rule_in_that_session_only():
uid = await _user()
for sid in ("s-1", "s-2"):
await gate_stops.record(uid, sid, gate="hold", outcome="stopped", tool="bash",
rule_id=RULE, at="work.deliver")
assert await gate_stops.mark_cleared(uid, "s-1", RULE)
# Nothing left to clear for it there, and another rule's open clears nothing.
assert not await gate_stops.mark_cleared(uid, "s-1", RULE)
assert not await gate_stops.mark_cleared(uid, "s-2", OTHER)
cleared = {r.session_id: r.cleared_at is not None for r in await _rows(uid)}
assert cleared == {"s-1": True, "s-2": False}
async def test_an_open_long_after_the_stop_does_not_clear_it():
uid = await _user()
await gate_stops.record(uid, "s-old", gate="checkpoint", outcome="stopped", tool="Bash", rule_id=RULE)
async with async_session() as s:
await s.execute(update(GateStop).where(GateStop.user_id == uid).values(
stopped_at=datetime.now(timezone.utc) - timedelta(days=1)))
await s.commit()
assert not await gate_stops.mark_cleared(uid, "s-old", RULE)
async def test_the_run_after_a_fence_ask_is_matched_by_its_call_id():
uid = await _user()
await gate_stops.record(uid, "s-f", gate="fence", outcome="asked", tool="retire_family_idea",
target="9", call_id="toolu_1")
assert not await gate_stops.mark_ran(uid, "s-f", "toolu_2")
assert await gate_stops.mark_ran(uid, "s-f", "toolu_1")
assert not await gate_stops.mark_ran(uid, "s-f", "toolu_1")
assert (await _rows(uid))[0].ran_at is not None
async def test_the_readout_counts_stops_reads_misfires_and_the_cap_per_gate_and_rule():
uid = await _user()
# Rule RULE held in three sessions: one cleared by a read, one called a
# misfire, one never answered. Then once let through by a spent budget.
for sid in ("a", "b", "c"):
await gate_stops.record(uid, sid, gate="hold", outcome="stopped", tool="bash",
rule_id=RULE, at="work.deliver")
await gate_stops.mark_cleared(uid, "a", RULE)
await rule_adherence.record(uid, "b", RULE, "work.deliver", NOT_APPLICABLE, MISFIRE, "not this act")
await gate_stops.record(uid, "d", gate="hold", outcome="let_through", tool="bash",
rule_id=RULE, at="work.deliver")
await gate_stops.record(uid, "a", gate="checkpoint", outcome="stopped", tool="Bash",
rule_id=OTHER, at="pre_tool_rule")
await gate_stops.record(uid, "a", gate="fence", outcome="asked", tool="update_task",
target="9", call_id="t1")
await gate_stops.record(uid, "a", gate="fence", outcome="asked", tool="update_task",
target="9", call_id="t2")
await gate_stops.mark_ran(uid, "a", "t1")
out = await gate_stops.summary(uid, days=7)
hold = out["by_gate"]["hold"]
assert (hold["stops"], hold["cleared"], hold["misfired"], hold["let_through"], hold["sessions"]) == (3, 1, 1, 1, 4)
assert out["by_gate"]["checkpoint"]["stops"] == 1
assert out["by_gate"]["enforce"] == {"stops": 0, "let_through": 0, "cleared": 0,
"misfired": 0, "ran": 0, "sessions": 0}
assert (out["by_gate"]["fence"]["stops"], out["by_gate"]["fence"]["ran"]) == (2, 1)
first = out["by_rule"][0]
assert (first["rule_id"], first["gate"], first["at"], first["stops"]) == (RULE, "hold", "work.deliver", 3)
assert out["fence"] == [{"tool": "update_task", "target": "9", "asks": 2, "ran": 1}]
assert out["complete_from"] is not None
async def test_stops_age_out_with_the_deliveries():
uid = await _user()
await gate_stops.record(uid, "s", gate="hold", outcome="stopped", tool="bash", rule_id=RULE)
async with async_session() as s:
await s.execute(update(GateStop).where(GateStop.user_id == uid).values(
stopped_at=datetime.now(timezone.utc) - timedelta(days=400)))
await s.commit()
await gate_stops.prune(datetime.now(timezone.utc) - timedelta(days=180))
assert await _rows(uid) == []
+12 -5
View File
@@ -123,6 +123,9 @@ async def test_the_semantic_backstop_holds_and_never_names_a_mounted_rule_twice(
arm, _surfaced, _lookup, stack = _stubs(mounted=[(DONE, "reply.report")], checkpoint=cp) arm, _surfaced, _lookup, stack = _stubs(mounted=[(DONE, "reply.report")], checkpoint=cp)
out = await _hold(stack) out = await _hold(stack)
assert out["rule_ids"] == [11, 40] assert out["rule_ids"] == [11, 40]
# Where each was reached, for the hook's gate report: a mount names its
# moment, the backstop names its arm.
assert out["rule_at"] == ["reply.report", rp.REPLY_RULE.source]
assert "scores 0.84 against this reply" in out["reason"] assert "scores 0.84 against this reply" in out["reason"]
spec, moment = arm.await_args.args spec, moment = arm.await_args.args
assert spec is rp.REPLY_RULE assert spec is rp.REPLY_RULE
@@ -207,7 +210,7 @@ async def test_the_route_passes_the_reply_and_all_three_ledgers():
with patch.object(routes.moment_delivery_svc, "reply_hold", hold): with patch.object(routes.moment_delivery_svc, "reply_hold", hold):
resp = await routes.reply_rules.__wrapped__() resp = await routes.reply_rules.__wrapped__()
body = await resp.get_json() body = await resp.get_json()
assert body == {"reason": "Held.", "rule_ids": [11], "moments": ["reply.report"], assert body == {"reason": "Held.", "rule_ids": [11], "rule_at": [], "moments": ["reply.report"],
"report_check": ""} "report_check": ""}
assert hold.await_args.args == (7, "done") assert hold.await_args.args == (7, "done")
assert hold.await_args.kwargs == { assert hold.await_args.kwargs == {
@@ -304,11 +307,12 @@ def test_the_hook_blocks_in_the_servers_words_and_records_the_hold(tmp_path):
out = json.loads(_run(tmp_path, port, t)) out = json.loads(_run(tmp_path, port, t))
_run(tmp_path, port, t) _run(tmp_path, port, t)
assert out == {"decision": "block", "reason": "Held for one read: get_rule(11)."} assert out == {"decision": "block", "reason": "Held for one read: get_rule(11)."}
sent = json.loads(seen[0]["_body"]) asks = [e for e in seen if e["_path"] == "/api/plugin/reply-rules"]
sent = json.loads(asks[0]["_body"])
assert sent["reply"] == "All done.\nLet me know if it works on your end?" assert sent["reply"] == "All done.\nLet me know if it works on your end?"
# The second turn tells the server what already held. # The second turn tells the server what already held.
assert seen[1]["stopped_rule_ids"] == ["11"] assert asks[1]["stopped_rule_ids"] == ["11"]
assert seen[1]["exclude_rule_ids"] == ["11"] assert asks[1]["exclude_rule_ids"] == ["11"]
def _closing_transcript(tmp_path, *replies): def _closing_transcript(tmp_path, *replies):
@@ -360,7 +364,10 @@ def test_a_rule_hold_on_a_closing_turn_does_not_mark_a_rewrite(tmp_path):
with http_sink(by_path={"/api/plugin/reply-rules": HELD}) as (port, seen): with http_sink(by_path={"/api/plugin/reply-rules": HELD}) as (port, seen):
_run(tmp_path, port, t) _run(tmp_path, port, t)
assert _run(tmp_path, port, t, active=True) == "" assert _run(tmp_path, port, t, active=True) == ""
assert len(seen) == 1 # One reply sent; the rewrite after a rule hold sends nothing. (The hold
# itself is also reported as a gate stop, a separate request.)
assert [e["_path"] for e in seen if e["_path"] == "/api/plugin/reply-rules"] == [
"/api/plugin/reply-rules"]
def test_the_hook_says_nothing_when_nothing_holds(tmp_path): def test_the_hook_says_nothing_when_nothing_holds(tmp_path):
+1
View File
@@ -42,6 +42,7 @@ def test_every_endpoint_is_reachable_on_the_app():
"/api/retrieval/surfaces/<surface>", "/api/retrieval/surfaces/<surface>",
"/api/retrieval/adherence", "/api/retrieval/adherence",
"/api/retrieval/record-reach", "/api/retrieval/record-reach",
"/api/retrieval/gate-stops",
"/api/retrieval/record-kinds", "/api/retrieval/record-kinds",
"/api/retrieval/gate", "/api/retrieval/gate",
"/api/retrieval/tuning-history", "/api/retrieval/tuning-history",
+34
View File
@@ -91,3 +91,37 @@ def test_the_window_counts_turns_asks_and_asks_walked_past():
# A window that spans the end-of-turn hold this check once was still sums. # 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"]) mixed = summarise(["blocked", "left_after_block", "noted", "judged_after_note"])
assert mixed == {"checked": 2, "asked": 2, "left": 1} assert mixed == {"checked": 2, "asked": 2, "left": 1}
def test_the_note_names_walked_past_shapes_apart_from_this_turns():
from grimoire.services.shape_check import note_text
fresh = [{"path": "a.py", "kind": "sym", "symbol": "new_one", "status": "new", "evidence": {}}]
old = [{"path": "b.py", "kind": "sym", "symbol": "old_one", "status": "unclassified",
"evidence": {}}]
both = note_text(fresh, project_id=2, repo="", earlier=old)
assert "last turn wrote 1 definition " in both
assert "Also: 1 definition you wrote earlier in this session is still unjudged" in both
assert both.index("a.py · new_one") < both.index("b.py · old_one")
alone = note_text([], project_id=2, repo="", earlier=old + old)
assert "last turn" not in alone
assert alone.startswith("2 definitions you wrote earlier in this session are still unjudged")
assert "classify_shapes(project_id=2" in alone
def test_the_after_phase_hands_back_ledger_lines():
from grimoire.services.shape_check import ledger_lines
items = [{"path": "a.py", "kind": "sym", "symbol": "f"},
{"path": "w/A.svelte", "kind": "file", "symbol": "A"}]
assert ledger_lines(items) == "a.py\tsym\tf\nw/A.svelte\tfile\tA"
assert ledger_lines([]) == ""
async def test_a_repeat_is_counted_apart_in_the_outcome_record():
from grimoire.services.shape_check import record_shape_check
session = make_mock_session()
with patch("grimoire.services.shape_check.async_session", return_value=session):
await record_shape_check(7, "noted", written=3, unjudged=2, project_id=2, earlier=1)
assert json.loads(session.add.call_args.args[0].details)["earlier"] == 1
+58
View File
@@ -237,3 +237,61 @@ def test_an_unreachable_instance_keeps_the_question_for_later(tmp_path):
ledger = _write_ledger(tmp_path, ["a.py\tsym\thelper"]) ledger = _write_ledger(tmp_path, ["a.py\tsym\thelper"])
assert _stop(env, _repo(tmp_path)) == "" assert _stop(env, _repo(tmp_path)) == ""
assert ledger.exists() assert ledger.exists()
# ── what the agent walked past is asked again, a bounded number of times ──
def _earlier_file(tmp_path, session="s1"):
return tmp_path / "grimoire-shapecheck" / f"{session}.earlier"
def test_a_walked_past_shape_is_named_again_then_dropped(tmp_path):
"""The after phase's `left` becomes the carried set: the next check sends
it as `earlier` even on a turn that wrote nothing, and a shape walked
past more than GRIMOIRE_EARLIER_MAX times stops being asked."""
reply = json.dumps({"status": "ok", "outcome": "noted", "note": NOTE,
"left": "a.py\tsym\tfirst"}).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)
assert seen[-1]["phase"] == ["check"] and "earlier" not in seen[-1]
for walked_past in (1, 2):
_prompt(env, repo)
_stop(env, repo)
after, check = seen[-2], seen[-1]
assert after["phase"] == ["after"]
assert check["phase"] == ["check"]
assert check["earlier"] == ["a.py\tsym\tfirst"]
assert "written" not in check, "this turn wrote nothing; the repeat is named apart"
assert _earlier_file(tmp_path).read_text() == f"{walked_past}\ta.py\tsym\tfirst\n"
_prompt(env, repo)
_stop(env, repo)
assert seen[-1]["phase"] == ["after"], "walked past a third time: not asked again"
assert seen[-1]["earlier"] == ["a.py\tsym\tfirst"]
assert not _earlier_file(tmp_path).exists()
def test_a_carried_shape_this_turn_rewrote_is_this_turns(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}")
_earlier_file(tmp_path).parent.mkdir(parents=True, exist_ok=True)
_earlier_file(tmp_path).write_text("1\ta.py\tsym\tfirst\n1\tb.py\tsym\tother\n")
_write_ledger(tmp_path, ["a.py\tsym\tfirst"])
_stop(env, _repo(tmp_path))
assert seen[-1]["written"] == ["a.py\tsym\tfirst"]
assert seen[-1]["earlier"] == ["b.py\tsym\tother"]
def test_a_check_with_nothing_unjudged_forgets_the_carried_set(tmp_path):
with http_sink(b'{"status":"ok","outcome":"passed","unjudged":[]}') as (port, seen):
env = _env(tmp_path, f"http://127.0.0.1:{port}")
_earlier_file(tmp_path).parent.mkdir(parents=True, exist_ok=True)
_earlier_file(tmp_path).write_text("1\ta.py\tsym\tfirst\n")
_stop(env, _repo(tmp_path))
assert seen[-1]["earlier"] == ["a.py\tsym\tfirst"]
assert not _earlier_file(tmp_path).exists(), "judged since: nothing left to carry"
+7 -6
View File
@@ -147,9 +147,10 @@ async def test_a_write_in_another_project_asks_and_says_how_to_file_an_issue_ins
out = await check_act(1, 2, tool="update_task", args={"task_id": 5}) out = await check_act(1, 2, tool="update_task", args={"task_id": 5})
assert out["allowed"] is False assert out["allowed"] is False
assert out["targets"] == [{"id": 9, "title": "Elsewhere"}] assert out["targets"] == [{"id": 9, "title": "Elsewhere"}]
assert "Home (project 2)" in out["reason"] first, ask, agent = out["reason"].split("\n")
assert "Elsewhere (project 9)" in out["reason"] assert first == "Update task in Elsewhere, but this session is working in Home."
assert 'create_task(project_id=9, kind="issue")' in out["reason"] assert ask == "Approve only if you asked for this change to Elsewhere."
assert 'create_task(project_id=9, kind="issue")' in agent
async def test_a_rule_edit_in_another_project_names_the_rule_and_suggests_no_issue(): async def test_a_rule_edit_in_another_project_names_the_rule_and_suggests_no_issue():
@@ -157,12 +158,12 @@ async def test_a_rule_edit_in_another_project_names_the_rule_and_suggests_no_iss
with a, b, c: with a, b, c:
out = await check_act(1, 2, tool="update_rule", args={"rule_id": 130, "salience": "low"}) out = await check_act(1, 2, tool="update_rule", args={"rule_id": 130, "salience": "low"})
assert out["allowed"] is False assert out["allowed"] is False
assert "rule 130 of Elsewhere (project 9)" in out["reason"] assert out["reason"].startswith("Changing rule 130 in Elsewhere, but this session is working in Home.")
assert "create_task" not in out["reason"] assert "create_task" not in out["reason"]
with a, b, c: with a, b, c:
related = await check_act(1, 2, tool="relate_rules", related = await check_act(1, 2, tool="relate_rules",
args={"from_rule_id": 4, "to_rule_id": 130, "kind": "overrides"}) args={"from_rule_id": 4, "to_rule_id": 130, "kind": "overrides"})
assert "rule 4, rule 130 of" in related["reason"] assert related["reason"].startswith("Changing rule 4, rule 130 in Elsewhere")
async def test_filing_an_issue_in_another_project_goes_ahead(): async def test_filing_an_issue_in_another_project_goes_ahead():
@@ -192,7 +193,7 @@ async def test_a_directory_in_another_project_asks_in_the_words_of_the_act():
out = await check_act(1, 2, target_project=9, act="git push in") out = await check_act(1, 2, target_project=9, act="git push in")
same = await check_act(1, 2, target_project=2, act="git push in") same = await check_act(1, 2, target_project=2, act="git push in")
assert out["allowed"] is False assert out["allowed"] is False
assert "git push in Elsewhere (project 9)" in out["reason"] assert out["reason"].startswith("Git push in Elsewhere, but this session is working in Home.")
assert same["allowed"] is True assert same["allowed"] is True