diff --git a/frontend/src/api/moments.ts b/frontend/src/api/moments.ts index dd9c7778..0b5800d1 100644 --- a/frontend/src/api/moments.ts +++ b/frontend/src/api/moments.ts @@ -354,7 +354,7 @@ export function getRecordReach(days = 30): Promise { } /** The gates that can stop a tool call. */ -export type GateName = "enforce" | "hold" | "checkpoint" | "fence" | "reply"; +export type GateName = "enforce" | "hold" | "checkpoint" | "fence" | "reply" | "project_check"; export interface GateCounts { /** Calls denied, or for the fence, put to the operator. */ @@ -385,6 +385,8 @@ export interface GateStopsPayload { by_gate: Record; by_rule: GateRuleRow[]; fence: { tool: string; target: string | null; asks: number; ran: number }[]; + /** Messages flagged as reading like another project's work, per that project. */ + project_check: { target: string | null; asks: number; last_asked_at: string | null }[]; /** The first stop ever recorded; null when none has been. */ complete_from: string | null; covers_window: boolean | null; diff --git a/frontend/src/components/GateStops.vue b/frontend/src/components/GateStops.vue index 0553c15d..b0192eac 100644 --- a/frontend/src/components/GateStops.vue +++ b/frontend/src/components/GateStops.vue @@ -24,6 +24,7 @@ const GATES: [GateName, string][] = [ ["checkpoint", "Command checkpoint"], ["fence", "Project fence"], ["reply", "Reply held for a read"], + ["project_check", "Message meant for another project?"], ]; const any = computed(() => @@ -32,6 +33,8 @@ const any = computed(() => function gateText(gate: GateName, c: GateCounts): string[] { if (gate === "fence") return [`asked ${c.stops}`, `approved ${c.ran}`]; + // The session is told to check with the operator; nothing is stopped. + if (gate === "project_check") return [`asked ${c.stops}`]; const parts = [`stopped ${c.stops}`, `cleared by a read ${c.cleared}`, `misfired ${c.misfired}`]; // An enforced refusal has no cap, and the reply's cap is applied by the // server before anything holds, so neither can let a call through. @@ -101,6 +104,18 @@ function gateText(gate: GateName, c: GateCounts): string[] { +
+ Messages that read as another project's +
    +
  • + project {{ p.target }} + + asked {{ p.asks }} + last {{ fmtDate(p.last_asked_at) }} + +
  • +
+
diff --git a/src/grimoire/models/gate_stop.py b/src/grimoire/models/gate_stop.py index c59fbef4..9f74ae3d 100644 --- a/src/grimoire/models/gate_stop.py +++ b/src/grimoire/models/gate_stop.py @@ -12,7 +12,13 @@ HOLD = "hold" # a moment rule set to hold: one read before the act CHECKPOINT = "checkpoint" # the act checkpoint on a command (tool-rules) FENCE = "fence" # the project fence: the operator is asked REPLY = "reply" # a rule holding the finished reply for one read -GATES = (ENFORCE, HOLD, CHECKPOINT, FENCE, REPLY) +# The operator's message reads as another project's: the session is asked to +# check with them before acting (`services/project_check.py`). `tool` is +# "prompt", `target` the other project, `at` the two scores. +PROJECT_CHECK = "project_check" +GATES = (ENFORCE, HOLD, CHECKPOINT, FENCE, REPLY, PROJECT_CHECK) +# The gates that stand in front of something other than a rule. +RULELESS_GATES = (FENCE, PROJECT_CHECK) # What the hook did with it. STOPPED = "stopped" # the call was denied, the reason shown instead diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 32d198c5..57befc12 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -18,6 +18,7 @@ from grimoire.services import gate_stops as gate_stops_svc from grimoire.services import hook_payload as hook_payload_svc from grimoire.services import moment_delivery as moment_delivery_svc from grimoire.services import plugin_context as plugin_ctx_svc +from grimoire.services import project_check as project_check_svc from grimoire.services import reply_shapes as reply_shapes_svc from grimoire.services import repo_bindings as repo_bindings_svc from grimoire.services import rule_adherence as rule_adherence_svc @@ -223,6 +224,15 @@ async def autoinject_retrieve(): held_rule_ids = _int_list(request.args.get("held_rule_ids")) ctx = request.args.get("ctx") or "" + # Whether the message is this project's at all. The operator's own words + # only: the conversation tail is this session's, so it would always vote + # for this project. A message with no subject ("yes, go ahead") says + # nothing about where it belongs. + wrong_project = "" + if project_id and not plugin_ctx_svc.is_harness_turn(q) and plugin_ctx_svc._has_subject(q): + wrong_project = await project_check_svc.check( + g.user.id, q, project_id, request.args.get("session_id"), + ) rules = await plugin_ctx_svc.build_prompt_rule_hint( g.user.id, q, project_id=project_id, exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids, context=ctx, @@ -263,6 +273,9 @@ async def autoinject_retrieve(): hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()), })] fitted = await hook_payload_svc.fit(g.user.id, [ + # First, ahead of every rule: if the message was meant for another + # session, nothing after it should be acted on yet. + *([hook_payload_svc.Part(text=wrong_project)] if wrong_project else []), *ordered, *([hook_payload_svc.Part(text=carry)] if carry else []), *hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}), diff --git a/src/grimoire/services/gate_stops.py b/src/grimoire/services/gate_stops.py index 0af5accd..a54de1fb 100644 --- a/src/grimoire/services/gate_stops.py +++ b/src/grimoire/services/gate_stops.py @@ -29,7 +29,8 @@ from sqlalchemy import and_, case, delete, exists, func, select, update from grimoire.models import async_session from grimoire.models.gate_stop import ( - ASKED, FENCE, GATES, LET_THROUGH, OUTCOMES, STOPPED, GateStop, + ASKED, FENCE, GATES, LET_THROUGH, OUTCOMES, PROJECT_CHECK, RULELESS_GATES, STOPPED, + GateStop, ) from grimoire.models.rule_adherence import MISFIRE, RuleAdherence from grimoire.models.rulebook import Rule @@ -59,7 +60,7 @@ async def record( sid = rule_deliveries.clean_session(session_id) if not sid or gate not in GATES or outcome not in OUTCOMES or not _field(tool): return False - if gate != FENCE and not rule_id: + if gate not in RULELESS_GATES and not rule_id: return False async with async_session() as session: session.add(GateStop( @@ -112,6 +113,21 @@ async def mark_ran(user_id: int, session_id: str | None, call_id: str | None) -> return bool(result.rowcount) +async def asked(user_id: int, session_id: str | None, *, gate: str, target: str) -> bool: + """Whether this gate already stood in front of this session about this + target, so a session is asked about one other project once.""" + sid = rule_deliveries.clean_session(session_id) + if not sid: + return False + async with async_session() as session: + return (await session.execute( + select(exists().where( + GateStop.user_id == user_id, GateStop.session_id == sid, + GateStop.gate == gate, GateStop.target == _field(target), + )) + )).scalar_one() + + def _misfired(): """Whether the session reported the stopped rule as a misfire.""" return exists().where( @@ -139,7 +155,9 @@ async def summary(user_id: int, days: int = 30, *, since: datetime | None = None for the fence, the operator's yes) and `sessions`. `by_rule`: the same per rule and place, most stops first. `fence`: the - asks per tool and target project. `complete_from` is the first stop ever + asks per tool and target project. `project_check`: per other project, how + often a message was flagged as reading like its work rather than the + session's. `complete_from` is the first stop ever recorded, so a window reaching further back says so. """ until = until or datetime.now(timezone.utc) @@ -180,6 +198,12 @@ async def summary(user_id: int, days: int = 30, *, since: datetime | None = None .group_by(GateStop.tool, GateStop.target) .order_by(func.count(GateStop.id).desc(), GateStop.tool) )).all() + check_rows = (await session.execute( + select(GateStop.target, func.count(GateStop.id), func.max(GateStop.stopped_at)) + .where(window, GateStop.gate == PROJECT_CHECK) + .group_by(GateStop.target) + .order_by(func.count(GateStop.id).desc(), GateStop.target) + )).all() first = (await session.execute( select(func.min(GateStop.stopped_at)).where(GateStop.user_id == user_id) )).scalar_one_or_none() @@ -205,6 +229,11 @@ async def summary(user_id: int, days: int = 30, *, since: datetime | None = None {"tool": tool, "target": target, "asks": int(n or 0), "ran": int(ran or 0)} for tool, target, n, ran in fence_rows ], + "project_check": [ + {"target": target, "asks": int(n or 0), + "last_asked_at": last.isoformat() if last else None} + for target, n, last in check_rows + ], "complete_from": first.isoformat() if first else None, "covers_window": None if first is None else first <= since, } diff --git a/src/grimoire/services/project_check.py b/src/grimoire/services/project_check.py new file mode 100644 index 00000000..a2a3de2c --- /dev/null +++ b/src/grimoire/services/project_check.py @@ -0,0 +1,171 @@ +"""Does the operator's message belong to the project this session is in? + +An operator who runs one session per project can type a message into the +wrong window. Such a message usually reads as an ordinary request the session +could carry out in its own repo, so nothing crosses a project line and the +project fence never fires. This check reads where the message lands among the +operator's own records: when the nearest ones clearly belong to another +project, the session is told so, first in the prompt's payload, and asked to +confirm with the operator before acting. It asks; it never blocks. + +Each flag is recorded as a `project_check` gate stop (`gate_stops`), with the +two scores in `at`, so the bars below can be tuned from real prompts, and a +session is asked about one other project once. +""" +from __future__ import annotations + +import logging +import re +from dataclasses import dataclass + +logger = logging.getLogger(__name__) + +# How many of the nearest records are read: enough for one project's records +# to show up as a group, few enough to stay one exact cut. +NEAREST = 12 +# The search's own floor. Low on purpose, so this project's best match is +# known even when it is weak, which is when a message most likely is not its. +SEARCH_FLOOR = 0.5 +# The other project's nearest record must score at least this. Below it the +# message matches no project's records well, and "it belongs elsewhere" is +# a guess. +FLOOR = 0.78 +# How far the other project's nearest record must beat this project's. +MARGIN = 0.05 +# How many of the nearest records must be the other project's, so a single +# stray record cannot call a message another project's. +SUPPORT = 3 +# A message that names the other project, and not this one, needs only this +# share of the margin. A name alone never flags: many project names are +# ordinary words ("portal", "interpreter"), and naming another project on +# purpose is common. +NAMED_MARGIN_SHARE = 0.5 +# The operator's words that are read; a long paste adds nothing to where the +# message lands. +QUERY_CHARS = 2000 + + +@dataclass(frozen=True) +class Verdict: + other_id: int + other_score: float + here_score: float + + +def judge( + hits: list[tuple[float, int | None]], project_id: int, *, + named: frozenset[int] = frozenset(), +) -> Verdict | None: + """Whether the nearest records say the message is another project's. + + `hits` are (score, project id) for the nearest records, any order; a + record in no project is left out. `named` holds the projects the message + names by title. Naming this project rules out a flag. + """ + if project_id in named: + return None + best: dict[int, float] = {} + count: dict[int, int] = {} + for score, pid in hits: + if pid is None: + continue + best[pid] = max(best.get(pid, score), score) + count[pid] = count.get(pid, 0) + 1 + here = best.get(project_id, 0.0) + others = [(score, pid) for pid, score in best.items() if pid != project_id] + if not others: + return None + other_score, other_id = max(others) + margin = MARGIN * (NAMED_MARGIN_SHARE if other_id in named else 1.0) + if other_score < FLOOR or other_score - here < margin or count[other_id] < SUPPORT: + return None + return Verdict(other_id=other_id, other_score=other_score, here_score=here) + + +def _name_forms(title: str) -> set[str]: + """The ways a message names a project: its title, and its title without a + leading "Fabled" ("Fabled Librarian" is called "Librarian").""" + title = " ".join((title or "").split()) + forms = {title.lower()} if title else set() + bare = re.sub(r"^fabled[\s-]*", "", title, flags=re.IGNORECASE) + if bare and len(bare) >= 4: + forms.add(bare.lower()) + return forms + + +def named_projects(prompt: str, titles: dict[int, str]) -> frozenset[int]: + """The projects whose title the message contains as a whole phrase.""" + text = (prompt or "").lower() + return frozenset( + pid for pid, title in titles.items() + if any(re.search(r"(? str: + other = titles.get(verdict.other_id, f"project {verdict.other_id}") + here = titles.get(project_id, f"project {project_id}") + return ( + f"> **This message may be meant for another session.** It reads as " + f"{other}'s work rather than {here}'s, the project this session is in: " + f"its nearest records are {other}'s ({verdict.other_score:.2f}, against " + f"{verdict.here_score:.2f} for {here}). The operator runs one session per " + f"project and can type into the wrong one. Before acting on it, ask them " + f"whether it was meant for this session, naming {other}; if it was, carry on." + ) + + +async def _titles(user_id: int) -> dict[int, str]: + from sqlalchemy import select + + from grimoire.models import async_session + from grimoire.models.project import Project + + async with async_session() as session: + return dict((await session.execute( + select(Project.id, Project.title).where(Project.user_id == user_id) + )).all()) + + +async def _asked_before(user_id: int, session_id: str | None, other_id: int) -> bool: + from grimoire.services import gate_stops + + return await gate_stops.asked(user_id, session_id, gate="project_check", + target=str(other_id)) + + +async def check(user_id: int, prompt: str, project_id: int, session_id: str | None = None) -> str: + """The line to lead the prompt's payload with, or "" when the message + fits this session's project, or nothing can be said. Fails open.""" + if not project_id or not (prompt or "").strip(): + return "" + from grimoire.services import gate_stops + from grimoire.services.embeddings import semantic_search_notes + + try: + hits = await semantic_search_notes( + user_id, prompt[:QUERY_CHARS], limit=NEAREST, threshold=SEARCH_FLOOR, + project_id=None, scope="own", demote_superseded=False, + ) + if not hits: + return "" + titles = await _titles(user_id) + verdict = judge( + [(score, getattr(note, "project_id", None)) for score, note in hits], + project_id, named=named_projects(prompt, titles), + ) + if verdict is None or verdict.other_id not in titles: + return "" + if session_id and await _asked_before(user_id, session_id, verdict.other_id): + return "" + if session_id: + await gate_stops.record( + user_id, session_id, gate="project_check", outcome="asked", tool="prompt", + target=str(verdict.other_id), + at=f"{verdict.other_score:.3f} vs {verdict.here_score:.3f}", + ) + return line(verdict, titles, project_id) + except Exception: # noqa: BLE001 - a hint never costs the operator their prompt + logger.warning("project check failed", exc_info=True) + return "" diff --git a/tests/test_integration_gate_stops.py b/tests/test_integration_gate_stops.py index d4d34578..1badffaf 100644 --- a/tests/test_integration_gate_stops.py +++ b/tests/test_integration_gate_stops.py @@ -111,6 +111,20 @@ async def test_the_readout_counts_stops_reads_misfires_and_the_cap_per_gate_and_ 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) diff --git a/tests/test_project_check.py b/tests/test_project_check.py new file mode 100644 index 00000000..2b1ce50e --- /dev/null +++ b/tests/test_project_check.py @@ -0,0 +1,131 @@ +"""The check on whether the operator's message belongs to the session's project. + +Pins, with the database stubbed: +- the nearest records decide: another project flags only when its best match + is high, clearly ahead of this project's, and backed by several records; +- a name helps but never flags alone, and naming this project rules a flag out; +- a session is asked about one other project once, and the ask is recorded; +- the line leads the prompt's payload, and a session with no project is never + checked. +""" +from __future__ import annotations + +import inspect +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch + +from quart import Quart, g + +from grimoire.services import project_check as pc + +HERE, OTHER, THIRD = 2, 6, 9 +TITLES = {HERE: "FabledGrimoire", OTHER: "Steward", THIRD: "Fabled Librarian"} + + +def _hits(*pairs): + return [(score, pid) for score, pid in pairs] + + +def test_a_message_whose_nearest_records_are_another_projects_is_flagged(): + verdict = pc.judge(_hits((0.86, OTHER), (0.84, OTHER), (0.83, OTHER), (0.74, HERE)), HERE) + assert verdict == pc.Verdict(other_id=OTHER, other_score=0.86, here_score=0.74) + + +def test_a_message_that_fits_this_project_is_not_flagged(): + assert pc.judge(_hits((0.86, HERE), (0.85, OTHER), (0.84, OTHER), (0.83, OTHER)), HERE) is None + + +def test_each_bar_on_its_own_keeps_a_flag_back(): + # Below the floor: nobody's records match the message well. + assert pc.judge(_hits((0.76, OTHER), (0.75, OTHER), (0.75, OTHER)), HERE) is None + # Ahead by less than the margin. + assert pc.judge(_hits((0.85, OTHER), (0.84, OTHER), (0.84, OTHER), (0.82, HERE)), HERE) is None + # One stray record is not a project's worth of support. + assert pc.judge(_hits((0.90, OTHER), (0.80, THIRD), (0.79, THIRD), (0.70, HERE)), HERE) is None + + +def test_records_in_no_project_say_nothing_about_where_a_message_belongs(): + assert pc.judge(_hits((0.95, None), (0.94, None), (0.93, None)), HERE) is None + + +def test_a_name_narrows_the_margin_but_naming_this_project_rules_a_flag_out(): + hits = _hits((0.85, OTHER), (0.84, OTHER), (0.83, OTHER), (0.82, HERE)) + assert pc.judge(hits, HERE) is None + assert pc.judge(hits, HERE, named=frozenset({OTHER})) is not None + assert pc.judge(hits, HERE, named=frozenset({OTHER, HERE})) is None + + +def test_names_are_matched_as_whole_phrases_with_or_without_fabled(): + assert pc.named_projects("the librarian sidebar flickers", TITLES) == {THIRD} + assert pc.named_projects("check Steward's backups", TITLES) == {OTHER} + assert pc.named_projects("stewardship of the data", TITLES) == frozenset() + + +def test_the_line_names_both_projects_and_asks_before_acting(): + text = pc.line(pc.Verdict(OTHER, 0.86, 0.74), TITLES, HERE) + assert "Steward" in text and "FabledGrimoire" in text + assert "0.86" in text and "0.74" in text + assert "ask them" in text + + +async def _check(hits, *, asked=False, session="s-1"): + record = AsyncMock(return_value=True) + notes = [(score, SimpleNamespace(project_id=pid)) for score, pid in hits] + with patch("grimoire.services.embeddings.semantic_search_notes", AsyncMock(return_value=notes)), \ + patch.object(pc, "_titles", AsyncMock(return_value=TITLES)), \ + patch.object(pc, "_asked_before", AsyncMock(return_value=asked)), \ + patch("grimoire.services.gate_stops.record", record): + out = await pc.check(1, "the backup job missed last night", HERE, session) + return out, record + + +async def test_a_flag_is_recorded_as_a_project_check_ask_with_both_scores(): + out, record = await _check(_hits((0.86, OTHER), (0.84, OTHER), (0.83, OTHER), (0.74, HERE))) + assert out.startswith("> **This message may be meant for another session.**") + kw = record.await_args.kwargs + assert kw["gate"] == "project_check" and kw["outcome"] == "asked" + assert kw["target"] == str(OTHER) and kw["at"] == "0.860 vs 0.740" + + +async def test_a_session_is_asked_about_one_other_project_once(): + out, record = await _check(_hits((0.86, OTHER), (0.84, OTHER), (0.83, OTHER)), asked=True) + assert out == "" + record.assert_not_awaited() + + +async def test_a_failed_search_lets_the_prompt_through_silently(): + with patch("grimoire.services.embeddings.semantic_search_notes", AsyncMock(side_effect=RuntimeError)): + assert await pc.check(1, "the backup job", HERE, "s-1") == "" + assert await pc.check(1, "the backup job", 0, "s-1") == "" + + +async def _retrieve(query_string, wrong="WRONG PROJECT LINE"): + from grimoire.routes import plugin as routes + + check = AsyncMock(return_value=wrong) + app = Quart(__name__) + async with app.test_request_context("/api/plugin/retrieve", query_string=query_string): + g.user = SimpleNamespace(id=7) + with patch.object(routes.project_check_svc, "check", check), \ + patch.object(routes.plugin_ctx_svc, "build_prompt_rule_hint", + AsyncMock(return_value={"context": "RULE LINE", "rule_ids": [11], + "shown_rule_ids": [11]})), \ + patch.object(routes.plugin_ctx_svc, "build_autoinject_hint", + AsyncMock(return_value={"context": "NOTES MENU", "note_ids": []})), \ + patch.object(routes.moment_delivery_svc, "deliver_for_turn", + AsyncMock(return_value={"context": "", "rule_ids": [], "shape_forms": {}})): + resp = await inspect.unwrap(routes.autoinject_retrieve)() + return await resp.get_json(), check + + +async def test_the_flag_leads_the_payload_ahead_of_every_rule(): + body, check = await _retrieve({"q": "the backup job missed", "project_id": "2", "session_id": "s-1"}) + assert body["context"].index("WRONG PROJECT LINE") < body["context"].index("RULE LINE") + assert check.await_args.args == (7, "the backup job missed", 2, "s-1") + + +async def test_a_session_with_no_project_or_a_message_with_no_subject_is_not_checked(): + _body, check = await _retrieve({"q": "the backup job missed"}) + check.assert_not_awaited() + _body, check = await _retrieve({"q": "yes go ahead", "project_id": "2"}) + check.assert_not_awaited()