Milestone 639 steps 5–6: enforced rules refuse the act, only hold rules hold, and a pass weighs each rule #226
@@ -56,8 +56,9 @@ export type RuleKind = "rule" | "preference";
|
||||
|
||||
/**
|
||||
* What a rule does when it arrives, declared by its author. `inform` puts a
|
||||
* line beside the work; `hold` makes the reply or act it governs wait for one
|
||||
* read; `enforce` checks the act itself. A preference is always `inform`.
|
||||
* line beside the work; `hold` makes the reply or command it governs wait for
|
||||
* one read; `enforce` refuses an act its moment or trigger reaches. A
|
||||
* preference is always `inform`.
|
||||
*/
|
||||
export type RuleEnforcement = "enforce" | "hold" | "inform";
|
||||
/** How a rule ranks among rules of the same enforcement at a crowded moment. */
|
||||
|
||||
@@ -344,14 +344,16 @@ watch(() => props.ruleId, load);
|
||||
<label class="kind-opt">
|
||||
<input v-model="enforcement" type="radio" value="hold" />
|
||||
<span>
|
||||
<strong>Hold</strong> — the reply or act it governs waits for one
|
||||
read of it. For a rule whose miss costs a rewrite.
|
||||
<strong>Hold</strong> — the reply or command it governs waits until
|
||||
the rule has been read once. File edits are never held. For a rule
|
||||
whose miss costs a rewrite.
|
||||
</span>
|
||||
</label>
|
||||
<label class="kind-opt">
|
||||
<input v-model="enforcement" type="radio" value="enforce" />
|
||||
<span>
|
||||
<strong>Enforce</strong> — the act itself is checked. For a hard
|
||||
<strong>Enforce</strong> — an act its moment or trigger reaches
|
||||
does not run, every time, until you change the rule. For a hard
|
||||
boundary.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
@@ -33,8 +33,8 @@ const emit = defineEmits<{
|
||||
v-if="r.enforcement === 'hold' || r.enforcement === 'enforce'"
|
||||
class="rule-chip"
|
||||
:title="r.enforcement === 'hold'
|
||||
? 'The reply or act it governs waits for one read of it'
|
||||
: 'The act it governs is checked against it'"
|
||||
? 'The reply or command it governs waits until it has been read once'
|
||||
: 'An act it is reached by does not run until the rule changes'"
|
||||
>{{ r.enforcement === "hold" ? "holds" : "enforced" }}</span>
|
||||
<!-- Marked only when something is WRONG: every rule arrives by
|
||||
retrieval now, so "conditional" stopped distinguishing anything.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "grimoire",
|
||||
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
|
||||
"version": "2026.11.23.0004",
|
||||
"version": "2026.11.23.0005",
|
||||
"author": {
|
||||
"name": "Bryan Van Deusen"
|
||||
},
|
||||
|
||||
+3
-3
@@ -15,7 +15,7 @@ another one means adding files, not moving or rewriting any.
|
||||
|---|---|---|
|
||||
| **The skills** | `plugin/skills/*/SKILL.md` | Agent Skills (the open SKILL.md format). They state every Grimoire reflex in full and name no client. `tests/test_guidance_ownership.py` fails if a skill names a particular client, or references anything outside its own folder. Every client package ships this folder verbatim. |
|
||||
| **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — the workflow across tools (≤1,600 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. |
|
||||
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule or — when the turn closed a task — for missing completion sections). |
|
||||
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule set to hold or — when the turn closed a task — for missing completion sections). |
|
||||
| **The API key** | Grimoire → Settings → MCP Access | One `fmcp_` key per install. Write scope covers the MCP tools and every hook; a read key runs only the `GET` hooks. |
|
||||
|
||||
## Added by each client
|
||||
@@ -40,9 +40,9 @@ another one means adding files, not moving or rewriting any.
|
||||
| `hooks/grimoire_after_write.sh` | PostToolUse on shell commands: the same check for code written through the shell. |
|
||||
| `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`. |
|
||||
| `hooks/grimoire_project_fence.sh` | PreToolUse on editor writes, shell commands and Grimoire's tools: `GET /api/plugin/write-scope` for an act aimed at another project, answered `ask` with the reason; PostToolUse on `enter_project` remembers the project a session without one entered. |
|
||||
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). |
|
||||
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). Denies the call when the response's `decision` is `enforce` (every time) or `hold` (once per rule and session). |
|
||||
| `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite. |
|
||||
| `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check`; blocks once, with the reason the server returns, so the agent judges what it built. |
|
||||
| `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check` and keeps the `note` it returns for the next prompt, which `grimoire_autoinject.sh` carries as `carry`, so the agent judges what it built. Never blocks. |
|
||||
| `hooks/grimoire_record_opened.sh` | PostToolUse on `get_rule`: notes the rule as read in the session ledger and `POST /api/plugin/rule-opened`. |
|
||||
| `hooks/grimoire_record_outcome.sh` | PostToolUse on `rule_outcome`: notes the rule as acted on, locally, for the session-scoped readout. |
|
||||
| `hooks/grimoire_claim_session.sh` | PostToolUse on `update_task` / `add_task_log`: `GET /api/plugin/claim-session`, so the task comes back after a compaction. |
|
||||
|
||||
+11
-7
@@ -97,7 +97,9 @@ On install you'll be asked for:
|
||||
→ `POST /api/plugin/moment`: the rules mounted on the moments the call
|
||||
reaches. It skips tools that `GET /api/plugin/moment-tools` says reach
|
||||
nothing mounted, and Grimoire's own tools, whose responses carry
|
||||
`moment_rules`.
|
||||
`moment_rules`. A rule set to enforce refuses the call (every time it is
|
||||
reached); one set to hold denies it once until it has been read, never on a
|
||||
file edit.
|
||||
- `hooks/hooks.json` → PostToolUse hooks on Grimoire's `get_rule`,
|
||||
`rule_outcome`, `update_task` and `add_task_log`: they keep the session's
|
||||
ledgers of rules opened and acted on (`get_rule` also reports to
|
||||
@@ -115,7 +117,8 @@ On install you'll be asked for:
|
||||
duplicate arm and the outage line are shared in `hooks/grimoire_defs.sh`.
|
||||
- `hooks/hooks.json` → Stop hook (`hooks/grimoire_reply_check.sh`): sends the
|
||||
reply that ends the turn to `POST /api/plugin/reply-rules`, which holds it
|
||||
once for an unopened rule mounted on the reply moments or matching the reply.
|
||||
once for an unopened rule set to hold (or enforce) that is mounted on the
|
||||
reply moments or matches the reply. A rule set to inform never holds it.
|
||||
When the turn closed a Grimoire task (`update_task`/`create_task` with status
|
||||
done), the same request has the server check the reply for the completion
|
||||
sections — where the work sits, what needs you, what comes next. If they are
|
||||
@@ -127,11 +130,12 @@ On install you'll be asked for:
|
||||
write hooks note every definition a write names (and every new file) in a
|
||||
session ledger; at the end of the turn this sends them to
|
||||
`GET /api/plugin/shape-check`, which answers with the ones nobody has judged.
|
||||
If any are, it blocks once with the server's reason, asking the agent that
|
||||
wrote them to say what each is — reusable (record a snippet), an instance or
|
||||
variant of one, or a one-off — in one `classify_shapes` call. Same discipline
|
||||
as the report check: never twice, never without a recorded check. Outcomes
|
||||
land under category `plugin`, action `shape_check`.
|
||||
If any are, the server's note rides the next prompt (the prompt hook sends it
|
||||
as `carry`), asking the agent that wrote them to say what each is — reusable
|
||||
(record a snippet), an instance or variant of one, or a one-off — in one
|
||||
`classify_shapes` call. It never holds the reply; the stop after that prompt
|
||||
records whether the lines were judged. Outcomes land under category
|
||||
`plugin`, action `shape_check`.
|
||||
- `skills/` → the universal process-skills, surfaced by description match.
|
||||
- `hooks/grimoire_sync_processes.sh` (a 2nd SessionStart hook) + the `/grimoire:sync`
|
||||
command → generate `~/.claude/skills/grimoire-proc-*` stubs from your Grimoire
|
||||
|
||||
@@ -134,10 +134,24 @@ if [ -n "$session_id" ]; then
|
||||
[ -n "$shapes_seen" ] && exclude_q="${exclude_q}&shapes_seen=${shapes_seen}"
|
||||
fi
|
||||
|
||||
# What the last stop left for this prompt: the definitions its turn wrote
|
||||
# that nobody has judged (grimoire_shape_check.sh). Carried to the server, which
|
||||
# fits it into the one payload, and removed once the server has answered.
|
||||
carry_q=""
|
||||
carry_file=""
|
||||
if [ -n "$session_id" ]; then
|
||||
carry_file="${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}.note"
|
||||
if [ -s "$carry_file" ]; then
|
||||
carry_enc=$(head -c 2000 "$carry_file" 2>/dev/null | grimoire_urlenc) || carry_enc=""
|
||||
[ -n "$carry_enc" ] && carry_q="&carry=${carry_enc}"
|
||||
fi
|
||||
fi
|
||||
|
||||
body=$(curl -fsS --max-time 5 \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}" 2>/dev/null) || exit 0
|
||||
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}${carry_q}" 2>/dev/null) || exit 0
|
||||
[ -n "$body" ] || exit 0
|
||||
[ -n "$carry_q" ] && rm -f "$carry_file" 2>/dev/null
|
||||
|
||||
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
|
||||
context=$(grimoire_json_pick "$body_flat" '.context')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Grimoire — PreToolUse moment arm: rules MOUNTED on a moment arrive when the
|
||||
# moment happens.
|
||||
# moment happens — beside the act, or, for a rule set to enforce or hold, in
|
||||
# front of it.
|
||||
#
|
||||
# The other PreToolUse arms search: they turn the act into a query and hope a
|
||||
# rule's words resemble it. A mount needs no resemblance. The operator said
|
||||
@@ -148,6 +149,34 @@ body_flat=$(printf '%s' "$body" | grimoire_json_flat)
|
||||
grimoire_json_list "$body_flat" '.rule_ids' | grimoire_rules_append "$rulefile"
|
||||
grimoire_json_list "$body_flat" '.shape_keys' | grimoire_shapes_append "$shapefile"
|
||||
|
||||
# ── The act itself: refused, held for one read, or let through ───────────
|
||||
#
|
||||
# The server decides and supplies the words (`decision`); this hook only
|
||||
# carries them. A rule set to ENFORCE refuses the call every time it is
|
||||
# reached — the operator drew that line, and it moves when they change the
|
||||
# rule, not when the agent has read it. A rule set to HOLD asks for one read
|
||||
# before the act, once per rule and under the session cap that the act
|
||||
# checkpoint and the reply hold share, so a mis-set rule costs one round trip
|
||||
# rather than a session that cannot move.
|
||||
d_kind=$(grimoire_json_pick "$body_flat" '.decision.kind')
|
||||
d_reason=$(grimoire_json_pick "$body_flat" '.decision.reason')
|
||||
d_rule=$(grimoire_json_list "$body_flat" '.decision.rule_ids' | head -n 1)
|
||||
if [ -n "$d_reason" ]; then
|
||||
case "$d_kind" in
|
||||
enforce)
|
||||
grimoire_json_deny PreToolUse "$d_reason"
|
||||
exit 0
|
||||
;;
|
||||
hold)
|
||||
if [ -n "$d_rule" ] \
|
||||
&& grimoire_checkpoint_allowed "$state_dir/${safe_sid}.checkpoint.ids" "$d_rule"; then
|
||||
grimoire_json_deny PreToolUse "$d_reason"
|
||||
exit 0
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
context=$(grimoire_json_pick "$body_flat" '.context')
|
||||
[ -n "$context" ] || exit 0
|
||||
grimoire_json_out PreToolUse "$context"
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
# tool call misses it. This hook sends the finished reply to the server, which
|
||||
# checks it twice over: the rules MOUNTED on the reply moments, and the reply
|
||||
# text against every rule's trigger, as the backstop for whatever the earlier
|
||||
# arms missed. An unopened rule from either half holds the reply for one read.
|
||||
# arms missed. An unopened rule set to hold, from either half, holds the reply
|
||||
# for one read; a rule set to inform was delivered before the reply and never
|
||||
# holds it.
|
||||
#
|
||||
# ONE END-OF-TURN REQUEST. When the turn closed a task, the same request
|
||||
# carries the task ids and the server also checks the reply for the completion
|
||||
|
||||
@@ -31,13 +31,14 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
|
||||
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
||||
[ -n "$session_id" ] || exit 0
|
||||
|
||||
# The moment arm's per-session files (its tool cache and the acts ledger) and
|
||||
# the fence's (the project the session entered, its outage marker) describe a
|
||||
# session that is over, on any exit — a clear included, since the next
|
||||
# conversation is a new session id.
|
||||
# The moment arm's per-session files (its tool cache and the acts ledger), the
|
||||
# shape check's (a note waiting for a prompt) and the fence's (the project the
|
||||
# session entered, its outage marker) describe a session that is over, on any
|
||||
# exit — a clear included, since the next conversation is a new session id.
|
||||
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
|
||||
rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* \
|
||||
"${TMPDIR:-/tmp}/grimoire-fence/${safe_sid}".* 2>/dev/null || true
|
||||
"${TMPDIR:-/tmp}/grimoire-fence/${safe_sid}".* \
|
||||
"${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}".* 2>/dev/null || true
|
||||
|
||||
reason=$(grimoire_json_pick "$event_flat" '.reason')
|
||||
[ "$reason" = "clear" ] && exit 0
|
||||
|
||||
@@ -1,29 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
# Grimoire plugin — Stop hook: the turn's new shapes are judged by the agent
|
||||
# that wrote them.
|
||||
# that wrote them, at the start of its next turn.
|
||||
#
|
||||
# The write hooks (grimoire_prior_art.sh, grimoire_after_write.sh) append every
|
||||
# definition a write names to a session ledger, `<sid>.written.ids`
|
||||
# (`path<TAB>kind<TAB>name`, see grimoire_written_append). At the end of the
|
||||
# turn this hook sends that ledger to the instance, which answers with what
|
||||
# nobody has judged yet. If anything is, the hook blocks ONCE, in the server's
|
||||
# words: the agent that built the code is the one participant who knows what
|
||||
# it is, and the end of the turn is the last moment that is still true.
|
||||
# nobody has judged yet as a `note`. The hook leaves the note for
|
||||
# grimoire_autoinject.sh, which carries it into the next prompt's payload: the
|
||||
# agent that built the code is the one participant who knows what it is, and
|
||||
# the next turn of the same session still does.
|
||||
#
|
||||
# THE SAME DISCIPLINE AS the completion-section check in grimoire_reply_check.sh:
|
||||
# - it blocks only on a `reason` the instance returned, which it returns
|
||||
# only for a block it RECORDED — an unconfigured or unreachable instance
|
||||
# never stops a session, and every intervention is one the numbers see;
|
||||
# - never twice for one turn: the stop that follows its own block
|
||||
# (`stop_hook_active` with this hook's marker present) is recorded as
|
||||
# judged_after_block / left_after_block and let through;
|
||||
# - another plugin's block loop is left alone (active, no marker).
|
||||
# IT NEVER HOLDS THE REPLY. A held reply is rewritten, and a hold on every turn
|
||||
# that wrote code made most replies cost two. The question waits one prompt
|
||||
# instead, and is asked inside that prompt's budget.
|
||||
#
|
||||
# THE LEDGER IS CONSUMED, NOT TURN-STAMPED. Everything written since the last
|
||||
# stop this hook answered is "this turn". It is emptied once the instance has
|
||||
# answered — after a pass, or after the post-block stop — and KEPT when the
|
||||
# instance could not be reached, so the question is asked at the next stop
|
||||
# that can be answered rather than silently dropped.
|
||||
# THE STATE, in <TMPDIR>/grimoire-shapecheck:
|
||||
# <sid>.note — the note, until a prompt carries it (the prompt hook
|
||||
# removes it once the instance has answered);
|
||||
# <sid>.asked — the lines that note named. At the first stop after the note
|
||||
# was carried, they go back as `phase=after`, which records
|
||||
# whether they were judged, and are then forgotten.
|
||||
# A note no prompt has carried yet (two stops in a row) is asked again with
|
||||
# that turn's writes added, so nothing is dropped and nothing is asked twice.
|
||||
#
|
||||
# Silent on outage: the ledger is kept when the instance could not be reached,
|
||||
# so the question is asked at the next stop that can be answered.
|
||||
#
|
||||
# Config (same as the other hooks):
|
||||
# CLAUDE_PLUGIN_OPTION_API_ENDPOINT base URL, no trailing slash
|
||||
@@ -43,36 +45,33 @@ session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
||||
active=$(grimoire_json_pick "$event_flat" '.stop_hook_active')
|
||||
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
|
||||
[ -n "$session_id" ] || exit 0
|
||||
# The stop after another hook held the reply: this turn's writes were already
|
||||
# sent at the stop before it.
|
||||
[ "$active" = "true" ] && exit 0
|
||||
|
||||
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
|
||||
ledger="${TMPDIR:-/tmp}/grimoire-priorart/${safe_sid}.written.ids"
|
||||
state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck"
|
||||
mkdir -p "$state_dir" 2>/dev/null || true
|
||||
marker="$state_dir/${safe_sid}.blocked"
|
||||
note_file="$state_dir/${safe_sid}.note"
|
||||
asked_file="$state_dir/${safe_sid}.asked"
|
||||
|
||||
if [ "$active" = "true" ]; then
|
||||
# A Stop hook already blocked this stop. Another plugin's → nothing to add.
|
||||
[ -f "$marker" ] || exit 0
|
||||
phase=after
|
||||
else
|
||||
rm -f "$marker" 2>/dev/null || true
|
||||
phase=check
|
||||
# A note no prompt has carried: its lines join this turn's, asked afresh.
|
||||
if [ -f "$note_file" ]; then
|
||||
if [ -s "$asked_file" ]; then
|
||||
mkdir -p "$(dirname "$ledger")" 2>/dev/null || true
|
||||
cat "$asked_file" >> "$ledger" 2>/dev/null || true
|
||||
fi
|
||||
rm -f "$note_file" "$asked_file" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if [ ! -s "$ledger" ]; then
|
||||
rm -f "$marker" 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
[ -s "$asked_file" ] || [ -s "$ledger" ] || exit 0
|
||||
grimoire_config || exit 0
|
||||
|
||||
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
|
||||
# key runs the plugin), and a turn that wrote more than this generated code.
|
||||
written=$(awk '!seen[$0]++' "$ledger" 2>/dev/null | head -n 80)
|
||||
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
|
||||
dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}"
|
||||
q="phase=${phase}&written=${written_enc}"
|
||||
scope_q=""
|
||||
scope=$(grimoire_scope_query "$dir")
|
||||
[ -n "$scope" ] && q="${q}&${scope}"
|
||||
[ -n "$scope" ] && scope_q="&${scope}"
|
||||
# The repo rides along even when a marker names the project: the instance
|
||||
# needs it to tell the agent which repo a just-written shape belongs to.
|
||||
case "$scope" in
|
||||
@@ -81,25 +80,38 @@ case "$scope" in
|
||||
remote=$(git -C "$dir" remote get-url origin 2>/dev/null || true)
|
||||
if [ -n "$remote" ]; then
|
||||
remote_enc=$(printf '%s' "$remote" | grimoire_urlenc) || remote_enc=""
|
||||
[ -n "$remote_enc" ] && q="${q}&repo=${remote_enc}"
|
||||
[ -n "$remote_enc" ] && scope_q="${scope_q}&repo=${remote_enc}"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
|
||||
# key runs the plugin), and a turn that wrote more than this generated code.
|
||||
_unique() { awk '!seen[$0]++' "$1" 2>/dev/null | head -n 80; }
|
||||
|
||||
# The note a prompt carried: were its lines judged since?
|
||||
if [ -s "$asked_file" ]; then
|
||||
asked_enc=$(_unique "$asked_file" | grimoire_urlenc) || asked_enc=""
|
||||
if [ -n "$asked_enc" ] && curl -fsS --max-time 4 \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"${url%/}/api/plugin/shape-check?phase=after&written=${asked_enc}${scope_q}" \
|
||||
>/dev/null 2>&1; then
|
||||
rm -f "$asked_file" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
[ -s "$ledger" ] || exit 0
|
||||
written=$(_unique "$ledger")
|
||||
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
|
||||
answer=$(curl -fsS --max-time 4 \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"${url%/}/api/plugin/shape-check?${q}" 2>/dev/null) || exit 0 # unreachable: keep the ledger
|
||||
"${url%/}/api/plugin/shape-check?phase=check&written=${written_enc}${scope_q}" 2>/dev/null) \
|
||||
|| exit 0 # unreachable: keep the ledger
|
||||
|
||||
if [ "$phase" = "after" ]; then
|
||||
rm -f "$marker" "$ledger" 2>/dev/null || true
|
||||
exit 0
|
||||
note=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.note')
|
||||
if [ -n "$note" ]; then
|
||||
printf '%s' "$note" > "$note_file" 2>/dev/null || true
|
||||
printf '%s\n' "$written" > "$asked_file" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
reason=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.reason')
|
||||
if [ -z "$reason" ]; then
|
||||
rm -f "$ledger" 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
: > "$marker" 2>/dev/null || true
|
||||
printf '{"decision":"block","reason":"%s"}\n' "$(printf '%s' "$reason" | grimoire_json_escape)"
|
||||
rm -f "$ledger" 2>/dev/null || true
|
||||
exit 0
|
||||
|
||||
@@ -123,6 +123,11 @@ async def session_context():
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
# The longest carried note a prompt takes: the shape check's note names a
|
||||
# few definitions and the call that lists the rest.
|
||||
_CARRY_CHARS = 3000
|
||||
|
||||
|
||||
@plugin_bp.get("/retrieve")
|
||||
@login_required
|
||||
@memoized_query_embeddings
|
||||
@@ -166,6 +171,10 @@ async def autoinject_retrieve():
|
||||
one-line reminder when present; the hook's
|
||||
ledger is swept on compaction, which is how the
|
||||
full core comes back after one.
|
||||
carry (opt) — a note the session's last stop left for this
|
||||
prompt: the definitions its turn wrote that
|
||||
nobody has judged (/shape-check's `note`).
|
||||
Fitted after the reply shape, before the records.
|
||||
|
||||
ONE PAYLOAD, IN ONE ORDER, UNDER ONE BUDGET (`hook_payload`): the rules
|
||||
this prompt reaches and those mounted on `reply.report`, then the turn's
|
||||
@@ -216,7 +225,9 @@ async def autoinject_retrieve():
|
||||
record=False,
|
||||
)
|
||||
# One payload, in the one order: the rules, then the reply shape, then
|
||||
# the records menu, then the lesson-rule proposal, fitted to the budget.
|
||||
# what the last turn left unjudged, then the records menu, then the
|
||||
# lesson-rule proposal, fitted to the budget.
|
||||
carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS]
|
||||
turn_parts = (
|
||||
[*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn
|
||||
else [hook_payload_svc.Part(text=turn.get("context") or "", ids={
|
||||
@@ -227,6 +238,7 @@ async def autoinject_retrieve():
|
||||
fitted = await hook_payload_svc.fit(g.user.id, [
|
||||
*hook_payload_svc.parts_of(rules, {hook_payload_svc.RULE: "shown_rule_ids"}),
|
||||
*turn_parts,
|
||||
*([hook_payload_svc.Part(text=carry)] if carry else []),
|
||||
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}),
|
||||
*([hook_payload_svc.Part(text=proposal)] if proposal else []),
|
||||
])
|
||||
@@ -365,12 +377,20 @@ async def moment():
|
||||
rules: in full unless `shapes_seen` names it, then as its reminder. The
|
||||
payload is fitted to the user's budget (`hook_payload`), and `shape_keys`
|
||||
are the ones sent in full and kept, for the hook's ledger.
|
||||
|
||||
`decision` is the answer for the act itself (`retrieval_pipeline.
|
||||
act_decision`): `{}` when it goes ahead; `kind: "enforce"` when a rule set
|
||||
to enforce refuses it — the hook denies the call with `reason`, every
|
||||
time; `kind: "hold"` when an unopened rule set to hold asks for one read
|
||||
first — the hook denies once per rule and session, under the act
|
||||
checkpoint's cap. A write is never held, only refused.
|
||||
"""
|
||||
event = await request.get_json(silent=True) or {}
|
||||
tool = str(event.get("tool_name") or "").strip()
|
||||
tool_input = event.get("tool_input")
|
||||
if not tool:
|
||||
return jsonify({"context": "", "rule_ids": [], "moments": [], "shape_keys": []})
|
||||
return jsonify({"context": "", "rule_ids": [], "moments": [], "shape_keys": [],
|
||||
"decision": {}})
|
||||
project_id, _repo, _unbound = await _project_scope()
|
||||
reached, result = await moment_delivery_svc.deliver_for_act(
|
||||
g.user.id, tool, tool_input if isinstance(tool_input, dict) else {},
|
||||
@@ -394,6 +414,7 @@ async def moment():
|
||||
"rule_ids": fitted.keep_only(hook_payload_svc.RULE, result.rule_ids),
|
||||
"moments": [hit["moment"] for hit in reached],
|
||||
"shape_keys": [k for k, form in forms.items() if form == reply_shapes_svc.FULL],
|
||||
"decision": result.decision,
|
||||
})
|
||||
|
||||
|
||||
@@ -633,9 +654,11 @@ async def shape_check():
|
||||
The client's write hooks keep a ledger of the definitions each turn wrote;
|
||||
its Stop hook sends them here. The server decides which carry no judgment
|
||||
— against the ledger and the project's recorded snippets — records the
|
||||
outcome, and for a block returns the `reason` the agent is sent back with.
|
||||
A hook blocks only on a reason it received, so only on a block that was
|
||||
recorded, and never on the stop that follows one (`phase=after`).
|
||||
outcome, and returns the `note` the agent reads at the start of its next
|
||||
turn. Nothing here holds the reply: the question rides the next prompt,
|
||||
in the same session, while the code is still in view. `phase=after` is
|
||||
the stop after that prompt, sent with the lines the note named, and
|
||||
records whether they were judged.
|
||||
|
||||
A GET like every plugin endpoint: a read-scoped key runs the plugin, and
|
||||
this records telemetry the way /reply-rules records its section check. It changes no ledger
|
||||
@@ -682,8 +705,8 @@ async def shape_check():
|
||||
)
|
||||
body["outcome"] = outcome
|
||||
body["unjudged"] = unjudged
|
||||
if outcome == "blocked":
|
||||
body["reason"] = shape_check_svc.block_reason(
|
||||
if outcome == "noted":
|
||||
body["note"] = shape_check_svc.note_text(
|
||||
unjudged, project_id=project_id, repo=repo_key or repo,
|
||||
)
|
||||
return jsonify(body)
|
||||
|
||||
@@ -16,7 +16,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from grimoire.services import hook_payload, moment_actions, reply_shapes
|
||||
from grimoire.services import hook_payload, moment_actions, reply_shapes, rule_order
|
||||
from grimoire.services import retrieval_pipeline as rp
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -121,9 +121,43 @@ async def deliver_for_act(
|
||||
result = await deliver_moments(
|
||||
user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board,
|
||||
)
|
||||
# A write is never held for a read: a recall aid does not stand in the
|
||||
# way of the work. A rule set to enforce still refuses one — that is a
|
||||
# boundary the operator drew, not a reminder.
|
||||
if result.decision.get("kind") == "hold" and moment_actions.tool_key(tool) in WRITE_TOOLS:
|
||||
result.decision = {}
|
||||
return reached, result
|
||||
|
||||
|
||||
# The file-writing tools, as tool keys: a `hold` rule never holds these.
|
||||
WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"})
|
||||
|
||||
|
||||
async def routed_to_acts(user_id: int, project_id: int | None = None) -> frozenset[int]:
|
||||
"""The rules that arrive at an act, so the prompt arm leaves them there.
|
||||
|
||||
A rule mounted on a moment some action is mapped to (every moment but the
|
||||
reply moments), or carrying a `tool`, `path` or `command` trigger, reaches
|
||||
the session at the call it governs. Delivered at the prompt too, it would
|
||||
arrive twice, and the first time beside a request it competes with. A
|
||||
keyword trigger can also match a reply, so it does not count.
|
||||
"""
|
||||
from grimoire.services import rule_triggers, rulebooks
|
||||
|
||||
mappings = await moment_actions.list_mappings(user_id)
|
||||
act_moments = sorted({
|
||||
action.moment for action, _via in moment_actions.effective_actions(mappings)
|
||||
if not action.moment.startswith("reply.")
|
||||
})
|
||||
out = {rule.id for rule, _at in await rulebooks.rules_on_moments(
|
||||
user_id, act_moments, project_id or None,
|
||||
)} if act_moments else set()
|
||||
for rule, triggers in await rule_triggers._in_scope(user_id, project_id or None):
|
||||
if any(t.kind in ("tool", "path", "command") and not t.moment for t in triggers):
|
||||
out.add(rule.id)
|
||||
return frozenset(out)
|
||||
|
||||
|
||||
def shapes_for_act(reached: list[dict], seen: frozenset[str] = frozenset()) -> tuple[list[str], dict[str, str]]:
|
||||
"""The default reply shapes riding the moments this act reached.
|
||||
|
||||
@@ -238,8 +272,8 @@ async def attach_moment_rules(
|
||||
# your end" gets said — so it is checked twice over: the rules MOUNTED on the
|
||||
# reply moments (deterministic, somebody said they belong here), and the
|
||||
# reply text against every rule's trigger (the backstop for whatever the
|
||||
# earlier arms missed). An unopened rule from either half HOLDS the reply for
|
||||
# one read, in these words; the hook never holds the rewrite.
|
||||
# earlier arms missed). An unopened rule set to hold, from either half, HOLDS
|
||||
# the reply for one read, in these words; the hook never holds the rewrite.
|
||||
|
||||
# The reply's head and tail. The embedder reads ~512 tokens, and the part of
|
||||
# a report that asks something of the reader — "let me know if it works" —
|
||||
@@ -339,13 +373,15 @@ async def reply_hold(
|
||||
room = pc.CHECKPOINT_SESSION_CAP - len(stopped)
|
||||
out: list[dict] = []
|
||||
|
||||
# The mounted half: deterministic, so every unopened RULE on these
|
||||
# moments holds. A preference claims no such force. A mount
|
||||
# conditional on a trigger holds only when the reply meets it.
|
||||
# The mounted half: deterministic, so every unopened rule on these
|
||||
# moments that is declared to hold (`hold` or `enforce`) holds. An
|
||||
# `inform` rule was put in front of the turn before the reply was
|
||||
# written, and a preference claims no force. A mount conditional on
|
||||
# a trigger holds only when the reply meets it.
|
||||
board = await _board(user_id, project_id, text=reply)
|
||||
gated = board.gated if board is not None else set()
|
||||
for rule, at in await rulebooks.rules_on_moments(user_id, names, project_id or None):
|
||||
if rule.id in skip or rule.kind == "preference" or (rule.id, at) in gated:
|
||||
if rule.id in skip or not rule_order.holds(rule) or (rule.id, at) in gated:
|
||||
continue
|
||||
out.append({"rule_id": rule.id, "title": rule.title, "moment": at,
|
||||
"trigger": (rule.when_to_apply or "").strip()})
|
||||
|
||||
@@ -985,6 +985,7 @@ async def build_prompt_rule_hint(
|
||||
# the bound project's own. An unbound session (project_id 0) gets
|
||||
# global rules only — this surface speaks unasked, and a whole-rulebook
|
||||
# answer is only right for someone who asked the whole rulebook.
|
||||
# A rule that reaches the session at an act is left for that act.
|
||||
result = await _rule_moment(
|
||||
rp.PROMPT_RULE,
|
||||
rp.RuleMoment(
|
||||
@@ -992,6 +993,7 @@ async def build_prompt_rule_hint(
|
||||
where="to this request",
|
||||
exclude=frozenset(exclude_rule_ids or []),
|
||||
held=frozenset(held_rule_ids or []),
|
||||
elsewhere=await _routed_for(user_id, project_id),
|
||||
),
|
||||
floor=await floor_for(user_id, "prompt_rule"),
|
||||
budget=await budget_for(user_id, "prompt_rule"),
|
||||
@@ -1011,6 +1013,18 @@ async def build_prompt_rule_hint(
|
||||
return out
|
||||
|
||||
|
||||
async def _routed_for(user_id: int, project_id: int) -> frozenset[int]:
|
||||
"""The rules that arrive at an act (`moment_delivery.routed_to_acts`);
|
||||
empty when they cannot be read, so the prompt arm delivers as before."""
|
||||
from grimoire.services import moment_delivery
|
||||
|
||||
try:
|
||||
return await moment_delivery.routed_to_acts(user_id, project_id or None)
|
||||
except Exception: # noqa: BLE001 - a recall aid never breaks the prompt
|
||||
logger.debug("act-routed rules unreadable", exc_info=True)
|
||||
return frozenset()
|
||||
|
||||
|
||||
def _rule_io() -> rp.RuleIO:
|
||||
"""The ranker and recorders the rule arms report to, read at call time.
|
||||
|
||||
|
||||
@@ -105,12 +105,11 @@ def checkpoint_for(
|
||||
floor; only a hit the corpus is confident about is allowed to stop
|
||||
anything.
|
||||
|
||||
2. IT IS A RULE, NEVER A PREFERENCE. A preference says how something has
|
||||
been done before and following it is what keeps work consistent; a rule
|
||||
says what happens if you do not. Stopping an act over a preference
|
||||
would assert a force the record explicitly does not claim, and
|
||||
`_rule_hint_line` already keeps that distinction in the one word that
|
||||
names it.
|
||||
2. IT IS A RULE DECLARED TO HOLD (`rule_order.holds`): `hold` or
|
||||
`enforce`, never `inform`, never a preference. A preference says how
|
||||
something has been done before; an `inform` rule asked to be put beside
|
||||
the work. Stopping an act over either would assert a force the record
|
||||
does not claim.
|
||||
|
||||
3. THE SESSION HAS NOT OPENED IT. `held` is observable — a PostToolUse
|
||||
hook watches for the `get_rule` call — so this is a recorded
|
||||
@@ -134,7 +133,7 @@ def checkpoint_for(
|
||||
score, rule = kept[0]
|
||||
if score < floor:
|
||||
return {}
|
||||
if getattr(rule, "kind", "") == "preference":
|
||||
if not rule_order.holds(rule):
|
||||
return {}
|
||||
if rule.id in held:
|
||||
return {}
|
||||
@@ -545,6 +544,12 @@ class RuleMoment:
|
||||
held: frozenset[int] = frozenset()
|
||||
"""Rules the session has OPENED."""
|
||||
|
||||
elsewhere: frozenset[int] = frozenset()
|
||||
"""Rules that arrive at an act — mounted on a moment a tool call reaches,
|
||||
or triggered by a tool, path or command — and so are not delivered here
|
||||
by resemblance. A reminder read at the act is the one acted on; the same
|
||||
line at the prompt competes with the request it came beside."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class RuleResult:
|
||||
@@ -563,6 +568,11 @@ class RuleResult:
|
||||
|
||||
checkpoint: dict = field(default_factory=dict)
|
||||
|
||||
decision: dict = field(default_factory=dict)
|
||||
"""The moment arm's answer for the act itself, empty when the act goes
|
||||
ahead: `{"kind": "enforce" | "hold", "rule_ids", "reason"}`. See
|
||||
`act_decision`."""
|
||||
|
||||
line_rule_ids: list[int] = field(default_factory=list)
|
||||
"""The rule behind each of `lines`, in order, when a caller added lines
|
||||
of its own after the arm's; empty means `shown_rule_ids` lines up."""
|
||||
@@ -644,6 +654,8 @@ async def _ranked(
|
||||
# this done" asserts a force the record does not have.
|
||||
hits = [(score, rule) for score, rule in hits
|
||||
if getattr(rule, "kind", None) == kind]
|
||||
if moment.elsewhere:
|
||||
hits = [(score, rule) for score, rule in hits if rule.id not in moment.elsewhere]
|
||||
kept = _rule_band(hits) if band else hits
|
||||
# The gate is part of the cut, like the band: what it turns away is not
|
||||
# shown, so it is not in the row's results either.
|
||||
@@ -1749,11 +1761,16 @@ async def run_moment_arm(
|
||||
taken.add(rule.id)
|
||||
cands.append((rule, trig.key, f"its trigger {trig.describe()} matched this act",
|
||||
rule_order.BY_TRIGGER))
|
||||
# Read before retirement: a rule that enforces does so on every act it
|
||||
# reaches, however often this session has been shown it.
|
||||
decision = act_decision(
|
||||
[(rule, at, where) for rule, at, where, _s in cands], held=moment.held,
|
||||
)
|
||||
gone = await _retired(io, moment, [rule for rule, _a, _w, _s in cands])
|
||||
if gone:
|
||||
cands = [c for c in cands if c[0].id not in gone]
|
||||
if not cands:
|
||||
return RuleResult()
|
||||
return RuleResult(decision=decision)
|
||||
# The one delivery order (services/rule_order.py), then the cap — so
|
||||
# what a crowded moment drops is the lowest-ranked, not the last
|
||||
# mounted. Ties keep catalog order.
|
||||
@@ -1798,7 +1815,83 @@ async def run_moment_arm(
|
||||
lines=lines, rule_ids=rule_ids,
|
||||
shown_rule_ids=[rule.id for rule, _at, _where in shown],
|
||||
shown=[(None, rule) for rule, _at, _where in shown],
|
||||
decision=decision,
|
||||
)
|
||||
except Exception: # noqa: BLE001 - a recall aid never breaks its act
|
||||
logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True)
|
||||
return RuleResult()
|
||||
|
||||
|
||||
def act_decision(reached: list[tuple], *, held: frozenset[int] = frozenset()) -> dict:
|
||||
"""What the act itself is told, from the rules its moments and triggers reached.
|
||||
|
||||
`reached` is `(rule, at, where)` for every rule the act reached, in any
|
||||
order. Sync and pure, so it can be read against a fixed list.
|
||||
|
||||
- A rule declared `enforce` REFUSES the act, every time it is reached:
|
||||
`{"kind": "enforce", ...}` with the rules' own words as the reason. It
|
||||
is a boundary the operator drew, and the act is the place it is drawn —
|
||||
reaching it by mount or trigger is a structural fact, never a
|
||||
resemblance. Opening the rule does not lift it; changing the rule does.
|
||||
- Otherwise the first rule declared `hold` that the session has not
|
||||
opened HOLDS the act for one read: `{"kind": "hold", ...}`. The client
|
||||
holds a rule once per session and caps holds per session, as at the act
|
||||
checkpoint.
|
||||
- Otherwise `{}`: the act goes ahead, with any lines beside it.
|
||||
|
||||
A preference never refuses or holds (`rule_order.force`).
|
||||
"""
|
||||
enforced = [item for item in reached if rule_order.force(item[0]) == "enforce"]
|
||||
if enforced:
|
||||
return {"kind": "enforce", "rule_ids": [rule.id for rule, _a, _w in enforced],
|
||||
"reason": enforce_reason(enforced)}
|
||||
for rule, at, where in reached:
|
||||
if rule_order.force(rule) == "hold" and rule.id not in held:
|
||||
return {"kind": "hold", "rule_ids": [rule.id],
|
||||
"reason": hold_reason(rule, at=at, where=where)}
|
||||
return {}
|
||||
|
||||
|
||||
def enforce_reason(enforced: list[tuple]) -> str:
|
||||
"""The text the agent reads instead of the act running, for an `enforce` rule.
|
||||
|
||||
Says which rule drew the line and where, gives its own words, and names
|
||||
who can move it: the operator, by changing the rule. A rule reached by
|
||||
the wrong act is a misfire the reader can record in one call.
|
||||
"""
|
||||
parts = []
|
||||
for rule, at, where in enforced:
|
||||
statement = _statement_excerpt(rule)
|
||||
parts.append(
|
||||
f"“{rule.title}” (Rule {rule.id}, {where})"
|
||||
+ (f": {statement}" if statement else "")
|
||||
)
|
||||
first_rule, first_at, _w = enforced[0]
|
||||
noun = "a rule" if len(enforced) == 1 else "rules"
|
||||
return (
|
||||
f"Not run: this act reaches {noun} the operator set to enforce. "
|
||||
+ " · ".join(parts)
|
||||
+ ". An enforced rule stops the act rather than sitting beside it, and "
|
||||
"opening it does not lift it. If the operator has asked for this act, "
|
||||
"tell them which rule stopped it: they lift it by changing the rule's "
|
||||
"enforcement or its trigger. If the rule has nothing to do with this "
|
||||
f"act, rule_misfired({first_rule.id}, \"{first_at}\", why) records that."
|
||||
)
|
||||
|
||||
|
||||
def hold_reason(rule, *, at: str, where: str) -> str:
|
||||
"""The text the agent reads instead of the act running, for a `hold` rule.
|
||||
|
||||
A practice on the act checkpoint's model: one read, then the act may be
|
||||
re-submitted unchanged.
|
||||
"""
|
||||
trigger = (getattr(rule, "when_to_apply", "") or "").strip()
|
||||
return (
|
||||
f"Held for one read. “{rule.title}” (Rule {rule.id}, {where}) is set to "
|
||||
f"hold the work it governs, and this session has not opened it"
|
||||
+ (f" — it applies when {trigger}" if trigger else "")
|
||||
+ f". Read it with get_rule({rule.id}), then re-submit this call — "
|
||||
"unchanged if the rule does not apply, which is a judgement only you "
|
||||
"can make. If it has nothing to do with this act, "
|
||||
f"rule_misfired({rule.id}, \"{at}\", why) records that."
|
||||
)
|
||||
|
||||
@@ -32,6 +32,29 @@ from typing import Any
|
||||
ENFORCEMENT_RANK = {"enforce": 0, "hold": 1, "inform": 2}
|
||||
SALIENCE_RANK = {"high": 0, "normal": 1, "low": 2}
|
||||
|
||||
|
||||
def force(rule: Any) -> str:
|
||||
"""What this rule does when it arrives: `enforce`, `hold` or `inform`.
|
||||
|
||||
A preference is always `inform`, whatever the field says: it records how
|
||||
work is liked, and claims no force that could stop it.
|
||||
"""
|
||||
if getattr(rule, "kind", None) == "preference":
|
||||
return "inform"
|
||||
value = getattr(rule, "enforcement", None)
|
||||
return value if value in ENFORCEMENT_RANK else "inform"
|
||||
|
||||
|
||||
def holds(rule: Any) -> bool:
|
||||
"""Whether this rule may make a reply or an act wait for one read.
|
||||
|
||||
Only a rule declared `hold` or `enforce` may. Every other rule is a line
|
||||
beside the work: holding the work on a rule nobody declared as one that
|
||||
holds made each reply after a write cost a rewrite, for rules that asked
|
||||
only to be read.
|
||||
"""
|
||||
return force(rule) in ("enforce", "hold")
|
||||
|
||||
# How narrowly a rule was reached, larger is narrower.
|
||||
BY_RESEMBLANCE = 0
|
||||
BY_MOUNT = 1
|
||||
|
||||
@@ -33,15 +33,21 @@ from sqlalchemy import select
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.app_log import AppLog
|
||||
|
||||
# check — the turn's first stop: block if anything is unjudged.
|
||||
# after — the stop that follows a block: never block again, only record
|
||||
# whether the agent answered.
|
||||
# check — a turn's stop: note what is unjudged, for the next prompt.
|
||||
# after — the stop after the note was read: record whether the agent
|
||||
# answered it.
|
||||
PHASES = ("check", "after")
|
||||
OUTCOMES = ("passed", "blocked", "judged_after_block", "left_after_block")
|
||||
# `blocked` and its two answers are the outcomes of the end-of-turn hold this
|
||||
# check once was; they stay readable so a window spanning both still sums.
|
||||
OUTCOMES = ("passed", "noted", "judged_after_note", "left_after_note",
|
||||
"blocked", "judged_after_block", "left_after_block")
|
||||
ASKED = ("noted", "blocked")
|
||||
LEFT = ("left_after_note", "left_after_block")
|
||||
|
||||
# How many shapes the reason names before "+N more". Enough to judge a normal
|
||||
# turn in one call; a turn that wrote more than this generated something.
|
||||
_LISTED = 25
|
||||
# How many shapes the note names before "+N more". It rides the next prompt
|
||||
# inside the payload budget, so it names the first few and the call that
|
||||
# lists the rest.
|
||||
_LISTED = 8
|
||||
|
||||
|
||||
def _evidence_note(evidence: dict) -> str:
|
||||
@@ -62,8 +68,9 @@ def _evidence_note(evidence: dict) -> str:
|
||||
return f" ({'; '.join(parts)})" if parts else ""
|
||||
|
||||
|
||||
def block_reason(unjudged: list[dict], *, project_id: int, repo: str) -> str:
|
||||
"""What the agent is told at the end of a turn that wrote unjudged shapes.
|
||||
def note_text(unjudged: list[dict], *, project_id: int, repo: str) -> str:
|
||||
"""What the agent reads at the start of the turn after one that wrote
|
||||
unjudged shapes.
|
||||
|
||||
Phrased as a practice: what to decide and the one
|
||||
call that records it, not a prohibition. The reusing-code skill owns the
|
||||
@@ -81,10 +88,10 @@ def block_reason(unjudged: list[dict], *, project_id: int, repo: str) -> str:
|
||||
lines.append(f"- … and {more} more (list_shapes(project_id={project_id}, path=…) shows them)")
|
||||
repo_arg = f', repo="{repo}"' if repo else ""
|
||||
return (
|
||||
f"This turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} "
|
||||
f"Your last turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} "
|
||||
"that nobody has judged yet. You built them, so you know what each one is — "
|
||||
"record it now, while that is still true, so the next session starts from your "
|
||||
"answer instead of rebuilding it:\n"
|
||||
"record it alongside this turn's work, while that is still true, so the next "
|
||||
"session starts from your answer instead of rebuilding it:\n"
|
||||
+ "\n".join(lines)
|
||||
+ "\n\nFor each: something another part of the code should reuse → record it "
|
||||
"with create_snippet (name, code, when to reach for it, location); built from a "
|
||||
@@ -122,11 +129,11 @@ async def record_shape_check(
|
||||
|
||||
|
||||
def outcome_for(phase: str, unjudged: list[dict]) -> str:
|
||||
"""The recorded outcome: a first stop blocks or passes; the stop after a
|
||||
block records whether the agent answered, and never blocks."""
|
||||
"""The recorded outcome: a turn's stop notes or passes; the stop after
|
||||
the note was read records whether the agent answered it."""
|
||||
if phase == "after":
|
||||
return "left_after_block" if unjudged else "judged_after_block"
|
||||
return "blocked" if unjudged else "passed"
|
||||
return "left_after_note" if unjudged else "judged_after_note"
|
||||
return "noted" if unjudged else "passed"
|
||||
|
||||
|
||||
def parse_written(raw: str, *, cap: int = 200) -> list[tuple[str, str, str]]:
|
||||
@@ -158,14 +165,14 @@ WINDOW_DAYS = 7
|
||||
def summarise(outcomes: list[str]) -> dict:
|
||||
"""{checked, asked, left} from a list of recorded outcomes.
|
||||
|
||||
`checked` is turns the question was put to (a first stop that wrote
|
||||
something): passed + blocked. `asked` is the blocked ones. `left` is
|
||||
asks the agent walked past — the stop after a block that still had
|
||||
unjudged shapes. That last number is the slip this check exists to make
|
||||
visible."""
|
||||
checked = sum(1 for o in outcomes if o in ("passed", "blocked"))
|
||||
asked = sum(1 for o in outcomes if o == "blocked")
|
||||
left = sum(1 for o in outcomes if o == "left_after_block")
|
||||
`checked` is turns the question was put to (a stop after a turn that
|
||||
wrote something): passed + asked. `asked` is the ones that found
|
||||
something unjudged. `left` is asks the agent walked past — answered by a
|
||||
stop that still had unjudged shapes. That last number is the slip this
|
||||
check exists to make visible."""
|
||||
checked = sum(1 for o in outcomes if o == "passed" or o in ASKED)
|
||||
asked = sum(1 for o in outcomes if o in ASKED)
|
||||
left = sum(1 for o in outcomes if o in LEFT)
|
||||
return {"checked": checked, "asked": asked, "left": left}
|
||||
|
||||
|
||||
|
||||
+4
-1
@@ -381,5 +381,8 @@ def _ungated_doors(request):
|
||||
return
|
||||
from grimoire.services import plugin_context
|
||||
|
||||
with patch.object(plugin_context, "_gate_for", AsyncMock(return_value=None)):
|
||||
# The same holds for the rules routed to acts, which read mounts and
|
||||
# triggers a test about something else has not written.
|
||||
with patch.object(plugin_context, "_gate_for", AsyncMock(return_value=None)), \
|
||||
patch.object(plugin_context, "_routed_for", AsyncMock(return_value=frozenset())):
|
||||
yield
|
||||
|
||||
@@ -7,6 +7,8 @@ tests/test_integration_rule_moments.py. These pin what is decided above it:
|
||||
- a rule the session was already shown is cited, not repeated, and only the
|
||||
fresh ones are recorded, each with its moment;
|
||||
- every door fails open;
|
||||
- a rule set to enforce refuses the act every time, one set to hold holds it
|
||||
once for a read (never a write), and an `inform` rule only sits beside it;
|
||||
- the plugin is told which tools can reach anything, and nothing more;
|
||||
- every Grimoire tool the shipped mappings name carries the attach, and the
|
||||
hook and the route agree on every name between them.
|
||||
@@ -238,7 +240,7 @@ async def test_the_route_reads_the_event_and_the_ledger():
|
||||
resp = await routes.moment.__wrapped__()
|
||||
body = await resp.get_json()
|
||||
assert body == {"context": "a line", "rule_ids": [5], "moments": ["work.deliver"],
|
||||
"shape_keys": []}
|
||||
"shape_keys": [], "decision": {}}
|
||||
args, kw = deliver.await_args
|
||||
assert args == (7, "Bash", {"command": "git push"})
|
||||
assert kw == {"project_id": 3, "exclude": frozenset({9}), "held": frozenset({4})}
|
||||
@@ -252,7 +254,7 @@ async def test_the_route_answers_an_empty_event_with_nothing():
|
||||
g.user = SimpleNamespace(id=7)
|
||||
resp = await routes.moment.__wrapped__()
|
||||
assert await resp.get_json() == {"context": "", "rule_ids": [], "moments": [],
|
||||
"shape_keys": []}
|
||||
"shape_keys": [], "decision": {}}
|
||||
|
||||
|
||||
def test_both_routes_are_on_the_app():
|
||||
@@ -296,10 +298,18 @@ def test_the_hook_leaves_grimoires_own_tools_to_their_responses():
|
||||
assert "mcp__*grimoire*__*) exit 0" in HOOK.read_text()
|
||||
|
||||
|
||||
def test_the_hook_never_returns_a_permission_decision():
|
||||
"""A mount is a recall aid: it informs the act and never holds it."""
|
||||
def test_the_hook_holds_only_behind_the_session_guard_and_refuses_only_on_enforce():
|
||||
"""Structural, and able to fail: every deny the hook emits is either the
|
||||
`enforce` branch or sits behind `grimoire_checkpoint_allowed`. A hold
|
||||
emitted outside the guard is a session the same rule can stop on every
|
||||
call."""
|
||||
code = [ln for ln in HOOK.read_text().splitlines() if not ln.lstrip().startswith("#")]
|
||||
assert not any("permissionDecision" in ln or "grimoire_json_deny" in ln for ln in code)
|
||||
denies = [i for i, ln in enumerate(code) if "grimoire_json_deny" in ln]
|
||||
assert len(denies) == 2, "one deny for enforce, one for hold"
|
||||
enforce, hold = denies
|
||||
assert "enforce)" in "\n".join(code[max(0, enforce - 3):enforce])
|
||||
assert "grimoire_checkpoint_allowed" in "\n".join(code[max(0, hold - 4):hold])
|
||||
assert "permissionDecision" not in "\n".join(code), "decisions go through grimoire_json_deny"
|
||||
|
||||
|
||||
def _hook(tmp_path, port, tool="Bash", command="git push origin dev", session="s-moment"):
|
||||
@@ -496,3 +506,124 @@ def test_the_hook_carries_the_shape_ledger_between_calls(tmp_path):
|
||||
assert "shapes_seen" not in moment_calls[0]
|
||||
assert moment_calls[1]["shapes_seen"] == ["asks"]
|
||||
|
||||
|
||||
|
||||
# ── what the act itself is told ─────────────────────────────────────────
|
||||
|
||||
|
||||
def _forced(rid, enforcement, kind="rule"):
|
||||
return fake_rule(id=rid, title=f"rule {rid}", kind=kind, enforcement=enforcement,
|
||||
statement=f"The words of rule {rid}.", when_to_apply="when it applies")
|
||||
|
||||
|
||||
async def _arm(pairs, **moment):
|
||||
io = rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock())
|
||||
return await rp.run_moment_arm(PUSH, _moment(**moment), io=io)
|
||||
|
||||
|
||||
async def test_a_rule_set_to_enforce_refuses_the_act_in_its_own_words():
|
||||
result = await _arm([(_forced(5, "inform"), "work.deliver"),
|
||||
(_forced(6, "enforce"), "work.deliver")])
|
||||
d = result.decision
|
||||
assert d["kind"] == "enforce" and d["rule_ids"] == [6]
|
||||
assert "The words of rule 6." in d["reason"]
|
||||
assert "at work.deliver, reached by `git push`" in d["reason"]
|
||||
assert 'rule_misfired(6, "work.deliver", why)' in d["reason"]
|
||||
# The lines still go out beside it, for a door that shows them.
|
||||
assert result.lines
|
||||
|
||||
|
||||
async def test_opening_an_enforced_rule_does_not_lift_it():
|
||||
result = await _arm([(_forced(6, "enforce"), "work.deliver")], held=frozenset({6}),
|
||||
exclude=frozenset({6}))
|
||||
assert result.decision["kind"] == "enforce"
|
||||
|
||||
|
||||
async def test_a_rule_set_to_hold_holds_until_the_session_opens_it():
|
||||
pairs = [(_forced(7, "hold"), "work.deliver")]
|
||||
held = (await _arm(pairs)).decision
|
||||
assert held["kind"] == "hold" and held["rule_ids"] == [7]
|
||||
assert "get_rule(7)" in held["reason"] and "re-submit" in held["reason"]
|
||||
assert (await _arm(pairs, held=frozenset({7}))).decision == {}
|
||||
|
||||
|
||||
async def test_an_inform_rule_and_a_preference_never_stop_the_act():
|
||||
pairs = [(_forced(8, "inform"), "work.deliver"),
|
||||
(_forced(9, "enforce", kind="preference"), "work.deliver")]
|
||||
assert (await _arm(pairs)).decision == {}
|
||||
|
||||
|
||||
async def _deliver_for(tool, decision):
|
||||
from grimoire.services import moment_actions as ma
|
||||
|
||||
with patch.object(ma, "moments_for", AsyncMock(return_value=PUSH)), \
|
||||
patch.object(md, "_board", AsyncMock(return_value=None)), \
|
||||
patch.object(md, "deliver_moments",
|
||||
AsyncMock(return_value=rp.RuleResult(decision=dict(decision)))):
|
||||
_reached, result = await _REAL_DELIVER(1, tool, {})
|
||||
return result.decision
|
||||
|
||||
|
||||
async def test_a_write_is_refused_by_an_enforced_rule_but_never_held():
|
||||
hold = {"kind": "hold", "rule_ids": [7], "reason": "read it"}
|
||||
enforce = {"kind": "enforce", "rule_ids": [6], "reason": "not run"}
|
||||
assert await _deliver_for("Edit", hold) == {}
|
||||
assert await _deliver_for("Bash", hold) == hold
|
||||
assert await _deliver_for("Write", enforce) == enforce
|
||||
|
||||
|
||||
def _decided(tmp_path, decision, session="s-decide"):
|
||||
replies = dict(TOOLS)
|
||||
replies["/api/plugin/moment"] = json.dumps(
|
||||
{"context": "a line beside it", "rule_ids": [], "moments": ["work.deliver"],
|
||||
"decision": decision}).encode()
|
||||
with http_sink(by_path=replies) as (port, _seen):
|
||||
return [_hook(tmp_path, port, session=session) for _ in range(2)]
|
||||
|
||||
|
||||
def test_the_hook_refuses_an_enforced_act_every_time(tmp_path):
|
||||
outs = _decided(tmp_path, {"kind": "enforce", "rule_ids": [6], "reason": "Not run: rule 6"})
|
||||
for out in outs:
|
||||
body = json.loads(out)["hookSpecificOutput"]
|
||||
assert body["permissionDecision"] == "deny"
|
||||
assert body["permissionDecisionReason"] == "Not run: rule 6"
|
||||
|
||||
|
||||
def test_the_hook_holds_an_act_once_then_lets_it_through_with_its_lines(tmp_path):
|
||||
first, second = _decided(tmp_path, {"kind": "hold", "rule_ids": [7], "reason": "Read rule 7"})
|
||||
assert json.loads(first)["hookSpecificOutput"]["permissionDecision"] == "deny"
|
||||
after = json.loads(second)["hookSpecificOutput"]
|
||||
assert "permissionDecision" not in after
|
||||
assert after["additionalContext"] == "a line beside it"
|
||||
|
||||
|
||||
# ── reminders wait for the act ──────────────────────────────────────────
|
||||
|
||||
|
||||
async def test_the_prompt_arm_leaves_a_rule_that_arrives_at_an_act_to_the_act():
|
||||
hits = [(0.9, _forced(21, "inform")), (0.89, _forced(22, "inform"))]
|
||||
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
|
||||
record_rule_surfaced=MagicMock())
|
||||
moment = rp.RuleMoment(user_id=1, query="merge it", project_id=2, where="to this request",
|
||||
elsewhere=frozenset({21}))
|
||||
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
|
||||
assert result.shown_rule_ids == [22]
|
||||
|
||||
|
||||
async def test_a_rule_arrives_at_an_act_by_a_mount_off_the_reply_or_an_act_trigger():
|
||||
from grimoire.services import rule_triggers
|
||||
|
||||
lookup = AsyncMock(return_value=[(_forced(31, "inform"), "work.deliver")])
|
||||
scoped = [
|
||||
(_forced(32, "inform"), [rule_triggers.Trigger("path", "alembic/**")]),
|
||||
(_forced(33, "inform"), [rule_triggers.Trigger("keyword", "let me know")]),
|
||||
(_forced(34, "inform"), [rule_triggers.Trigger("command", "git push", "work.deliver")]),
|
||||
]
|
||||
with patch.object(moment_actions, "list_mappings", AsyncMock(return_value=[])), \
|
||||
patch.object(rulebooks, "rules_on_moments", lookup), \
|
||||
patch.object(rule_triggers, "_in_scope", AsyncMock(return_value=scoped)):
|
||||
routed = await md.routed_to_acts(1, 2)
|
||||
# A keyword can match a reply; a trigger scoped to a moment is that moment's mount.
|
||||
assert routed == frozenset({31, 32})
|
||||
moments = lookup.await_args.args[1]
|
||||
assert moments and not any(m.startswith("reply.") for m in moments)
|
||||
|
||||
@@ -15,7 +15,8 @@ unchanged.
|
||||
|
||||
WHAT THIS PINS, AND WHAT IT DELIBERATELY DOES NOT
|
||||
|
||||
Pinned: the four conditions under which an act may be held, the two guards
|
||||
Pinned: the conditions under which an act may be held — among them that the
|
||||
rule is declared to hold — the two guards
|
||||
that stop it recurring, and the shape of the envelope. Not pinned: the bar
|
||||
itself (a tuning value, and a test asserting 0.80 would fail on every retune
|
||||
while proving nothing) or the wording of the reason (prose, and it will be
|
||||
@@ -58,7 +59,8 @@ def hit(score: float, rule_id: int, **attrs):
|
||||
# `attrs` overrides rather than duplicates: passing `when_to_apply=""` for
|
||||
# the no-trigger case alongside a hard-coded default is a duplicate keyword
|
||||
# and a TypeError, not a test.
|
||||
fields = {"id": rule_id, "title": f"rule {rule_id}", "when_to_apply": TRIGGER}
|
||||
fields = {"id": rule_id, "title": f"rule {rule_id}", "when_to_apply": TRIGGER,
|
||||
"enforcement": "hold"}
|
||||
fields.update(attrs)
|
||||
return (score, fake_rule(**fields))
|
||||
|
||||
@@ -97,6 +99,13 @@ def test_a_preference_never_holds_an_act():
|
||||
assert hold([hit(0.99, 2, kind="preference")]) == {}
|
||||
|
||||
|
||||
def test_a_rule_set_to_inform_never_holds_an_act():
|
||||
"""Only a rule declared to hold may stop the work; an `inform` rule asked
|
||||
to be put beside it, however confident the score."""
|
||||
assert hold([hit(0.99, 2, enforcement="inform")]) == {}
|
||||
assert hold([hit(0.99, 2, enforcement="enforce")])["rule_id"] == 2
|
||||
|
||||
|
||||
def test_a_rule_the_session_already_opened_never_holds_an_act():
|
||||
"""`held` is observable — a PostToolUse hook watches for the `get_rule`
|
||||
call — so this is a recorded event, not a model's self-report
|
||||
|
||||
@@ -4,9 +4,10 @@ An unopened rule above the stop bar HOLDS the reply
|
||||
once, in the server's words — the backstop for whatever the earlier arms
|
||||
missed — and the rewrite is never held. These pin, with the database stubbed:
|
||||
- which moments a reply reaches;
|
||||
- what holds: a mounted RULE the session has not opened, or the reply's top
|
||||
semantic hit above the reply surface's bar — never a preference, never a
|
||||
rule already opened or already held once, never past the session cap;
|
||||
- what holds: a mounted rule declared to hold that the session has not
|
||||
opened, or the reply's top semantic hit above the reply surface's bar when
|
||||
it is declared to hold — never an `inform` rule, never a preference, never
|
||||
a rule already opened or already held once, never past the session cap;
|
||||
- that the stop-only arm records surfacing for the held rule alone;
|
||||
- the hook's contract: blocks only on the server's reason, records the hold
|
||||
before emitting it, and never holds the rewrite.
|
||||
@@ -32,7 +33,7 @@ from tests.helpers import fake_rule, http_sink, need_tools
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HOOK = ROOT / "plugin" / "hooks" / "grimoire_reply_check.sh"
|
||||
|
||||
DONE = fake_rule(id=11, title="Definition of done", kind="rule",
|
||||
DONE = fake_rule(id=11, title="Definition of done", kind="rule", enforcement="hold",
|
||||
when_to_apply="about to tell the operator work is finished")
|
||||
|
||||
|
||||
@@ -100,13 +101,22 @@ async def test_a_mounted_rule_the_session_has_not_opened_holds_the_reply():
|
||||
|
||||
async def test_an_opened_rule_a_preference_and_an_earlier_hold_do_not_hold():
|
||||
pref = fake_rule(id=12, title="Lead with the outcome", kind="preference")
|
||||
other = fake_rule(id=13, title="Name the commit", kind="rule")
|
||||
other = fake_rule(id=13, title="Name the commit", kind="rule", enforcement="hold")
|
||||
mounted = [(DONE, "reply.report"), (pref, "reply.report"), (other, "reply.report")]
|
||||
_arm, surfaced, _lookup, stack = _stubs(mounted=mounted)
|
||||
assert await _hold(stack, held=frozenset({11}), stopped=frozenset({13})) == {}
|
||||
surfaced.assert_not_called()
|
||||
|
||||
|
||||
async def test_a_mounted_rule_set_to_inform_does_not_hold_the_reply():
|
||||
"""It was put in front of the turn before the reply was written; holding
|
||||
the reply on it again costs a rewrite for a rule that asked to be read."""
|
||||
inform = fake_rule(id=14, title="Lead with the outcome", kind="rule", enforcement="inform")
|
||||
_arm, surfaced, _lookup, stack = _stubs(mounted=[(inform, "reply.report")])
|
||||
assert await _hold(stack) == {}
|
||||
surfaced.assert_not_called()
|
||||
|
||||
|
||||
async def test_the_semantic_backstop_holds_and_never_names_a_mounted_rule_twice():
|
||||
cp = {"rule_id": 40, "title": "Read the job log first", "score": 0.84,
|
||||
"trigger": "a CI run overran"}
|
||||
@@ -130,7 +140,8 @@ async def test_past_the_session_cap_nothing_holds_and_nothing_is_asked():
|
||||
|
||||
|
||||
async def test_the_cap_trims_before_anything_is_recorded():
|
||||
rules = [(fake_rule(id=i, title=f"rule {i}", kind="rule"), "reply.report") for i in range(1, 9)]
|
||||
rules = [(fake_rule(id=i, title=f"rule {i}", kind="rule", enforcement="hold"), "reply.report")
|
||||
for i in range(1, 9)]
|
||||
_arm, surfaced, _lookup, stack = _stubs(mounted=rules)
|
||||
out = await _hold(stack, stopped=frozenset({50, 51}))
|
||||
room = pc.CHECKPOINT_SESSION_CAP - 2
|
||||
@@ -149,8 +160,8 @@ async def test_the_reply_check_fails_open():
|
||||
|
||||
|
||||
async def test_the_stop_only_arm_records_only_the_rule_that_holds():
|
||||
hits = [(0.86, fake_rule(id=40, title="a", kind="rule", when_to_apply="t")),
|
||||
(0.82, fake_rule(id=41, title="b", kind="rule", when_to_apply="t"))]
|
||||
hits = [(0.86, fake_rule(id=40, title="a", kind="rule", when_to_apply="t", enforcement="hold")),
|
||||
(0.82, fake_rule(id=41, title="b", kind="rule", when_to_apply="t", enforcement="hold"))]
|
||||
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
|
||||
record_rule_surfaced=MagicMock())
|
||||
moment = rp.RuleMoment(user_id=1, query="the reply", project_id=2,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""The server half of the end-of-turn shape check: what the
|
||||
agent is asked, what the hook's ledger may say, and the outcome record."""
|
||||
agent is asked at its next prompt, what the hook's ledger may say, and the
|
||||
outcome record."""
|
||||
import json
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -21,18 +22,18 @@ def test_the_ledger_lines_parse_and_garbage_is_dropped():
|
||||
assert len(parse_written("".join(f"p\tsym\tn{i}\n" for i in range(500)), cap=7)) == 7
|
||||
|
||||
|
||||
def test_a_first_stop_blocks_or_passes_and_the_next_never_blocks():
|
||||
def test_a_stop_notes_or_passes_and_the_stop_after_the_note_records_the_answer():
|
||||
from grimoire.services.shape_check import outcome_for
|
||||
|
||||
one = [{"path": "a", "kind": "sym", "symbol": "b"}]
|
||||
assert outcome_for("check", one) == "blocked"
|
||||
assert outcome_for("check", one) == "noted"
|
||||
assert outcome_for("check", []) == "passed"
|
||||
assert outcome_for("after", one) == "left_after_block"
|
||||
assert outcome_for("after", []) == "judged_after_block"
|
||||
assert outcome_for("after", one) == "left_after_note"
|
||||
assert outcome_for("after", []) == "judged_after_note"
|
||||
|
||||
|
||||
def test_the_reason_names_each_shape_its_evidence_and_the_one_call():
|
||||
from grimoire.services.shape_check import block_reason
|
||||
def test_the_note_names_each_shape_its_evidence_and_the_one_call():
|
||||
from grimoire.services.shape_check import note_text
|
||||
|
||||
unjudged = [
|
||||
{"path": "web/A.svelte", "kind": "file", "symbol": "A", "status": "new", "evidence": {}},
|
||||
@@ -40,8 +41,8 @@ def test_the_reason_names_each_shape_its_evidence_and_the_one_call():
|
||||
"evidence": {"looks_like": {"snippet_id": 12, "basis": "semantic", "score": 0.84},
|
||||
"diverges_from": 9}},
|
||||
]
|
||||
reason = block_reason(unjudged, project_id=3, repo="git.example.com/a/w")
|
||||
assert "2 definitions" in reason
|
||||
reason = note_text(unjudged, project_id=3, repo="git.example.com/a/w")
|
||||
assert "last turn wrote 2 definitions" in reason
|
||||
assert "web/A.svelte · A (file) — new" in reason
|
||||
assert "looks like #12 0.84" in reason and "#9 is canon in this directory" in reason
|
||||
assert 'classify_shapes(project_id=3, repo="git.example.com/a/w"' in reason
|
||||
@@ -50,11 +51,11 @@ def test_the_reason_names_each_shape_its_evidence_and_the_one_call():
|
||||
|
||||
|
||||
def test_a_long_turn_is_listed_with_a_tail_not_dropped():
|
||||
from grimoire.services.shape_check import _LISTED, block_reason
|
||||
from grimoire.services.shape_check import _LISTED, note_text
|
||||
|
||||
many = [{"path": "p.py", "kind": "sym", "symbol": f"f{i}", "status": "new", "evidence": {}}
|
||||
for i in range(_LISTED + 3)]
|
||||
reason = block_reason(many, project_id=1, repo="")
|
||||
reason = note_text(many, project_id=1, repo="")
|
||||
assert "… and 3 more" in reason
|
||||
assert "repo=" not in reason
|
||||
|
||||
@@ -64,10 +65,10 @@ async def test_the_outcome_is_recorded_as_a_plugin_event():
|
||||
|
||||
session = make_mock_session()
|
||||
with patch("grimoire.services.shape_check.async_session", return_value=session):
|
||||
await record_shape_check(7, "blocked", written=5, unjudged=2, project_id=2)
|
||||
await record_shape_check(7, "noted", written=5, unjudged=2, project_id=2)
|
||||
row = session.add.call_args.args[0]
|
||||
assert (row.category, row.action, row.user_id) == ("plugin", "shape_check", 7)
|
||||
assert json.loads(row.details) == {"outcome": "blocked", "written": 5,
|
||||
assert json.loads(row.details) == {"outcome": "noted", "written": 5,
|
||||
"unjudged": 2, "project_id": 2}
|
||||
|
||||
|
||||
@@ -85,5 +86,8 @@ def test_the_window_counts_turns_asks_and_asks_walked_past():
|
||||
from grimoire.services.shape_check import summarise
|
||||
|
||||
assert summarise([]) == {"checked": 0, "asked": 0, "left": 0}
|
||||
got = summarise(["passed", "blocked", "judged_after_block", "blocked", "left_after_block"])
|
||||
got = summarise(["passed", "noted", "judged_after_note", "noted", "left_after_note"])
|
||||
assert got == {"checked": 3, "asked": 2, "left": 1}
|
||||
# A window that spans the end-of-turn hold this check once was still sums.
|
||||
mixed = summarise(["blocked", "left_after_block", "noted", "judged_after_note"])
|
||||
assert mixed == {"checked": 2, "asked": 2, "left": 1}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""The end-of-turn shape check: the write hooks note what each
|
||||
write defined, and the Stop hook asks the instance which of those nobody has
|
||||
judged, blocking once in the server's words.
|
||||
write defined, the Stop hook asks the instance which of those nobody has
|
||||
judged, and the answer rides the next prompt rather than holding the reply.
|
||||
|
||||
Runs the real shell against the shared HTTP sink. What it pins: the write
|
||||
hooks' ledger (a Write of a new file adds a `file` line; a skipped path adds
|
||||
nothing); silence with nothing written; a block only on a reason the instance
|
||||
returned; the post-block stop recorded and let through; another hook's block
|
||||
loop left alone; the ledger kept when the instance could not be reached.
|
||||
nothing); silence with nothing written; the Stop hook never blocks; a note
|
||||
only when the instance returned one, carried by the next prompt and then
|
||||
gone; the stop after that prompt records the answer; a note no prompt carried
|
||||
is asked again with the next turn's writes; another hook's block loop left
|
||||
alone; the ledger kept when the instance could not be reached.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -23,7 +25,8 @@ from tests.helpers import http_sink
|
||||
HOOKS = Path(__file__).resolve().parents[1] / "plugin" / "hooks"
|
||||
CHECK = HOOKS / "grimoire_shape_check.sh"
|
||||
PRIOR_ART = HOOKS / "grimoire_prior_art.sh"
|
||||
REASON = "SERVER REASON: judge what you wrote"
|
||||
PROMPT = HOOKS / "grimoire_autoinject.sh"
|
||||
NOTE = "SERVER NOTE: judge what you wrote"
|
||||
|
||||
|
||||
def _env(tmp_path, url="http://127.0.0.1:9"):
|
||||
@@ -127,7 +130,7 @@ def test_a_skipped_path_notes_nothing(tmp_path):
|
||||
# ── the Stop hook asks ────────────────────────────────────────────────────
|
||||
|
||||
def test_nothing_written_is_silent_and_asks_nothing(tmp_path):
|
||||
with http_sink(b'{"status":"ok","reason":"x"}') as (port, seen):
|
||||
with http_sink(b'{"status":"ok","note":"x"}') as (port, seen):
|
||||
env = _env(tmp_path, f"http://127.0.0.1:{port}")
|
||||
assert _stop(env, _repo(tmp_path)) == ""
|
||||
assert seen == []
|
||||
@@ -144,32 +147,84 @@ def test_all_judged_passes_silently_and_empties_the_ledger(tmp_path):
|
||||
assert not ledger.exists()
|
||||
|
||||
|
||||
def test_unjudged_blocks_once_in_the_servers_words_then_records_the_answer(tmp_path):
|
||||
reply = json.dumps({"status": "ok", "outcome": "blocked", "reason": REASON}).encode()
|
||||
def _note_file(tmp_path, session="s1"):
|
||||
return tmp_path / "grimoire-shapecheck" / f"{session}.note"
|
||||
|
||||
|
||||
def _asked_file(tmp_path, session="s1"):
|
||||
return tmp_path / "grimoire-shapecheck" / f"{session}.asked"
|
||||
|
||||
|
||||
def _prompt(env, cwd, text="carry on", session="s1"):
|
||||
out = subprocess.run(
|
||||
["bash", str(PROMPT)],
|
||||
input=json.dumps({"session_id": session, "prompt": text, "cwd": str(cwd),
|
||||
"transcript_path": "/nonexistent",
|
||||
"hook_event_name": "UserPromptSubmit"}),
|
||||
capture_output=True, text=True, env=env, timeout=30,
|
||||
)
|
||||
assert out.returncode == 0, out.stderr
|
||||
return out.stdout.strip()
|
||||
|
||||
|
||||
def test_unjudged_is_noted_for_the_next_prompt_and_never_holds_the_reply(tmp_path):
|
||||
reply = json.dumps({"status": "ok", "outcome": "noted", "note": NOTE,
|
||||
"context": "", "note_ids": []}).encode()
|
||||
with http_sink(reply) as (port, seen):
|
||||
env = _env(tmp_path, f"http://127.0.0.1:{port}")
|
||||
repo = _repo(tmp_path)
|
||||
ledger = _write_ledger(tmp_path, ["web/A.svelte\tfile\tA"])
|
||||
assert json.loads(_stop(env, repo)) == {"decision": "block", "reason": REASON}
|
||||
assert ledger.exists(), "kept, so the stop after the block asks about the same set"
|
||||
|
||||
# The stop after the block: recorded, never blocked, ledger consumed.
|
||||
assert _stop(env, repo, active=True) == ""
|
||||
assert [q["phase"] for q in seen] == [["check"], ["after"]]
|
||||
assert _stop(env, repo) == "", "the reply goes out as written"
|
||||
assert _note_file(tmp_path).read_text() == NOTE
|
||||
assert _asked_file(tmp_path).read_text().splitlines() == ["web/A.svelte\tfile\tA"]
|
||||
assert not ledger.exists()
|
||||
assert _stop(env, repo, active=True) == ""
|
||||
assert len(seen) == 2
|
||||
|
||||
# The next prompt carries the note, and it is gone once answered.
|
||||
_prompt(env, repo)
|
||||
assert seen[-1]["carry"] == [NOTE]
|
||||
assert not _note_file(tmp_path).exists()
|
||||
|
||||
# The stop after it records whether the noted lines were judged.
|
||||
assert _stop(env, repo) == ""
|
||||
assert seen[-1]["phase"] == ["after"]
|
||||
assert seen[-1]["written"] == ["web/A.svelte\tfile\tA"]
|
||||
assert not _asked_file(tmp_path).exists()
|
||||
before = len(seen)
|
||||
assert _stop(env, repo) == ""
|
||||
assert len(seen) == before, "asked once, recorded once"
|
||||
|
||||
|
||||
def test_no_block_without_a_reason_from_the_instance(tmp_path):
|
||||
def test_a_note_no_prompt_carried_is_asked_again_with_the_next_turns_writes(tmp_path):
|
||||
reply = json.dumps({"status": "ok", "outcome": "noted", "note": NOTE}).encode()
|
||||
with http_sink(reply) as (port, seen):
|
||||
env = _env(tmp_path, f"http://127.0.0.1:{port}")
|
||||
repo = _repo(tmp_path)
|
||||
_write_ledger(tmp_path, ["a.py\tsym\tfirst"])
|
||||
_stop(env, repo)
|
||||
_write_ledger(tmp_path, ["b.py\tsym\tsecond"])
|
||||
_stop(env, repo)
|
||||
assert seen[-1]["phase"] == ["check"]
|
||||
assert seen[-1]["written"] == ["b.py\tsym\tsecond\na.py\tsym\tfirst"]
|
||||
assert [q["phase"] for q in seen] == [["check"], ["check"]], "no prompt read it: no answer to record"
|
||||
|
||||
|
||||
def test_the_stop_hook_never_blocks(tmp_path):
|
||||
"""Structural, and able to fail: no decision is ever printed."""
|
||||
code = [ln for ln in CHECK.read_text().splitlines() if not ln.lstrip().startswith("#")]
|
||||
assert not any('"decision"' in ln or "block" in ln for ln in code)
|
||||
|
||||
|
||||
def test_no_note_without_one_from_the_instance(tmp_path):
|
||||
with http_sink(b'{"status":"ok"}') as (port, _seen):
|
||||
env = _env(tmp_path, f"http://127.0.0.1:{port}")
|
||||
_write_ledger(tmp_path, ["a.py\tsym\thelper"])
|
||||
ledger = _write_ledger(tmp_path, ["a.py\tsym\thelper"])
|
||||
assert _stop(env, _repo(tmp_path)) == ""
|
||||
assert not _note_file(tmp_path).exists()
|
||||
assert not ledger.exists()
|
||||
|
||||
|
||||
def test_another_hooks_block_loop_is_left_alone(tmp_path):
|
||||
with http_sink(b'{"status":"ok","reason":"x"}') as (port, seen):
|
||||
with http_sink(b'{"status":"ok","note":"x"}') as (port, seen):
|
||||
env = _env(tmp_path, f"http://127.0.0.1:{port}")
|
||||
ledger = _write_ledger(tmp_path, ["a.py\tsym\thelper"])
|
||||
assert _stop(env, _repo(tmp_path), active=True) == ""
|
||||
|
||||
Reference in New Issue
Block a user