Files
FabledGrimoire/tests/test_integration_gate_stops.py
T
bvandeusenandClaude Opus 5.5 58991038d8
CI & Build / TypeScript typecheck (push) Successful in 10s
CI & Build / Python lint (push) Successful in 1s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / integration (push) Successful in 2m57s
CI & Build / Build & push image (push) Successful in 35s
feat(8815): a message that reads as another project's work asks the session to check before acting
An operator running one session per project can type into the wrong
window, and nothing caught it: the message usually asks for work the
session can do in its own repo, so the project fence never fires.

The prompt lookup (/api/plugin/retrieve) now ranks the operator's own
words against every project's records (services/project_check.py). When
another project's records clearly win (best match >= 0.78, ahead of this
project's by 0.05, with at least 3 of the 12 nearest), a line leads the
payload, ahead of every rule, telling the session to ask the operator
whether the message was meant for it. Naming the other project halves the
margin but never flags alone; naming this project rules a flag out. A
message with no subject, or a session with no project, is not checked.

Each flag is a new `project_check` gate stop with both scores, asked once
per session per other project, read back in retrieval_telemetry's gates
block and in the web UI's gate readout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 22:21:49 -05:00

137 lines
6.8 KiB
Python

"""Real-Postgres tests for `gate_stops`: each time a gate stood in front of a
tool call, the read that cleared it, the run that followed a yes, and the
readout per gate and per rule."""
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import delete, select, update
from grimoire.models import async_session
from grimoire.models.gate_stop import GateStop
from grimoire.models.rule_adherence import MISFIRE, NOT_APPLICABLE, RuleAdherence
from grimoire.services import gate_stops, rule_adherence
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
RULE = 9_300_001
OTHER = 9_300_002
async def _user(name: str = "gate_stop_owner") -> int:
async with async_session() as s:
user = await ensure_user(s, name)
uid = user.id
await s.commit()
await s.execute(delete(GateStop).where(GateStop.user_id == uid))
await s.execute(delete(RuleAdherence).where(RuleAdherence.user_id == uid))
await s.commit()
return uid
async def _rows(uid) -> list[GateStop]:
async with async_session() as s:
return list((await s.execute(
select(GateStop).where(GateStop.user_id == uid).order_by(GateStop.id)
)).scalars().all())
async def test_a_stop_without_a_session_gate_or_rule_records_nothing():
uid = await _user()
assert not await gate_stops.record(uid, "", gate="hold", outcome="stopped", tool="bash", rule_id=RULE)
assert not await gate_stops.record(uid, "s", gate="nonsense", outcome="stopped", tool="bash", rule_id=RULE)
assert not await gate_stops.record(uid, "s", gate="hold", outcome="stopped", tool="bash")
# The fence is the one gate with no rule behind it.
assert await gate_stops.record(uid, "s", gate="fence", outcome="asked", tool="update_task", target="9")
assert [(r.gate, r.rule_id, r.target) for r in await _rows(uid)] == [("fence", None, "9")]
async def test_an_open_clears_the_latest_stop_of_that_rule_in_that_session_only():
uid = await _user()
for sid in ("s-1", "s-2"):
await gate_stops.record(uid, sid, gate="hold", outcome="stopped", tool="bash",
rule_id=RULE, at="work.deliver")
assert await gate_stops.mark_cleared(uid, "s-1", RULE)
# Nothing left to clear for it there, and another rule's open clears nothing.
assert not await gate_stops.mark_cleared(uid, "s-1", RULE)
assert not await gate_stops.mark_cleared(uid, "s-2", OTHER)
cleared = {r.session_id: r.cleared_at is not None for r in await _rows(uid)}
assert cleared == {"s-1": True, "s-2": False}
async def test_an_open_long_after_the_stop_does_not_clear_it():
uid = await _user()
await gate_stops.record(uid, "s-old", gate="checkpoint", outcome="stopped", tool="Bash", rule_id=RULE)
async with async_session() as s:
await s.execute(update(GateStop).where(GateStop.user_id == uid).values(
stopped_at=datetime.now(timezone.utc) - timedelta(days=1)))
await s.commit()
assert not await gate_stops.mark_cleared(uid, "s-old", RULE)
async def test_the_run_after_a_fence_ask_is_matched_by_its_call_id():
uid = await _user()
await gate_stops.record(uid, "s-f", gate="fence", outcome="asked", tool="retire_family_idea",
target="9", call_id="toolu_1")
assert not await gate_stops.mark_ran(uid, "s-f", "toolu_2")
assert await gate_stops.mark_ran(uid, "s-f", "toolu_1")
assert not await gate_stops.mark_ran(uid, "s-f", "toolu_1")
assert (await _rows(uid))[0].ran_at is not None
async def test_the_readout_counts_stops_reads_misfires_and_the_cap_per_gate_and_rule():
uid = await _user()
# Rule RULE held in three sessions: one cleared by a read, one called a
# misfire, one never answered. Then once let through by a spent budget.
for sid in ("a", "b", "c"):
await gate_stops.record(uid, sid, gate="hold", outcome="stopped", tool="bash",
rule_id=RULE, at="work.deliver")
await gate_stops.mark_cleared(uid, "a", RULE)
await rule_adherence.record(uid, "b", RULE, "work.deliver", NOT_APPLICABLE, MISFIRE, "not this act")
await gate_stops.record(uid, "d", gate="hold", outcome="let_through", tool="bash",
rule_id=RULE, at="work.deliver")
await gate_stops.record(uid, "a", gate="checkpoint", outcome="stopped", tool="Bash",
rule_id=OTHER, at="pre_tool_rule")
await gate_stops.record(uid, "a", gate="fence", outcome="asked", tool="update_task",
target="9", call_id="t1")
await gate_stops.record(uid, "a", gate="fence", outcome="asked", tool="update_task",
target="9", call_id="t2")
await gate_stops.mark_ran(uid, "a", "t1")
out = await gate_stops.summary(uid, days=7)
hold = out["by_gate"]["hold"]
assert (hold["stops"], hold["cleared"], hold["misfired"], hold["let_through"], hold["sessions"]) == (3, 1, 1, 1, 4)
assert out["by_gate"]["checkpoint"]["stops"] == 1
assert out["by_gate"]["enforce"] == {"stops": 0, "let_through": 0, "cleared": 0,
"misfired": 0, "ran": 0, "sessions": 0}
assert (out["by_gate"]["fence"]["stops"], out["by_gate"]["fence"]["ran"]) == (2, 1)
first = out["by_rule"][0]
assert (first["rule_id"], first["gate"], first["at"], first["stops"]) == (RULE, "hold", "work.deliver", 3)
assert out["fence"] == [{"tool": "update_task", "target": "9", "asks": 2, "ran": 1}]
assert out["complete_from"] is not None
async def test_a_project_check_needs_no_rule_is_asked_once_per_session_and_is_read_back():
uid = await _user()
assert not await gate_stops.asked(uid, "s-1", gate="project_check", target="6")
assert await gate_stops.record(uid, "s-1", gate="project_check", outcome="asked",
tool="prompt", target="6", at="0.860 vs 0.740")
assert await gate_stops.asked(uid, "s-1", gate="project_check", target="6")
# Another session, or another project, has not been asked.
assert not await gate_stops.asked(uid, "s-2", gate="project_check", target="6")
assert not await gate_stops.asked(uid, "s-1", gate="project_check", target="9")
out = await gate_stops.summary(uid, days=1)
assert out["by_gate"]["project_check"]["stops"] == 1
assert [(p["target"], p["asks"]) for p in out["project_check"]] == [("6", 1)]
async def test_stops_age_out_with_the_deliveries():
uid = await _user()
await gate_stops.record(uid, "s", gate="hold", outcome="stopped", tool="bash", rule_id=RULE)
async with async_session() as s:
await s.execute(update(GateStop).where(GateStop.user_id == uid).values(
stopped_at=datetime.now(timezone.utc) - timedelta(days=400)))
await s.commit()
await gate_stops.prune(datetime.now(timezone.utc) - timedelta(days=180))
assert await _rows(uid) == []