dev → main: wrong-session check, path-trigger holds on writes, query alias #243
@@ -354,7 +354,7 @@ export function getRecordReach(days = 30): Promise<RecordReachPayload> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The gates that can stop a tool call. */
|
/** 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 {
|
export interface GateCounts {
|
||||||
/** Calls denied, or for the fence, put to the operator. */
|
/** Calls denied, or for the fence, put to the operator. */
|
||||||
@@ -385,6 +385,8 @@ export interface GateStopsPayload {
|
|||||||
by_gate: Record<GateName, GateCounts & { sessions: number }>;
|
by_gate: Record<GateName, GateCounts & { sessions: number }>;
|
||||||
by_rule: GateRuleRow[];
|
by_rule: GateRuleRow[];
|
||||||
fence: { tool: string; target: string | null; asks: number; ran: number }[];
|
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. */
|
/** The first stop ever recorded; null when none has been. */
|
||||||
complete_from: string | null;
|
complete_from: string | null;
|
||||||
covers_window: boolean | null;
|
covers_window: boolean | null;
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ const GATES: [GateName, string][] = [
|
|||||||
["checkpoint", "Command checkpoint"],
|
["checkpoint", "Command checkpoint"],
|
||||||
["fence", "Project fence"],
|
["fence", "Project fence"],
|
||||||
["reply", "Reply held for a read"],
|
["reply", "Reply held for a read"],
|
||||||
|
["project_check", "Message meant for another project?"],
|
||||||
];
|
];
|
||||||
|
|
||||||
const any = computed(() =>
|
const any = computed(() =>
|
||||||
@@ -32,6 +33,8 @@ const any = computed(() =>
|
|||||||
|
|
||||||
function gateText(gate: GateName, c: GateCounts): string[] {
|
function gateText(gate: GateName, c: GateCounts): string[] {
|
||||||
if (gate === "fence") return [`asked ${c.stops}`, `approved ${c.ran}`];
|
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}`];
|
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
|
// 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.
|
// server before anything holds, so neither can let a call through.
|
||||||
@@ -101,6 +104,18 @@ function gateText(gate: GateName, c: GateCounts): string[] {
|
|||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</details>
|
</details>
|
||||||
|
<details v-if="data.project_check?.length" class="gate-detail">
|
||||||
|
<summary>Messages that read as another project's</summary>
|
||||||
|
<ul class="gate-list">
|
||||||
|
<li v-for="p in data.project_check" :key="`${p.target}`" class="gate-row">
|
||||||
|
<span class="gate-title">project {{ p.target }}</span>
|
||||||
|
<span class="gate-counts">
|
||||||
|
<span>asked {{ p.asks }}</span>
|
||||||
|
<span v-if="p.last_asked_at" class="stat-when">last {{ fmtDate(p.last_asked_at) }}</span>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
</template>
|
</template>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "grimoire",
|
"name": "grimoire",
|
||||||
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon, reviewing-tests), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
|
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon, reviewing-tests), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
|
||||||
"version": "2026.12.04.1944",
|
"version": "2026.12.06.0317",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "Bryan Van Deusen"
|
"name": "Bryan Van Deusen"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -48,7 +48,8 @@ declared `enforce` refuses the call every time, in its own words: that is a
|
|||||||
boundary the operator drew, and it moves only when they change the rule, so
|
boundary the operator drew, and it moves only when they change the rule, so
|
||||||
tell them what you were doing and what the rule said. A rule with triggers of
|
tell them what you were doing and what the rule said. A rule with triggers of
|
||||||
its own holds or refuses only the acts those triggers match; at the rest of
|
its own holds or refuses only the acts those triggers match; at the rest of
|
||||||
its moments it arrives as a line.
|
its moments it arrives as a line. A file edit is held only by a rule whose
|
||||||
|
path trigger names that file.
|
||||||
|
|
||||||
A moment sends a few lines, not every rule mounted there: ordered by
|
A moment sends a few lines, not every rule mounted there: ordered by
|
||||||
enforcement, then salience, then how exactly the act reached the rule, then
|
enforcement, then salience, then how exactly the act reached the rule, then
|
||||||
|
|||||||
@@ -295,6 +295,23 @@ def _body_calls_write_tool(body: bytes) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
# Spellings callers reach for that mean exactly one declared argument. A tool
|
||||||
|
# that declares the canonical name and not the alias takes the alias in its
|
||||||
|
# place: `query` is the most common miss for the search tools' `q`, and it
|
||||||
|
# cannot mean anything else. Passing both is left to the unknown-argument check.
|
||||||
|
_ALIASES = {"query": "q"}
|
||||||
|
|
||||||
|
|
||||||
|
def _with_aliases(arguments: dict | None, declared: set[str]) -> dict | None:
|
||||||
|
if not arguments:
|
||||||
|
return arguments
|
||||||
|
out = dict(arguments)
|
||||||
|
for alias, name in _ALIASES.items():
|
||||||
|
if alias in out and alias not in declared and name in declared and name not in out:
|
||||||
|
out[name] = out.pop(alias)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
class StrictArgsMCPServer(MCPServer):
|
class StrictArgsMCPServer(MCPServer):
|
||||||
"""An MCPServer that REJECTS tool calls carrying undeclared arguments.
|
"""An MCPServer that REJECTS tool calls carrying undeclared arguments.
|
||||||
|
|
||||||
@@ -323,6 +340,7 @@ class StrictArgsMCPServer(MCPServer):
|
|||||||
tool = None # unknown tool → let upstream produce its own error
|
tool = None # unknown tool → let upstream produce its own error
|
||||||
if tool is not None:
|
if tool is not None:
|
||||||
declared = set((tool.parameters or {}).get("properties", {}))
|
declared = set((tool.parameters or {}).get("properties", {}))
|
||||||
|
arguments = _with_aliases(arguments, declared)
|
||||||
unknown = sorted(set(arguments or {}) - declared)
|
unknown = sorted(set(arguments or {}) - declared)
|
||||||
if unknown:
|
if unknown:
|
||||||
hints = []
|
hints = []
|
||||||
|
|||||||
@@ -255,7 +255,8 @@ async def rules_to_weigh(limit: int = 25, offset: int = 0) -> dict:
|
|||||||
|
|
||||||
- `enforcement`: `inform` is a line beside the work, and is right for
|
- `enforcement`: `inform` is a line beside the work, and is right for
|
||||||
most rules. `hold` makes the act or reply wait until the rule has been
|
most rules. `hold` makes the act or reply wait until the rule has been
|
||||||
read once in the session (file edits are never held). `enforce` refuses
|
read once in the session (a file edit only through a path trigger
|
||||||
|
naming that file). `enforce` refuses
|
||||||
the act the rule governs, in the rule's own words, every time — for a
|
the act the rule governs, in the rule's own words, every time — for a
|
||||||
rule whose breach an act commits and that must never be crossed without
|
rule whose breach an act commits and that must never be crossed without
|
||||||
the operator (pushing to a protected branch, a destructive command). A
|
the operator (pushing to a protected branch, a destructive command). A
|
||||||
|
|||||||
@@ -553,7 +553,7 @@ async def create_rule(
|
|||||||
enforcement: What this rule does when it arrives. `inform` (the
|
enforcement: What this rule does when it arrives. `inform` (the
|
||||||
default) puts a line beside the work. `hold` makes the reply or
|
default) puts a line beside the work. `hold` makes the reply or
|
||||||
act it governs wait until the session has read the rule once
|
act it governs wait until the session has read the rule once
|
||||||
(file edits are never held) — for a rule whose miss costs a
|
(a file edit only through a path trigger naming that file) — for a rule whose miss costs a
|
||||||
rewrite. `enforce` refuses the act it governs, in the rule's own
|
rewrite. `enforce` refuses the act it governs, in the rule's own
|
||||||
words, every time — for a boundary only the operator moves; it
|
words, every time — for a boundary only the operator moves; it
|
||||||
needs a trigger, or a mount on a moment an act reaches, to have
|
needs a trigger, or a mount on a moment an act reaches, to have
|
||||||
@@ -691,7 +691,7 @@ async def create_project_rule(
|
|||||||
enforcement: What this rule does when it arrives. `inform` (the
|
enforcement: What this rule does when it arrives. `inform` (the
|
||||||
default) puts a line beside the work. `hold` makes the reply or
|
default) puts a line beside the work. `hold` makes the reply or
|
||||||
act it governs wait until the session has read the rule once
|
act it governs wait until the session has read the rule once
|
||||||
(file edits are never held) — for a rule whose miss costs a
|
(a file edit only through a path trigger naming that file) — for a rule whose miss costs a
|
||||||
rewrite. `enforce` refuses the act it governs, in the rule's own
|
rewrite. `enforce` refuses the act it governs, in the rule's own
|
||||||
words, every time — for a boundary only the operator moves; it
|
words, every time — for a boundary only the operator moves; it
|
||||||
needs a trigger, or a mount on a moment an act reaches, to have
|
needs a trigger, or a mount on a moment an act reaches, to have
|
||||||
@@ -814,7 +814,7 @@ async def update_rule(
|
|||||||
enforcement: What this rule does when it arrives. `inform` (the
|
enforcement: What this rule does when it arrives. `inform` (the
|
||||||
default for a new rule) puts a line beside the work. `hold` makes the reply or
|
default for a new rule) puts a line beside the work. `hold` makes the reply or
|
||||||
act it governs wait until the session has read the rule once
|
act it governs wait until the session has read the rule once
|
||||||
(file edits are never held) — for a rule whose miss costs a
|
(a file edit only through a path trigger naming that file) — for a rule whose miss costs a
|
||||||
rewrite. `enforce` refuses the act it governs, in the rule's own
|
rewrite. `enforce` refuses the act it governs, in the rule's own
|
||||||
words, every time — for a boundary only the operator moves; it
|
words, every time — for a boundary only the operator moves; it
|
||||||
needs a trigger, or a mount on a moment an act reaches, to have
|
needs a trigger, or a mount on a moment an act reaches, to have
|
||||||
|
|||||||
@@ -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)
|
CHECKPOINT = "checkpoint" # the act checkpoint on a command (tool-rules)
|
||||||
FENCE = "fence" # the project fence: the operator is asked
|
FENCE = "fence" # the project fence: the operator is asked
|
||||||
REPLY = "reply" # a rule holding the finished reply for one read
|
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.
|
# What the hook did with it.
|
||||||
STOPPED = "stopped" # the call was denied, the reason shown instead
|
STOPPED = "stopped" # the call was denied, the reason shown instead
|
||||||
|
|||||||
@@ -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 hook_payload as hook_payload_svc
|
||||||
from grimoire.services import moment_delivery as moment_delivery_svc
|
from grimoire.services import moment_delivery as moment_delivery_svc
|
||||||
from grimoire.services import plugin_context as plugin_ctx_svc
|
from grimoire.services import plugin_context as plugin_ctx_svc
|
||||||
|
from grimoire.services import project_check as project_check_svc
|
||||||
from grimoire.services import reply_shapes as reply_shapes_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 repo_bindings as repo_bindings_svc
|
||||||
from grimoire.services import rule_adherence as rule_adherence_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"))
|
held_rule_ids = _int_list(request.args.get("held_rule_ids"))
|
||||||
|
|
||||||
ctx = request.args.get("ctx") or ""
|
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(
|
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,
|
g.user.id, q, project_id=project_id, exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
|
||||||
context=ctx,
|
context=ctx,
|
||||||
@@ -263,6 +273,9 @@ async def autoinject_retrieve():
|
|||||||
hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()),
|
hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()),
|
||||||
})]
|
})]
|
||||||
fitted = await hook_payload_svc.fit(g.user.id, [
|
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,
|
*ordered,
|
||||||
*([hook_payload_svc.Part(text=carry)] if carry else []),
|
*([hook_payload_svc.Part(text=carry)] if carry else []),
|
||||||
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}),
|
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}),
|
||||||
|
|||||||
@@ -29,7 +29,8 @@ from sqlalchemy import and_, case, delete, exists, func, select, update
|
|||||||
|
|
||||||
from grimoire.models import async_session
|
from grimoire.models import async_session
|
||||||
from grimoire.models.gate_stop import (
|
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.rule_adherence import MISFIRE, RuleAdherence
|
||||||
from grimoire.models.rulebook import Rule
|
from grimoire.models.rulebook import Rule
|
||||||
@@ -59,7 +60,7 @@ async def record(
|
|||||||
sid = rule_deliveries.clean_session(session_id)
|
sid = rule_deliveries.clean_session(session_id)
|
||||||
if not sid or gate not in GATES or outcome not in OUTCOMES or not _field(tool):
|
if not sid or gate not in GATES or outcome not in OUTCOMES or not _field(tool):
|
||||||
return False
|
return False
|
||||||
if gate != FENCE and not rule_id:
|
if gate not in RULELESS_GATES and not rule_id:
|
||||||
return False
|
return False
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
session.add(GateStop(
|
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)
|
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():
|
def _misfired():
|
||||||
"""Whether the session reported the stopped rule as a misfire."""
|
"""Whether the session reported the stopped rule as a misfire."""
|
||||||
return exists().where(
|
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`.
|
for the fence, the operator's yes) and `sessions`.
|
||||||
|
|
||||||
`by_rule`: the same per rule and place, most stops first. `fence`: the
|
`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.
|
recorded, so a window reaching further back says so.
|
||||||
"""
|
"""
|
||||||
until = until or datetime.now(timezone.utc)
|
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)
|
.group_by(GateStop.tool, GateStop.target)
|
||||||
.order_by(func.count(GateStop.id).desc(), GateStop.tool)
|
.order_by(func.count(GateStop.id).desc(), GateStop.tool)
|
||||||
)).all()
|
)).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(
|
first = (await session.execute(
|
||||||
select(func.min(GateStop.stopped_at)).where(GateStop.user_id == user_id)
|
select(func.min(GateStop.stopped_at)).where(GateStop.user_id == user_id)
|
||||||
)).scalar_one_or_none()
|
)).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)}
|
{"tool": tool, "target": target, "asks": int(n or 0), "ran": int(ran or 0)}
|
||||||
for tool, target, n, ran in fence_rows
|
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,
|
"complete_from": first.isoformat() if first else None,
|
||||||
"covers_window": None if first is None else first <= since,
|
"covers_window": None if first is None else first <= since,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -126,11 +126,15 @@ async def deliver_for_act(
|
|||||||
result = await deliver_moments(
|
result = await deliver_moments(
|
||||||
user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board,
|
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
|
# A write is held only by a rule whose own path trigger names the file:
|
||||||
# way of the work. A rule set to enforce still refuses one — that is a
|
# a rule about a kind of file, set to hold, is read before that file
|
||||||
# boundary the operator drew, not a reminder.
|
# changes. Reached by a mount or a keyword alone, a write goes ahead, so a
|
||||||
|
# recall aid does not stand in the way of ordinary work. A rule set to
|
||||||
|
# enforce still refuses one. Rules & Governance carries this as a ruling.
|
||||||
if result.decision.get("kind") == "hold" and moment_actions.tool_key(tool) in WRITE_TOOLS:
|
if result.decision.get("kind") == "hold" and moment_actions.tool_key(tool) in WRITE_TOOLS:
|
||||||
result.decision = {}
|
holding = set(result.decision.get("rule_ids") or [])
|
||||||
|
if not (board is not None and holding & board.path_hits):
|
||||||
|
result.decision = {}
|
||||||
return reached, result
|
return reached, result
|
||||||
|
|
||||||
|
|
||||||
@@ -159,7 +163,8 @@ async def lessons_for_act(
|
|||||||
return [lesson_situations.line(a) for a in arrivals], [a.lesson_id for a in arrivals]
|
return [lesson_situations.line(a) for a in arrivals], [a.lesson_id for a in arrivals]
|
||||||
|
|
||||||
|
|
||||||
# The file-writing tools, as tool keys: a `hold` rule never holds these.
|
# The file-writing tools, as tool keys: a `hold` rule holds these only through
|
||||||
|
# a path trigger that names the file.
|
||||||
WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"})
|
WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"})
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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"(?<!\w)" + re.escape(form) + r"(?!\w)", text)
|
||||||
|
for form in _name_forms(title))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def line(verdict: Verdict, titles: dict[int, str], project_id: int) -> 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 ""
|
||||||
@@ -250,12 +250,15 @@ class Board:
|
|||||||
`triggered` — every in-scope rule that has a trigger at all, whether or
|
`triggered` — every in-scope rule that has a trigger at all, whether or
|
||||||
not this act met it: such a rule names the acts it governs, so a mount
|
not this act met it: such a rule names the acts it governs, so a mount
|
||||||
alone shows it beside the work and only its trigger can stop an act.
|
alone shows it beside the work and only its trigger can stop an act.
|
||||||
|
`path_hits` — rules with a `path` trigger, scoped or not, that names the
|
||||||
|
file this act touches: the only rules a hold may hold a write for.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
gated: set[tuple[int, str]] = field(default_factory=set)
|
gated: set[tuple[int, str]] = field(default_factory=set)
|
||||||
matched: set[tuple[int, str]] = field(default_factory=set)
|
matched: set[tuple[int, str]] = field(default_factory=set)
|
||||||
fired: list[tuple[object, Trigger]] = field(default_factory=list)
|
fired: list[tuple[object, Trigger]] = field(default_factory=list)
|
||||||
triggered: set[int] = field(default_factory=set)
|
triggered: set[int] = field(default_factory=set)
|
||||||
|
path_hits: set[int] = field(default_factory=set)
|
||||||
|
|
||||||
|
|
||||||
async def board(
|
async def board(
|
||||||
@@ -270,6 +273,8 @@ async def board(
|
|||||||
first_unscoped = None
|
first_unscoped = None
|
||||||
for trig in triggers:
|
for trig in triggers:
|
||||||
hit = matches(trig, tool, tool_input, text)
|
hit = matches(trig, tool, tool_input, text)
|
||||||
|
if hit and trig.kind == PATH:
|
||||||
|
out.path_hits.add(rule.id)
|
||||||
if trig.moment:
|
if trig.moment:
|
||||||
pair = (rule.id, trig.moment)
|
pair = (rule.id, trig.moment)
|
||||||
if hit:
|
if hit:
|
||||||
|
|||||||
@@ -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
|
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():
|
async def test_stops_age_out_with_the_deliveries():
|
||||||
uid = await _user()
|
uid = await _user()
|
||||||
await gate_stops.record(uid, "s", gate="hold", outcome="stopped", tool="bash", rule_id=RULE)
|
await gate_stops.record(uid, "s", gate="hold", outcome="stopped", tool="bash", rule_id=RULE)
|
||||||
|
|||||||
@@ -44,6 +44,44 @@ async def test_unknown_argument_is_an_error_not_a_silent_drop():
|
|||||||
assert "Nothing was created or changed" in msg
|
assert "Nothing was created or changed" in msg
|
||||||
|
|
||||||
|
|
||||||
|
def _query_server() -> StrictArgsMCPServer:
|
||||||
|
mcp = StrictArgsMCPServer("alias-test")
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def find(q: str = "") -> str:
|
||||||
|
return f"found:{q}"
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def own(query: str = "") -> str:
|
||||||
|
return f"own:{query}"
|
||||||
|
|
||||||
|
return mcp
|
||||||
|
|
||||||
|
|
||||||
|
async def test_query_is_taken_as_q_by_a_tool_that_declares_q():
|
||||||
|
mcp = _query_server()
|
||||||
|
assert "found:backups" in str(await mcp.call_tool("find", {"query": "backups"}))
|
||||||
|
# A tool that declares `query` itself keeps it.
|
||||||
|
assert "own:backups" in str(await mcp.call_tool("own", {"query": "backups"}))
|
||||||
|
|
||||||
|
|
||||||
|
async def test_query_beside_q_is_still_refused():
|
||||||
|
mcp = _query_server()
|
||||||
|
with pytest.raises(ToolError) as exc:
|
||||||
|
await mcp.call_tool("find", {"q": "a", "query": "b"})
|
||||||
|
assert "'query'" in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_the_real_search_tool_takes_query():
|
||||||
|
"""Against the REAL server: search declares `q`, so `query` is renamed
|
||||||
|
before the unknown-argument check rather than refused by it."""
|
||||||
|
from grimoire.mcp.server import _with_aliases, build_mcp_server
|
||||||
|
|
||||||
|
tool = build_mcp_server()._tool_manager.get_tool("search")
|
||||||
|
declared = set(tool.parameters["properties"])
|
||||||
|
assert _with_aliases({"query": "x"}, declared) == {"q": "x"}
|
||||||
|
|
||||||
|
|
||||||
async def test_empty_arguments_pass():
|
async def test_empty_arguments_pass():
|
||||||
mcp = _echo_server()
|
mcp = _echo_server()
|
||||||
assert await mcp.call_tool("echo", {}) is not None
|
assert await mcp.call_tool("echo", {}) is not None
|
||||||
|
|||||||
@@ -563,23 +563,45 @@ async def test_an_inform_rule_and_a_preference_never_stop_the_act():
|
|||||||
assert (await _arm(pairs)).decision == {}
|
assert (await _arm(pairs)).decision == {}
|
||||||
|
|
||||||
|
|
||||||
async def _deliver_for(tool, decision):
|
async def _deliver_for(tool, decision, board=None):
|
||||||
from grimoire.services import moment_actions as ma
|
from grimoire.services import moment_actions as ma
|
||||||
|
|
||||||
with patch.object(ma, "moments_for", AsyncMock(return_value=PUSH)), \
|
with patch.object(ma, "moments_for", AsyncMock(return_value=PUSH)), \
|
||||||
patch.object(md, "_board", AsyncMock(return_value=None)), \
|
patch.object(md, "_board", AsyncMock(return_value=board)), \
|
||||||
patch.object(md, "deliver_moments",
|
patch.object(md, "deliver_moments",
|
||||||
AsyncMock(return_value=rp.RuleResult(decision=dict(decision)))):
|
AsyncMock(return_value=rp.RuleResult(decision=dict(decision)))):
|
||||||
_reached, result = await _REAL_DELIVER(1, tool, {})
|
_reached, result = await _REAL_DELIVER(1, tool, {})
|
||||||
return result.decision
|
return result.decision
|
||||||
|
|
||||||
|
|
||||||
async def test_a_write_is_refused_by_an_enforced_rule_but_never_held():
|
async def test_a_write_is_refused_by_an_enforced_rule_and_held_only_through_a_path_trigger():
|
||||||
|
from grimoire.services.rule_triggers import Board
|
||||||
|
|
||||||
hold = {"kind": "hold", "rule_ids": [7], "reason": "read it"}
|
hold = {"kind": "hold", "rule_ids": [7], "reason": "read it"}
|
||||||
enforce = {"kind": "enforce", "rule_ids": [6], "reason": "not run"}
|
enforce = {"kind": "enforce", "rule_ids": [6], "reason": "not run"}
|
||||||
assert await _deliver_for("Edit", hold) == {}
|
assert await _deliver_for("Edit", hold) == {}
|
||||||
assert await _deliver_for("Bash", hold) == hold
|
assert await _deliver_for("Bash", hold) == hold
|
||||||
assert await _deliver_for("Write", enforce) == enforce
|
assert await _deliver_for("Write", enforce) == enforce
|
||||||
|
# Rule 7's own path trigger names the file: the write waits for one read.
|
||||||
|
assert await _deliver_for("Edit", hold, Board(path_hits={7})) == hold
|
||||||
|
# Another rule's path trigger matched; rule 7 reached the write otherwise.
|
||||||
|
assert await _deliver_for("Write", hold, Board(path_hits={8})) == {}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_the_board_names_the_rules_a_path_trigger_matched(monkeypatch):
|
||||||
|
from grimoire.services import rule_triggers as rt
|
||||||
|
|
||||||
|
compose = fake_rule(id=198, title="defaults")
|
||||||
|
keyword = fake_rule(id=5, title="keyword only")
|
||||||
|
monkeypatch.setattr(rt, "_in_scope", AsyncMock(return_value=[
|
||||||
|
(compose, [rt.Trigger("keyword", "update_config"), rt.Trigger("path", "**/compose*.yml")]),
|
||||||
|
(keyword, [rt.Trigger("keyword", "update_config")]),
|
||||||
|
]))
|
||||||
|
edit = {"file_path": "/repo/deploy/compose.deploy.yml", "new_string": "update_config:"}
|
||||||
|
board = await rt.board(1, 2, tool="Edit", tool_input=edit)
|
||||||
|
assert board.path_hits == {198}
|
||||||
|
other = await rt.board(1, 2, tool="Edit", tool_input={**edit, "file_path": "/repo/README.md"})
|
||||||
|
assert other.path_hits == set()
|
||||||
|
|
||||||
|
|
||||||
def _decided(tmp_path, decision, session="s-decide"):
|
def _decided(tmp_path, decision, session="s-decide"):
|
||||||
|
|||||||
@@ -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()
|
||||||
Reference in New Issue
Block a user