feat(7731): enforced rules refuse the act, only hold rules hold, and the shape question rides the next prompt
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m45s
CI & Build / integration (push) Successful in 2m10s
CI & Build / Build & push image (push) Skipped
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m45s
CI & Build / integration (push) Successful in 2m10s
CI & Build / Build & push image (push) Skipped
- A rule set to enforce, reached by a mount or a trigger, refuses the tool call in its own words every time (`act_decision`, `/moment` returns `decision`, grimoire_moment.sh denies). Opening it does not lift it. - A rule set to hold denies the call once until read, under the act checkpoint's per-rule and per-session guard; file writes are never held. - The reply hold, the reply backstop and the act checkpoint hold only on rules declared hold or enforce (`rule_order.holds`). An inform rule is a line beside the work. - The prompt arm leaves rules that arrive at an act (mounted on a non-reply moment, or with a tool/path/command trigger) to that act. - The end-of-turn shape check no longer blocks: its note is kept for the next prompt, carried as `carry` into the one fitted payload, and the stop after that prompt records whether the lines were judged (noted / judged_after_note / left_after_note). - Rule editor and list copy say what hold and enforce now do. Plugin 2026.11.23.0005. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+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